maxapi-python 0.1.2__py3-none-any.whl → 1.0.1__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.
- {maxapi_python-0.1.2.dist-info → maxapi_python-1.0.1.dist-info}/METADATA +3 -1
- maxapi_python-1.0.1.dist-info/RECORD +27 -0
- {maxapi_python-0.1.2.dist-info → maxapi_python-1.0.1.dist-info}/licenses/LICENSE +21 -21
- pymax/__init__.py +55 -55
- pymax/core.py +170 -156
- pymax/crud.py +99 -99
- pymax/exceptions.py +29 -20
- pymax/files.py +86 -85
- pymax/filters.py +38 -38
- pymax/interfaces.py +73 -67
- pymax/mixins/__init__.py +20 -18
- pymax/mixins/auth.py +81 -81
- pymax/mixins/channel.py +25 -25
- pymax/mixins/group.py +220 -220
- pymax/mixins/handler.py +60 -60
- pymax/mixins/message.py +293 -293
- pymax/mixins/self.py +38 -38
- pymax/mixins/telemetry.py +114 -0
- pymax/mixins/user.py +82 -82
- pymax/mixins/websocket.py +262 -242
- pymax/models.py +8 -8
- pymax/navigation.py +185 -0
- pymax/payloads.py +195 -175
- pymax/static.py +210 -210
- pymax/types.py +434 -432
- pymax/utils.py +38 -38
- maxapi_python-0.1.2.dist-info/RECORD +0 -25
- {maxapi_python-0.1.2.dist-info → maxapi_python-1.0.1.dist-info}/WHEEL +0 -0
pymax/mixins/group.py
CHANGED
@@ -1,220 +1,220 @@
|
|
1
|
-
import time
|
2
|
-
|
3
|
-
from pymax.interfaces import ClientProtocol
|
4
|
-
from pymax.payloads import (
|
5
|
-
ChangeGroupProfilePayload,
|
6
|
-
ChangeGroupSettingsOptions,
|
7
|
-
ChangeGroupSettingsPayload,
|
8
|
-
CreateGroupAttach,
|
9
|
-
CreateGroupMessage,
|
10
|
-
CreateGroupPayload,
|
11
|
-
InviteUsersPayload,
|
12
|
-
RemoveUsersPayload,
|
13
|
-
)
|
14
|
-
from pymax.static import Opcode
|
15
|
-
from pymax.types import Chat, Message
|
16
|
-
|
17
|
-
|
18
|
-
class GroupMixin(ClientProtocol):
|
19
|
-
async def create_group(
|
20
|
-
self, name: str, participant_ids: list[int] | None = None, notify: bool = True
|
21
|
-
) -> tuple[Chat, Message] | None:
|
22
|
-
"""
|
23
|
-
Создает группу
|
24
|
-
|
25
|
-
Args:
|
26
|
-
name (str): Название группы.
|
27
|
-
participant_ids (list[int] | None, optional): Список идентификаторов участников. Defaults to None.
|
28
|
-
notify (bool, optional): Флаг оповещения. Defaults to True.
|
29
|
-
|
30
|
-
Returns:
|
31
|
-
tuple[Chat, Message] | None: Объект Chat и Message или None при ошибке.
|
32
|
-
"""
|
33
|
-
try:
|
34
|
-
payload = CreateGroupPayload(
|
35
|
-
message=CreateGroupMessage(
|
36
|
-
cid=int(time.time() * 1000),
|
37
|
-
attaches=[
|
38
|
-
CreateGroupAttach(
|
39
|
-
_type="CONTROL",
|
40
|
-
title=name,
|
41
|
-
user_ids=participant_ids if participant_ids else [],
|
42
|
-
)
|
43
|
-
],
|
44
|
-
),
|
45
|
-
notify=notify,
|
46
|
-
).model_dump(by_alias=True)
|
47
|
-
|
48
|
-
data = await self._send_and_wait(opcode=Opcode.MSG_SEND, payload=payload)
|
49
|
-
if error := data.get("payload", {}).get("error"):
|
50
|
-
self.logger.error("Create group error: %s", error)
|
51
|
-
return None
|
52
|
-
|
53
|
-
chat = Chat.from_dict(data["payload"]["chat"])
|
54
|
-
message = Message.from_dict(data["payload"]["message"])
|
55
|
-
|
56
|
-
if chat:
|
57
|
-
cached_chat = await self._get_chat(chat.id)
|
58
|
-
if cached_chat is None:
|
59
|
-
self.chats.append(chat)
|
60
|
-
else:
|
61
|
-
idx = self.chats.index(cached_chat)
|
62
|
-
self.chats[idx] = chat
|
63
|
-
|
64
|
-
return chat, message
|
65
|
-
|
66
|
-
except Exception:
|
67
|
-
self.logger.exception("Create group failed")
|
68
|
-
|
69
|
-
async def invite_users_to_group(
|
70
|
-
self,
|
71
|
-
chat_id: int,
|
72
|
-
user_ids: list[int],
|
73
|
-
show_history: bool = True,
|
74
|
-
) -> bool:
|
75
|
-
"""
|
76
|
-
Приглашает пользователей в группу
|
77
|
-
|
78
|
-
Args:
|
79
|
-
chat_id (int): ID группы.
|
80
|
-
user_ids (list[int]): Список идентификаторов пользователей.
|
81
|
-
show_history (bool, optional): Флаг оповещения. Defaults to True.
|
82
|
-
|
83
|
-
Returns:
|
84
|
-
bool: True, если пользователи успешно приглашены
|
85
|
-
"""
|
86
|
-
try:
|
87
|
-
payload = InviteUsersPayload(
|
88
|
-
chat_id=chat_id,
|
89
|
-
user_ids=user_ids,
|
90
|
-
show_history=show_history,
|
91
|
-
operation="add",
|
92
|
-
).model_dump(by_alias=True)
|
93
|
-
|
94
|
-
data = await self._send_and_wait(
|
95
|
-
opcode=Opcode.CHAT_MEMBERS_UPDATE, payload=payload
|
96
|
-
)
|
97
|
-
|
98
|
-
if error := data.get("payload", {}).get("error"):
|
99
|
-
self.logger.error("Create group error: %s", error)
|
100
|
-
return False
|
101
|
-
|
102
|
-
chat = Chat.from_dict(data["payload"]["chat"])
|
103
|
-
if chat:
|
104
|
-
cached_chat = await self._get_chat(chat.id)
|
105
|
-
if cached_chat is None:
|
106
|
-
self.chats.append(chat)
|
107
|
-
else:
|
108
|
-
idx = self.chats.index(cached_chat)
|
109
|
-
self.chats[idx] = chat
|
110
|
-
|
111
|
-
return True
|
112
|
-
|
113
|
-
except Exception:
|
114
|
-
self.logger.exception("Invite users to group failed")
|
115
|
-
return False
|
116
|
-
|
117
|
-
async def remove_users_from_group(
|
118
|
-
self,
|
119
|
-
chat_id: int,
|
120
|
-
user_ids: list[int],
|
121
|
-
clean_msg_period: int,
|
122
|
-
) -> bool:
|
123
|
-
try:
|
124
|
-
payload = RemoveUsersPayload(
|
125
|
-
chat_id=chat_id,
|
126
|
-
user_ids=user_ids,
|
127
|
-
clean_msg_period=clean_msg_period,
|
128
|
-
).model_dump(by_alias=True)
|
129
|
-
|
130
|
-
data = await self._send_and_wait(
|
131
|
-
opcode=Opcode.CHAT_MEMBERS_UPDATE, payload=payload
|
132
|
-
)
|
133
|
-
|
134
|
-
if error := data.get("payload", {}).get("error"):
|
135
|
-
self.logger.error("Remove users from group error: %s", error)
|
136
|
-
return False
|
137
|
-
|
138
|
-
chat = Chat.from_dict(data["payload"]["chat"])
|
139
|
-
if chat:
|
140
|
-
cached_chat = await self._get_chat(chat.id)
|
141
|
-
if cached_chat is None:
|
142
|
-
self.chats.append(chat)
|
143
|
-
else:
|
144
|
-
idx = self.chats.index(cached_chat)
|
145
|
-
self.chats[idx] = chat
|
146
|
-
|
147
|
-
return True
|
148
|
-
except Exception:
|
149
|
-
self.logger.exception("Remove users from group failed")
|
150
|
-
return False
|
151
|
-
|
152
|
-
async def change_group_settings(
|
153
|
-
self,
|
154
|
-
chat_id: int,
|
155
|
-
all_can_pin_message: bool | None = None,
|
156
|
-
only_owner_can_change_icon_title: bool | None = None,
|
157
|
-
only_admin_can_add_member: bool | None = None,
|
158
|
-
only_admin_can_call: bool | None = None,
|
159
|
-
members_can_see_private_link: bool | None = None,
|
160
|
-
):
|
161
|
-
try:
|
162
|
-
payload = ChangeGroupSettingsPayload(
|
163
|
-
chat_id=chat_id,
|
164
|
-
options=ChangeGroupSettingsOptions(
|
165
|
-
ALL_CAN_PIN_MESSAGE=all_can_pin_message,
|
166
|
-
ONLY_OWNER_CAN_CHANGE_ICON_TITLE=only_owner_can_change_icon_title,
|
167
|
-
ONLY_ADMIN_CAN_ADD_MEMBER=only_admin_can_add_member,
|
168
|
-
ONLY_ADMIN_CAN_CALL=only_admin_can_call,
|
169
|
-
MEMBERS_CAN_SEE_PRIVATE_LINK=members_can_see_private_link,
|
170
|
-
),
|
171
|
-
).model_dump(by_alias=True, exclude_none=True)
|
172
|
-
|
173
|
-
data = await self._send_and_wait(opcode=Opcode.CHAT_UPDATE, payload=payload)
|
174
|
-
|
175
|
-
if error := data.get("payload", {}).get("error"):
|
176
|
-
self.logger.error("Change group settings error: %s", error)
|
177
|
-
return
|
178
|
-
|
179
|
-
chat = Chat.from_dict(data["payload"]["chat"])
|
180
|
-
if chat:
|
181
|
-
cached_chat = await self._get_chat(chat.id)
|
182
|
-
if cached_chat is None:
|
183
|
-
self.chats.append(chat)
|
184
|
-
else:
|
185
|
-
idx = self.chats.index(cached_chat)
|
186
|
-
self.chats[idx] = chat
|
187
|
-
|
188
|
-
except Exception:
|
189
|
-
self.logger.exception("Change group settings failed")
|
190
|
-
|
191
|
-
async def change_group_profile(
|
192
|
-
self,
|
193
|
-
chat_id: int,
|
194
|
-
name: str | None,
|
195
|
-
description: str | None = None,
|
196
|
-
):
|
197
|
-
try:
|
198
|
-
payload = ChangeGroupProfilePayload(
|
199
|
-
chat_id=chat_id,
|
200
|
-
theme=name,
|
201
|
-
description=description,
|
202
|
-
).model_dump(by_alias=True, exclude_none=True)
|
203
|
-
|
204
|
-
data = await self._send_and_wait(opcode=Opcode.CHAT_UPDATE, payload=payload)
|
205
|
-
|
206
|
-
if error := data.get("payload", {}).get("error"):
|
207
|
-
self.logger.error("Change group profile error: %s", error)
|
208
|
-
return
|
209
|
-
|
210
|
-
chat = Chat.from_dict(data["payload"]["chat"])
|
211
|
-
if chat:
|
212
|
-
cached_chat = await self._get_chat(chat.id)
|
213
|
-
if cached_chat is None:
|
214
|
-
self.chats.append(chat)
|
215
|
-
else:
|
216
|
-
idx = self.chats.index(cached_chat)
|
217
|
-
self.chats[idx] = chat
|
218
|
-
|
219
|
-
except Exception:
|
220
|
-
self.logger.exception("Change group profile failed")
|
1
|
+
import time
|
2
|
+
|
3
|
+
from pymax.interfaces import ClientProtocol
|
4
|
+
from pymax.payloads import (
|
5
|
+
ChangeGroupProfilePayload,
|
6
|
+
ChangeGroupSettingsOptions,
|
7
|
+
ChangeGroupSettingsPayload,
|
8
|
+
CreateGroupAttach,
|
9
|
+
CreateGroupMessage,
|
10
|
+
CreateGroupPayload,
|
11
|
+
InviteUsersPayload,
|
12
|
+
RemoveUsersPayload,
|
13
|
+
)
|
14
|
+
from pymax.static import Opcode
|
15
|
+
from pymax.types import Chat, Message
|
16
|
+
|
17
|
+
|
18
|
+
class GroupMixin(ClientProtocol):
|
19
|
+
async def create_group(
|
20
|
+
self, name: str, participant_ids: list[int] | None = None, notify: bool = True
|
21
|
+
) -> tuple[Chat, Message] | None:
|
22
|
+
"""
|
23
|
+
Создает группу
|
24
|
+
|
25
|
+
Args:
|
26
|
+
name (str): Название группы.
|
27
|
+
participant_ids (list[int] | None, optional): Список идентификаторов участников. Defaults to None.
|
28
|
+
notify (bool, optional): Флаг оповещения. Defaults to True.
|
29
|
+
|
30
|
+
Returns:
|
31
|
+
tuple[Chat, Message] | None: Объект Chat и Message или None при ошибке.
|
32
|
+
"""
|
33
|
+
try:
|
34
|
+
payload = CreateGroupPayload(
|
35
|
+
message=CreateGroupMessage(
|
36
|
+
cid=int(time.time() * 1000),
|
37
|
+
attaches=[
|
38
|
+
CreateGroupAttach(
|
39
|
+
_type="CONTROL",
|
40
|
+
title=name,
|
41
|
+
user_ids=participant_ids if participant_ids else [],
|
42
|
+
)
|
43
|
+
],
|
44
|
+
),
|
45
|
+
notify=notify,
|
46
|
+
).model_dump(by_alias=True)
|
47
|
+
|
48
|
+
data = await self._send_and_wait(opcode=Opcode.MSG_SEND, payload=payload)
|
49
|
+
if error := data.get("payload", {}).get("error"):
|
50
|
+
self.logger.error("Create group error: %s", error)
|
51
|
+
return None
|
52
|
+
|
53
|
+
chat = Chat.from_dict(data["payload"]["chat"])
|
54
|
+
message = Message.from_dict(data["payload"]["message"])
|
55
|
+
|
56
|
+
if chat:
|
57
|
+
cached_chat = await self._get_chat(chat.id)
|
58
|
+
if cached_chat is None:
|
59
|
+
self.chats.append(chat)
|
60
|
+
else:
|
61
|
+
idx = self.chats.index(cached_chat)
|
62
|
+
self.chats[idx] = chat
|
63
|
+
|
64
|
+
return chat, message
|
65
|
+
|
66
|
+
except Exception:
|
67
|
+
self.logger.exception("Create group failed")
|
68
|
+
|
69
|
+
async def invite_users_to_group(
|
70
|
+
self,
|
71
|
+
chat_id: int,
|
72
|
+
user_ids: list[int],
|
73
|
+
show_history: bool = True,
|
74
|
+
) -> bool:
|
75
|
+
"""
|
76
|
+
Приглашает пользователей в группу
|
77
|
+
|
78
|
+
Args:
|
79
|
+
chat_id (int): ID группы.
|
80
|
+
user_ids (list[int]): Список идентификаторов пользователей.
|
81
|
+
show_history (bool, optional): Флаг оповещения. Defaults to True.
|
82
|
+
|
83
|
+
Returns:
|
84
|
+
bool: True, если пользователи успешно приглашены
|
85
|
+
"""
|
86
|
+
try:
|
87
|
+
payload = InviteUsersPayload(
|
88
|
+
chat_id=chat_id,
|
89
|
+
user_ids=user_ids,
|
90
|
+
show_history=show_history,
|
91
|
+
operation="add",
|
92
|
+
).model_dump(by_alias=True)
|
93
|
+
|
94
|
+
data = await self._send_and_wait(
|
95
|
+
opcode=Opcode.CHAT_MEMBERS_UPDATE, payload=payload
|
96
|
+
)
|
97
|
+
|
98
|
+
if error := data.get("payload", {}).get("error"):
|
99
|
+
self.logger.error("Create group error: %s", error)
|
100
|
+
return False
|
101
|
+
|
102
|
+
chat = Chat.from_dict(data["payload"]["chat"])
|
103
|
+
if chat:
|
104
|
+
cached_chat = await self._get_chat(chat.id)
|
105
|
+
if cached_chat is None:
|
106
|
+
self.chats.append(chat)
|
107
|
+
else:
|
108
|
+
idx = self.chats.index(cached_chat)
|
109
|
+
self.chats[idx] = chat
|
110
|
+
|
111
|
+
return True
|
112
|
+
|
113
|
+
except Exception:
|
114
|
+
self.logger.exception("Invite users to group failed")
|
115
|
+
return False
|
116
|
+
|
117
|
+
async def remove_users_from_group(
|
118
|
+
self,
|
119
|
+
chat_id: int,
|
120
|
+
user_ids: list[int],
|
121
|
+
clean_msg_period: int,
|
122
|
+
) -> bool:
|
123
|
+
try:
|
124
|
+
payload = RemoveUsersPayload(
|
125
|
+
chat_id=chat_id,
|
126
|
+
user_ids=user_ids,
|
127
|
+
clean_msg_period=clean_msg_period,
|
128
|
+
).model_dump(by_alias=True)
|
129
|
+
|
130
|
+
data = await self._send_and_wait(
|
131
|
+
opcode=Opcode.CHAT_MEMBERS_UPDATE, payload=payload
|
132
|
+
)
|
133
|
+
|
134
|
+
if error := data.get("payload", {}).get("error"):
|
135
|
+
self.logger.error("Remove users from group error: %s", error)
|
136
|
+
return False
|
137
|
+
|
138
|
+
chat = Chat.from_dict(data["payload"]["chat"])
|
139
|
+
if chat:
|
140
|
+
cached_chat = await self._get_chat(chat.id)
|
141
|
+
if cached_chat is None:
|
142
|
+
self.chats.append(chat)
|
143
|
+
else:
|
144
|
+
idx = self.chats.index(cached_chat)
|
145
|
+
self.chats[idx] = chat
|
146
|
+
|
147
|
+
return True
|
148
|
+
except Exception:
|
149
|
+
self.logger.exception("Remove users from group failed")
|
150
|
+
return False
|
151
|
+
|
152
|
+
async def change_group_settings(
|
153
|
+
self,
|
154
|
+
chat_id: int,
|
155
|
+
all_can_pin_message: bool | None = None,
|
156
|
+
only_owner_can_change_icon_title: bool | None = None,
|
157
|
+
only_admin_can_add_member: bool | None = None,
|
158
|
+
only_admin_can_call: bool | None = None,
|
159
|
+
members_can_see_private_link: bool | None = None,
|
160
|
+
):
|
161
|
+
try:
|
162
|
+
payload = ChangeGroupSettingsPayload(
|
163
|
+
chat_id=chat_id,
|
164
|
+
options=ChangeGroupSettingsOptions(
|
165
|
+
ALL_CAN_PIN_MESSAGE=all_can_pin_message,
|
166
|
+
ONLY_OWNER_CAN_CHANGE_ICON_TITLE=only_owner_can_change_icon_title,
|
167
|
+
ONLY_ADMIN_CAN_ADD_MEMBER=only_admin_can_add_member,
|
168
|
+
ONLY_ADMIN_CAN_CALL=only_admin_can_call,
|
169
|
+
MEMBERS_CAN_SEE_PRIVATE_LINK=members_can_see_private_link,
|
170
|
+
),
|
171
|
+
).model_dump(by_alias=True, exclude_none=True)
|
172
|
+
|
173
|
+
data = await self._send_and_wait(opcode=Opcode.CHAT_UPDATE, payload=payload)
|
174
|
+
|
175
|
+
if error := data.get("payload", {}).get("error"):
|
176
|
+
self.logger.error("Change group settings error: %s", error)
|
177
|
+
return
|
178
|
+
|
179
|
+
chat = Chat.from_dict(data["payload"]["chat"])
|
180
|
+
if chat:
|
181
|
+
cached_chat = await self._get_chat(chat.id)
|
182
|
+
if cached_chat is None:
|
183
|
+
self.chats.append(chat)
|
184
|
+
else:
|
185
|
+
idx = self.chats.index(cached_chat)
|
186
|
+
self.chats[idx] = chat
|
187
|
+
|
188
|
+
except Exception:
|
189
|
+
self.logger.exception("Change group settings failed")
|
190
|
+
|
191
|
+
async def change_group_profile(
|
192
|
+
self,
|
193
|
+
chat_id: int,
|
194
|
+
name: str | None,
|
195
|
+
description: str | None = None,
|
196
|
+
):
|
197
|
+
try:
|
198
|
+
payload = ChangeGroupProfilePayload(
|
199
|
+
chat_id=chat_id,
|
200
|
+
theme=name,
|
201
|
+
description=description,
|
202
|
+
).model_dump(by_alias=True, exclude_none=True)
|
203
|
+
|
204
|
+
data = await self._send_and_wait(opcode=Opcode.CHAT_UPDATE, payload=payload)
|
205
|
+
|
206
|
+
if error := data.get("payload", {}).get("error"):
|
207
|
+
self.logger.error("Change group profile error: %s", error)
|
208
|
+
return
|
209
|
+
|
210
|
+
chat = Chat.from_dict(data["payload"]["chat"])
|
211
|
+
if chat:
|
212
|
+
cached_chat = await self._get_chat(chat.id)
|
213
|
+
if cached_chat is None:
|
214
|
+
self.chats.append(chat)
|
215
|
+
else:
|
216
|
+
idx = self.chats.index(cached_chat)
|
217
|
+
self.chats[idx] = chat
|
218
|
+
|
219
|
+
except Exception:
|
220
|
+
self.logger.exception("Change group profile failed")
|
pymax/mixins/handler.py
CHANGED
@@ -1,60 +1,60 @@
|
|
1
|
-
from typing import Any, Awaitable, Callable
|
2
|
-
|
3
|
-
from pymax.interfaces import ClientProtocol, Filter
|
4
|
-
from pymax.types import Message
|
5
|
-
|
6
|
-
|
7
|
-
class HandlerMixin(ClientProtocol):
|
8
|
-
def on_message(
|
9
|
-
self, *, filter: Filter | None = None
|
10
|
-
) -> Callable[
|
11
|
-
[Callable[[Any], Any | Awaitable[Any]]], Callable[[Any], Any | Awaitable[Any]]
|
12
|
-
]:
|
13
|
-
"""
|
14
|
-
Декоратор для установки обработчика входящих сообщений.
|
15
|
-
|
16
|
-
Args:
|
17
|
-
filter: Фильтр для обработки сообщений.
|
18
|
-
|
19
|
-
Returns:
|
20
|
-
Декоратор.
|
21
|
-
"""
|
22
|
-
|
23
|
-
def decorator(
|
24
|
-
handler: Callable[[Any], Any | Awaitable[Any]],
|
25
|
-
) -> Callable[[Any], Any | Awaitable[Any]]:
|
26
|
-
self._on_message_handlers.append((handler, filter))
|
27
|
-
self.logger.info(f"on_message handler set: {handler}, filter: {filter}")
|
28
|
-
return handler
|
29
|
-
|
30
|
-
return decorator
|
31
|
-
|
32
|
-
def on_start(
|
33
|
-
self, handler: Callable[[], Any | Awaitable[Any]]
|
34
|
-
) -> Callable[[], Any | Awaitable[Any]]:
|
35
|
-
"""
|
36
|
-
Устанавливает обработчик, вызываемый при старте клиента.
|
37
|
-
|
38
|
-
Args:
|
39
|
-
handler: Функция или coroutine без аргументов.
|
40
|
-
|
41
|
-
Returns:
|
42
|
-
Установленный обработчик.
|
43
|
-
"""
|
44
|
-
self._on_start_handler = handler
|
45
|
-
self.logger.debug("on_start handler set: %r", handler)
|
46
|
-
return handler
|
47
|
-
|
48
|
-
def add_message_handler(
|
49
|
-
self, handler: Callable[[Message], Any | Awaitable[Any]], filter: Filter | None
|
50
|
-
) -> Callable[[Message], Any | Awaitable[Any]]:
|
51
|
-
self.logger.debug("add_message_handler (alias) used")
|
52
|
-
self._on_message_handlers.append((handler, filter))
|
53
|
-
return handler
|
54
|
-
|
55
|
-
def add_on_start_handler(
|
56
|
-
self, handler: Callable[[], Any | Awaitable[Any]]
|
57
|
-
) -> Callable[[], Any | Awaitable[Any]]:
|
58
|
-
self.logger.debug("add_on_start_handler (alias) used")
|
59
|
-
self._on_start_handler = handler
|
60
|
-
return handler
|
1
|
+
from typing import Any, Awaitable, Callable
|
2
|
+
|
3
|
+
from pymax.interfaces import ClientProtocol, Filter
|
4
|
+
from pymax.types import Message
|
5
|
+
|
6
|
+
|
7
|
+
class HandlerMixin(ClientProtocol):
|
8
|
+
def on_message(
|
9
|
+
self, *, filter: Filter | None = None
|
10
|
+
) -> Callable[
|
11
|
+
[Callable[[Any], Any | Awaitable[Any]]], Callable[[Any], Any | Awaitable[Any]]
|
12
|
+
]:
|
13
|
+
"""
|
14
|
+
Декоратор для установки обработчика входящих сообщений.
|
15
|
+
|
16
|
+
Args:
|
17
|
+
filter: Фильтр для обработки сообщений.
|
18
|
+
|
19
|
+
Returns:
|
20
|
+
Декоратор.
|
21
|
+
"""
|
22
|
+
|
23
|
+
def decorator(
|
24
|
+
handler: Callable[[Any], Any | Awaitable[Any]],
|
25
|
+
) -> Callable[[Any], Any | Awaitable[Any]]:
|
26
|
+
self._on_message_handlers.append((handler, filter))
|
27
|
+
self.logger.info(f"on_message handler set: {handler}, filter: {filter}")
|
28
|
+
return handler
|
29
|
+
|
30
|
+
return decorator
|
31
|
+
|
32
|
+
def on_start(
|
33
|
+
self, handler: Callable[[], Any | Awaitable[Any]]
|
34
|
+
) -> Callable[[], Any | Awaitable[Any]]:
|
35
|
+
"""
|
36
|
+
Устанавливает обработчик, вызываемый при старте клиента.
|
37
|
+
|
38
|
+
Args:
|
39
|
+
handler: Функция или coroutine без аргументов.
|
40
|
+
|
41
|
+
Returns:
|
42
|
+
Установленный обработчик.
|
43
|
+
"""
|
44
|
+
self._on_start_handler = handler
|
45
|
+
self.logger.debug("on_start handler set: %r", handler)
|
46
|
+
return handler
|
47
|
+
|
48
|
+
def add_message_handler(
|
49
|
+
self, handler: Callable[[Message], Any | Awaitable[Any]], filter: Filter | None
|
50
|
+
) -> Callable[[Message], Any | Awaitable[Any]]:
|
51
|
+
self.logger.debug("add_message_handler (alias) used")
|
52
|
+
self._on_message_handlers.append((handler, filter))
|
53
|
+
return handler
|
54
|
+
|
55
|
+
def add_on_start_handler(
|
56
|
+
self, handler: Callable[[], Any | Awaitable[Any]]
|
57
|
+
) -> Callable[[], Any | Awaitable[Any]]:
|
58
|
+
self.logger.debug("add_on_start_handler (alias) used")
|
59
|
+
self._on_start_handler = handler
|
60
|
+
return handler
|