Skip to content

Commit

Permalink
refactor:插件基础架构重构
Browse files Browse the repository at this point in the history
  • Loading branch information
zmdyy0318 committed Aug 18, 2022
1 parent 55bf4ab commit 477aeb1
Show file tree
Hide file tree
Showing 19 changed files with 369 additions and 309 deletions.
18 changes: 9 additions & 9 deletions src/common_utils/genshin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,28 +174,28 @@ 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

@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/",
Expand All @@ -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
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down
12 changes: 9 additions & 3 deletions src/common_utils/interface.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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
Expand Down
52 changes: 0 additions & 52 deletions src/common_utils/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
41 changes: 17 additions & 24 deletions src/plugins/adult/__init__.py
Original file line number Diff line number Diff line change
@@ -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)

38 changes: 25 additions & 13 deletions src/plugins/adult/image.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,44 @@
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
# 10kb以下的图片不计算
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):
Expand Down
57 changes: 16 additions & 41 deletions src/plugins/chat/__init__.py
Original file line number Diff line number Diff line change
@@ -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)


Loading

0 comments on commit 477aeb1

Please sign in to comment.