diff --git a/src/common_utils/genshin_api.py b/src/common_utils/genshin_api.py index 02ee363..9dd4550 100644 --- a/src/common_utils/genshin_api.py +++ b/src/common_utils/genshin_api.py @@ -174,20 +174,20 @@ def get_last_error_msg(self): @staticmethod def __generate_230_headers(cookie: str, with_ds: bool = False): ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) " \ - "AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.3.0" + "AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.34.1" headers = { "User-Agent": ua, "Referer": "https://webstatic.mihoyo.com/", "Cookie": cookie } if with_ds: - n = 'h8w582wxwgqvahcdkpvdhbh2w9casgfl' + n = '9nQiU3AV0rJSIBWgdynfoGMGKaklfbM7' i = int(time.time()) r = ''.join(random.sample(string.ascii_lowercase + string.digits, 6)) d = "salt=%s&t=%d&r=%s" % (n, i, r) c = hashlib.md5(d.encode(encoding="UTF-8")).hexdigest() headers["DS"] = "%s,%s,%s" % (i, r, c) - headers["x-rpc-app_version"] = "2.3.0" + headers["x-rpc-app_version"] = "2.34.1" headers["x-rpc-client_type"] = "5" headers["x-rpc-device_id"] = str(uuid.uuid3(uuid.NAMESPACE_URL, ua)).replace('-', '').upper() return headers @@ -195,7 +195,7 @@ def __generate_230_headers(cookie: str, with_ds: bool = False): @staticmethod def __generate_211_headers(cookie: str, with_ds: bool = False, query: dict = {}, body: str = ""): ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) " \ - "AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1" + "AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.34.1" headers = { "User-Agent": ua, "Referer": "https://webstatic.mihoyo.com/", @@ -209,7 +209,7 @@ def __generate_211_headers(cookie: str, with_ds: bool = False, query: dict = {}, d = "salt=%s&t=%d&r=%s&b=%s&q=%s" % (n, i, r, body, q) c = hashlib.md5(d.encode(encoding="UTF-8")).hexdigest() headers["DS"] = "%s,%s,%s" % (i, r, c) - headers["x-rpc-app_version"] = "2.3.0" + headers["x-rpc-app_version"] = "2.34.1" headers["x-rpc-client_type"] = "5" headers["x-rpc-device_id"] = str(uuid.uuid3(uuid.NAMESPACE_URL, ua)).replace('-', '').upper() return headers @@ -257,7 +257,7 @@ async def __httpx_post_data(self, url: str, params: dict, body: dict, headers: d json_ret = response.json() if json_ret["retcode"] != 0: logger.error(f"API::__httpx_post_data ret code error, " - f"retcode:{json_ret['code']}, msg: {json_ret['message']}") + f"msg: {json_ret['message']}") self.__last_error_msg = "返回错误,请检查cookie是否有效,错误内容: %s" % json_ret["message"] return None ret = json_ret["data"] @@ -304,7 +304,7 @@ async def __get_sign_info(self): async def __get_rewards_info(self): if self.__is_login is False: - logger.error("API::__get_sign_info error, not login") + logger.error("API::__get_rewards_info error, not login") self.__last_error_msg = "未登录,请绑定cookie" return None @@ -314,7 +314,7 @@ async def __get_rewards_info(self): headers = self.__generate_211_headers(self.__cookie) data = await self.__httpx_get_data(self.__url_rewards_info, query, headers) if data is None: - logger.error("API::__get_sign_info error, data is None") + logger.error("API::__get_rewards_info error, data is None") return None return data @@ -345,7 +345,7 @@ async def __get_news(self, page_size: int, news_type: int): headers = self.__generate_211_headers("") data = await self.__httpx_get_data(self.__url_news, query, headers) if data is None: - logger.error("API::__get_sign_info error, data is None") + logger.error("API::__get_news error, data is None") return None return data diff --git a/src/common_utils/interface.py b/src/common_utils/interface.py index c7c5074..45e53f2 100644 --- a/src/common_utils/interface.py +++ b/src/common_utils/interface.py @@ -1,16 +1,18 @@ from abc import ABCMeta, abstractmethod from .system import BeanContainer +from nonebot.adapters.onebot.v11 import Event -class IPluginTextBase(metaclass=ABCMeta): +class IPluginBase(metaclass=ABCMeta): __keyword: str __help_text: str bean_container: BeanContainer - def __init__(self, keyword: str, help_text: str, bean_container: BeanContainer): + def __init__(self, bean_container: BeanContainer, keyword: str = "", help_text: str = ""): self.__keyword = keyword self.__help_text = help_text self.bean_container = bean_container + self.init_module() def match_keyword(self, plain_text: str) -> bool: if plain_text.find(self.__keyword) == 0: @@ -28,7 +30,11 @@ def get_help(self) -> str: return self.__help_text @abstractmethod - async def handle(self, from_id: int, plain_text: str): + def init_module(self): + pass + + @abstractmethod + async def handle_event(self, event: Event): pass @abstractmethod diff --git a/src/common_utils/system.py b/src/common_utils/system.py index 1e0e71a..19bb7a0 100644 --- a/src/common_utils/system.py +++ b/src/common_utils/system.py @@ -52,55 +52,3 @@ def json_str_to_dict(cls, json_str: str) -> (bool, dict): logger.error(f"json_str_to_dict error, e:{e}") return False, None - -async def is_plugin_enable(event: Event, core_db: Database, plugin_name: str, default: bool = True) -> bool: - success, enable_val = core_db.get_value(plugin_name, "enable") - if success is False: - return default - if enable_val == 0: - return False - - if not hasattr(event, "group_id"): - return True - - sender_group = event.group_id - - success, enable_list_val = core_db.get_value(plugin_name, "group_id_list") - if success is False: - return default - if enable_list_val is None: - return default - - ret, enable_list = JsonUtil.json_str_to_list(enable_list_val) - if ret is False: - return default - - if len(enable_list) == 0: - return True - - for group_id in enable_list: - if group_id == sender_group: - return True - - return False - - -async def get_enable_group(core_db: Database, plugin_name: str) -> list: - default = [] - success, enable_val = core_db.get_value(plugin_name, "enable") - if success is False: - return default - if enable_val == 0: - return default - - success, enable_list_val = core_db.get_value(plugin_name, "group_id_list") - if success is False: - return default - if enable_list_val is None: - return default - - ret, enable_list = JsonUtil.json_str_to_list(enable_list_val) - if ret is False: - return default - - return enable_list diff --git a/src/plugins/adult/__init__.py b/src/plugins/adult/__init__.py index d3db2da..af2d949 100644 --- a/src/plugins/adult/__init__.py +++ b/src/plugins/adult/__init__.py @@ -1,48 +1,41 @@ from nonebot import require from nonebot import get_driver from nonebot import on_message -from nonebot.adapters.onebot.v11 import Event +from nonebot.adapters.onebot.v11 import GroupMessageEvent from .config import Config -from src.common_utils.database import Database -from src.common_utils.system import BeanContainer, is_plugin_enable +from src.common_utils.system import BeanContainer from src.common_utils.aliyun import Green from .image import Image - require('core') +from src.plugins.core.core import GlobalCore global_config = get_driver().config config = Config.parse_obj(global_config) plugin_name = "adult" -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") +global_core = GlobalCore() green = Green(config.ali_access_id, config.ali_access_key, config.ali_region_sh) + bean_container = BeanContainer() bean_container.register(green) +bean_container.register(config) module_image = Image(bean_container) -adult = on_message(priority=10) + +async def check_enable(event: GroupMessageEvent) -> bool: + if not isinstance(event, GroupMessageEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) + +adult = on_message(priority=10, rule=check_enable) @adult.handle() -async def handle(event: Event): - url_list = [] - for seg in event.get_message(): - if seg.type == "image": - url_list.append(seg.data["url"]) - if len(url_list) == 0: - return - enable = await is_plugin_enable(event, core_db, plugin_name) - if enable is False: - return - handle_ret, score = await module_image.handle(url_list) - if handle_ret is False or score < 0.5: - return - - count = round(score / 20.0) + 1 - await adult.send("💦" * count) +async def handle(event: GroupMessageEvent): + message = await module_image.handle_event(event) + if message is not None: + await adult.finish(message) diff --git a/src/plugins/adult/image.py b/src/plugins/adult/image.py index 20b1397..921a60d 100644 --- a/src/plugins/adult/image.py +++ b/src/plugins/adult/image.py @@ -1,20 +1,24 @@ from src.common_utils.aliyun import Green +from src.common_utils.interface import IPluginBase from nonebot.log import logger +from nonebot.adapters.onebot.v11 import GroupMessageEvent from httpx import AsyncClient -from src.common_utils.system import BeanContainer -class Image: - __bean_container: BeanContainer +class Image(IPluginBase): + def init_module(self): + pass - def __init__(self, bean_container: BeanContainer): - self.__bean_container = bean_container + async def handle_event(self, event: GroupMessageEvent): + url_list = [] + for seg in event.get_message(): + if seg.type == "image": + url = seg.data["url"] + if len(url) != 0: + url_list.append(seg.data["url"]) - async def handle(self, urls: list) -> (bool, float): large_url_list = [] - for url in urls: - if len(url) == 0: - continue + for url in url_list: ret, image_size = await self.__get_url_content_size(url) if ret is False: continue @@ -22,11 +26,19 @@ async def handle(self, urls: list) -> (bool, float): if image_size > 1024 * 10: large_url_list.append(url) - green: Green = self.__bean_container.get_bean(Green) + if len(large_url_list) == 0: + return None + + green: Green = self.bean_container.get_bean(Green) ret, score = green.get_image_score_by_url(large_url_list) - if ret is True: - logger.info(f"Image::get_image_score_by_url ret: {ret}, score: {score}") - return ret, score + if ret is False or score < 0.5: + return None + + count = round(score / 20.0) + 1 + return "💦" * count + + async def task(self, groups: list): + pass @staticmethod async def __get_url_content_size(url: str) -> (bool, int): diff --git a/src/plugins/chat/__init__.py b/src/plugins/chat/__init__.py index 1fb57ae..4352489 100644 --- a/src/plugins/chat/__init__.py +++ b/src/plugins/chat/__init__.py @@ -1,67 +1,42 @@ from nonebot import require from nonebot import get_driver from nonebot import on_message -from nonebot.adapters.onebot.v11 import Event, GroupMessageEvent +from nonebot.adapters.onebot.v11 import GroupMessageEvent from .config import Config -from src.common_utils.database import Database -from src.common_utils.system import BeanContainer, is_plugin_enable +from src.common_utils.system import BeanContainer from src.common_utils.aliyun import Nlp from .chatter import Chatter - require('core') +from src.plugins.core.core import GlobalCore global_config = get_driver().config config = Config.parse_obj(global_config) plugin_name = "chat" -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") +global_core = GlobalCore() +nlp = Nlp(config.ali_access_id, config.ali_access_key, config.ali_region_hz) + bean_container = BeanContainer() bean_container.register(config) - -nlp = Nlp(config.ali_access_id, config.ali_access_key, config.ali_region_hz) bean_container.register(nlp) module_chatter = Chatter(bean_container) -chat = on_message(priority=10) +async def check_enable(event: GroupMessageEvent) -> bool: + if not isinstance(event, GroupMessageEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) -@chat.handle() -async def handle(event: Event): - text = event.get_plaintext() - if len(text) == 0 or text.strip() == "": - return - enable = await is_plugin_enable(event, core_db, plugin_name) - if enable is False: - return +chat = on_message(priority=10, rule=check_enable) - if not isinstance(event, GroupMessageEvent): - return - if event.reply is not None \ - and event.reply.sender.user_id == event.self_id \ - and text == "不可以": - search_text = event.reply.message.extract_plain_text() - db_ret, exist = await module_chatter.reply_exist(search_text) - if db_ret is False: - await chat.send("下次还敢") - return - if exist is False: - await chat.send("不是我说的") - return - remove_ret = await module_chatter.reply_delete(search_text) - if remove_ret is False: - await chat.send("下次还敢") - else: - await chat.send("我错了") - else: - handle_ret, reply_text = await module_chatter.handle(event.group_id, text) - if handle_ret is False or len(reply_text) == 0: - return - await chat.send(reply_text) +@chat.handle() +async def handle(event: GroupMessageEvent): + message = await module_chatter.handle_event(event) + if message is not None: + await chat.finish(message) diff --git a/src/plugins/chat/chatter.py b/src/plugins/chat/chatter.py index 9607a84..c05b318 100644 --- a/src/plugins/chat/chatter.py +++ b/src/plugins/chat/chatter.py @@ -1,12 +1,14 @@ from src.common_utils.system import BeanContainer +from src.common_utils.aliyun import Nlp +from src.common_utils.database import Database +from src.common_utils.interface import IPluginBase from nonebot.log import logger +from nonebot.adapters.onebot.v11 import GroupMessageEvent from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from .config import Config from .tagging import CustomLemmaTagger from .attrs import STOP_WORDS -from src.common_utils.aliyun import Nlp -from src.common_utils.database import Database import time @@ -17,19 +19,18 @@ class MessageCache: next_interval: int -class Chatter: - __bean_container: BeanContainer +class Chatter(IPluginBase): __config: Config __message_cache: dict __default_interval: int __nlp = None __chatbot = None + __stop_words = STOP_WORDS + __statement_db: Database() - def __init__(self, bean_container: BeanContainer): - self.__bean_container = bean_container - self.__config = bean_container.get_bean(Config) - self.__nlp: Nlp = bean_container.get_bean(Nlp) - self.stop_word = STOP_WORDS + def init_module(self): + self.__config = self.bean_container.get_bean(Config) + self.__nlp: Nlp = self.bean_container.get_bean(Nlp) self.__message_cache = {} self.__default_interval = 60 * 10 success, bot = self.__create_bot(0) @@ -41,13 +42,34 @@ def __init__(self, bean_container: BeanContainer): if not self.__statement_db.connect_table("statement", self.__config.maria_chat_database): raise Exception("connect statement table error") - async def reply_exist(self, plain_text: str) -> (bool, bool): - return self.__statement_db.is_value_exist("text", plain_text) + async def handle_event(self, event: GroupMessageEvent): + plain_text = event.get_plaintext() + if len(plain_text) == 0 or plain_text.strip() == "": + return + if event.reply is not None \ + and event.reply.sender.user_id == event.self_id \ + and plain_text == "不可以": + search_text = event.reply.message.extract_plain_text() + db_ret, exist = self.__statement_db.is_value_exist("text", search_text) + if db_ret is False: + return "下次还敢" + if exist is False: + return "不是我说的" + remove_ret = self.__statement_db.delete_value("text", search_text) + if remove_ret is False: + return "下次还敢" + else: + return "我错了" + else: + handle_ret, reply_text = self.__process_chat(event.group_id, plain_text) + if handle_ret is False or len(reply_text) == 0: + return None + return reply_text - async def reply_delete(self, plain_text: str) -> bool: - return self.__statement_db.delete_value("text", plain_text) + async def task(self, groups: list): + pass - async def handle(self, group_id: int, plain_text: str) -> (bool, str): + def __process_chat(self, group_id: int, plain_text: str) -> (bool, str): if len(plain_text) == 0: return False, "" @@ -131,3 +153,4 @@ def __train_bot(self, bot: ChatBot, group_id: int): message_cache.message.clear() message_cache.next_interval = self.__default_interval return + diff --git a/src/plugins/core/__init__.py b/src/plugins/core/__init__.py index e79a543..7e21a87 100644 --- a/src/plugins/core/__init__.py +++ b/src/plugins/core/__init__.py @@ -4,8 +4,8 @@ from nonebot.adapters.onebot.v11 import Event, GroupMessageEvent from nonebot.log import logger from .config import Config +from .core import GlobalCore -from src.common_utils.database import Database from src.common_utils.system import JsonUtil global_config = get_driver().config @@ -16,23 +16,10 @@ plugin_keyword = "/" + plugin_keyword -data_base_col = { - "enable": "int", - "group_id_list": "text" -} - -core_db = Database() -if not core_db.init_table(table_name=plugin_name, table_key="name", table_key_type=str, table_col=data_base_col): - raise Exception("init core table error") plugin_names = config.plugin_names -for plugin_name in plugin_names: - success, exist = core_db.is_key_exist(plugin_name) - if not success: - raise Exception("init core key error") - if not exist: - core_db.insert_key(plugin_name) - core_db.update_value(plugin_name, "enable", 1) - core_db.update_value(plugin_name, "group_id_list", "[]") +global_core = GlobalCore() +global_core.init_core_db(config.plugin_names) +core_db = global_core.get_core_db() core = on_startswith(plugin_keyword, priority=1) diff --git a/src/plugins/core/core.py b/src/plugins/core/core.py new file mode 100644 index 0000000..998590e --- /dev/null +++ b/src/plugins/core/core.py @@ -0,0 +1,72 @@ +from src.common_utils.system import Singleton, JsonUtil +from src.common_utils.database import Database + + +class GlobalCore(metaclass=Singleton): + __core_db: Database + + def init_core_db(self, plugin_names: list): + data_base_col = { + "enable": "int", + "group_id_list": "text" + } + self.__core_db = Database() + if not self.__core_db.init_table(table_name="core", table_key="name", + table_key_type=str, table_col=data_base_col): + raise Exception("init core table error") + for plugin_name in plugin_names: + success, exist = self.__core_db.is_key_exist(plugin_name) + if not success: + raise Exception("init core key error") + if not exist: + self.__core_db.insert_key(plugin_name) + self.__core_db.update_value(plugin_name, "enable", 1) + self.__core_db.update_value(plugin_name, "group_id_list", "[]") + + def is_plugin_enable(self, plugin_name: str, group_id: int, default: bool = True) -> bool: + success, enable_val = self.__core_db.get_value(plugin_name, "enable") + if success is False: + return default + if enable_val == 0: + return False + + success, enable_list_val = self.__core_db.get_value(plugin_name, "group_id_list") + if success is False: + return default + if enable_list_val is None: + return default + + ret, enable_list = JsonUtil.json_str_to_list(enable_list_val) + if ret is False: + return default + + if len(enable_list) == 0: + return True + + if group_id in enable_list: + return True + + return False + + def get_enable_group(self, plugin_name: str) -> list: + default = [] + success, enable_val = self.__core_db.get_value(plugin_name, "enable") + if success is False: + return default + if enable_val == 0: + return default + + success, enable_list_val = self.__core_db.get_value(plugin_name, "group_id_list") + if success is False: + return default + if enable_list_val is None: + return default + + ret, enable_list = JsonUtil.json_str_to_list(enable_list_val) + if ret is False: + return default + + return enable_list + + def get_core_db(self) -> Database: + return self.__core_db diff --git a/src/plugins/genshin/__init__.py b/src/plugins/genshin/__init__.py index ac83ac9..e9687aa 100644 --- a/src/plugins/genshin/__init__.py +++ b/src/plugins/genshin/__init__.py @@ -1,15 +1,15 @@ from nonebot import require from nonebot import get_driver from nonebot import on_startswith -from nonebot.adapters.onebot.v11 import Event +from nonebot.adapters.onebot.v11 import GroupMessageEvent from .config import Config from src.common_utils.database import Database -from src.common_utils.system import BeanContainer, is_plugin_enable +from src.common_utils.system import BeanContainer from .sign_reward import SignReward from .bind_account import BindAccount - require('core') +from src.plugins.core.core import GlobalCore global_config = get_driver().config config = Config.parse_obj(global_config) @@ -24,38 +24,38 @@ genshin_db = Database() if not genshin_db.init_table(table_name=plugin_name, table_key="id", table_key_type=int, table_col=data_base_col): raise Exception("init genshin table error") +global_core = GlobalCore() + bean_container = BeanContainer() bean_container.register(genshin_db) -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") module_list = [ - BindAccount("绑定", "绑定米游社账号", bean_container), - SignReward("签到", "米游社每日签到", bean_container), + BindAccount(bean_container, plugin_keyword + "绑定", "绑定米游社账号"), + SignReward(bean_container, plugin_keyword + "签到", "米游社每日签到"), ] -genshin = on_startswith(plugin_keyword, priority=1) + +async def check_enable(event: GroupMessageEvent) -> bool: + if not isinstance(event, GroupMessageEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) + +genshin = on_startswith(plugin_keyword, priority=1, rule=check_enable) @genshin.handle() -async def handle(event: Event): - enable = await is_plugin_enable(event, core_db, plugin_name) - if enable is False: - return - sender_id = int(event.get_user_id()) +async def handle(event: GroupMessageEvent): text = event.get_plaintext() - text = text.lstrip(plugin_keyword).strip() - if len(text) == 0: + if text == plugin_keyword: message = "指令格式:\n" for module in module_list: - message += f"{plugin_keyword}{module.get_keyword()}:{module.get_help()}\n" + message += f"{module.get_keyword()}:{module.get_help()}\n" message = message.rstrip("\n") await genshin.finish(message) for module in module_list: if module.match_keyword(text): - message = await module.handle(sender_id, module.strip_keyword(text)) + message = await module.handle_event(event) if message is not None: await genshin.finish(message) diff --git a/src/plugins/genshin/bind_account.py b/src/plugins/genshin/bind_account.py index a6a666e..c72311f 100644 --- a/src/plugins/genshin/bind_account.py +++ b/src/plugins/genshin/bind_account.py @@ -1,10 +1,11 @@ -from src.common_utils.interface import IPluginTextBase +from src.common_utils.interface import IPluginBase from src.common_utils.database import Database from src.common_utils.genshin_api import API from nonebot.log import logger +from nonebot.adapters.onebot.v11 import GroupMessageEvent -class BindAccount(IPluginTextBase): +class BindAccount(IPluginBase): __bind_tip = "PC打开https://bbs.mihoyo.com/ys/登陆后,右键检查,选择控制台,粘贴以下代码,在弹出的窗口点确认,然后粘贴发送,绑定完毕记得撤回:\n" \ "var cookie=document.cookie;" \ "var Str_Num=cookie.indexOf('_MHYUUID=');" \ @@ -14,8 +15,14 @@ class BindAccount(IPluginTextBase): __bind_success = "绑定成功,请及时撤回绑定cookie\n%s" __bind_fail = "绑定失败,%s" - async def handle(self, from_id: int, plain_text: str): - logger.info("BindAccount handle from_id:%d plain_text:%s" % (from_id, plain_text)) + def init_module(self): + pass + + async def handle_event(self, event: GroupMessageEvent): + from_id = int(event.get_user_id()) + plain_text = event.get_plaintext() + plain_text = self.strip_keyword(plain_text) + if len(plain_text) == 0: return self.__bind_tip diff --git a/src/plugins/genshin/sign_reward.py b/src/plugins/genshin/sign_reward.py index 4a36f27..6e887eb 100644 --- a/src/plugins/genshin/sign_reward.py +++ b/src/plugins/genshin/sign_reward.py @@ -1,15 +1,24 @@ -from src.common_utils.interface import IPluginTextBase +from src.common_utils.interface import IPluginBase from src.common_utils.database import Database from src.common_utils.genshin_api import API from nonebot.log import logger +from nonebot.adapters.onebot.v11 import GroupMessageEvent -class SignReward(IPluginTextBase): +class SignReward(IPluginBase): __sign_success = "签到成功,%s" __sign_fail = "签到失败,%s" - async def handle(self, from_id: int, plain_text: str): - logger.info(f"SignReward handle from_id:{from_id} plain_text:{plain_text}") + def init_module(self): + pass + + async def handle_event(self, event: GroupMessageEvent): + from_id = int(event.get_user_id()) + plain_text = event.get_plaintext() + plain_text = self.strip_keyword(plain_text) + if len(plain_text) != 0: + return None + db: Database = self.bean_container.get_bean(Database) ret, cookie = db.get_value(from_id, "cookie") if ret is False: diff --git a/src/plugins/genshin_news/__init__.py b/src/plugins/genshin_news/__init__.py index 6f355bc..fcd56f0 100644 --- a/src/plugins/genshin_news/__init__.py +++ b/src/plugins/genshin_news/__init__.py @@ -1,16 +1,16 @@ from nonebot import require from nonebot import get_driver from nonebot import on_startswith -from nonebot.adapters.onebot.v11 import Event +from nonebot.adapters.onebot.v11 import GroupMessageEvent require("nonebot_plugin_apscheduler") from nonebot_plugin_apscheduler import scheduler from .config import Config from src.common_utils.database import Database -from src.common_utils.system import BeanContainer, is_plugin_enable, get_enable_group +from src.common_utils.system import BeanContainer from .fetch_news import FetchNews - require('core') +from src.plugins.core.core import GlobalCore global_config = get_driver().config config = Config.parse_obj(global_config) @@ -26,46 +26,46 @@ genshin_news_db = Database() if not genshin_news_db.init_table(table_name=plugin_name, table_key="id", table_key_type=int, table_col=data_base_col): raise Exception("init genshin_news table error") +global_core = GlobalCore() + bean_container = BeanContainer() bean_container.register(genshin_news_db) -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") module_list = [ - FetchNews("获取公告", "获取最新公告", bean_container), - FetchNews("获取活动", "获取最新活动", bean_container), - FetchNews("获取资讯", "获取最新资讯", bean_container), + FetchNews(bean_container, plugin_keyword + "获取公告", "获取最新公告"), + FetchNews(bean_container, plugin_keyword + "获取活动", "获取最新活动"), + FetchNews(bean_container, plugin_keyword + "获取资讯", "获取最新资讯"), ] -genshin_news = on_startswith(plugin_keyword, priority=1) + +async def check_enable(event: GroupMessageEvent) -> bool: + if not isinstance(event, GroupMessageEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) + +genshin_news = on_startswith(plugin_keyword, priority=1, rule=check_enable) @genshin_news.handle() -async def handle(event: Event): - enable = await is_plugin_enable(event, core_db, plugin_name) - if enable is False: - return - sender_id = int(event.get_user_id()) +async def handle(event: GroupMessageEvent): text = event.get_plaintext() - text = text.lstrip(plugin_keyword).strip() - if len(text) == 0: + if text == plugin_keyword: message = "指令格式:\n" for module in module_list: - message += f"{plugin_keyword}{module.get_keyword()}:{module.get_help()}\n" + message += f"{module.get_keyword()}:{module.get_help()}\n" message = message.rstrip("\n") await genshin_news.finish(message) for module in module_list: if module.match_keyword(text): - message = await module.handle(sender_id, module.strip_keyword(text)) + message = await module.handle_event(event) if message is not None: await genshin_news.finish(message) @scheduler.scheduled_job("interval", seconds=60*10) async def task(): - groups = await get_enable_group(core_db, plugin_name) + groups = global_core.get_enable_group(plugin_name) for module in module_list: await module.task(groups) diff --git a/src/plugins/genshin_news/fetch_news.py b/src/plugins/genshin_news/fetch_news.py index 849ab13..8b570a4 100644 --- a/src/plugins/genshin_news/fetch_news.py +++ b/src/plugins/genshin_news/fetch_news.py @@ -1,27 +1,22 @@ import nonebot -from src.common_utils.interface import IPluginTextBase +from src.common_utils.interface import IPluginBase from src.common_utils.genshin_api import API from src.common_utils.database import Database from src.common_utils.system import JsonUtil from nonebot.log import logger +from nonebot.adapters.onebot.v11 import GroupMessageEvent from nonebot.adapters.onebot.v11.message import Message, MessageSegment -class FetchNews(IPluginTextBase): +class FetchNews(IPluginBase): __fetched_news = "获取新闻成功,%s" __fetch_fail = "获取新闻失败,%s" __bbs_url = "https://bbs.mihoyo.com/ys/article/" - async def handle(self, from_id: int, plain_text: str): - logger.info("FetchNews handle from_id:%d plain_text:%s" % (from_id, plain_text)) - - if self.get_keyword() == "获取公告": - pass - elif self.get_keyword() == "获取活动": - pass - elif self.get_keyword() == "获取咨询": - pass + def init_module(self): + pass + async def handle_event(self, event: GroupMessageEvent): url_type = self.get_url_type() gs = API() success, news_list = await gs.get_news(3, url_type) @@ -122,10 +117,10 @@ async def task(self, groups: list): def get_url_type(self) -> int: key_word = self.get_keyword() - if key_word == "获取公告": + if key_word.find("获取公告") >= 0: return 1 - elif key_word == "获取活动": + elif key_word.find("获取活动") >= 0: return 2 - elif key_word == "获取资讯": + elif key_word.find("获取资讯") >= 0: return 3 return 0 diff --git a/src/plugins/member/__init__.py b/src/plugins/member/__init__.py index c692319..cb86a17 100644 --- a/src/plugins/member/__init__.py +++ b/src/plugins/member/__init__.py @@ -6,21 +6,21 @@ from nonebot.log import logger from .config import Config -from src.common_utils.database import Database -from src.common_utils.system import is_plugin_enable - - require('core') +from src.plugins.core.core import GlobalCore global_config = get_driver().config config = Config.parse_obj(global_config) plugin_name = "member" -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") +global_core = GlobalCore() + +async def check_enable(event: Event) -> bool: + if not isinstance(event, GroupDecreaseNoticeEvent) and not isinstance(event, GroupIncreaseNoticeEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) -member = on_notice(priority=10) +member = on_notice(priority=10, rule=check_enable) @member.handle() @@ -28,10 +28,6 @@ async def handle(event: Event): if not isinstance(event, GroupDecreaseNoticeEvent) and not isinstance(event, GroupIncreaseNoticeEvent): return - enable = await is_plugin_enable(event, core_db, plugin_name) - if enable is False: - return - bot = nonebot.get_bot() group_id = int(event.group_id) user_id = int(event.user_id) diff --git a/src/plugins/ping/__init__.py b/src/plugins/ping/__init__.py index 0aab4c8..e6bee20 100644 --- a/src/plugins/ping/__init__.py +++ b/src/plugins/ping/__init__.py @@ -1,45 +1,55 @@ -import nonebot from nonebot import require from nonebot import get_driver +from nonebot import on_startswith from nonebot.log import logger +from nonebot.adapters.onebot.v11 import GroupMessageEvent require("nonebot_plugin_apscheduler") from nonebot_plugin_apscheduler import scheduler from .config import Config from .ping import Ping -from src.common_utils.database import Database -from src.common_utils.system import BeanContainer, get_enable_group - - +from src.common_utils.system import BeanContainer require('core') +from src.plugins.core.core import GlobalCore global_config = get_driver().config config = Config.parse_obj(global_config) plugin_name = "ping" -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") +plugin_keyword = "ping" +if global_config.environment == "dev": + plugin_keyword = "/" + plugin_keyword +global_core = GlobalCore() + bean_container = BeanContainer() bean_container.register(config) -module_ping = Ping(bean_container) +module_list = [ + Ping(bean_container, plugin_keyword, "获取服务器状态") +] + + +async def check_enable(event: GroupMessageEvent) -> bool: + if not isinstance(event, GroupMessageEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) + +ping = on_startswith(plugin_keyword, priority=1, rule=check_enable) + + +@ping.handle() +async def handle(event: GroupMessageEvent): + text = event.get_plaintext() + for module in module_list: + if module.match_keyword(text): + message = await module.handle_event(event) + if message is not None: + await ping.finish(message) @scheduler.scheduled_job("interval", seconds=60*60) async def task(): - groups = await get_enable_group(core_db, plugin_name) - if len(groups) == 0: - return - - message = "ping" - message += await module_ping.ping_proxy() - - bot = nonebot.get_bot() - for group in groups: - try: - await bot.send_group_msg(group_id=group, message=message) - except Exception as e: - logger.error(f"send ping msg error, e:{e}") - continue + groups = global_core.get_enable_group(plugin_name) + for module in module_list: + await module.task(groups) diff --git a/src/plugins/ping/ping.py b/src/plugins/ping/ping.py index 408c297..7e2770f 100644 --- a/src/plugins/ping/ping.py +++ b/src/plugins/ping/ping.py @@ -1,17 +1,34 @@ import httpx -from src.common_utils.system import BeanContainer +import nonebot +from src.common_utils.interface import IPluginBase +from nonebot.adapters.onebot.v11 import GroupMessageEvent +from nonebot.log import logger from .config import Config -class Ping: - __bean_container: BeanContainer +class Ping(IPluginBase): __config: Config - def __init__(self, bean_container: BeanContainer): - self.__bean_container = bean_container - self.__config = bean_container.get_bean(Config) + def init_module(self): + self.__config = self.bean_container.get_bean(Config) - async def ping_proxy(self): + async def handle_event(self, event: GroupMessageEvent): + message = "ping" + message += self.__ping_proxy() + return message + + async def task(self, groups: list): + message = "ping" + message += self.__ping_proxy() + bot = nonebot.get_bot() + for group in groups: + try: + await bot.send_group_msg(group_id=group, message=message) + except Exception as e: + logger.error(f"send ping msg error, e:{e}") + continue + + def __ping_proxy(self): proxy_url = f"http://{self.__config.proxy_host}:{self.__config.proxy_port}" ping_url = "http://www.google.com" ret_msg = "\nproxy " diff --git a/src/plugins/repeat/__init__.py b/src/plugins/repeat/__init__.py index c44f98a..c4170be 100644 --- a/src/plugins/repeat/__init__.py +++ b/src/plugins/repeat/__init__.py @@ -1,18 +1,16 @@ from nonebot import require from nonebot import get_driver from nonebot import on_message -from nonebot.adapters.onebot.v11 import Event, GroupMessageEvent +from nonebot.adapters.onebot.v11 import GroupMessageEvent from .config import Config from src.common_utils.database import Database -from src.common_utils.system import BeanContainer, is_plugin_enable +from src.common_utils.system import BeanContainer from src.common_utils.aliyun import Ocr from .repeat import Repeat - - require('core') - +from src.plugins.core.core import GlobalCore data_base_col = { "cur_num": "int", @@ -26,24 +24,26 @@ if not repeat_db.init_table(table_name=plugin_name, table_key="id", table_key_type=str, table_col=data_base_col): raise Exception("init repeat table error") ocr = Ocr(config.ali_access_id, config.ali_access_key, config.ali_region_hz) +global_core = GlobalCore() + bean_container = BeanContainer() bean_container.register(repeat_db) bean_container.register(ocr) -core_db = Database() -if not core_db.connect_table("core"): - raise Exception("connect core table error") module_repeat = Repeat(bean_container) -repeat = on_message(priority=10) + +async def check_enable(event: GroupMessageEvent) -> bool: + if not isinstance(event, GroupMessageEvent): + return False + return global_core.is_plugin_enable(plugin_name, event.group_id) + +repeat = on_message(priority=10, rule=check_enable) @repeat.handle() -async def handle(event: Event): - enable = await is_plugin_enable(event, core_db, plugin_name) - if enable is False: - return - if not isinstance(event, GroupMessageEvent): - return - await module_repeat.handle(event) +async def handle(event: GroupMessageEvent): + message = await module_repeat.handle_event(event) + if message is not None: + await repeat.finish(message) diff --git a/src/plugins/repeat/repeat.py b/src/plugins/repeat/repeat.py index 3ab4eaa..093d239 100644 --- a/src/plugins/repeat/repeat.py +++ b/src/plugins/repeat/repeat.py @@ -7,7 +7,8 @@ from src.common_utils.system import BeanContainer from src.common_utils.database import Database from src.common_utils.aliyun import Ocr -from nonebot.adapters.onebot.v11 import Event, GroupMessageEvent +from src.common_utils.interface import IPluginBase +from nonebot.adapters.onebot.v11 import GroupMessageEvent from nonebot.adapters.onebot.v11.message import Message, MessageSegment from PIL import Image, ImageOps @@ -21,34 +22,43 @@ def __init__(self, last_message, count): self.count = count -class Repeat: - __bean_container: BeanContainer +class Repeat(IPluginBase): __group_map = {} - def __init__(self, bean_container: BeanContainer): - self.__bean_container = bean_container + def init_module(self): + pass - async def handle(self, event: GroupMessageEvent): - await self.__handle_message(event) - await self.__handle_image(event) + async def handle_event(self, event: GroupMessageEvent): + ret = self.__handle_image(event) + if ret is not None: + return ret + ret = self.__handle_message(event) + if ret is not None: + return ret - async def __handle_message(self, event: GroupMessageEvent): - bot = nonebot.get_bot() + return None + + async def task(self, groups: list): + pass + + def __handle_message(self, event: GroupMessageEvent): group_id = int(event.group_id) + if group_id not in self.__group_map: self.__group_map[group_id] = GroupInfo(event.message, 1) - return + return None if self.__group_map[group_id].last_message != event.message: self.__group_map[group_id].count = 1 self.__group_map[group_id].last_message = event.message - return + return None self.__group_map[group_id].count += 1 if self.__group_map[group_id].count == 3: - await bot.send_group_msg(group_id=group_id, message=event.message) + return event.message - async def __handle_image(self, event: GroupMessageEvent): + def __handle_image(self, event: GroupMessageEvent): + ret_message = None data_list = [] for seg in event.get_message(): if seg.type == "image": @@ -61,8 +71,7 @@ async def __handle_image(self, event: GroupMessageEvent): return group_id = int(event.group_id) - bot = nonebot.get_bot() - db: Database = self.__bean_container.get_bean(Database) + db: Database = self.bean_container.get_bean(Database) for data in data_list: file = data["file"] url = data["url"] @@ -93,13 +102,14 @@ async def __handle_image(self, event: GroupMessageEvent): ret, buffer = self.__flip_image(url) if ret is True and buffer is not None: message = Message(MessageSegment.image(buffer)) - await bot.send_group_msg(group_id=group_id, message=message) + ret_message = message else: db.update_value(file, "cur_num", cur_num) db.update_value(file, "last_time", int(time.time())) + return ret_message def __flip_image(self, url: str) -> (bool, io.BytesIO): - ocr: Ocr = self.__bean_container.get_bean(Ocr) + ocr: Ocr = self.bean_container.get_bean(Ocr) try: response = httpx.get(url) if response.status_code != 200: