-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathModuleClass.py
More file actions
260 lines (204 loc) · 7.29 KB
/
ModuleClass.py
File metadata and controls
260 lines (204 loc) · 7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import inspect
from hyperot import events, listener, hyperogger, configurator
from hyperot.utils.hypetyping import Any, Union
from hyperot.utils.typextensions import String
import gc
import asyncio
import importlib
import dataclasses
config: configurator.BotConfig = configurator.BotConfig.get("hyper-bot")
logger = hyperogger.Logger()
logger.set_level(config.log_level)
@dataclasses.dataclass
class ModuleInfo:
is_hidden: bool = True
module_name: str = "None"
author: str = "None"
version: str = "0.0"
desc: str = "None"
helps: str = "None"
class Module:
config = config
def __init__(
self,
actions: listener.Actions,
event: Union[
events.GroupMessageEvent,
events.PrivateMessageEvent,
events.GroupFileUploadEvent,
events.GroupAdminEvent,
events.GroupMemberDecreaseEvent,
events.GroupMemberIncreaseEvent,
events.GroupMuteEvent,
events.FriendAddEvent,
events.GroupRecallEvent,
events.FriendRecallEvent,
events.NotifyEvent,
events.GroupEssenceEvent,
events.MessageReactionEvent,
events.FriendAddRequestEvent,
events.GroupAddInviteEvent,
events.HyperListenerStartNotify,
events.HyperListenerStopNotify
]
):
self.actions: listener.Actions = actions
self.event: Union[
events.GroupMessageEvent,
events.PrivateMessageEvent,
events.GroupFileUploadEvent,
events.GroupAdminEvent,
events.GroupMemberDecreaseEvent,
events.GroupMemberIncreaseEvent,
events.GroupMuteEvent,
events.FriendAddEvent,
events.GroupRecallEvent,
events.FriendRecallEvent,
events.NotifyEvent,
events.GroupEssenceEvent,
events.MessageReactionEvent,
events.GroupAddInviteEvent,
events.HyperListenerStartNotify,
events.HyperListenerStopNotify
] = event
async def handle(self):
pass
@staticmethod
def info() -> ModuleInfo:
return ModuleInfo()
@staticmethod
def filter(event: events.Event, allowed: list) -> bool:
for i in allowed:
if isinstance(event, i):
return True
return False
@dataclasses.dataclass
class CommandPara:
name: str
annotation: type = str
default: annotation = ""
def para_empty(obj: Any) -> bool:
return obj is inspect.Parameter.empty
class FieldNotEqualException(Exception):
pass
class CommandRegistration:
def __init__(self, chain: list[str], mapping: dict[Union[int, str], str], function: callable):
self.chain = chain
self.mapping = mapping
self.function = function
signature = inspect.signature(self.function).parameters
self.signature: list[CommandPara] = []
for i, j in signature.items():
self.signature.append(CommandPara(i, j.annotation, j.default, ))
async def __call__(self, sub_self: "CommandHandler", cmds: list) -> Any:
return await self.function(**self.gen_args(cmds, sub_self))
@property
def length_chain(self) -> int:
return len(self.chain)
def if_equal(self, cmd: list) -> bool:
flags = [False for _ in self.chain]
try:
for i in range(len(self.chain)):
if self.chain[i] == cmd[i]:
flags[i] = True
if all(flags):
return True
except IndexError:
return False
return False
def gen_args(self, cmd: list, sub_self: "CommandHandler") -> dict:
new = {"self": sub_self}
for i in self.mapping:
if isinstance(i, int):
try:
new[self.mapping[i]] = cmd[i]
except IndexError:
for j in self.signature:
if j.name == self.mapping[i] and not para_empty(j.default):
new[self.mapping[i]] = j.default
break
else:
raise FieldNotEqualException(f"index={i}: 缺少参数")
elif isinstance(i, str):
have = False
for j in cmd:
if isinstance(j, dict) and j.get(i):
have = True
if not have:
for k in self.signature:
if k.name == self.mapping[i] and not para_empty(k.default):
new[self.mapping[i]] = k.default
continue
else:
raise FieldNotEqualException(f"缺少参数 {i}")
return new
def command(chain: list[str], mapping: dict[Union[int, str], str]):
def decorator(func) -> CommandRegistration:
return CommandRegistration(chain, mapping, func)
return decorator
class CommandHandler(Module):
handlers: list[CommandRegistration] = []
async def handle(self):
cmds = String(self.event.message).cmdl_parse()
for i in self.handlers:
if i.if_equal(cmds):
try:
await i(self, cmds)
except Exception as e:
await self.actions.send(
group_id=self.event.group_id,
user_id=self.event.user_id,
message=repr(e)
)
def __init_subclass__(cls, **kwargs):
cls.handlers = [].copy()
for i in inspect.getmembers(cls):
if not isinstance(i[1], CommandRegistration):
continue
else:
cls.handlers.append(i[1])
return cls
class InnerHandler:
def __init__(self, module: Module, allowed: list):
self.module = module
self.allowed = allowed
register_modules: list[InnerHandler] = []
class ModuleRegister:
@staticmethod
def register(*args):
def decorator(cls):
if len(args) < 1:
allowed = [events.Event]
else:
allowed = list(args)
def init(self, actions: listener.Actions, event: events.Event):
self.actions = actions
self.event = event
cls.__init__ = init
register_modules.append(InnerHandler(cls, allowed))
return cls
return decorator
@staticmethod
def get_registered() -> list:
return register_modules
imported = None
def load() -> None:
global imported, register_modules
register_modules = []
if imported is not None:
imported.load()
imported = importlib.reload(imported)
else:
imported = importlib.import_module("modules")
class TaskCxt:
def __init__(self):
self.tasks = []
def add(self, task: asyncio.Task) -> None:
self.tasks.append(task)
async def wait(self) -> None:
await asyncio.gather(*self.tasks)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.wait()
gc.collect()