From e4672de401e4460c7dbf44af3e87924f1fb43c95 Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 7 Nov 2023 16:37:44 +0800 Subject: [PATCH 1/8] feature: move OneBot adapters --- README.md | 2 +- amiyabot/adapters/comwechat/__init__.py | 2 +- amiyabot/adapters/comwechat/builder.py | 2 +- amiyabot/adapters/comwechat/package.py | 2 +- amiyabot/adapters/cqhttp/__init__.py | 2 +- amiyabot/adapters/cqhttp/api.py | 2 +- amiyabot/adapters/cqhttp/forwardMessage.py | 2 +- amiyabot/adapters/{onebot11 => onebot/v11}/__init__.py | 0 amiyabot/adapters/{onebot11 => onebot/v11}/api.py | 0 amiyabot/adapters/{onebot11 => onebot/v11}/builder.py | 0 amiyabot/adapters/{onebot11 => onebot/v11}/package.py | 2 +- amiyabot/adapters/{onebot12 => onebot/v12}/__init__.py | 0 amiyabot/adapters/{onebot12 => onebot/v12}/api.py | 0 amiyabot/adapters/{onebot12 => onebot/v12}/builder.py | 0 amiyabot/adapters/{onebot12 => onebot/v12}/package.py | 2 +- 15 files changed, 9 insertions(+), 9 deletions(-) rename amiyabot/adapters/{onebot11 => onebot/v11}/__init__.py (100%) rename amiyabot/adapters/{onebot11 => onebot/v11}/api.py (100%) rename amiyabot/adapters/{onebot11 => onebot/v11}/builder.py (100%) rename amiyabot/adapters/{onebot11 => onebot/v11}/package.py (98%) rename amiyabot/adapters/{onebot12 => onebot/v12}/__init__.py (100%) rename amiyabot/adapters/{onebot12 => onebot/v12}/api.py (100%) rename amiyabot/adapters/{onebot12 => onebot/v12}/builder.py (100%) rename amiyabot/adapters/{onebot12 => onebot/v12}/package.py (98%) diff --git a/README.md b/README.md index 8f6de93..6142ed3 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ asyncio.run(bots.start()) import asyncio from amiyabot import AmiyaBot, Message, Chain -from amiyabot.adapters.onebot11 import onebot11 +from amiyabot.adapters.onebot.v11 import onebot11 bot = AmiyaBot( appid='******', diff --git a/amiyabot/adapters/comwechat/__init__.py b/amiyabot/adapters/comwechat/__init__.py index e72d190..a66e152 100644 --- a/amiyabot/adapters/comwechat/__init__.py +++ b/amiyabot/adapters/comwechat/__init__.py @@ -1,7 +1,7 @@ import asyncio from amiyabot.adapters import HANDLER_TYPE -from amiyabot.adapters.onebot12 import OneBot12Instance +from amiyabot.adapters.onebot.v12 import OneBot12Instance from amiyabot.builtin.messageChain import Chain from .package import package_com_wechat_message diff --git a/amiyabot/adapters/comwechat/builder.py b/amiyabot/adapters/comwechat/builder.py index 76be129..0ac9bd9 100644 --- a/amiyabot/adapters/comwechat/builder.py +++ b/amiyabot/adapters/comwechat/builder.py @@ -1,6 +1,6 @@ from amiyabot.adapters import MessageCallback from amiyabot.adapters.apiProtocol import BotInstanceAPIProtocol -from amiyabot.adapters.onebot12.builder import build_message_send as build_ob12 +from amiyabot.adapters.onebot.v12 import build_message_send as build_ob12 from amiyabot.builtin.message import Message from amiyabot.builtin.messageChain import Chain from amiyabot.builtin.messageChain.element import * diff --git a/amiyabot/adapters/comwechat/package.py b/amiyabot/adapters/comwechat/package.py index bd623c8..651e14f 100644 --- a/amiyabot/adapters/comwechat/package.py +++ b/amiyabot/adapters/comwechat/package.py @@ -1,5 +1,5 @@ from amiyabot.adapters import BotAdapterProtocol -from amiyabot.adapters.onebot12.package import package_onebot12_message +from amiyabot.adapters.onebot.v12 import package_onebot12_message async def package_com_wechat_message(instance: BotAdapterProtocol, data: dict): diff --git a/amiyabot/adapters/cqhttp/__init__.py b/amiyabot/adapters/cqhttp/__init__.py index 64da9f0..2955c06 100644 --- a/amiyabot/adapters/cqhttp/__init__.py +++ b/amiyabot/adapters/cqhttp/__init__.py @@ -1,4 +1,4 @@ -from amiyabot.adapters.onebot11 import OneBot11Instance +from amiyabot.adapters.onebot.v11 import OneBot11Instance from .api import CQHttpAPI from .forwardMessage import CQHTTPForwardMessage diff --git a/amiyabot/adapters/cqhttp/api.py b/amiyabot/adapters/cqhttp/api.py index 478e285..655d00a 100644 --- a/amiyabot/adapters/cqhttp/api.py +++ b/amiyabot/adapters/cqhttp/api.py @@ -1,6 +1,6 @@ from typing import Optional -from amiyabot.adapters.onebot11.api import OneBot11API +from amiyabot.adapters.onebot.v11.api import OneBot11API from amiyabot.adapters.mirai.api import MiraiAPI diff --git a/amiyabot/adapters/cqhttp/forwardMessage.py b/amiyabot/adapters/cqhttp/forwardMessage.py index 3e7c03b..7d9673f 100644 --- a/amiyabot/adapters/cqhttp/forwardMessage.py +++ b/amiyabot/adapters/cqhttp/forwardMessage.py @@ -3,7 +3,7 @@ from typing import Union, Optional from amiyabot.builtin.message import Message from amiyabot.builtin.messageChain import Chain -from amiyabot.adapters.onebot11.builder import build_message_send, OneBot11MessageCallback +from amiyabot.adapters.onebot.v11.builder import build_message_send, OneBot11MessageCallback from .api import CQHttpAPI diff --git a/amiyabot/adapters/onebot11/__init__.py b/amiyabot/adapters/onebot/v11/__init__.py similarity index 100% rename from amiyabot/adapters/onebot11/__init__.py rename to amiyabot/adapters/onebot/v11/__init__.py diff --git a/amiyabot/adapters/onebot11/api.py b/amiyabot/adapters/onebot/v11/api.py similarity index 100% rename from amiyabot/adapters/onebot11/api.py rename to amiyabot/adapters/onebot/v11/api.py diff --git a/amiyabot/adapters/onebot11/builder.py b/amiyabot/adapters/onebot/v11/builder.py similarity index 100% rename from amiyabot/adapters/onebot11/builder.py rename to amiyabot/adapters/onebot/v11/builder.py diff --git a/amiyabot/adapters/onebot11/package.py b/amiyabot/adapters/onebot/v11/package.py similarity index 98% rename from amiyabot/adapters/onebot11/package.py rename to amiyabot/adapters/onebot/v11/package.py index 6986a9c..890da62 100644 --- a/amiyabot/adapters/onebot11/package.py +++ b/amiyabot/adapters/onebot/v11/package.py @@ -1,7 +1,7 @@ from amiyabot.builtin.message import Event, EventList, Message from amiyabot.adapters import BotAdapterProtocol -from ..common import text_convert +from amiyabot.adapters.common import text_convert async def package_onebot11_message(instance: BotAdapterProtocol, account: str, data: dict): diff --git a/amiyabot/adapters/onebot12/__init__.py b/amiyabot/adapters/onebot/v12/__init__.py similarity index 100% rename from amiyabot/adapters/onebot12/__init__.py rename to amiyabot/adapters/onebot/v12/__init__.py diff --git a/amiyabot/adapters/onebot12/api.py b/amiyabot/adapters/onebot/v12/api.py similarity index 100% rename from amiyabot/adapters/onebot12/api.py rename to amiyabot/adapters/onebot/v12/api.py diff --git a/amiyabot/adapters/onebot12/builder.py b/amiyabot/adapters/onebot/v12/builder.py similarity index 100% rename from amiyabot/adapters/onebot12/builder.py rename to amiyabot/adapters/onebot/v12/builder.py diff --git a/amiyabot/adapters/onebot12/package.py b/amiyabot/adapters/onebot/v12/package.py similarity index 98% rename from amiyabot/adapters/onebot12/package.py rename to amiyabot/adapters/onebot/v12/package.py index 663518b..da9df6a 100644 --- a/amiyabot/adapters/onebot12/package.py +++ b/amiyabot/adapters/onebot/v12/package.py @@ -1,7 +1,7 @@ from amiyabot.builtin.message import Event, EventList, Message from amiyabot.adapters import BotAdapterProtocol -from ..common import text_convert +from amiyabot.adapters.common import text_convert from .api import OneBot12API From dd1821f9867622e874909ce79fe7e3e21656edc4 Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 7 Nov 2023 16:51:14 +0800 Subject: [PATCH 2/8] feature: move QQ adapters --- amiyabot/__init__.py | 7 +++++-- amiyabot/adapters/tencent/{ => qqGuild}/__init__.py | 10 +++++----- amiyabot/adapters/tencent/{ => qqGuild}/api.py | 2 +- amiyabot/adapters/tencent/{ => qqGuild}/builder.py | 4 ++-- amiyabot/adapters/tencent/{ => qqGuild}/intents.py | 0 amiyabot/adapters/tencent/{ => qqGuild}/model.py | 0 amiyabot/adapters/tencent/{ => qqGuild}/package.py | 6 +++--- amiyabot/builtin/lib/timedTask/__init__.py | 12 ++++++++++-- 8 files changed, 26 insertions(+), 15 deletions(-) rename amiyabot/adapters/tencent/{ => qqGuild}/__init__.py (97%) rename amiyabot/adapters/tencent/{ => qqGuild}/api.py (99%) rename amiyabot/adapters/tencent/{ => qqGuild}/builder.py (97%) rename amiyabot/adapters/tencent/{ => qqGuild}/intents.py (100%) rename amiyabot/adapters/tencent/{ => qqGuild}/model.py (100%) rename amiyabot/adapters/tencent/{ => qqGuild}/package.py (96%) diff --git a/amiyabot/__init__.py b/amiyabot/__init__.py index 8d99e42..806eb9d 100644 --- a/amiyabot/__init__.py +++ b/amiyabot/__init__.py @@ -11,7 +11,10 @@ from amiyabot.adapters.kook import KOOKBotInstance from amiyabot.adapters.mirai import MiraiBotInstance from amiyabot.adapters.cqhttp import CQHttpBotInstance -from amiyabot.adapters.tencent import TencentBotInstance +from amiyabot.adapters.onebot.v11 import OneBot11Instance +from amiyabot.adapters.onebot.v12 import OneBot12Instance +from amiyabot.adapters.tencent.qqGuild import QQGuildBotInstance, QQGuildSandboxBotInstance +from amiyabot.adapters.comwechat import ComWeChatBotInstance from amiyabot.adapters.common import CQCode # network @@ -51,7 +54,7 @@ def __init__( appid: Optional[str] = None, token: Optional[str] = None, private: bool = False, - adapter: typing.Type[BotAdapterProtocol] = TencentBotInstance, + adapter: typing.Type[BotAdapterProtocol] = QQGuildBotInstance, ): if not appid: appid = random_code(10) diff --git a/amiyabot/adapters/tencent/__init__.py b/amiyabot/adapters/tencent/qqGuild/__init__.py similarity index 97% rename from amiyabot/adapters/tencent/__init__.py rename to amiyabot/adapters/tencent/qqGuild/__init__.py index 59e4b2c..b997411 100644 --- a/amiyabot/adapters/tencent/__init__.py +++ b/amiyabot/adapters/tencent/qqGuild/__init__.py @@ -10,7 +10,7 @@ from amiyabot.builtin.messageChain import Chain from amiyabot.adapters import BotAdapterProtocol, HANDLER_TYPE -from .api import TencentAPI +from .api import QQGuildAPI from .model import GateWay, Payload, ShardsRecord, ConnectionHandler from .intents import Intents from .package import package_tencent_message @@ -19,7 +19,7 @@ log = LoggerManager('Tencent') -class TencentBotInstance(BotAdapterProtocol): +class QQGuildBotInstance(BotAdapterProtocol): def __init__(self, appid: str, token: str): super().__init__(appid, token) @@ -33,7 +33,7 @@ def __str__(self): @property def api(self): - return TencentAPI(self.appid, self.token) + return QQGuildAPI(self.appid, self.token) def __create_heartbeat(self, websocket, interval: int, record: ShardsRecord): heartbeat_key = random_code(10) @@ -229,7 +229,7 @@ async def recall_message(self, message_id: str, data: Optional[Message] = None): await self.api.delete_message(message_id, data.guild_id if data.is_direct else data.channel_id, data.is_direct) -class TencentSandboxBotInstance(TencentBotInstance): +class QQGuildSandboxBotInstance(QQGuildBotInstance): @property def api(self): - return TencentAPI(self.appid, self.token, True) + return QQGuildAPI(self.appid, self.token, True) diff --git a/amiyabot/adapters/tencent/api.py b/amiyabot/adapters/tencent/qqGuild/api.py similarity index 99% rename from amiyabot/adapters/tencent/api.py rename to amiyabot/adapters/tencent/qqGuild/api.py index d89f1ce..fe1147a 100644 --- a/amiyabot/adapters/tencent/api.py +++ b/amiyabot/adapters/tencent/qqGuild/api.py @@ -19,7 +19,7 @@ class MessageSendRequest: upload_image: bool = False -class TencentAPI(BotInstanceAPIProtocol): +class QQGuildAPI(BotInstanceAPIProtocol): def __init__(self, appid: str, token: str, sandbox: bool = False, post_message_max_retry_times: int = 3): self.appid = appid self.token = token diff --git a/amiyabot/adapters/tencent/builder.py b/amiyabot/adapters/tencent/qqGuild/builder.py similarity index 97% rename from amiyabot/adapters/tencent/builder.py rename to amiyabot/adapters/tencent/qqGuild/builder.py index c504fe0..0a0b543 100644 --- a/amiyabot/adapters/tencent/builder.py +++ b/amiyabot/adapters/tencent/qqGuild/builder.py @@ -2,7 +2,7 @@ from amiyabot.builtin.messageChain import Chain from amiyabot.builtin.messageChain.element import * -from .api import TencentAPI, MessageSendRequest +from .api import QQGuildAPI, MessageSendRequest from .package import package_tencent_message @@ -18,7 +18,7 @@ async def get_message(self): if not self.response: return None - api: TencentAPI = self.instance.api + api: QQGuildAPI = self.instance.api response = self.response.json message = await api.get_message(response['channel_id'], response['id']) diff --git a/amiyabot/adapters/tencent/intents.py b/amiyabot/adapters/tencent/qqGuild/intents.py similarity index 100% rename from amiyabot/adapters/tencent/intents.py rename to amiyabot/adapters/tencent/qqGuild/intents.py diff --git a/amiyabot/adapters/tencent/model.py b/amiyabot/adapters/tencent/qqGuild/model.py similarity index 100% rename from amiyabot/adapters/tencent/model.py rename to amiyabot/adapters/tencent/qqGuild/model.py diff --git a/amiyabot/adapters/tencent/package.py b/amiyabot/adapters/tencent/qqGuild/package.py similarity index 96% rename from amiyabot/adapters/tencent/package.py rename to amiyabot/adapters/tencent/qqGuild/package.py index f273071..4ede703 100644 --- a/amiyabot/adapters/tencent/package.py +++ b/amiyabot/adapters/tencent/qqGuild/package.py @@ -3,8 +3,8 @@ from amiyabot.builtin.message import Event, Message from amiyabot.adapters import BotAdapterProtocol -from .api import TencentAPI -from ..common import text_convert +from .api import QQGuildAPI +from amiyabot.adapters.common import text_convert ADMIN = ['2', '4', '5'] @@ -22,7 +22,7 @@ async def package_tencent_message(instance: BotAdapterProtocol, event: str, mess data = get_info(Message(instance, message), message) data.is_direct = 'direct_message' in message and message['direct_message'] - api: TencentAPI = instance.api + api: QQGuildAPI = instance.api bot = await api.get_me() if not data.is_direct: diff --git a/amiyabot/builtin/lib/timedTask/__init__.py b/amiyabot/builtin/lib/timedTask/__init__.py index ce99220..0b8005c 100644 --- a/amiyabot/builtin/lib/timedTask/__init__.py +++ b/amiyabot/builtin/lib/timedTask/__init__.py @@ -31,10 +31,18 @@ def add_timed_task(cls, task: Task): if task.each is not None: scheduler.add_job( - task.func, id=f'{task.tag}.{task.sub_tag}', trigger='interval', seconds=task.each, **task.kwargs + task.func, + id=f'{task.tag}.{task.sub_tag}', + trigger='interval', + seconds=task.each, + **task.kwargs, ) else: - scheduler.add_job(task.func, id=f'{task.tag}.{task.sub_tag}', **task.kwargs) + scheduler.add_job( + task.func, + id=f'{task.tag}.{task.sub_tag}', + **task.kwargs, + ) @classmethod def remove_task(cls, tag: str, sub_tag: Optional[str] = None): From 3b1405a8e697ade7c808643a053cef98c18b8ced Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 7 Nov 2023 18:37:58 +0800 Subject: [PATCH 3/8] =?UTF-8?q?feature:=20=E6=B5=8B=E8=AF=95=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=E6=94=AF=E6=8C=81=E5=8F=91=E9=80=81=E8=AF=AD=E9=9F=B3?= =?UTF-8?q?=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- amiyabot/__init__.py | 7 +--- amiyabot/adapters/test/__init__.py | 6 +-- amiyabot/adapters/test/builder.py | 43 ++++++++++++++++++--- amiyabot/adapters/test/{ws.py => server.py} | 28 +++++++------- 4 files changed, 56 insertions(+), 28 deletions(-) rename amiyabot/adapters/test/{ws.py => server.py} (73%) diff --git a/amiyabot/__init__.py b/amiyabot/__init__.py index 806eb9d..548dd49 100644 --- a/amiyabot/__init__.py +++ b/amiyabot/__init__.py @@ -30,12 +30,10 @@ # lib from amiyabot.builtin.lib.eventBus import event_bus from amiyabot.builtin.lib.timedTask import TasksControl -from amiyabot.builtin.lib.browserService import ( - BrowserLaunchConfig, - basic_browser_service, -) +from amiyabot.builtin.lib.browserService import BrowserLaunchConfig, basic_browser_service # message +from amiyabot.builtin.messageChain import Chain, ChainBuilder from amiyabot.builtin.message import ( Event, EventList, @@ -45,7 +43,6 @@ WaitEventOutOfFocus, Equal, ) -from amiyabot.builtin.messageChain import Chain, ChainBuilder class AmiyaBot(BotInstance): diff --git a/amiyabot/adapters/test/__init__.py b/amiyabot/adapters/test/__init__.py index 845d6f8..2444b60 100644 --- a/amiyabot/adapters/test/__init__.py +++ b/amiyabot/adapters/test/__init__.py @@ -6,12 +6,12 @@ from amiyabot.log import LoggerManager from .builder import build_message_send -from .ws import TestServer +from .server import TestServer log = LoggerManager('Test') -def test_instance(host: str, port: int): +def test_instance(host: str = '127.0.0.1', port: int = 32001): def adapter(appid: str, _): return TestInstance(appid, host, port) @@ -33,7 +33,7 @@ def __init__(self, appid: str, host: str, port: int): self.host = host self.port = port - self.server = TestServer(appid, host, port) + self.server = TestServer(self, appid, host, port) @self.server.app.on_event('startup') async def startup(): diff --git a/amiyabot/adapters/test/builder.py b/amiyabot/adapters/test/builder.py index b0c68dc..32c2a5c 100644 --- a/amiyabot/adapters/test/builder.py +++ b/amiyabot/adapters/test/builder.py @@ -1,8 +1,8 @@ +import os import base64 from amiyabot.builtin.messageChain import Chain from amiyabot.builtin.messageChain.element import * -from amiyabot import log async def build_message_send(chain: Chain, custom_chain: Optional[CHAIN_LIST] = None): @@ -10,6 +10,8 @@ async def build_message_send(chain: Chain, custom_chain: Optional[CHAIN_LIST] = chain_data = [] voice_list = [] + event_id = chain.data.message_id + if chain_list: for item in chain_list: # At @@ -22,7 +24,7 @@ async def build_message_send(chain: Chain, custom_chain: Optional[CHAIN_LIST] = # Face if isinstance(item, Face): - chain_data.append({'type': 'text', 'data': f'[{item.face_id}]'}) + chain_data.append({'type': 'face', 'data': item.face_id}) # Text if isinstance(item, Text): @@ -35,7 +37,20 @@ async def build_message_send(chain: Chain, custom_chain: Optional[CHAIN_LIST] = # Voice if isinstance(item, Voice): - voice_list.append(send_msg([{'type': 'text', 'data': '[voice]'}])) + d, t = await append_voice(item.file) + voice_list.append( + send_msg( + event_id, + [ + { + 'type': 'voice', + 'data': d, + 'file': os.path.basename(item.file), + 'audio_type': f'audio/{t}', + } + ], + ) + ) # Html if isinstance(item, Html): @@ -43,7 +58,7 @@ async def build_message_send(chain: Chain, custom_chain: Optional[CHAIN_LIST] = if result: chain_data.append({'type': 'image', 'data': await append_image(result)}) - return send_msg(chain_data), voice_list + return send_msg(event_id, chain_data), voice_list async def append_image(img: Union[bytes, str]): @@ -52,5 +67,21 @@ async def append_image(img: Union[bytes, str]): return img -def send_msg(chain_data: list): - return json.dumps({'event': 'message', 'event_data': chain_data}, ensure_ascii=False) +async def append_voice(file: str): + _type = os.path.splitext(file)[-1].strip('.') + + with open(file, mode='rb') as vf: + data = vf.read() + + return f'data:audio/{_type};base64,{base64.b64encode(data).decode()}', _type + + +def send_msg(event_id: str, chain_data: list): + return json.dumps( + { + 'event': 'message', + 'event_id': event_id, + 'event_data': chain_data, + }, + ensure_ascii=False, + ) diff --git a/amiyabot/adapters/test/ws.py b/amiyabot/adapters/test/server.py similarity index 73% rename from amiyabot/adapters/test/ws.py rename to amiyabot/adapters/test/server.py index 8a55f42..0c15bc4 100644 --- a/amiyabot/adapters/test/ws.py +++ b/amiyabot/adapters/test/server.py @@ -1,13 +1,13 @@ import json import asyncio -from typing import Callable, List +from typing import Optional, List from dataclasses import dataclass from fastapi import WebSocket, WebSocketDisconnect +from amiyabot.adapters import BotAdapterProtocol, HANDLER_TYPE from amiyabot.network.httpServer import HttpServer -from amiyabot import log - from amiyabot.builtin.message import Message, Event +from amiyabot import log from ..common import text_convert @@ -19,11 +19,12 @@ class ReceivedMessage: class TestServer(HttpServer): - def __init__(self, appid: str, host: str, port: int): + def __init__(self, instance: BotAdapterProtocol, appid: str, host: str, port: int): super().__init__(host, port) self.appid = appid - self.handler = None + self.instance = instance + self.handler: Optional[HANDLER_TYPE] = None self.clients: List[WebSocket] = [] self.__create_websocket_api() @@ -48,7 +49,7 @@ async def websocket_endpoint(websocket: WebSocket): self.clients.remove(websocket) - async def run(self, handler: Callable): + async def run(self, handler: HANDLER_TYPE): self.handler = handler await self.serve() @@ -60,19 +61,18 @@ async def send(self, data: str): async def __handle_message(self, data: ReceivedMessage): async with log.catch(ignore=[json.JSONDecodeError]): content = json.loads(data.data) - asyncio.create_task( - self.handler( - self.package_message(content['event'], content['event_data']), - ), - ) + message = await self.package_message(content['event'], content['event_id'], content['event_data']) + + asyncio.create_task(self.handler(message)) - async def package_message(self, event: str, message: dict): + async def package_message(self, event: str, event_id: str, message: dict): if event != 'message': - return Event(self, event, message) + return Event(self.instance, event, message) text = message['message'] - msg = Message(self, message) + msg = Message(self.instance, message) + msg.message_id = event_id msg.user_id = message['user_id'] msg.channel_id = message['channel_id'] msg.message_type = message['message_type'] From d51aba1cbe5f8577ee5cb9bff12b2c772dd120d7 Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Wed, 8 Nov 2023 11:32:05 +0800 Subject: [PATCH 4/8] =?UTF-8?q?feature:=20=E6=B5=8B=E8=AF=95=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=E6=94=AF=E6=8C=81=E6=8E=A5=E6=94=B6=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + amiyabot/adapters/test/server.py | 38 +++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index e189163..3666315 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ /dist/ /venv/ /log/ +/testTemp/ /*.egg-info/ .DS_Store diff --git a/amiyabot/adapters/test/server.py b/amiyabot/adapters/test/server.py index 0c15bc4..46b1fa2 100644 --- a/amiyabot/adapters/test/server.py +++ b/amiyabot/adapters/test/server.py @@ -1,4 +1,6 @@ import json +import base64 +import shutil import asyncio from typing import Optional, List @@ -7,6 +9,7 @@ from amiyabot.adapters import BotAdapterProtocol, HANDLER_TYPE from amiyabot.network.httpServer import HttpServer from amiyabot.builtin.message import Message, Event +from amiyabot.util import random_code, create_dir from amiyabot import log from ..common import text_convert @@ -22,14 +25,20 @@ class TestServer(HttpServer): def __init__(self, instance: BotAdapterProtocol, appid: str, host: str, port: int): super().__init__(host, port) + create_dir('testTemp') + self.add_static_folder('/testTemp', 'testTemp') + + self.host = host + self.port = port self.appid = appid self.instance = instance self.handler: Optional[HANDLER_TYPE] = None self.clients: List[WebSocket] = [] - self.__create_websocket_api() + @self.app.on_event('shutdown') + def clean_temp(): + shutil.rmtree('testTemp') - def __create_websocket_api(self): @self.app.websocket(f'/{self.appid}') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() @@ -39,7 +48,12 @@ async def websocket_endpoint(websocket: WebSocket): while True: try: asyncio.create_task( - self.__handle_message(ReceivedMessage(await websocket.receive_text(), websocket)) + self.handle_message( + ReceivedMessage( + await websocket.receive_text(), + websocket, + ) + ) ) except WebSocketDisconnect: break @@ -58,7 +72,7 @@ async def send(self, data: str): for item in self.clients: await item.send_text(data) - async def __handle_message(self, data: ReceivedMessage): + async def handle_message(self, data: ReceivedMessage): async with log.catch(ignore=[json.JSONDecodeError]): content = json.loads(data.data) message = await self.package_message(content['event'], content['event_id'], content['event_data']) @@ -69,7 +83,6 @@ async def package_message(self, event: str, event_id: str, message: dict): if event != 'message': return Event(self.instance, event, message) - text = message['message'] msg = Message(self.instance, message) msg.message_id = event_id @@ -78,5 +91,20 @@ async def package_message(self, event: str, event_id: str, message: dict): msg.message_type = message['message_type'] msg.nickname = message['nickname'] msg.is_admin = message['is_admin'] + msg.image = [self.base64_to_temp_url(item) for item in message['images']] + + text = message.get('message', '') return text_convert(msg, text, text) + + def base64_to_temp_url(self, base64_string: str): + data = base64_string.split('base64,')[-1] + decoded_data = base64.b64decode(data) + + temp_file_path = f'testTemp/images/{random_code(20)}.png' + create_dir(temp_file_path, is_file=True) + + with open(temp_file_path, 'wb') as temp_file: + temp_file.write(decoded_data) + + return f'http://%s:{self.port}/{temp_file_path}' % ('localhost' if self.host == '0.0.0.0' else self.host) From 4c8f7a4d36f2ac8745d3edc044ebaa7175cc7901 Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 14 Nov 2023 10:18:29 +0800 Subject: [PATCH 5/8] =?UTF-8?q?update:=20=E4=BC=98=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- amiyabot/builtin/lib/browserService.py | 10 ++++++++-- amiyabot/builtin/messageChain/element.py | 11 ++--------- amiyabot/log/manager.py | 2 +- amiyabot/util.py | 1 + 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/amiyabot/builtin/lib/browserService.py b/amiyabot/builtin/lib/browserService.py index f81b6b5..95323b0 100644 --- a/amiyabot/builtin/lib/browserService.py +++ b/amiyabot/builtin/lib/browserService.py @@ -17,16 +17,22 @@ log = LoggerManager('Browser') +DEFAULT_WIDTH = argv('browser-width', int) or 1280 +DEFAULT_HEIGHT = argv('browser-height', int) or 720 +DEFAULT_RENDER_TIME = argv('browser-render-time', int) or 200 +BROWSER_PAGE_NOT_CLOSE = argv('browser-page-not-close', bool) +BROWSER_LAUNCH_WITH_HEADED = argv('browser-launch-with-headed', bool) + class BrowserLaunchConfig: def __init__(self): self.browser_type: str = 'chromium' - self.debug: bool = bool(argv('debug')) + self.debug: bool = argv('debug', bool) async def launch_browser(self, playwright: Playwright) -> Union[Browser, BrowserContext]: browser: BrowserType = getattr(playwright, self.browser_type) - return await browser.launch(headless=not self.debug) + return await browser.launch(headless=not BROWSER_LAUNCH_WITH_HEADED) async def new_page(self, browser: Union[Browser, BrowserContext], viewport_size: ViewportSize) -> Page: return await browser.new_page(no_viewport=True, viewport=viewport_size) diff --git a/amiyabot/builtin/messageChain/element.py b/amiyabot/builtin/messageChain/element.py index 426d791..7eacfea 100644 --- a/amiyabot/builtin/messageChain/element.py +++ b/amiyabot/builtin/messageChain/element.py @@ -2,18 +2,11 @@ import asyncio from dataclasses import dataclass -from typing import Optional, Union, List, Any -from playwright.async_api import Page -from amiyabot.builtin.lib.browserService import basic_browser_service +from typing import List, Any +from amiyabot.builtin.lib.browserService import * from amiyabot.adapters.common import CQCode -from amiyabot.util import argv from amiyabot import log -DEFAULT_WIDTH = argv('browser-width', int) or 1280 -DEFAULT_HEIGHT = argv('browser-height', int) or 720 -DEFAULT_RENDER_TIME = argv('browser-render-time', int) or 200 -BROWSER_PAGE_NOT_CLOSE = bool(argv('browser-page-not-close')) - class ChainBuilder: @classmethod diff --git a/amiyabot/log/manager.py b/amiyabot/log/manager.py index 3f5179a..4fad396 100644 --- a/amiyabot/log/manager.py +++ b/amiyabot/log/manager.py @@ -25,7 +25,7 @@ def __init__( self.handlers: Dict[str, logging.Logger] = {} self.name = name - self._debug = argv('debug') + self._debug = argv('debug', bool) self.level = level or (logging.DEBUG if self._debug else logging.INFO) self.formatter = formatter self.save_path = save_path diff --git a/amiyabot/util.py b/amiyabot/util.py index c11b8c8..a0a08a8 100644 --- a/amiyabot/util.py +++ b/amiyabot/util.py @@ -82,6 +82,7 @@ def argv(name: str, formatter: Callable = str): return True return formatter(sys.argv[index]) + return formatter() def create_dir(path: str, is_file: bool = False): From 5f3907eb7e2e24ec1042f0ade9217d60006ddf14 Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 14 Nov 2023 10:19:00 +0800 Subject: [PATCH 6/8] =?UTF-8?q?update:=20=E6=B7=BB=E5=8A=A0=E5=85=BC?= =?UTF-8?q?=E5=AE=B9=E5=B9=B6=E5=A3=B0=E6=98=8E=E6=9C=AA=E6=9D=A5=E7=A7=BB?= =?UTF-8?q?=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- amiyabot/adapters/tencent/__init__.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 amiyabot/adapters/tencent/__init__.py diff --git a/amiyabot/adapters/tencent/__init__.py b/amiyabot/adapters/tencent/__init__.py new file mode 100644 index 0000000..cc2c32e --- /dev/null +++ b/amiyabot/adapters/tencent/__init__.py @@ -0,0 +1,21 @@ +from .qqGuild import QQGuildBotInstance, QQGuildSandboxBotInstance + + +notice = ( + '\nWarning: "{name}" is deprecated and will be removed in future versions. ' + 'Please using "from amiyabot.adapters.tencent.qqGuild import {new_name}"\n' +) + + +class TencentBotInstance(QQGuildBotInstance): + def __init__(self, appid: str, token: str): + super().__init__(appid, token) + + print(notice.format(name=self.__class__.__name__, new_name=QQGuildBotInstance.__name__)) + + +class TencentSandboxBotInstance(QQGuildSandboxBotInstance): + def __init__(self, appid: str, token: str): + super().__init__(appid, token) + + print(notice.format(name=self.__class__.__name__, new_name=QQGuildSandboxBotInstance.__name__)) From cbc937e80e695be03573c3ab216ca246c200aa3e Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 14 Nov 2023 10:29:00 +0800 Subject: [PATCH 7/8] =?UTF-8?q?update:=20=E6=B7=BB=E5=8A=A0=E5=85=BC?= =?UTF-8?q?=E5=AE=B9=E5=B9=B6=E5=A3=B0=E6=98=8E=E6=9C=AA=E6=9D=A5=E7=A7=BB?= =?UTF-8?q?=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- amiyabot/adapters/tencent/__init__.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/amiyabot/adapters/tencent/__init__.py b/amiyabot/adapters/tencent/__init__.py index cc2c32e..1b97026 100644 --- a/amiyabot/adapters/tencent/__init__.py +++ b/amiyabot/adapters/tencent/__init__.py @@ -1,21 +1,21 @@ from .qqGuild import QQGuildBotInstance, QQGuildSandboxBotInstance -notice = ( - '\nWarning: "{name}" is deprecated and will be removed in future versions. ' - 'Please using "from amiyabot.adapters.tencent.qqGuild import {new_name}"\n' -) - - class TencentBotInstance(QQGuildBotInstance): def __init__(self, appid: str, token: str): super().__init__(appid, token) - print(notice.format(name=self.__class__.__name__, new_name=QQGuildBotInstance.__name__)) - class TencentSandboxBotInstance(QQGuildSandboxBotInstance): def __init__(self, appid: str, token: str): super().__init__(appid, token) - print(notice.format(name=self.__class__.__name__, new_name=QQGuildSandboxBotInstance.__name__)) + +notice = ( + '"{name}" is deprecated and will be removed in future versions. ' + 'Please using "from amiyabot.adapters.tencent.qqGuild import {new_name}"' +) +print('\n==== Warning ===============================================') +print(notice.format(name=TencentBotInstance.__name__, new_name=QQGuildBotInstance.__name__)) +print(notice.format(name=TencentSandboxBotInstance.__name__, new_name=QQGuildSandboxBotInstance.__name__)) +print('============================================================\n') From 504c47ddfbf97775181b31671ce42b580c0f7963 Mon Sep 17 00:00:00 2001 From: Vivien <34387011+vivien8261@users.noreply.github.com> Date: Tue, 14 Nov 2023 10:32:06 +0800 Subject: [PATCH 8/8] fix: pylint --- amiyabot/adapters/tencent/__init__.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/amiyabot/adapters/tencent/__init__.py b/amiyabot/adapters/tencent/__init__.py index 1b97026..7a90c72 100644 --- a/amiyabot/adapters/tencent/__init__.py +++ b/amiyabot/adapters/tencent/__init__.py @@ -2,13 +2,11 @@ class TencentBotInstance(QQGuildBotInstance): - def __init__(self, appid: str, token: str): - super().__init__(appid, token) + ... class TencentSandboxBotInstance(QQGuildSandboxBotInstance): - def __init__(self, appid: str, token: str): - super().__init__(appid, token) + ... notice = (