aiogram/aiogram/dispatcher/__init__.py

462 lines
16 KiB
Python
Raw Normal View History

2017-05-26 10:55:07 +03:00
import asyncio
import logging
from aiogram.utils.deprecated import deprecated
2017-06-02 08:50:23 +03:00
from .filters import CommandsFilter, RegexpFilter, ContentTypeFilter, generate_default_filters
from .handler import Handler, NextStepHandler
from .. import types
from ..bot import Bot
2017-05-27 03:09:14 +03:00
from ..types.message import ContentType
2017-05-26 10:55:07 +03:00
log = logging.getLogger(__name__)
# TODO: Fix functions (functools.wraps(func))
2017-05-26 10:55:07 +03:00
class Dispatcher:
"""
Simple Updates dispatcher
It will be can process incoming updates, messages, edited messages, channel posts, edited channels posts,
inline query, chosen inline result, callback query, shipping query, pre-checkout query.
Provide next step handler and etc.
"""
2017-05-27 03:09:14 +03:00
def __init__(self, bot, loop=None):
2017-07-11 23:41:40 +03:00
self.bot: 'Bot' = bot
2017-05-27 03:09:14 +03:00
if loop is None:
loop = self.bot.loop
self.loop = loop
2017-05-26 10:55:07 +03:00
self.last_update_id = 0
2017-06-02 08:50:23 +03:00
self.updates_handler = Handler(self)
self.message_handlers = Handler(self)
self.edited_message_handlers = Handler(self)
self.channel_post_handlers = Handler(self)
self.edited_channel_post_handlers = Handler(self)
self.inline_query_handlers = Handler(self)
self.chosen_inline_result_handlers = Handler(self)
self.callback_query_handlers = Handler(self)
self.shipping_query_handlers = Handler(self)
self.pre_checkout_query_handlers = Handler(self)
2017-05-26 10:55:07 +03:00
2017-06-02 08:50:23 +03:00
self.next_step_message_handlers = NextStepHandler(self)
self.updates_handler.register(self.process_update)
# self.message_handlers.register(self._notify_next_message)
self._pooling = False
def __del__(self):
2017-05-26 10:55:07 +03:00
self._pooling = False
async def skip_updates(self):
"""
You can skip old incoming updates from queue.
This method is not recomended to use if you use payments or you bot has high-load.
:return: count of skipped updates
"""
2017-05-26 10:55:07 +03:00
total = 0
updates = await self.bot.get_updates(offset=self.last_update_id, timeout=1)
while updates:
total += len(updates)
for update in updates:
if update.update_id > self.last_update_id:
self.last_update_id = update.update_id
updates = await self.bot.get_updates(offset=self.last_update_id + 1, timeout=1)
return total
async def process_updates(self, updates):
"""
Process list of updates
:param updates:
:return:
"""
2017-05-26 10:55:07 +03:00
for update in updates:
2017-06-02 08:50:23 +03:00
self.loop.create_task(self.updates_handler.notify(update))
2017-05-26 10:55:07 +03:00
async def process_update(self, update):
"""
Process single update object
:param update:
:return:
"""
2017-06-02 08:50:23 +03:00
self.last_update_id = update.update_id
2017-05-26 10:55:07 +03:00
if update.message:
2017-06-02 08:50:23 +03:00
if not await self.next_step_message_handlers.notify(update.message):
await self.message_handlers.notify(update.message)
if update.edited_message:
await self.edited_message_handlers.notify(update.edited_message)
if update.channel_post:
await self.channel_post_handlers.notify(update.channel_post)
if update.edited_channel_post:
await self.edited_channel_post_handlers.notify(update.edited_channel_post)
if update.inline_query:
await self.inline_query_handlers.notify(update.inline_query)
if update.chosen_inline_result:
await self.chosen_inline_result_handlers.notify(update.chosen_inline_result)
if update.callback_query:
await self.callback_query_handlers.notify(update.callback_query)
if update.shipping_query:
await self.shipping_query_handlers.notify(update.shipping_query)
if update.pre_checkout_query:
await self.pre_checkout_query_handlers.notify(update.pre_checkout_query)
2017-05-26 10:55:07 +03:00
async def start_pooling(self, timeout=20, relax=0.1):
"""
Start long-pooling
:param timeout:
:param relax:
:return:
"""
2017-05-26 10:55:07 +03:00
if self._pooling:
raise RuntimeError('Pooling already started')
2017-05-27 03:09:14 +03:00
log.info('Start pooling.')
2017-05-26 10:55:07 +03:00
self._pooling = True
offset = None
while self._pooling:
try:
updates = await self.bot.get_updates(offset=offset, timeout=timeout)
except Exception as e:
log.exception('Cause exception while getting updates')
await asyncio.sleep(relax)
continue
if updates:
2017-07-25 04:45:33 +03:00
log.info("Received {0} updates.".format(len(updates)))
2017-05-26 10:55:07 +03:00
offset = updates[-1].update_id + 1
await self.process_updates(updates)
await asyncio.sleep(relax)
2017-05-27 03:09:14 +03:00
log.warning('Pooling is stopped.')
2017-05-26 10:55:07 +03:00
def stop_pooling(self):
"""
Break long-pooling process.
:return:
"""
2017-05-26 10:55:07 +03:00
self._pooling = False
2017-05-27 03:09:14 +03:00
2017-06-02 19:41:35 +03:00
def message_handler(self, commands=None, regexp=None, content_types=None, func=None, custom_filters=None, **kwargs):
"""
Decorator for messages handler
Examples:
Simple commands handler:
.. code-block:: python3
@dp.messages_handler(commands=['start', 'welcome', 'about'])
async def cmd_handler(message: types.Message):
Filter messages by regular expression:
.. code-block:: python3
@dp.messages_handler(rexexp='^[a-z]+-[0-9]+')
async def msg_handler(message: types.Message):
Filter by content type:
.. code-block:: python3
@dp.messages_handler(content_types=ContentType.PHOTO | ContentType.DOCUMENT)
async def audio_handler(message: types.Message):
Filter by custom function:
.. code-block:: python3
@dp.messages_handler(func=lambda message: message.text and 'hello' in message.text.lower())
async def text_handler(message: types.Message):
Use multiple filters:
.. code-block:: python3
@dp.messages_handler(commands=['command'], content_types=ContentType.TEXT)
async def text_handler(message: types.Message):
Register multiple filters set for one handler:
.. code-block:: python3
p.messages_handler(commands=['command'])
@dp.messages_handler(func=lambda message: demojize(message.text) == ':new_moon_with_face:')
async def text_handler(message: types.Message):
This handler will be called if the message starts with '/command' OR is some emoji
By default content_type is :class:`ContentType.TEXT`
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param func: custom any callable object
:param custom_filters: list of custom filters
:param kwargs:
:return: decorated function
"""
2017-05-27 03:09:14 +03:00
if commands is None:
commands = []
2017-06-02 19:41:35 +03:00
if content_types is None:
content_types = ContentType.TEXT
2017-05-27 03:09:14 +03:00
if custom_filters is None:
custom_filters = []
2017-06-02 08:50:23 +03:00
filters_set = generate_default_filters(*custom_filters,
commands=commands,
regexp=regexp,
2017-06-02 19:41:35 +03:00
content_types=content_types,
2017-06-02 08:50:23 +03:00
func=func,
**kwargs)
2017-05-27 03:09:14 +03:00
def decorator(handler):
self.message_handlers.register(handler, filters_set)
return handler
2017-05-27 03:09:14 +03:00
2017-06-02 08:50:23 +03:00
return decorator
2017-05-27 03:09:14 +03:00
2017-06-02 19:41:35 +03:00
def edited_message_handler(self, commands=None, regexp=None, content_types=None, func=None, custom_filters=None,
2017-06-02 08:50:23 +03:00
**kwargs):
"""
Analog of message_handler but only for edited messages
You can use combination of different handlers
.. code-block:: python3
@dp.message_handler()
@dp.edited_message_handler()
async def msg_handler(message: types.Message):
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param func: custom any callable object
:param custom_filters: list of custom filters
:param kwargs:
:return: decorated function
"""
2017-06-02 08:50:23 +03:00
if commands is None:
commands = []
2017-06-02 19:41:35 +03:00
if content_types is None:
content_types = ContentType.TEXT
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
2017-05-27 03:09:14 +03:00
2017-06-02 08:50:23 +03:00
filters_set = generate_default_filters(*custom_filters,
commands=commands,
regexp=regexp,
2017-06-02 19:41:35 +03:00
content_types=content_types,
2017-06-02 08:50:23 +03:00
func=func,
**kwargs)
2017-05-27 03:09:14 +03:00
def decorator(handler):
self.edited_message_handlers.register(handler, filters_set)
return handler
2017-05-27 03:09:14 +03:00
return decorator
def channel_post_handler(self, commands=None, regexp=None, content_types=None, func=None, *custom_filters,
**kwargs):
"""
Register channels posts handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param func: custom any callable object
:param custom_filters: list of custom filters
:param kwargs:
:return: decorated function
"""
2017-06-02 08:50:23 +03:00
if commands is None:
commands = []
2017-06-02 19:41:35 +03:00
if content_types is None:
content_types = ContentType.TEXT
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
commands=commands,
regexp=regexp,
2017-06-02 19:41:35 +03:00
content_types=content_types,
2017-06-02 08:50:23 +03:00
func=func,
**kwargs)
def decorator(handler):
self.channel_post_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
2017-06-02 19:41:35 +03:00
def edited_channel_post_handler(self, commands=None, regexp=None, content_types=None, func=None, *custom_filters,
2017-06-02 08:50:23 +03:00
**kwargs):
"""
Register handler for edited channels posts
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param func: custom any callable object
:param custom_filters: list of custom filters
:param kwargs:
:return: decorated function
"""
2017-06-02 08:50:23 +03:00
if commands is None:
commands = []
2017-06-02 19:41:35 +03:00
if content_types is None:
content_types = ContentType.TEXT
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
commands=commands,
regexp=regexp,
2017-06-02 19:41:35 +03:00
content_types=content_types,
2017-06-02 08:50:23 +03:00
func=func,
**kwargs)
def decorator(handler):
self.edited_channel_post_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
def inline_handler(self, func=None, *custom_filters, **kwargs):
"""
Handle inline query
Example:
.. code-block:: python3
@dp.inline_handler(func=lambda inline_query: True)
async def handler(inline_query: types.InlineQuery)
:param func: custom any callable object
:param custom_filters: list of custom filters
:param kwargs:
:return: decorated function
"""
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
func=func,
**kwargs)
def decorator(handler):
self.inline_query_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
def chosen_inline_handler(self, func=None, *custom_filters, **kwargs):
"""
Register chosen inline handler
Example:
.. code-block:: python3
@dp.chosen_inline_handler(func=lambda chosen_inline_query: True)
async def handler(chosen_inline_query: types.ChosenInlineResult)
:param func: custom any callable object
:param custom_filters:
:param kwargs:
:return:
"""
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
func=func,
**kwargs)
def decorator(handler):
self.chosen_inline_result_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
def callback_query_handler(self, func=None, *custom_filters, **kwargs):
"""
Add callback query handler
Example:
.. code-block:: python3
@dp.callback_query_handler(func=lambda callback_query: True)
async def handler(callback_query: types.CallbackQuery)
:param func: custom any callable object
:param custom_filters:
:param kwargs:
"""
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
func=func,
**kwargs)
def decorator(handler):
self.chosen_inline_result_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
def shipping_query_handler(self, func=None, *custom_filters, **kwargs):
"""
Add shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(func=lambda shipping_query: True)
async def handler(shipping_query: types.ShippingQuery)
:param func: custom any callable object
:param custom_filters:
:param kwargs:
"""
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
func=func,
**kwargs)
def decorator(handler):
self.shipping_query_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
def pre_checkout_query_handler(self, func=None, *custom_filters, **kwargs):
"""
Add shipping query handler
Example:
.. code-block:: python3
@dp.shipping_query_handler(func=lambda shipping_query: True)
async def handler(shipping_query: types.ShippingQuery)
:param func: custom any callable object
:param custom_filters:
:param kwargs:
"""
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
func=func,
**kwargs)
def decorator(handler):
self.pre_checkout_query_handlers.register(handler, filters_set)
return handler
2017-06-02 08:50:23 +03:00
return decorator
@deprecated("Use FSM instead of next step message handler.")
2017-06-03 10:50:48 +03:00
async def next_message(self, message: types.Message, otherwise=None, once=False, include_cancel=True,
2017-06-02 19:41:35 +03:00
regexp=None, content_types=None, func=None, custom_filters=None, **kwargs):
if content_types is None:
content_types = []
2017-06-02 08:50:23 +03:00
if custom_filters is None:
custom_filters = []
filters_set = generate_default_filters(*custom_filters,
regexp=regexp,
2017-06-02 19:41:35 +03:00
content_types=content_types,
2017-06-02 08:50:23 +03:00
func=func,
**kwargs)
2017-06-03 10:50:48 +03:00
self.next_step_message_handlers.register(message, otherwise, once, include_cancel, filters_set)
2017-06-02 08:50:23 +03:00
return await self.next_step_message_handlers.wait(message)