Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: 去除多余引用,更正部分类型注解,完全兼容pydantic v1 & v2 #118

Merged
merged 2 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions src/common/utils/rpc/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import json
import grpc
from typing import List, Dict, Tuple, Optional, Type, TypeVar, Any
from typing import List, Dict, Tuple, Optional, Any
from src.common.utils.rpc import pymongo_rpc_pb2, pymongo_rpc_pb2_grpc
from src.common.config import plugin_config


T = TypeVar('T')


class CollectionProxy:
def __init__(self, rpc_client: Type['MongoClient'], collection_name: str):
def __init__(self, rpc_client: 'MongoClient', collection_name: str):
self.rpc_client = rpc_client
self.collection_name = collection_name

def __getitem__(self: T, collection_name: str) -> T:
def __getitem__(self, collection_name: str) -> 'CollectionProxy':
return CollectionProxy(self.rpc_client, collection_name)

def find(self, filter: Dict = {}) -> List[Dict[str, Any]]:
Expand All @@ -39,7 +36,7 @@ def create_index(self, keys: List[Tuple], name: Optional[str] = None, default_la


class MongoClient:
def __init__(self, mongo_host: str, mongo_port: str, **kwargs):
def __init__(self, mongo_host: str, mongo_port: int, **kwargs):
self.channel = grpc.insecure_channel(f'{mongo_host}:{mongo_port}')
self.stub = pymongo_rpc_pb2_grpc.MongoDBServiceStub(self.channel)
self.metadata = [('authorization', plugin_config.rpc_token)]
Expand Down
12 changes: 6 additions & 6 deletions src/plugins/auto_accept/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import nonebot
from nonebot import on_command, on_request, on_notice, get_driver
from nonebot.adapters.onebot.v11 import MessageSegment, Message, FriendRequestEvent, GroupRequestEvent, Bot
from nonebot import on_request
from nonebot.adapters.onebot.v11 import FriendRequestEvent, GroupRequestEvent, Bot
from nonebot.typing import T_State

from src.common.config import BotConfig, GroupConfig, UserConfig
Expand All @@ -12,7 +11,7 @@


@request_cmd.handle()
async def handle_request(bot: Bot, event: GroupRequestEvent, state: T_State):
async def handle_group_request(bot: Bot, event: GroupRequestEvent, state: T_State):
if event.sub_type == 'invite':
if GroupConfig(event.group_id).is_banned() or UserConfig(event.user_id).is_banned():
await event.reject(bot)
Expand All @@ -24,11 +23,12 @@ async def handle_request(bot: Bot, event: GroupRequestEvent, state: T_State):


@request_cmd.handle()
async def handle_request(bot: Bot, event: FriendRequestEvent, state: T_State):
async def handle_friend_request(bot: Bot, event: FriendRequestEvent, state: T_State):
if UserConfig(event.user_id).is_banned():
await event.reject(bot)
return

bot_config = BotConfig(event.self_id)
if bot_config.is_admin_of_bot(event.user_id): # or bot_config.auto_accept(): # 自动加好友太容易被封号了,先关了
# or bot_config.auto_accept(): # 自动加好友太容易被封号了,先关了
if bot_config.is_admin_of_bot(event.user_id):
await event.approve(bot)
4 changes: 2 additions & 2 deletions src/plugins/block/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import time
from typing import List, Union

import nonebot
from nonebot import get_bots
from nonebot.adapters import Bot
from nonebot.adapters.onebot.v11 import GroupIncreaseNoticeEvent, GroupMessageEvent, PokeNotifyEvent, permission
Expand Down Expand Up @@ -36,7 +35,8 @@ def refresh_accounts(self) -> None:
onebot_accounts: list[int] = [
int(self_id) for self_id, bot in get_bots().items() if self_id.isnumeric() and bot.type == 'OneBot V11'
]
self.accounts = list(set(go_cqhttp_plugin_accounts + onebot_accounts))
self.accounts = list(
set(go_cqhttp_plugin_accounts + onebot_accounts))

async def is_other_bot(self, bot: Bot, event: GroupMessageEvent, state: T_State) -> bool:
self.refresh_accounts()
Expand Down
8 changes: 4 additions & 4 deletions src/plugins/chat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from asyncer import asyncify
from nonebot.adapters.onebot.v11 import MessageSegment, Message, permission, GroupMessageEvent
from nonebot.adapters.onebot.v11 import MessageSegment, permission, GroupMessageEvent
from nonebot.adapters import Bot, Event
from nonebot.rule import Rule
from nonebot.typing import T_State
from nonebot import on_message, get_driver, logger
from nonebot import on_message, logger

from src.common.config import BotConfig, GroupConfig, plugin_config

Expand All @@ -30,14 +30,14 @@


@BotConfig.handle_sober_up
def on_sober_up(bot_id, group_id, drunkenness) -> bool:
def on_sober_up(bot_id, group_id, drunkenness) -> None:
session = f'{bot_id}_{group_id}'
logger.info(
f'bot [{bot_id}] sober up in group [{group_id}], clear session [{session}]')
chat.del_session(session)


def is_drunk(bot: Bot, event: Event, state: T_State) -> bool:
def is_drunk(bot: Bot, event: Event, state: T_State) -> int:
config = BotConfig(event.self_id, event.group_id)
return config.drunkenness()

Expand Down
8 changes: 4 additions & 4 deletions src/plugins/drink/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import random
import asyncio

from nonebot import on_message, require, get_bot, logger, get_driver
from nonebot import on_message, require, logger
from nonebot.exception import ActionFailed
from nonebot.typing import T_State
from nonebot.rule import keyword, to_me, Rule
from nonebot.adapters import Bot, Event
from nonebot.rule import Rule
from nonebot.adapters import Bot
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent
from nonebot.adapters.onebot.v11 import permission
from src.common.config import BotConfig, GroupConfig
from src.common.config import BotConfig


async def is_drink_msg(bot: Bot, event: GroupMessageEvent, state: T_State) -> bool:
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/greeting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import asyncio

from pathlib import Path
from nonebot import on_command, on_message, on_notice, get_driver, get_bot
from nonebot import on_message, on_notice, get_bot
from nonebot.adapters.onebot.v11 import MessageSegment, Message, permission, GroupMessageEvent
from nonebot.rule import keyword, startswith, to_me, Rule
from nonebot.rule import to_me, Rule
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from src.common.config import BotConfig, GroupConfig, UserConfig
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/repeater/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
import time
import threading

from nonebot import on_message, on_notice, require, get_bot, logger, get_driver
from nonebot import on_message, on_notice, require, get_bot, logger
from nonebot.exception import ActionFailed
from nonebot.typing import T_State
from nonebot.rule import keyword, to_me, Rule
from nonebot.adapters import Bot, Event
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent, GroupRecallNoticeEvent
from nonebot.adapters.onebot.v11 import GroupMessageEvent, GroupRecallNoticeEvent
from nonebot.adapters.onebot.v11 import permission, Message, MessageSegment
from nonebot.permission import Permission
from nonebot.permission import SUPERUSER
Expand Down
8 changes: 4 additions & 4 deletions src/plugins/roulette/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import asyncio
from collections import defaultdict
from typing import Awaitable, Optional
from nonebot import on_message, on_request, get_bot, logger, get_driver
from nonebot import on_message, on_request, get_bot, logger
from nonebot.typing import T_State
from nonebot.rule import keyword, to_me, Rule
from nonebot.rule import Rule
from nonebot.adapters import Bot, Event
from nonebot.adapters.onebot.v11 import GroupMessageEvent, GroupRequestEvent
from nonebot.adapters.onebot.v11 import MessageSegment, Message, permission, GroupMessageEvent
from nonebot.adapters.onebot.v11 import MessageSegment, permission, GroupMessageEvent
from nonebot.permission import Permission
from src.common.config import BotConfig, GroupConfig

Expand Down Expand Up @@ -164,7 +164,7 @@ async def shot(self_id: int, user_id: int, group_id: int) -> Optional[Awaitable[
if self_role == 'owner': # 牛牛是群主不能退群,不然群就解散了
return None

async def group_leave():
async def group_leave() -> None:
await get_bot(str(self_id)).call_api('set_group_leave', **{
'group_id': group_id
})
Expand Down
8 changes: 4 additions & 4 deletions src/plugins/sing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import time
import os

from nonebot import get_driver, on_message, require, logger
from nonebot import on_message, require, logger
from nonebot.typing import T_State
from nonebot.rule import Rule
from nonebot.adapters import Bot, Event
Expand Down Expand Up @@ -34,10 +34,10 @@ async def is_to_sing(bot: Bot, event: Event, state: T_State) -> bool:
text = event.get_plaintext()
if not text:
return False

if not SING_CMD in text and not any([cmd in text for cmd in SING_CONTINUE_CMDS]):
return False

if text.endswith(SING_CMD):
return False

Expand Down Expand Up @@ -79,7 +79,7 @@ async def is_to_sing(bot: Bot, event: Event, state: T_State) -> bool:
progress = GroupConfig(group_id=event.group_id).sing_progress()
if not progress:
return False

song_id = progress['song_id']
chunk_index = progress['chunk_index']
key_val = progress['key']
Expand Down
13 changes: 10 additions & 3 deletions src/plugins/sing/ncm_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ class Config(BaseModel, extra=Extra.ignore):
ncm_ctcode: int = 86


config = Config.parse_obj(get_driver().config)
try:
# pydantic v2
from nonebot import get_plugin_config
config = get_plugin_config(Config)
except ImportError:
# pydantic v1
config = Config.parse_obj(get_driver().config)


if config.ncm_phone and config.ncm_password:
ncm.login.LoginViaCellphone(
Expand Down Expand Up @@ -72,7 +79,7 @@ def get_song_id(song_name: str):

if res["result"]["songCount"] == 0:
return None

for song in res["result"]["songs"]:
privilege = song["privilege"]
if "chargeInfoList" not in privilege:
Expand All @@ -86,5 +93,5 @@ def get_song_id(song_name: str):
continue

return song["id"]

return None
Loading