forked from pyrogram/pyrogram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdispatcher.py
More file actions
371 lines (314 loc) · 13.1 KB
/
dispatcher.py
File metadata and controls
371 lines (314 loc) · 13.1 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import inspect
import logging
from collections import OrderedDict
import pyrogram
from pyrogram import utils
from pyrogram import raw
from pyrogram import errors
from pyrogram.handlers import (
CallbackQueryHandler,
MessageHandler,
EditedMessageHandler,
DeletedMessagesHandler,
UserStatusHandler,
RawUpdateHandler,
InlineQueryHandler,
PollHandler,
ChosenInlineResultHandler,
ChatMemberUpdatedHandler,
ChatJoinRequestHandler,
)
from pyrogram.raw.types import (
UpdateNewMessage,
UpdateNewChannelMessage,
UpdateNewScheduledMessage,
UpdateEditMessage,
UpdateEditChannelMessage,
UpdateDeleteMessages,
UpdateDeleteChannelMessages,
UpdateBotCallbackQuery,
UpdateInlineBotCallbackQuery,
UpdateUserStatus,
UpdateBotInlineQuery,
UpdateMessagePoll,
UpdateBotInlineSend,
UpdateChatParticipant,
UpdateChannelParticipant,
UpdateBotChatInviteRequester,
)
log = logging.getLogger(__name__)
class Dispatcher:
NEW_MESSAGE_UPDATES = (
UpdateNewMessage,
UpdateNewChannelMessage,
UpdateNewScheduledMessage,
)
EDIT_MESSAGE_UPDATES = (UpdateEditMessage, UpdateEditChannelMessage)
DELETE_MESSAGES_UPDATES = (UpdateDeleteMessages, UpdateDeleteChannelMessages)
CALLBACK_QUERY_UPDATES = (UpdateBotCallbackQuery, UpdateInlineBotCallbackQuery)
CHAT_MEMBER_UPDATES = (UpdateChatParticipant, UpdateChannelParticipant)
USER_STATUS_UPDATES = (UpdateUserStatus,)
BOT_INLINE_QUERY_UPDATES = (UpdateBotInlineQuery,)
POLL_UPDATES = (UpdateMessagePoll,)
CHOSEN_INLINE_RESULT_UPDATES = (UpdateBotInlineSend,)
CHAT_JOIN_REQUEST_UPDATES = (UpdateBotChatInviteRequester,)
def __init__(self, client: "pyrogram.Client"):
self.client = client
self.loop = asyncio.get_event_loop()
self.handler_worker_tasks = []
self.locks_list = []
self.updates_queue = asyncio.Queue()
self.groups = OrderedDict()
async def message_parser(update, users, chats):
return (
await pyrogram.types.Message._parse(
self.client,
update.message,
users,
chats,
isinstance(update, UpdateNewScheduledMessage),
),
MessageHandler,
)
async def edited_message_parser(update, users, chats):
# Edited messages are parsed the same way as new messages, but the handler is different
parsed, _ = await message_parser(update, users, chats)
return (parsed, EditedMessageHandler)
async def deleted_messages_parser(update, users, chats):
return (
utils.parse_deleted_messages(self.client, update),
DeletedMessagesHandler,
)
async def callback_query_parser(update, users, chats):
return (
await pyrogram.types.CallbackQuery._parse(self.client, update, users),
CallbackQueryHandler,
)
async def user_status_parser(update, users, chats):
return (
pyrogram.types.User._parse_user_status(self.client, update),
UserStatusHandler,
)
async def inline_query_parser(update, users, chats):
return (
pyrogram.types.InlineQuery._parse(self.client, update, users),
InlineQueryHandler,
)
async def poll_parser(update, users, chats):
return (pyrogram.types.Poll._parse_update(self.client, update), PollHandler)
async def chosen_inline_result_parser(update, users, chats):
return (
pyrogram.types.ChosenInlineResult._parse(self.client, update, users),
ChosenInlineResultHandler,
)
async def chat_member_updated_parser(update, users, chats):
return (
pyrogram.types.ChatMemberUpdated._parse(
self.client, update, users, chats
),
ChatMemberUpdatedHandler,
)
async def chat_join_request_parser(update, users, chats):
return (
pyrogram.types.ChatJoinRequest._parse(
self.client, update, users, chats
),
ChatJoinRequestHandler,
)
self.update_parsers = {
Dispatcher.NEW_MESSAGE_UPDATES: message_parser,
Dispatcher.EDIT_MESSAGE_UPDATES: edited_message_parser,
Dispatcher.DELETE_MESSAGES_UPDATES: deleted_messages_parser,
Dispatcher.CALLBACK_QUERY_UPDATES: callback_query_parser,
Dispatcher.USER_STATUS_UPDATES: user_status_parser,
Dispatcher.BOT_INLINE_QUERY_UPDATES: inline_query_parser,
Dispatcher.POLL_UPDATES: poll_parser,
Dispatcher.CHOSEN_INLINE_RESULT_UPDATES: chosen_inline_result_parser,
Dispatcher.CHAT_MEMBER_UPDATES: chat_member_updated_parser,
Dispatcher.CHAT_JOIN_REQUEST_UPDATES: chat_join_request_parser,
}
self.update_parsers = {
key: value
for key_tuple, value in self.update_parsers.items()
for key in key_tuple
}
async def start(self):
if not self.client.no_updates:
for i in range(self.client.workers):
self.locks_list.append(asyncio.Lock())
self.handler_worker_tasks.append(
self.loop.create_task(self.handler_worker(self.locks_list[-1]))
)
log.info("Started %s HandlerTasks", self.client.workers)
async def stop(self):
if not self.client.no_updates:
for i in range(self.client.workers):
self.updates_queue.put_nowait(None)
for i in self.handler_worker_tasks:
await i
self.handler_worker_tasks.clear()
self.groups.clear()
log.info("Stopped %s HandlerTasks", self.client.workers)
def add_handler(self, handler, group: int):
async def fn():
for lock in self.locks_list:
await lock.acquire()
try:
if group not in self.groups:
self.groups[group] = []
self.groups = OrderedDict(sorted(self.groups.items()))
self.groups[group].append(handler)
finally:
for lock in self.locks_list:
lock.release()
self.loop.create_task(fn())
def remove_handler(self, handler, group: int):
async def fn():
for lock in self.locks_list:
await lock.acquire()
try:
if group not in self.groups:
raise ValueError(
f"Group {group} does not exist. Handler was not removed."
)
self.groups[group].remove(handler)
finally:
for lock in self.locks_list:
lock.release()
self.loop.create_task(fn())
async def handler_worker(self, lock):
while True:
packet = await self.updates_queue.get()
if packet is None:
break
try:
update, users, chats = packet
parser = self.update_parsers.get(type(update), None)
parsed_update, handler_type = (
await parser(update, users, chats)
if parser is not None
else (None, type(None))
)
async with lock:
for group in self.groups.values():
for handler in group:
args = None
if isinstance(handler, handler_type):
try:
if await handler.check(self.client, parsed_update):
args = (parsed_update,)
except Exception as e:
log.exception(e)
continue
elif isinstance(handler, RawUpdateHandler):
args = (update, users, chats)
if args is None:
continue
try:
if inspect.iscoroutinefunction(handler.callback):
await handler.callback(self.client, *args)
else:
await self.loop.run_in_executor(
self.client.executor,
handler.callback,
self.client,
*args,
)
except pyrogram.StopPropagation:
raise
except pyrogram.ContinuePropagation:
continue
except Exception as e:
log.exception(e)
break
except pyrogram.StopPropagation:
pass
except Exception as e:
log.exception(e)
async def _process_diff(self, state: tuple) -> tuple[int, int] | None:
id, local_pts, local_qts, local_date, local_seq = state
try:
diff = await self.client.invoke(
raw.functions.updates.GetChannelDifference(
channel=await self.client.resolve_peer(id),
filter=raw.types.ChannelMessagesFilterEmpty(),
pts=local_pts,
limit=10_000,
)
if id != 0
else raw.functions.updates.GetDifference(
pts=local_pts, date=local_date, qts=0
)
)
except (errors.ChannelPrivate, errors.ChannelInvalid):
await self.client.storage.delete_state(id)
return
if isinstance(diff, raw.types.updates.DifferenceEmpty):
return
elif isinstance(diff, raw.types.updates.DifferenceTooLong):
return
elif isinstance(diff, raw.types.updates.ChannelDifferenceEmpty):
return
elif isinstance(diff, raw.types.updates.ChannelDifferenceTooLong):
return
elif isinstance(diff, raw.types.updates.Difference):
local_pts = diff.state.pts
elif isinstance(diff, raw.types.updates.ChannelDifference):
local_qts = diff.pts
elif isinstance(diff, raw.types.updates.DifferenceSlice):
if diff.intermediate_state.pts == local_pts:
return
local_pts = diff.intermediate_state.pts
local_date = diff.intermediate_state.date
await self._process_diff((id, local_pts, local_qts, local_date, local_seq))
return
users = {i.id: i for i in diff.users}
chats = {i.id: i for i in diff.chats}
for message in diff.new_messages:
self.updates_queue.put_nowait(
(
raw.types.UpdateNewMessage(
message=message, pts=local_pts, pts_count=-1
)
if id == 0
else raw.types.UpdateNewChannelMessage(
message=message, pts=local_pts, pts_count=-1
),
users,
chats,
)
)
for update in diff.other_updates:
self.updates_queue.put_nowait((update, users, chats))
await self.client.storage.update_state(
(id, local_pts, local_qts, local_date, local_seq)
)
return len(diff.new_messages), len(diff.other_updates)
async def fill_difference_gap(self):
states = await self.client.storage.get_states()
messages_count = updates_count = 0
for state in states:
result = await self._process_diff(state)
if result is not None:
m, u = result
messages_count += m
updates_count += u
log.info("Recovered %s messages and %s updates", messages_count, updates_count)