Skip to content

Commit

Permalink
refactor(adapter)!: rewrite kook, apscheduler adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
HsiangNianian committed Feb 23, 2024
1 parent 6613510 commit a09bf3f
Show file tree
Hide file tree
Showing 35 changed files with 1,158 additions and 1,112 deletions.
7 changes: 4 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,7 @@ docs_build/_build
examples/config.json
examples/config.toml
examples/logs
examples/data/**/*
iamai/adapter/**
examples/data/*

.pdm-python
%Project%retrofor%iamai/chat_history/history.sqlite
Expand All @@ -151,4 +150,6 @@ dist/**/*
.pdm-build/**/*

# docs
_build
_build

# iamai/adapter/**/*
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
本适配器用于实现定时任务,适配器将使用 APScheduler 实现定时任务,在设定的时间产生一个事件供插件处理。
APScheduler 使用方法请参考:[APScheduler](https://apscheduler.readthedocs.io/)。
"""

import inspect
from functools import wraps
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Type, Union
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""APScheduler 适配器配置。"""

from typing import Any, Dict

from pydantic import Field
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""APScheduler 适配器事件。"""

from typing import TYPE_CHECKING, Any, Dict, Optional, Type, Union

from apscheduler.job import Job
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
- [ ] onebot 适配
- [ ] api
"""

import os
import re
import sys
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,10 +249,7 @@ async def _init_host_server(self):
) as res:
if res.status != 200:
logger.warning(
"room %d getConf失败:%d %s",
self._room_id,
res.status,
res.reason,
"room %d getConf失败:%d %s", self._room_id, res.status, res.reason
)
return False
data = await res.json()
Expand Down Expand Up @@ -339,9 +336,7 @@ async def _message_loop(self):
logger.warn(f"{self.room_id} 程序被強制取消。")
raise
except Exception:
logger.exception(
"room %d 处理消息时发生错误:", self.room_id
)
logger.exception("room %d 处理消息时发生错误:", self.room_id)

except asyncio.CancelledError:
break
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Bililive 适配器配置。"""

from typing import Any, Dict, List, Union, Literal, Optional

from iamai.config import ConfigModel
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Bililive 适配器事件。"""

import asyncio
import inspect
from enum import IntEnum
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Bililive 适配器异常。"""

from typing import Optional

from iamai.exceptions import AdapterException
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Bililive 适配器消息。"""

import json
from io import StringIO
from dataclasses import dataclass
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Console适配器。
"""

from asyncio import Condition

from iamai.event import Event
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Console 适配器配置。"""

from typing import Any, Dict

from iamai.config import ConfigModel
Expand Down
48 changes: 2 additions & 46 deletions packages/iamai-adapter-console/iamai/adapter/console/event.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Console 适配器事件。"""

import inspect
from datetime import datetime
from typing import (
Expand Down Expand Up @@ -48,8 +47,7 @@ class Robot(User, frozen=True):
class ConsoleEvent(Event["ConsoleAdapter"]):
"""Console 事件基类。"""

__event__ = ""
type = "console"
message: str

def get_event_description(self) -> str:
return str(self.dict())
Expand All @@ -65,46 +63,4 @@ def get_session_id(self) -> str:

def is_tome(self) -> bool:
"""获取事件是否与机器人有关的方法。"""
return True


class MessageEvent(ConsoleEvent):
__event__ = "message"
post_type: Literal["message"] = "message"
message: str # ConsoleMessage
type: str = "message"

def get_message(self) -> str: # ConsoleMessage:
return self.message

def is_tome(self) -> bool:
return True


# 事件类映射
_console_events = {
model.__event__: model
for model in globals().values()
if inspect.isclass(model) and issubclass(model, ConsoleEvent)
}


def get_event_class(
post_type: str, event_type: str, sub_type: Optional[str] = None
) -> Type[T_ConsoleEvent]: # type: ignore
"""根据接收到的消息类型返回对应的事件类。
Args:
post_type: 请求类型。
event_type: 事件类型。
sub_type: 子类型。
Returns:
对应的事件类。
"""
if sub_type is None:
return _console_events[".".join((post_type, event_type))] # type: ignore
return (
_console_events.get(".".join((post_type, event_type, sub_type)))
or _console_events[".".join((post_type, event_type))]
) # type: ignore
return True
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
本适配器适配了钉钉企业自建机器人协议。
协议详情请参考:[钉钉开放平台](https://open.dingtalk.com/document/robots/robot-overview)。
"""

import base64
import hashlib
import hmac
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""DingTalk 适配器配置。"""

from iamai.config import ConfigModel

__all__ = ["Config"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""DingTalk 适配器事件。"""

import time
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
from typing_extensions import Self
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""DingTalk 适配器异常。"""

from iamai.exceptions import AdapterException

__all__ = ["DingTalkException", "NetworkError", "WebhookExpiredError"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""DingTalk 适配器消息。"""

from typing import Any, Dict, List, Optional

from pydantic import model_serializer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
本适配器适配了 gensokyo obv11 协议。
协议详情请参考:[OneBot](https://github.com/howmanybots/onebot/blob/master/README.md)。
"""

import asyncio
import inspect
import json
Expand Down Expand Up @@ -102,11 +101,9 @@ async def websocket_connect(self) -> None:
logger.info("Tying to connect to WebSocket server...")
async with self.session.ws_connect(
f"ws://{self.host}:{self.port}/",
headers=(
{"Authorization": f"Bearer {self.config.access_token}"}
if self.config.access_token
else None
),
headers={"Authorization": f"Bearer {self.config.access_token}"}
if self.config.access_token
else None,
) as self.websocket:
await self.handle_websocket()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""GSK 适配器配置。"""

from typing import Literal

from iamai.config import ConfigModel
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""GSK 适配器事件。"""

# pyright: reportIncompatibleVariableOverride=false

from typing import (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""GSK 适配器异常。"""

from typing import Any, ClassVar, Dict

from iamai.exceptions import AdapterException
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""GSK 适配器消息。"""

from typing import Literal, Optional, Type, Union
from typing_extensions import Self

Expand Down
Loading

0 comments on commit a09bf3f

Please sign in to comment.