MTPyroger/pyrogram/client/ext/dispatcher.py

196 lines
6.7 KiB
Python
Raw Normal View History

2018-04-06 16:36:29 +00:00
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <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/>.
2018-06-17 16:41:07 +00:00
import asyncio
2018-04-06 16:36:29 +00:00
import logging
from collections import OrderedDict
2018-12-17 15:40:06 +00:00
import pyrogram
2018-04-06 16:36:29 +00:00
from pyrogram.api import types
2019-06-08 13:28:03 +00:00
from . import utils
2018-11-09 12:08:28 +00:00
from ..handlers import (
CallbackQueryHandler, MessageHandler, DeletedMessagesHandler,
UserStatusHandler, RawUpdateHandler, InlineQueryHandler, PollHandler
2018-11-09 12:08:28 +00:00
)
2018-04-06 16:36:29 +00:00
log = logging.getLogger(__name__)
class Dispatcher:
2018-04-28 21:48:38 +00:00
NEW_MESSAGE_UPDATES = (
2018-04-08 10:43:47 +00:00
types.UpdateNewMessage,
types.UpdateNewChannelMessage
)
2018-04-28 21:48:38 +00:00
EDIT_MESSAGE_UPDATES = (
2018-04-08 10:43:47 +00:00
types.UpdateEditMessage,
types.UpdateEditChannelMessage
)
2018-12-17 15:40:06 +00:00
DELETE_MESSAGES_UPDATES = (
2018-06-19 14:18:12 +00:00
types.UpdateDeleteMessages,
types.UpdateDeleteChannelMessages
)
CALLBACK_QUERY_UPDATES = (
types.UpdateBotCallbackQuery,
types.UpdateInlineBotCallbackQuery
)
2018-04-28 21:48:38 +00:00
MESSAGE_UPDATES = NEW_MESSAGE_UPDATES + EDIT_MESSAGE_UPDATES
2018-04-08 10:43:47 +00:00
def __init__(self, client, workers: int):
2018-04-06 16:36:29 +00:00
self.client = client
self.workers = workers
self.update_worker_tasks = []
self.locks_list = []
self.updates_queue = asyncio.Queue()
2018-06-17 16:41:07 +00:00
self.groups = OrderedDict()
2018-04-06 16:36:29 +00:00
2018-11-09 09:10:26 +00:00
async def message_parser(update, users, chats):
Merge branch 'develop' into asyncio # Conflicts: # pyrogram/client/client.py # pyrogram/client/dispatcher/dispatcher.py # pyrogram/client/ext/utils.py # pyrogram/client/methods/bots/get_inline_bot_results.py # pyrogram/client/methods/bots/request_callback_answer.py # pyrogram/client/methods/bots/send_inline_bot_result.py # pyrogram/client/methods/chats/delete_chat_photo.py # pyrogram/client/methods/chats/export_chat_invite_link.py # pyrogram/client/methods/chats/get_chat.py # pyrogram/client/methods/chats/get_chat_member.py # pyrogram/client/methods/chats/get_chat_members.py # pyrogram/client/methods/chats/get_chat_members_count.py # pyrogram/client/methods/chats/get_dialogs.py # pyrogram/client/methods/chats/join_chat.py # pyrogram/client/methods/chats/kick_chat_member.py # pyrogram/client/methods/chats/leave_chat.py # pyrogram/client/methods/chats/pin_chat_message.py # pyrogram/client/methods/chats/promote_chat_member.py # pyrogram/client/methods/chats/restrict_chat_member.py # pyrogram/client/methods/chats/set_chat_description.py # pyrogram/client/methods/chats/set_chat_photo.py # pyrogram/client/methods/chats/set_chat_title.py # pyrogram/client/methods/chats/unban_chat_member.py # pyrogram/client/methods/chats/unpin_chat_message.py # pyrogram/client/methods/contacts/add_contacts.py # pyrogram/client/methods/contacts/delete_contacts.py # pyrogram/client/methods/messages/delete_messages.py # pyrogram/client/methods/messages/edit_message_caption.py # pyrogram/client/methods/messages/edit_message_media.py # pyrogram/client/methods/messages/edit_message_reply_markup.py # pyrogram/client/methods/messages/edit_message_text.py # pyrogram/client/methods/messages/forward_messages.py # pyrogram/client/methods/messages/get_history.py # pyrogram/client/methods/messages/get_messages.py # pyrogram/client/methods/messages/send_animation.py # pyrogram/client/methods/messages/send_audio.py # pyrogram/client/methods/messages/send_chat_action.py # pyrogram/client/methods/messages/send_contact.py # pyrogram/client/methods/messages/send_document.py # pyrogram/client/methods/messages/send_location.py # pyrogram/client/methods/messages/send_media_group.py # pyrogram/client/methods/messages/send_message.py # pyrogram/client/methods/messages/send_photo.py # pyrogram/client/methods/messages/send_sticker.py # pyrogram/client/methods/messages/send_venue.py # pyrogram/client/methods/messages/send_video.py # pyrogram/client/methods/messages/send_video_note.py # pyrogram/client/methods/messages/send_voice.py # pyrogram/client/methods/password/change_cloud_password.py # pyrogram/client/methods/password/enable_cloud_password.py # pyrogram/client/methods/password/remove_cloud_password.py # pyrogram/client/methods/users/delete_user_profile_photos.py # pyrogram/client/methods/users/get_me.py # pyrogram/client/methods/users/get_user_profile_photos.py # pyrogram/client/methods/users/get_users.py # pyrogram/client/methods/utilities/download_media.py # pyrogram/client/types/messages_and_media/message.py
2018-12-22 11:23:08 +00:00
return await pyrogram.Message._parse(self.client, update.message, users, chats), MessageHandler
2018-11-09 09:10:26 +00:00
async def deleted_messages_parser(update, users, chats):
2019-06-20 02:17:24 +00:00
return utils.parse_deleted_messages(self.client, update), DeletedMessagesHandler
2018-11-09 09:10:26 +00:00
async def callback_query_parser(update, users, chats):
Merge branch 'develop' into asyncio # Conflicts: # pyrogram/client/client.py # pyrogram/client/dispatcher/dispatcher.py # pyrogram/client/ext/utils.py # pyrogram/client/methods/bots/get_inline_bot_results.py # pyrogram/client/methods/bots/request_callback_answer.py # pyrogram/client/methods/bots/send_inline_bot_result.py # pyrogram/client/methods/chats/delete_chat_photo.py # pyrogram/client/methods/chats/export_chat_invite_link.py # pyrogram/client/methods/chats/get_chat.py # pyrogram/client/methods/chats/get_chat_member.py # pyrogram/client/methods/chats/get_chat_members.py # pyrogram/client/methods/chats/get_chat_members_count.py # pyrogram/client/methods/chats/get_dialogs.py # pyrogram/client/methods/chats/join_chat.py # pyrogram/client/methods/chats/kick_chat_member.py # pyrogram/client/methods/chats/leave_chat.py # pyrogram/client/methods/chats/pin_chat_message.py # pyrogram/client/methods/chats/promote_chat_member.py # pyrogram/client/methods/chats/restrict_chat_member.py # pyrogram/client/methods/chats/set_chat_description.py # pyrogram/client/methods/chats/set_chat_photo.py # pyrogram/client/methods/chats/set_chat_title.py # pyrogram/client/methods/chats/unban_chat_member.py # pyrogram/client/methods/chats/unpin_chat_message.py # pyrogram/client/methods/contacts/add_contacts.py # pyrogram/client/methods/contacts/delete_contacts.py # pyrogram/client/methods/messages/delete_messages.py # pyrogram/client/methods/messages/edit_message_caption.py # pyrogram/client/methods/messages/edit_message_media.py # pyrogram/client/methods/messages/edit_message_reply_markup.py # pyrogram/client/methods/messages/edit_message_text.py # pyrogram/client/methods/messages/forward_messages.py # pyrogram/client/methods/messages/get_history.py # pyrogram/client/methods/messages/get_messages.py # pyrogram/client/methods/messages/send_animation.py # pyrogram/client/methods/messages/send_audio.py # pyrogram/client/methods/messages/send_chat_action.py # pyrogram/client/methods/messages/send_contact.py # pyrogram/client/methods/messages/send_document.py # pyrogram/client/methods/messages/send_location.py # pyrogram/client/methods/messages/send_media_group.py # pyrogram/client/methods/messages/send_message.py # pyrogram/client/methods/messages/send_photo.py # pyrogram/client/methods/messages/send_sticker.py # pyrogram/client/methods/messages/send_venue.py # pyrogram/client/methods/messages/send_video.py # pyrogram/client/methods/messages/send_video_note.py # pyrogram/client/methods/messages/send_voice.py # pyrogram/client/methods/password/change_cloud_password.py # pyrogram/client/methods/password/enable_cloud_password.py # pyrogram/client/methods/password/remove_cloud_password.py # pyrogram/client/methods/users/delete_user_profile_photos.py # pyrogram/client/methods/users/get_me.py # pyrogram/client/methods/users/get_user_profile_photos.py # pyrogram/client/methods/users/get_users.py # pyrogram/client/methods/utilities/download_media.py # pyrogram/client/types/messages_and_media/message.py
2018-12-22 11:23:08 +00:00
return await pyrogram.CallbackQuery._parse(self.client, update, users), CallbackQueryHandler
2018-11-09 09:10:26 +00:00
async def user_status_parser(update, users, chats):
Merge branch 'develop' into asyncio # Conflicts: # pyrogram/client/client.py # pyrogram/client/dispatcher/dispatcher.py # pyrogram/client/ext/utils.py # pyrogram/client/methods/bots/get_inline_bot_results.py # pyrogram/client/methods/bots/request_callback_answer.py # pyrogram/client/methods/bots/send_inline_bot_result.py # pyrogram/client/methods/chats/delete_chat_photo.py # pyrogram/client/methods/chats/export_chat_invite_link.py # pyrogram/client/methods/chats/get_chat.py # pyrogram/client/methods/chats/get_chat_member.py # pyrogram/client/methods/chats/get_chat_members.py # pyrogram/client/methods/chats/get_chat_members_count.py # pyrogram/client/methods/chats/get_dialogs.py # pyrogram/client/methods/chats/join_chat.py # pyrogram/client/methods/chats/kick_chat_member.py # pyrogram/client/methods/chats/leave_chat.py # pyrogram/client/methods/chats/pin_chat_message.py # pyrogram/client/methods/chats/promote_chat_member.py # pyrogram/client/methods/chats/restrict_chat_member.py # pyrogram/client/methods/chats/set_chat_description.py # pyrogram/client/methods/chats/set_chat_photo.py # pyrogram/client/methods/chats/set_chat_title.py # pyrogram/client/methods/chats/unban_chat_member.py # pyrogram/client/methods/chats/unpin_chat_message.py # pyrogram/client/methods/contacts/add_contacts.py # pyrogram/client/methods/contacts/delete_contacts.py # pyrogram/client/methods/messages/delete_messages.py # pyrogram/client/methods/messages/edit_message_caption.py # pyrogram/client/methods/messages/edit_message_media.py # pyrogram/client/methods/messages/edit_message_reply_markup.py # pyrogram/client/methods/messages/edit_message_text.py # pyrogram/client/methods/messages/forward_messages.py # pyrogram/client/methods/messages/get_history.py # pyrogram/client/methods/messages/get_messages.py # pyrogram/client/methods/messages/send_animation.py # pyrogram/client/methods/messages/send_audio.py # pyrogram/client/methods/messages/send_chat_action.py # pyrogram/client/methods/messages/send_contact.py # pyrogram/client/methods/messages/send_document.py # pyrogram/client/methods/messages/send_location.py # pyrogram/client/methods/messages/send_media_group.py # pyrogram/client/methods/messages/send_message.py # pyrogram/client/methods/messages/send_photo.py # pyrogram/client/methods/messages/send_sticker.py # pyrogram/client/methods/messages/send_venue.py # pyrogram/client/methods/messages/send_video.py # pyrogram/client/methods/messages/send_video_note.py # pyrogram/client/methods/messages/send_voice.py # pyrogram/client/methods/password/change_cloud_password.py # pyrogram/client/methods/password/enable_cloud_password.py # pyrogram/client/methods/password/remove_cloud_password.py # pyrogram/client/methods/users/delete_user_profile_photos.py # pyrogram/client/methods/users/get_me.py # pyrogram/client/methods/users/get_user_profile_photos.py # pyrogram/client/methods/users/get_users.py # pyrogram/client/methods/utilities/download_media.py # pyrogram/client/types/messages_and_media/message.py
2018-12-22 11:23:08 +00:00
return pyrogram.UserStatus._parse(self.client, update.status, update.user_id), UserStatusHandler
async def inline_query_parser(update, users, chats):
return pyrogram.InlineQuery._parse(self.client, update, users), InlineQueryHandler
2018-11-09 12:08:28 +00:00
2019-05-06 15:27:21 +00:00
async def poll_parser(update, users, chats):
return pyrogram.Poll._parse_update(self.client, update), PollHandler
self.update_parsers = {
2018-11-09 09:10:26 +00:00
Dispatcher.MESSAGE_UPDATES: message_parser,
Dispatcher.DELETE_MESSAGES_UPDATES: deleted_messages_parser,
2018-11-09 09:10:26 +00:00
Dispatcher.CALLBACK_QUERY_UPDATES: callback_query_parser,
(types.UpdateUserStatus,): user_status_parser,
2019-05-06 15:27:21 +00:00
(types.UpdateBotInlineQuery,): inline_query_parser,
(types.UpdateMessagePoll,): poll_parser
}
self.update_parsers = {key: value for key_tuple, value in self.update_parsers.items() for key in key_tuple}
2018-06-17 16:41:07 +00:00
async def start(self):
for i in range(self.workers):
self.locks_list.append(asyncio.Lock())
self.update_worker_tasks.append(
asyncio.ensure_future(self.update_worker(self.locks_list[-1]))
)
log.info("Started {} UpdateWorkerTasks".format(self.workers))
2018-06-17 16:41:07 +00:00
async def stop(self):
for i in range(self.workers):
self.updates_queue.put_nowait(None)
for i in self.update_worker_tasks:
await i
self.update_worker_tasks.clear()
self.groups.clear()
log.info("Stopped {} UpdateWorkerTasks".format(self.workers))
2018-04-11 01:16:48 +00:00
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()))
2018-04-10 12:52:31 +00:00
self.groups[group].append(handler)
finally:
for lock in self.locks_list:
lock.release()
asyncio.get_event_loop().run_until_complete(fn())
2018-04-06 16:36:29 +00:00
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("Group {} does not exist. Handler was not removed.".format(group))
self.groups[group].remove(handler)
finally:
for lock in self.locks_list:
lock.release()
2018-04-28 21:48:38 +00:00
asyncio.get_event_loop().run_until_complete(fn())
2018-06-17 16:41:07 +00:00
async def update_worker(self, lock):
2018-04-06 16:36:29 +00:00
while True:
2019-06-02 17:13:17 +00:00
packet = await self.updates_queue.get()
2018-04-06 16:36:29 +00:00
2019-06-01 11:18:48 +00:00
if packet is None:
2018-04-06 16:36:29 +00:00
break
try:
2019-06-01 11:18:48 +00:00
update, users, chats = packet
parser = self.update_parsers.get(type(update), None)
2018-06-19 14:18:12 +00:00
parsed_update, handler_type = (
await parser(update, users, chats)
if parser is not None
else (None, type(None))
)
async with lock:
2019-06-20 23:53:17 +00:00
for group in self.groups.values():
for handler in group:
args = None
if isinstance(handler, handler_type):
if handler.check(parsed_update):
args = (parsed_update,)
elif isinstance(handler, RawUpdateHandler):
args = (update, users, chats)
if args is None:
continue
try:
2019-06-21 00:04:16 +00:00
await handler.callback(self.client, *args)
2019-06-20 23:53:17 +00:00
except pyrogram.StopPropagation:
raise
except pyrogram.ContinuePropagation:
continue
except Exception as e:
log.error(e, exc_info=True)
break
except pyrogram.StopPropagation:
pass
2018-04-06 16:36:29 +00:00
except Exception as e:
log.error(e, exc_info=True)