MTPyroger/pyrogram/client/dispatcher/dispatcher.py

183 lines
6.5 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
import pyrogram
from pyrogram.api import types
from ..ext import utils
2018-04-28 21:48:38 +00:00
from ..handlers import RawUpdateHandler, CallbackQueryHandler, MessageHandler
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-04-28 21:48:38 +00:00
MESSAGE_UPDATES = NEW_MESSAGE_UPDATES + EDIT_MESSAGE_UPDATES
2018-04-08 10:43:47 +00:00
2018-04-06 16:36:29 +00:00
def __init__(self, client, workers):
self.client = client
self.workers = workers
self.update_worker_tasks = []
2018-06-17 16:41:07 +00:00
self.updates = asyncio.Queue()
self.groups = OrderedDict()
2018-04-06 16:36:29 +00:00
2018-06-17 16:41:07 +00:00
async def start(self):
for i in range(self.workers):
self.update_worker_tasks.append(
asyncio.ensure_future(self.update_worker())
)
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.put_nowait(None)
for i in self.update_worker_tasks:
await i
self.update_worker_tasks.clear()
log.info("Stopped {} UpdateWorkerTasks".format(self.workers))
2018-04-11 01:16:48 +00:00
def add_handler(self, handler, group: int):
2018-05-26 16:04:17 +00:00
if group not in self.groups:
self.groups[group] = []
self.groups = OrderedDict(sorted(self.groups.items()))
2018-04-10 12:52:31 +00:00
2018-05-26 16:04:17 +00:00
self.groups[group].append(handler)
2018-04-06 16:36:29 +00:00
def remove_handler(self, handler, group: int):
2018-05-26 16:04:17 +00:00
if group not in self.groups:
raise ValueError("Group {} does not exist. "
"Handler was not removed.".format(group))
self.groups[group].remove(handler)
2018-06-17 16:41:07 +00:00
async def dispatch(self, update, users: dict = None, chats: dict = None, is_raw: bool = False):
tasks = []
2018-05-26 16:04:17 +00:00
for group in self.groups.values():
for handler in group:
if is_raw:
if not isinstance(handler, RawUpdateHandler):
continue
args = (self.client, update, users, chats)
else:
message = (update.message
or update.channel_post
or update.edited_message
or update.edited_channel_post)
callback_query = update.callback_query
if message and isinstance(handler, MessageHandler):
if not handler.check(message):
2018-04-28 21:48:38 +00:00
continue
2018-05-26 16:04:17 +00:00
args = (self.client, message)
elif callback_query and isinstance(handler, CallbackQueryHandler):
if not handler.check(callback_query):
continue
2018-05-26 16:04:17 +00:00
args = (self.client, callback_query)
else:
continue
2018-06-17 16:41:07 +00:00
tasks.append(handler.callback(*args))
2018-05-26 16:04:17 +00:00
break
2018-04-06 16:36:29 +00:00
2018-06-17 16:41:07 +00:00
await asyncio.gather(*tasks)
async def update_worker(self):
2018-04-06 16:36:29 +00:00
while True:
2018-06-17 16:41:07 +00:00
update = await self.updates.get()
2018-04-06 16:36:29 +00:00
if update is None:
break
try:
users = {i.id: i for i in update[1]}
chats = {i.id: i for i in update[2]}
update = update[0]
2018-06-18 19:12:04 +00:00
await self.dispatch(update, users=users, chats=chats, is_raw=True)
2018-04-08 11:20:31 +00:00
2018-04-28 21:48:38 +00:00
if isinstance(update, Dispatcher.MESSAGE_UPDATES):
2018-05-09 19:40:24 +00:00
if isinstance(update.message, types.MessageEmpty):
continue
2018-06-18 19:12:04 +00:00
message = await utils.parse_messages(
2018-04-08 10:43:47 +00:00
self.client,
update.message,
users,
chats
)
2018-04-06 16:36:29 +00:00
2018-04-28 21:48:38 +00:00
is_edited_message = isinstance(update, Dispatcher.EDIT_MESSAGE_UPDATES)
2018-06-18 19:12:04 +00:00
await self.dispatch(
2018-04-28 21:48:38 +00:00
pyrogram.Update(
message=((message if message.chat.type != "channel"
else None) if not is_edited_message
else None),
edited_message=((message if message.chat.type != "channel"
else None) if is_edited_message
else None),
channel_post=((message if message.chat.type == "channel"
else None) if not is_edited_message
else None),
edited_channel_post=((message if message.chat.type == "channel"
else None) if is_edited_message
else None)
)
2018-06-18 19:12:04 +00:00
)
2018-04-28 21:48:38 +00:00
elif isinstance(update, types.UpdateBotCallbackQuery):
2018-06-18 19:12:04 +00:00
await self.dispatch(
2018-04-28 21:48:38 +00:00
pyrogram.Update(
2018-06-18 19:12:04 +00:00
callback_query=await utils.parse_callback_query(
self.client, update, users
2018-04-28 21:48:38 +00:00
)
)
2018-06-18 19:12:04 +00:00
)
2018-06-06 10:29:21 +00:00
elif isinstance(update, types.UpdateInlineBotCallbackQuery):
2018-06-18 19:12:04 +00:00
await self.dispatch(
2018-06-06 10:29:21 +00:00
pyrogram.Update(
2018-06-18 19:12:04 +00:00
callback_query=await utils.parse_inline_callback_query(
2018-06-06 10:29:21 +00:00
update, users
)
)
2018-06-18 19:12:04 +00:00
)
2018-04-28 21:48:38 +00:00
else:
continue
2018-04-06 16:36:29 +00:00
except Exception as e:
log.error(e, exc_info=True)