euler-onebot 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
euleronebot/config.py ADDED
@@ -0,0 +1,79 @@
1
+ from typing import Literal, Annotated, Union
2
+ from pydantic import BaseModel, Field
3
+ from pydantic_settings import BaseSettings
4
+ import os
5
+
6
+
7
+ class SignerConfig(BaseModel):
8
+ url: str = ""
9
+ token: str = ""
10
+
11
+
12
+ class BaseAdapterConfig(BaseModel):
13
+ type: Literal["ForwardWebSocket", "ReverseWebSocket", "HTTP", "HTTPPost"] = "ForwardWebSocket"
14
+ url: str = ""
15
+
16
+
17
+ class ForwardWebsocketConfig(BaseAdapterConfig):
18
+ type: Literal["ForwardWebSocket"] = "ForwardWebSocket"
19
+ ...
20
+
21
+
22
+ class ReverseWebsocketConfig(BaseAdapterConfig):
23
+ type: Literal["ReverseWebSocket"] = "ReverseWebSocket"
24
+ api_url: str = ""
25
+ event_url: str = ""
26
+ use_universal_client: bool = False
27
+ reconnect_interval: int = 3000
28
+
29
+
30
+ class HTTPConfig(BaseAdapterConfig):
31
+ type: Literal["HTTP"] = "HTTP"
32
+
33
+
34
+ class HTTPPostConfig(BaseAdapterConfig):
35
+ type: Literal["HTTPPost"] = "HTTPPost"
36
+ timeout: int = 0
37
+ secret: str = ""
38
+
39
+
40
+ AdapterConfig = Annotated[
41
+ Union[HTTPConfig, HTTPPostConfig, ForwardWebsocketConfig, ReverseWebsocketConfig], Field(discriminator="type")
42
+ ]
43
+
44
+
45
+ class HeartbeatConfig(BaseModel):
46
+ enabled: bool = True
47
+ interval: int = 15000
48
+
49
+
50
+ class LoginConfig(BaseModel):
51
+ uin: int = 0
52
+ signer_url: str = "https://"
53
+ signer_token: str = ""
54
+
55
+
56
+ class BotConfig(BaseSettings):
57
+ log_level: Literal["INFO", "DEBUG", "TRACE", "WARNING", "ERROR", "CRITICAL"] = "INFO"
58
+ log_nf: bool = True
59
+ connections: list[AdapterConfig] = [ForwardWebsocketConfig()]
60
+ login: LoginConfig = LoginConfig()
61
+ heartbeat: HeartbeatConfig = HeartbeatConfig()
62
+
63
+
64
+ loaded_config: BotConfig = None
65
+
66
+
67
+ def load_config(file: str) -> BotConfig:
68
+ if loaded_config:
69
+ return loaded_config
70
+ if os.path.exists(file):
71
+ with open(file, "r", encoding="utf-8") as f:
72
+ return BotConfig.model_validate_json(f.read())
73
+ else:
74
+ try:
75
+ with open(file, "w", encoding="utf-8") as f:
76
+ f.write(BotConfig().model_dump_json(indent=2, ensure_ascii=False))
77
+ except Exception as e:
78
+ raise RuntimeError(f"无法创建配置文件: {e} ,请检查路径是否有误")
79
+ raise FileNotFoundError(f"配置文件 {file} 不存在, 已创建,请填写后重启")
@@ -0,0 +1,171 @@
1
+ import datetime
2
+ import traceback
3
+ import sys
4
+ import logging
5
+ from typing import Any, Self
6
+
7
+ from .utils import color_txt, rgb, NerdICONs
8
+
9
+
10
+
11
+ __all__ = ["Logger", "Levels"]
12
+
13
+
14
+ class Levels:
15
+ def __init__(self, nf_icons: NerdICONs):
16
+ self.nf_icons = nf_icons
17
+ self.TRACE = color_txt(f"|{nf_icons.nf_cod_debug_breakpoint_log} Trace |", rgb(184, 255, 254))
18
+ self.INFO = color_txt(f"|{nf_icons.nf_fa_circle_info} Info |", rgb(90, 221, 225))
19
+ self.WARNING = color_txt(f"|{nf_icons.nf_fa_warn} Warning |", rgb(82, 171, 237))
20
+ self.ERROR = color_txt(f"|{nf_icons.nf_cod_error} Error |", rgb(255, 48, 70))
21
+ self.CRITICAL = color_txt(f"|{nf_icons.nf_cod_bracket_error} Critical |", rgb(178, 33, 48))
22
+ self.DEBUG = color_txt(f"|{nf_icons.nf_cod_debug_alt} Debug |", rgb(93, 227, 144))
23
+
24
+ self.level_nums = {
25
+ self.TRACE: -1,
26
+ self.INFO: 0,
27
+ self.WARNING: 1,
28
+ self.ERROR: 2,
29
+ self.CRITICAL: 3,
30
+ self.DEBUG: 10,
31
+ }
32
+
33
+ self.level_names = {
34
+ "TRACE": self.TRACE,
35
+ "INFO": self.INFO,
36
+ "WARNING": self.WARNING,
37
+ "ERROR": self.ERROR,
38
+ "CRITICAL": self.CRITICAL,
39
+ "DEBUG": self.DEBUG,
40
+ }
41
+
42
+
43
+ class Logger:
44
+ running_loggers: dict[str, "Logger"] = {}
45
+
46
+ def __init__(self, use_nf: bool = True):
47
+ self.levels = Levels(NerdICONs(use_nf))
48
+ self._use_nf = use_nf
49
+ self.log_level = self.levels.INFO
50
+ self.log_level_text = ""
51
+
52
+ @classmethod
53
+ def create(cls, key: str, level: str, use_nf: bool = True):
54
+ c = cls(use_nf)
55
+ c.set_level(level)
56
+ cls.running_loggers[key] = c
57
+ return c
58
+
59
+ @classmethod
60
+ def fetch(cls, key: str) -> Self:
61
+ return cls.running_loggers.get(key)
62
+
63
+ def set_level(self, level: str):
64
+ if level in self.levels.level_names:
65
+ self.log_level = self.levels.level_names[level]
66
+ self.log_level_text = level
67
+ else:
68
+ self.log("未知的日志等级", self.levels.ERROR)
69
+
70
+ return self
71
+
72
+ @staticmethod
73
+ def format_exec():
74
+ exc_type, exc_value, exc_traceback = sys.exc_info()
75
+ formatted = color_txt("\nTraceback: \n\n", rgb(255, 47, 47))
76
+ tb_frames = traceback.extract_tb(exc_traceback)
77
+ FILE = color_txt("File", rgb(85, 173, 238))
78
+ LINE = color_txt("line", rgb(85, 173, 238))
79
+ for frame in tb_frames:
80
+ filename, lineno, func_name, code = frame
81
+ formatted += (
82
+ f" {FILE} {color_txt(filename, rgb(104, 255, 244))},"
83
+ f" {LINE} {color_txt(str(lineno), rgb(215, 255, 255))},"
84
+ f" in {color_txt(func_name, rgb(70, 172, 107))}\n"
85
+ f" {color_txt(code, rgb(255, 255, 255))}\n\n"
86
+ )
87
+ formatted += f"{color_txt(exc_type.__name__, rgb(255, 47, 47))}: "
88
+ formatted += color_txt(exc_value, rgb(255, 255, 255)) + "\n"
89
+
90
+ return formatted
91
+
92
+ def register_hook(self) -> None:
93
+ def hook(exc_t: Any, exc_v: Any, exc_tb: Any) -> None:
94
+ self.error(self.format_exec())
95
+
96
+ sys.excepthook = hook
97
+
98
+ def name_custom(self, name: str) -> "Logger":
99
+ new_logger = type(self)(self._use_nf)
100
+ new_logger.set_level(self.log_level_text)
101
+ new_logger._set_name_bind(name)
102
+ return new_logger
103
+
104
+ def _set_name_bind(self, name: str) -> None:
105
+ def nlog(message: str, level: str):
106
+ patch = color_txt(f"[{name}]", rgb(97, 192, 224))
107
+ self._log(f"{patch} {color_txt(message, rgb(215, 255, 255))}", level)
108
+ self.log = nlog
109
+
110
+ def _log(self, message: str, level: str) -> None:
111
+ if self.levels.level_nums[level] < self.levels.level_nums[self.log_level]:
112
+ return
113
+ time = color_txt(self.levels.nf_icons.nf_weather_time_4 + " " + str(datetime.datetime.now())[:-4], rgb(65, 128, 176))
114
+ if "\n" in message:
115
+ listed = message.split("\n")
116
+ for i in listed:
117
+ if listed.index(i) == 0:
118
+ listed[0] = "\n"
119
+ content = f" {time} {level} {color_txt(i, rgb(215, 255, 255))}"
120
+ else:
121
+ content = " " * int((len(f"{time}{level}") - 2) / 2) + color_txt(i, rgb(215, 255, 255))
122
+ print(content)
123
+ else:
124
+ content = f" {time} {level} {color_txt(message, rgb(215, 255, 255))}"
125
+ print(content)
126
+
127
+ def log(self, message: str, level: str) -> None:
128
+ self._log(message, level)
129
+
130
+ def info(self, message: Any) -> None:
131
+ self.log(str(message), self.levels.INFO)
132
+
133
+ def warning(self, message: Any) -> None:
134
+ self.log(str(message), self.levels.WARNING)
135
+
136
+ def error(self, message: Any) -> None:
137
+ self.log(str(message), self.levels.ERROR)
138
+
139
+ def critical(self, message: Any) -> None:
140
+ self.log(str(message), self.levels.CRITICAL)
141
+
142
+ def debug(self, message: Any) -> None:
143
+ self.log(str(message), self.levels.DEBUG)
144
+
145
+ def trace(self, message: Any) -> None:
146
+ self.log(str(message), self.levels.TRACE)
147
+
148
+ def set_handler(self) -> None:
149
+ custom_logger = self
150
+ class StdHandler(logging.Handler):
151
+ def emit(self, record: logging.LogRecord) -> None:
152
+ msg = self.format(record)
153
+ patch = color_txt(f"[{record.name}]", rgb(97, 192, 224))
154
+ msg = f"{patch} {color_txt(msg, rgb(215, 255, 255))}"
155
+ match record.levelno:
156
+ case logging.CRITICAL:
157
+ custom_logger.critical(msg)
158
+ case logging.ERROR:
159
+ custom_logger.error(msg)
160
+ case logging.WARNING:
161
+ custom_logger.warning(msg)
162
+ case logging.INFO:
163
+ custom_logger.info(msg)
164
+ case logging.DEBUG:
165
+ custom_logger.trace(msg)
166
+ case _:
167
+ custom_logger.debug(msg)
168
+
169
+ root = logging.getLogger()
170
+ root.handlers.clear()
171
+ root.addHandler(StdHandler())
@@ -0,0 +1,80 @@
1
+ import asyncio
2
+ import traceback
3
+ from typing import NoReturn, Union, TYPE_CHECKING, Any
4
+ from pydantic import TypeAdapter, ValidationError
5
+
6
+ from .connector import Connector
7
+ from .api import *
8
+ from .events import *
9
+ from ..hyperogger import Logger
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from ..config import AdapterConfig, ForwardWebsocketConfig
14
+
15
+ ADAPTER_CONFIG = AdapterConfig
16
+ FORWARD_WEBSOCKET_CONFIG = ForwardWebsocketConfig
17
+ else:
18
+ ADAPTER_CONFIG = Any
19
+ FORWARD_WEBSOCKET_CONFIG = Any
20
+
21
+ logger = Logger.fetch("euler").name_custom("euler.onebot")
22
+
23
+
24
+
25
+ class Adapter:
26
+ def __init__(self, impls: list[ADAPTER_CONFIG]):
27
+ self.connector = Connector(impls)
28
+ self.api_calls: asyncio.Queue[BaseAPICall] = asyncio.Queue()
29
+ self.api_validation = TypeAdapter(
30
+ Union[
31
+ SendPrivateMessage,
32
+ SendGroupMessage,
33
+ SendMessage,
34
+ DeleteMessage,
35
+ GetMessage,
36
+ GetForwardMessage,
37
+ SendLike,
38
+ SetGroupKick,
39
+ SetGroupBan,
40
+ SetGroupWholeBan,
41
+ SetGroupAdmin,
42
+ SetGroupCard,
43
+ SetGroupName,
44
+ SetGroupLeave,
45
+ SetGroupSpecialTitle,
46
+ SetFriendAddRequest,
47
+ SetGroupAddRequest,
48
+ GetLoginInfo,
49
+ GetStrangerInfo,
50
+ GetFriendList,
51
+ GetGroupInfo,
52
+ GetGroupList,
53
+ GetGroupMemberInfo,
54
+ GetGroupMemberList,
55
+ GetStatus,
56
+ GetVersionInfo,
57
+ ]
58
+ )
59
+
60
+ async def setup(self) -> None:
61
+ self.connector = await self.connector.setup()
62
+
63
+ async def cycle(self) -> NoReturn:
64
+ asyncio.create_task(self.connector.run())
65
+ while True:
66
+ data = await self.connector.received.get()
67
+ try:
68
+ api_call = self.api_validation.validate_json(data)
69
+ await self.api_calls.put(api_call)
70
+ except (ValueError, TypeError, ValidationError):
71
+ logger.error(data)
72
+ logger.error(traceback.format_exc())
73
+ continue
74
+
75
+ async def trigger(self, event: BaseEvent) -> None:
76
+ await self.connector.trigger(event.model_dump_json())
77
+
78
+ async def report(self, rsp: BaseAPIResponse) -> None:
79
+ logger.info(f"API Result: {rsp}")
80
+ await self.connector.report(rsp.model_dump_json())
@@ -0,0 +1,291 @@
1
+ from pydantic import BaseModel
2
+ from typing import TypeVar, Generic, Literal, Optional
3
+
4
+ from .api_data import *
5
+
6
+ DataType = TypeVar('DataType')
7
+ ResponseType = TypeVar('ResponseType')
8
+
9
+ __all__ = [
10
+ "BaseAPICall",
11
+ "BaseAPIResponse",
12
+ "SendPrivateMessage",
13
+ "SendPrivateMsgData",
14
+ "SendPrivateMessageResponse",
15
+ "SendGroupMessage",
16
+ "SendGroupMsgData",
17
+ "SendGroupMessageResponse",
18
+ "SendMessage",
19
+ "SendMessageResponse",
20
+ "DeleteMessage",
21
+ "DeleteMessageResponse",
22
+ "GetMessage",
23
+ "GetMessageResponse",
24
+ "GetForwardMessage",
25
+ "GetForwardMessageResponse",
26
+ "SendLike",
27
+ "SendLikeResponse",
28
+ "SetGroupKick",
29
+ "SetGroupKickResponse",
30
+ "SetGroupBan",
31
+ "SetGroupBanResponse",
32
+ "SetGroupWholeBan",
33
+ "SetGroupWholeBanResponse",
34
+ "SetGroupAdmin",
35
+ "SetGroupAdminResponse",
36
+ "SetGroupCard",
37
+ "SetGroupCardResponse",
38
+ "SetGroupName",
39
+ "SetGroupNameResponse",
40
+ "SetGroupLeave",
41
+ "SetGroupLeaveResponse",
42
+ "SetGroupSpecialTitle",
43
+ "SetGroupSpecialTitleResponse",
44
+ "SetFriendAddRequest",
45
+ "SetFriendAddRequestResponse",
46
+ "SetGroupAddRequest",
47
+ "SetGroupAddRequestResponse",
48
+ "GetLoginInfo",
49
+ "GetLoginInfoResponse",
50
+ "GetStrangerInfo",
51
+ "GetStrangerInfoResponse",
52
+ "GetFriendList",
53
+ "GetFriendListResponse",
54
+ "GetGroupInfo",
55
+ "GetGroupInfoResponse",
56
+ "GetGroupList",
57
+ "GetGroupListResponse",
58
+ "GetGroupMemberInfo",
59
+ "GetGroupMemberInfoResponse",
60
+ "GetGroupMemberList",
61
+ "GetGroupMemberListResponse",
62
+ "GetStatus",
63
+ "GetStatusResponse",
64
+ "GetVersionInfo",
65
+ "GetVersionInfoResponse",
66
+ "ActionFailedResponse"
67
+ ]
68
+
69
+
70
+ class BaseAPICall(BaseModel, Generic[DataType]):
71
+ action: str
72
+ params: DataType
73
+ echo: str = ""
74
+
75
+
76
+ class BaseAPIResponse(BaseModel, Generic[ResponseType]):
77
+ status: Literal["ok", "failed"]
78
+ retcode: int
79
+ data: Optional[ResponseType]
80
+ echo: str = ""
81
+
82
+
83
+ class SendPrivateMessage(BaseAPICall[SendPrivateMsgData]):
84
+ action: Literal["send_private_msg"] = "send_private_msg"
85
+
86
+
87
+ class SendPrivateMessageResponse(BaseAPIResponse[SendMsgRsp]):
88
+ ...
89
+
90
+
91
+ class SendGroupMessage(BaseAPICall[SendGroupMsgData]):
92
+ action: Literal["send_group_msg"] = "send_group_msg"
93
+
94
+
95
+ class SendGroupMessageResponse(BaseAPIResponse[SendMsgRsp]):
96
+ ...
97
+
98
+
99
+ class SendMessage(BaseAPICall[SendMsgData]):
100
+ action: Literal["send_msg"] = "send_msg"
101
+
102
+
103
+ class SendMessageResponse(BaseAPIResponse[SendMsgRsp]):
104
+ ...
105
+
106
+
107
+ class DeleteMessage(BaseAPICall[DeleteMsgData]):
108
+ action: Literal["delete_msg"] = "delete_msg"
109
+
110
+
111
+ class DeleteMessageResponse(BaseAPIResponse[EmptyRsp]):
112
+ ...
113
+
114
+
115
+ class GetMessage(BaseAPICall[GetMsgData]):
116
+ action: Literal["get_msg"] = "get_msg"
117
+
118
+
119
+ class GetMessageResponse(BaseAPIResponse[GetMsgRsp]):
120
+ ...
121
+
122
+
123
+ class GetForwardMessage(BaseAPICall[GetForwardMsgData]):
124
+ action: Literal["get_forward_msg"] = "get_forward_msg"
125
+
126
+
127
+ class GetForwardMessageResponse(BaseAPIResponse[GetForwardMsgRsp]):
128
+ ...
129
+
130
+
131
+ class SendLike(BaseAPICall[SendLikeData]):
132
+ action: Literal["send_like"] = "send_like"
133
+
134
+
135
+ class SendLikeResponse(BaseAPIResponse[EmptyRsp]):
136
+ ...
137
+
138
+
139
+ class SetGroupKick(BaseAPICall[SetGroupKickData]):
140
+ action: Literal["set_group_kick"] = "set_group_kick"
141
+
142
+
143
+ class SetGroupKickResponse(BaseAPIResponse[EmptyRsp]):
144
+ ...
145
+
146
+
147
+ class SetGroupBan(BaseAPICall[SetGroupBanData]):
148
+ action: Literal["set_group_ban"] = "set_group_ban"
149
+
150
+
151
+ class SetGroupBanResponse(BaseAPIResponse[EmptyRsp]):
152
+ ...
153
+
154
+
155
+ class SetGroupWholeBan(BaseAPICall[SetGroupWholeBanData]):
156
+ action: Literal["set_group_whole_ban"] = "set_group_whole_ban"
157
+
158
+
159
+ class SetGroupWholeBanResponse(BaseAPIResponse[EmptyRsp]):
160
+ ...
161
+
162
+
163
+ class SetGroupAdmin(BaseAPICall[SetGroupAdminData]):
164
+ action: Literal["set_group_admin"] = "set_group_admin"
165
+
166
+
167
+ class SetGroupAdminResponse(BaseAPIResponse[EmptyRsp]):
168
+ ...
169
+
170
+
171
+ class SetGroupCard(BaseAPICall[SetGroupCardData]):
172
+ action: Literal["set_group_card"] = "set_group_card"
173
+
174
+
175
+ class SetGroupCardResponse(BaseAPIResponse[EmptyRsp]):
176
+ ...
177
+
178
+
179
+ class SetGroupName(BaseAPICall[SetGroupNameData]):
180
+ action: Literal["set_group_name"] = "set_group_name"
181
+
182
+
183
+ class SetGroupNameResponse(BaseAPIResponse[EmptyRsp]):
184
+ ...
185
+
186
+
187
+ class SetGroupLeave(BaseAPICall[SetGroupLeaveData]):
188
+ action: Literal["set_group_leave"] = "set_group_leave"
189
+
190
+
191
+ class SetGroupLeaveResponse(BaseAPIResponse[EmptyRsp]):
192
+ ...
193
+
194
+
195
+ class SetGroupSpecialTitle(BaseAPICall[SetGroupSpecialTitleData]):
196
+ action: Literal["set_group_special_title"] = "set_group_special_title"
197
+
198
+
199
+ class SetGroupSpecialTitleResponse(BaseAPIResponse[EmptyRsp]):
200
+ ...
201
+
202
+
203
+ class SetFriendAddRequest(BaseAPICall[SetFriendAddRequestData]):
204
+ action: Literal["set_friend_add_request"] = "set_friend_add_request"
205
+
206
+
207
+ class SetFriendAddRequestResponse(BaseAPIResponse[EmptyRsp]):
208
+ ...
209
+
210
+
211
+ class SetGroupAddRequest(BaseAPICall[SetGroupAddRequestData]):
212
+ action: Literal["set_group_add_request"] = "set_group_add_request"
213
+
214
+
215
+ class SetGroupAddRequestResponse(BaseAPIResponse[EmptyRsp]):
216
+ ...
217
+
218
+
219
+ class GetLoginInfo(BaseAPICall[GetLoginInfoData]):
220
+ action: Literal["get_login_info"] = "get_login_info"
221
+
222
+
223
+ class GetLoginInfoResponse(BaseAPIResponse[GetLoginInfoRsp]):
224
+ ...
225
+
226
+
227
+ class GetStrangerInfo(BaseAPICall[GetStrangerInfoData]):
228
+ action: Literal["get_stranger_info"] = "get_stranger_info"
229
+
230
+
231
+ class GetStrangerInfoResponse(BaseAPIResponse[GetStrangerInfoRsp]):
232
+ ...
233
+
234
+
235
+ class GetFriendList(BaseAPICall[GetFriendListData]):
236
+ action: Literal["get_friend_list"] = "get_friend_list"
237
+
238
+
239
+ class GetFriendListResponse(BaseAPIResponse[GetFriendListRsp]):
240
+ ...
241
+
242
+
243
+ class GetGroupInfo(BaseAPICall[GetGroupInfoData]):
244
+ action: Literal["get_group_info"] = "get_group_info"
245
+
246
+
247
+ class GetGroupInfoResponse(BaseAPIResponse[GetGroupInfoRsp]):
248
+ ...
249
+
250
+
251
+ class GetGroupList(BaseAPICall[GetGroupListData]):
252
+ action: Literal["get_group_list"] = "get_group_list"
253
+
254
+
255
+ class GetGroupListResponse(BaseAPIResponse[GetGroupListRsp]):
256
+ ...
257
+
258
+
259
+ class GetGroupMemberInfo(BaseAPICall[GetGroupMemberInfoData]):
260
+ action: Literal["get_group_member_info"] = "get_group_member_info"
261
+
262
+
263
+ class GetGroupMemberInfoResponse(BaseAPIResponse[GetGroupMemberInfoRsp]):
264
+ ...
265
+
266
+
267
+ class GetGroupMemberList(BaseAPICall[GetGroupMemberListData]):
268
+ action: Literal["get_group_member_list"] = "get_group_member_list"
269
+
270
+
271
+ class GetGroupMemberListResponse(BaseAPIResponse[GetGroupMemberListRsp]):
272
+ ...
273
+
274
+
275
+ class GetStatus(BaseAPICall[GetStatusData]):
276
+ action: Literal["get_status"] = "get_status"
277
+
278
+
279
+ class GetStatusResponse(BaseAPIResponse[EmptyRsp]):
280
+ ...
281
+
282
+
283
+ class GetVersionInfo(BaseAPICall[GetVersionInfoData]):
284
+ action: Literal["get_version_info"] = "get_version_info"
285
+
286
+
287
+ class GetVersionInfoResponse(BaseAPIResponse[GetVersionInfoRsp]):
288
+ ...
289
+
290
+ class ActionFailedResponse(BaseAPIResponse[EmptyRsp]):
291
+ ...