From 1f05b47ad663c50dba6f7cc60ffa0b0f8394b377 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 20 Nov 2021 15:47:55 +0500 Subject: [PATCH] Asynchronous Telebot --- telebot/__init__.py | 3073 ++++++++++++++++++++++++--- telebot/asyncio_filters.py | 176 ++ telebot/asyncio_handler_backends.py | 343 +++ telebot/asyncio_helper.py | 1607 ++++++++++++++ 4 files changed, 4937 insertions(+), 262 deletions(-) create mode 100644 telebot/asyncio_filters.py create mode 100644 telebot/asyncio_handler_backends.py create mode 100644 telebot/asyncio_helper.py diff --git a/telebot/__init__.py b/telebot/__init__.py index cab3714..65906f2 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -12,10 +12,9 @@ from typing import Any, Callable, List, Optional, Union # this imports are used to avoid circular import error import telebot.util import telebot.types -from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter - logger = logging.getLogger('TeleBot') + formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' ) @@ -26,8 +25,13 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) -from telebot import apihelper, util, types +from telebot import apihelper, util, types, asyncio_helper from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, StateMemory, StateFile +from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter +import asyncio +from telebot import asyncio_handler_backends +from telebot import asyncio_filters + REPLY_MARKUP_TYPES = Union[ @@ -35,6 +39,7 @@ REPLY_MARKUP_TYPES = Union[ types.ReplyKeyboardRemove, types.ForceReply] + """ Module : telebot """ @@ -3308,338 +3313,2882 @@ class TeleBot: break -class AsyncTeleBot(TeleBot): - def __init__(self, *args, **kwargs): - TeleBot.__init__(self, *args, **kwargs) +class AsyncTeleBot: - # I'm not sure if `get_updates` should be added here too - @util.async_dec() - def enable_save_next_step_handlers(self, delay=120, filename="./.handler-saves/step.save"): - return TeleBot.enable_save_next_step_handlers(self, delay, filename) + def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, + exception_handler=None,suppress_middleware_excepions=False) -> None: # TODO: ADD TYPEHINTS + self.token = token + logger.info('creating some objects..') + self.loop = asyncio.get_event_loop() + self.offset = offset + self.token = token + self.parse_mode = parse_mode + self.update_listener = [] + self.suppress_middleware_excepions = suppress_middleware_excepions - @util.async_dec() - def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"): - return TeleBot.enable_save_reply_handlers(self, delay, filename) + self.exc_info = None - @util.async_dec() - def disable_save_next_step_handlers(self): - return TeleBot.disable_save_next_step_handlers(self) + self.exception_handler = exception_handler - @util.async_dec() - def disable_save_reply_handlers(self): - return TeleBot.enable_save_reply_handlers(self) + self.message_handlers = [] + self.edited_message_handlers = [] + self.channel_post_handlers = [] + self.edited_channel_post_handlers = [] + self.inline_handlers = [] + self.chosen_inline_handlers = [] + self.callback_query_handlers = [] + self.shipping_query_handlers = [] + self.pre_checkout_query_handlers = [] + self.poll_handlers = [] + self.poll_answer_handlers = [] + self.my_chat_member_handlers = [] + self.chat_member_handlers = [] + self.chat_join_request_handlers = [] + self.custom_filters = {} + self.state_handlers = [] - @util.async_dec() - def load_next_step_handlers(self, filename="./.handler-saves/step.save", del_file_after_loading=True): - return TeleBot.load_next_step_handlers(self, filename, del_file_after_loading) + self.current_states = asyncio_handler_backends.StateMemory() - @util.async_dec() - def load_reply_handlers(self, filename="./.handler-saves/reply.save", del_file_after_loading=True): - return TeleBot.load_reply_handlers(self, filename, del_file_after_loading) - @util.async_dec() - def get_me(self): - return TeleBot.get_me(self) + if asyncio_helper.ENABLE_MIDDLEWARE: + self.typed_middleware_handlers = { + 'message': [], + 'edited_message': [], + 'channel_post': [], + 'edited_channel_post': [], + 'inline_query': [], + 'chosen_inline_result': [], + 'callback_query': [], + 'shipping_query': [], + 'pre_checkout_query': [], + 'poll': [], + 'poll_answer': [], + 'my_chat_member': [], + 'chat_member': [], + 'chat_join_request': [] + } + self.default_middleware_handlers = [] - @util.async_dec() - def log_out(self): - return TeleBot.log_out(self) - @util.async_dec() - def close(self): - return TeleBot.close(self) + async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, + timeout: Optional[int]=None, allowed_updates: Optional[List]=None) -> types.Update: + json_updates = await asyncio_helper.get_updates(self.token, offset, limit, timeout, allowed_updates) + return [types.Update.de_json(ju) for ju in json_updates] - @util.async_dec() - def get_my_commands(self, *args, **kwargs): # needed args because new scope and language_code - return TeleBot.get_my_commands(self, *args, **kwargs) + async def polling(self, non_stop: bool=False, skip_pending=False, interval: int=0, timeout: int=20, + long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None, + none_stop: Optional[bool]=None): + """ + This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly. - @util.async_dec() - def set_my_commands(self, *args, **kwargs): - return TeleBot.set_my_commands(self, *args, **kwargs) + Warning: Do not call this function more than once! + + Always get updates. + :param interval: Delay between two update retrivals + :param non_stop: Do not stop polling when an ApiException occurs. + :param timeout: Request connection timeout + :param skip_pending: skip old updates + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + :param none_stop: Deprecated, use non_stop. Old typo f***up compatibility + :return: + """ + if none_stop is not None: + non_stop = none_stop + + if skip_pending: + await self.skip_updates() + await self._process_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates) + + async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, long_polling_timeout: int=20, logger_level=logging.ERROR, + allowed_updates: Optional[List[str]]=None, *args, **kwargs): + """ + Wrap polling with infinite loop and exception handling to avoid bot stops polling. + + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param skip_pending: skip old updates + :param logger_level: Custom logging level for infinity_polling logging. + Use logger levels from logging as a value. None/NOTSET = no error logging + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + """ + if skip_pending: + await self.skip_updates() + self._polling = True + while self._polling: + try: + await self._process_polling(non_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, + allowed_updates=allowed_updates, *args, **kwargs) + except Exception as e: + if logger_level and logger_level >= logging.ERROR: + logger.error("Infinity polling exception: %s", str(e)) + if logger_level and logger_level >= logging.DEBUG: + logger.error("Exception traceback:\n%s", traceback.format_exc()) + time.sleep(3) + continue + if logger_level and logger_level >= logging.INFO: + logger.error("Infinity polling: polling exited") + if logger_level and logger_level >= logging.INFO: + logger.error("Break infinity polling") + + async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20, + long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): + """ + Function to process polling. + :param non_stop: Do not stop polling when an ApiException occurs. + :param interval: Delay between two update retrivals + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + :return: + + """ + self._polling = True + + try: + while self._polling: + try: + + updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout) + + if updates: + logger.debug(f"Received {len(updates)} updates.") + + await self.process_new_updates(updates) + if interval: await asyncio.sleep(interval) + except KeyboardInterrupt: + logger.info("KeyboardInterrupt received.") + break + except asyncio.CancelledError: + break + except asyncio_helper.ApiTelegramException as e: + logger.info(str(e)) + + continue + except Exception as e: + print('Cause exception while getting updates.') + logger.critical(str(e)) + await asyncio.sleep(3) + continue + + finally: + self._polling = False + logger.warning('Polling is stopped.') + + + async def _loop_create_task(self, coro): + return asyncio.create_task(coro) + + async def _process_updates(self, handlers, messages): + for message in messages: + for message_handler in handlers: + process_update = await self._test_message_handler(message_handler, message) + if not process_update: + continue + elif process_update: + try: + await self._loop_create_task(message_handler['function'](message)) + break + except Exception as e: + print(str(e)) + + # update handling + async def process_new_updates(self, updates): + upd_count = len(updates) + logger.info('Received {0} new updates'.format(upd_count)) + if upd_count == 0: return + + new_messages = None + new_edited_messages = None + new_channel_posts = None + new_edited_channel_posts = None + new_inline_queries = None + new_chosen_inline_results = None + new_callback_queries = None + new_shipping_queries = None + new_pre_checkout_queries = None + new_polls = None + new_poll_answers = None + new_my_chat_members = None + new_chat_members = None + chat_join_request = None + for update in updates: + if asyncio_helper.ENABLE_MIDDLEWARE: + try: + self.process_middlewares(update) + except Exception as e: + logger.error(str(e)) + if not self.suppress_middleware_excepions: + raise + else: + if update.update_id > self.offset: self.offset = update.update_id + continue + logger.debug('Processing updates: {0}'.format(update)) + if update.update_id: + self.offset = update.update_id + 1 + if update.message: + logger.info('Processing message') + if new_messages is None: new_messages = [] + new_messages.append(update.message) + if update.edited_message: + if new_edited_messages is None: new_edited_messages = [] + new_edited_messages.append(update.edited_message) + if update.channel_post: + if new_channel_posts is None: new_channel_posts = [] + new_channel_posts.append(update.channel_post) + if update.edited_channel_post: + if new_edited_channel_posts is None: new_edited_channel_posts = [] + new_edited_channel_posts.append(update.edited_channel_post) + if update.inline_query: + if new_inline_queries is None: new_inline_queries = [] + new_inline_queries.append(update.inline_query) + if update.chosen_inline_result: + if new_chosen_inline_results is None: new_chosen_inline_results = [] + new_chosen_inline_results.append(update.chosen_inline_result) + if update.callback_query: + if new_callback_queries is None: new_callback_queries = [] + new_callback_queries.append(update.callback_query) + if update.shipping_query: + if new_shipping_queries is None: new_shipping_queries = [] + new_shipping_queries.append(update.shipping_query) + if update.pre_checkout_query: + if new_pre_checkout_queries is None: new_pre_checkout_queries = [] + new_pre_checkout_queries.append(update.pre_checkout_query) + if update.poll: + if new_polls is None: new_polls = [] + new_polls.append(update.poll) + if update.poll_answer: + if new_poll_answers is None: new_poll_answers = [] + new_poll_answers.append(update.poll_answer) + if update.my_chat_member: + if new_my_chat_members is None: new_my_chat_members = [] + new_my_chat_members.append(update.my_chat_member) + if update.chat_member: + if new_chat_members is None: new_chat_members = [] + new_chat_members.append(update.chat_member) + if update.chat_join_request: + if chat_join_request is None: chat_join_request = [] + chat_join_request.append(update.chat_join_request) + + if new_messages: + await self.process_new_messages(new_messages) + if new_edited_messages: + await self.process_new_edited_messages(new_edited_messages) + if new_channel_posts: + await self.process_new_channel_posts(new_channel_posts) + if new_edited_channel_posts: + await self.process_new_edited_channel_posts(new_edited_channel_posts) + if new_inline_queries: + await self.process_new_inline_query(new_inline_queries) + if new_chosen_inline_results: + await self.process_new_chosen_inline_query(new_chosen_inline_results) + if new_callback_queries: + await self.process_new_callback_query(new_callback_queries) + if new_shipping_queries: + await self.process_new_shipping_query(new_shipping_queries) + if new_pre_checkout_queries: + await self.process_new_pre_checkout_query(new_pre_checkout_queries) + if new_polls: + await self.process_new_poll(new_polls) + if new_poll_answers: + await self.process_new_poll_answer(new_poll_answers) + if new_my_chat_members: + await self.process_new_my_chat_member(new_my_chat_members) + if new_chat_members: + await self.process_new_chat_member(new_chat_members) + if chat_join_request: + await self.process_chat_join_request(chat_join_request) + + + async def process_new_messages(self, new_messages): + await self.__notify_update(new_messages) + await self._process_updates(self.message_handlers, new_messages) + + async def process_new_edited_messages(self, edited_message): + await self._process_updates(self.edited_message_handlers, edited_message) + + async def process_new_channel_posts(self, channel_post): + await self._process_updates(self.channel_post_handlers, channel_post) + + async def process_new_edited_channel_posts(self, edited_channel_post): + await self._process_updates(self.edited_channel_post_handlers, edited_channel_post) + + async def process_new_inline_query(self, new_inline_querys): + await self._process_updates(self.inline_handlers, new_inline_querys) + + async def process_new_chosen_inline_query(self, new_chosen_inline_querys): + await self._process_updates(self.chosen_inline_handlers, new_chosen_inline_querys) + + async def process_new_callback_query(self, new_callback_querys): + await self._process_updates(self.callback_query_handlers, new_callback_querys) + + async def process_new_shipping_query(self, new_shipping_querys): + await self._process_updates(self.shipping_query_handlers, new_shipping_querys) + + async def process_new_pre_checkout_query(self, pre_checkout_querys): + await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys) + + async def process_new_poll(self, polls): + await self._process_updates(self.poll_handlers, polls) + + async def process_new_poll_answer(self, poll_answers): + await self._process_updates(self.poll_answer_handlers, poll_answers) - @util.async_dec() - def delete_my_commands(self, *args, **kwargs): - return TeleBot.delete_my_commands(self, *args, **kwargs) + async def process_new_my_chat_member(self, my_chat_members): + await self._process_updates(self.my_chat_member_handlers, my_chat_members) - @util.async_dec() - def get_file(self, *args): - return TeleBot.get_file(self, *args) + async def process_new_chat_member(self, chat_members): + await self._process_updates(self.chat_member_handlers, chat_members) - @util.async_dec() - def download_file(self, *args): - return TeleBot.download_file(self, *args) + async def process_chat_join_request(self, chat_join_request): + await self._process_updates(self.chat_join_request_handlers, chat_join_request) - @util.async_dec() - def get_user_profile_photos(self, *args, **kwargs): - return TeleBot.get_user_profile_photos(self, *args, **kwargs) + async def process_middlewares(self, update): + for update_type, middlewares in self.typed_middleware_handlers.items(): + if getattr(update, update_type) is not None: + for typed_middleware_handler in middlewares: + try: + typed_middleware_handler(self, getattr(update, update_type)) + except Exception as e: + e.args = e.args + (f'Typed middleware handler "{typed_middleware_handler.__qualname__}"',) + raise - @util.async_dec() - def get_chat(self, *args): - return TeleBot.get_chat(self, *args) + if len(self.default_middleware_handlers) > 0: + for default_middleware_handler in self.default_middleware_handlers: + try: + default_middleware_handler(self, update) + except Exception as e: + e.args = e.args + (f'Default middleware handler "{default_middleware_handler.__qualname__}"',) + raise - @util.async_dec() - def leave_chat(self, *args): - return TeleBot.leave_chat(self, *args) - - @util.async_dec() - def get_chat_administrators(self, *args): - return TeleBot.get_chat_administrators(self, *args) - - @util.async_dec() - def get_chat_members_count(self, *args): - logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead') - return TeleBot.get_chat_member_count(self, *args) - @util.async_dec() - def get_chat_member_count(self, *args): - return TeleBot.get_chat_member_count(self, *args) + async def __notify_update(self, new_messages): + if len(self.update_listener) == 0: + return + for listener in self.update_listener: + self._loop_create_task(listener, new_messages) - @util.async_dec() - def set_chat_sticker_set(self, *args): - return TeleBot.set_chat_sticker_set(self, *args) + async def _test_message_handler(self, message_handler, message): + """ + Test message handler + :param message_handler: + :param message: + :return: + """ + for message_filter, filter_value in message_handler['filters'].items(): + if filter_value is None: + continue - @util.async_dec() - def delete_chat_sticker_set(self, *args): - return TeleBot.delete_chat_sticker_set(self, *args) + if not await self._test_filter(message_filter, filter_value, message): + return False - @util.async_dec() - def get_chat_member(self, *args): - return TeleBot.get_chat_member(self, *args) + return True - @util.async_dec() - def send_message(self, *args, **kwargs): - return TeleBot.send_message(self, *args, **kwargs) + def add_custom_filter(self, custom_filter): + """ + Create custom filter. + custom_filter: Class with check(message) method. + """ + self.custom_filters[custom_filter.key] = custom_filter - @util.async_dec() - def send_dice(self, *args, **kwargs): - return TeleBot.send_dice(self, *args, **kwargs) + async def _test_filter(self, message_filter, filter_value, message): + """ + Test filters + :param message_filter: Filter type passed in handler + :param filter_value: Filter value passed in handler + :param message: Message to test + :return: True if filter conforms + """ + # test_cases = { + # 'content_types': lambda msg: msg.content_type in filter_value, + # 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), + # 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + # 'func': lambda msg: filter_value(msg) + # } + # return test_cases.get(message_filter, lambda msg: False)(message) + if message_filter == 'content_types': + return message.content_type in filter_value + elif message_filter == 'regexp': + return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) + elif message_filter == 'commands': + return message.content_type == 'text' and util.extract_command(message.text) in filter_value + elif message_filter == 'chat_types': + return message.chat.type in filter_value + elif message_filter == 'func': + return filter_value(message) + elif self.custom_filters and message_filter in self.custom_filters: + return await self._check_filter(message_filter,filter_value,message) + else: + return False - @util.async_dec() - def send_animation(self, *args, **kwargs): - return TeleBot.send_animation(self, *args, **kwargs) + async def _check_filter(self, message_filter, filter_value, message): + """ + Check up the filter + :param message_filter: + :param filter_value: + :param message: + :return: + """ + filter_check = self.custom_filters.get(message_filter) + if not filter_check: + return False + elif isinstance(filter_check, asyncio_filters.SimpleCustomFilter): + return filter_value == await filter_check.check(message) + elif isinstance(filter_check, asyncio_filters.AdvancedCustomFilter): + return await filter_check.check(message, filter_value) + else: + logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter!") + return False - @util.async_dec() - def forward_message(self, *args, **kwargs): - return TeleBot.forward_message(self, *args, **kwargs) + def middleware_handler(self, update_types=None): + """ + Middleware handler decorator. - @util.async_dec() - def copy_message(self, *args, **kwargs): - return TeleBot.copy_message(self, *args, **kwargs) + This decorator can be used to decorate functions that must be handled as middlewares before entering any other + message handlers + But, be careful and check type of the update inside the handler if more than one update_type is given - @util.async_dec() - def delete_message(self, *args): - return TeleBot.delete_message(self, *args) + Example: - @util.async_dec() - def send_photo(self, *args, **kwargs): - return TeleBot.send_photo(self, *args, **kwargs) + bot = TeleBot('TOKEN') - @util.async_dec() - def send_audio(self, *args, **kwargs): - return TeleBot.send_audio(self, *args, **kwargs) + # Print post message text before entering to any post_channel handlers + @bot.middleware_handler(update_types=['channel_post', 'edited_channel_post']) + def print_channel_post_text(bot_instance, channel_post): + print(channel_post.text) - @util.async_dec() - def send_voice(self, *args, **kwargs): - return TeleBot.send_voice(self, *args, **kwargs) + # Print update id before entering to any handlers + @bot.middleware_handler() + def print_channel_post_text(bot_instance, update): + print(update.update_id) - @util.async_dec() - def send_document(self, *args, **kwargs): - return TeleBot.send_document(self, *args, **kwargs) + :param update_types: Optional list of update types that can be passed into the middleware handler. - @util.async_dec() - def send_sticker(self, *args, **kwargs): - return TeleBot.send_sticker(self, *args, **kwargs) + """ - @util.async_dec() - def send_video(self, *args, **kwargs): - return TeleBot.send_video(self, *args, **kwargs) + def decorator(handler): + self.add_middleware_handler(handler, update_types) + return handler - @util.async_dec() - def send_video_note(self, *args, **kwargs): - return TeleBot.send_video_note(self, *args, **kwargs) + return decorator - @util.async_dec() - def send_media_group(self, *args, **kwargs): - return TeleBot.send_media_group(self, *args, **kwargs) + def add_middleware_handler(self, handler, update_types=None): + """ + Add middleware handler + :param handler: + :param update_types: + :return: + """ + if not asyncio_helper.ENABLE_MIDDLEWARE: + raise RuntimeError("Middleware is not enabled. Use asyncio_helper.ENABLE_MIDDLEWARE.") - @util.async_dec() - def send_location(self, *args, **kwargs): - return TeleBot.send_location(self, *args, **kwargs) + if update_types: + for update_type in update_types: + self.typed_middleware_handlers[update_type].append(handler) + else: + self.default_middleware_handlers.append(handler) - @util.async_dec() - def edit_message_live_location(self, *args, **kwargs): - return TeleBot.edit_message_live_location(self, *args, **kwargs) + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + """ + Message handler decorator. + This decorator can be used to decorate functions that must handle certain types of messages. + All message handlers are tested in the order they were added. - @util.async_dec() - def stop_message_live_location(self, *args, **kwargs): - return TeleBot.stop_message_live_location(self, *args, **kwargs) + Example: - @util.async_dec() - def send_venue(self, *args, **kwargs): - return TeleBot.send_venue(self, *args, **kwargs) + bot = TeleBot('TOKEN') - @util.async_dec() - def send_contact(self, *args, **kwargs): - return TeleBot.send_contact(self, *args, **kwargs) + # Handles all messages which text matches regexp. + @bot.message_handler(regexp='someregexp') + async def command_help(message): + bot.send_message(message.chat.id, 'Did someone call for help?') - @util.async_dec() - def send_chat_action(self, *args, **kwargs): - return TeleBot.send_chat_action(self, *args, **kwargs) + # Handles messages in private chat + @bot.message_handler(chat_types=['private']) # You can add more chat types + async def command_help(message): + bot.send_message(message.chat.id, 'Private chat detected, sir!') - @util.async_dec() - def kick_chat_member(self, *args, **kwargs): + # Handle all sent documents of type 'text/plain'. + @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', + content_types=['document']) + async def command_handle_document(message): + bot.send_message(message.chat.id, 'Document received, sir!') + + # Handle all other messages. + @bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document', + 'text', 'location', 'contact', 'sticker']) + async def async default_command(message): + bot.send_message(message.chat.id, "This is the async default command handler.") + + :param commands: Optional list of strings (commands to handle). + :param regexp: Optional regular expression. + :param func: Optional lambda function. The lambda receives the message to test as the first parameter. + It must return True if the command should handle the message. + :param content_types: Supported message content types. Must be a list. async defaults to ['text']. + :param chat_types: list of chat types + """ + + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) + return handler + + return decorator + + def add_message_handler(self, handler_dict): + """ + Adds a message handler + :param handler_dict: + :return: + """ + self.message_handlers.append(handler_dict) + + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + Registers message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :param chat_types: True for private chat + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) + + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + """ + Edit message handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param chat_types: list of chat types + :param kwargs: + :return: + """ + + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) + return handler + + return decorator + + def add_edited_message_handler(self, handler_dict): + """ + Adds the edit message handler + :param handler_dict: + :return: + """ + self.edited_message_handlers.append(handler_dict) + + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + Registers edited message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :param chat_types: True for private chat + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) + + + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + """ + Channel post handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param kwargs: + :return: + """ + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) + return handler + + return decorator + + def add_channel_post_handler(self, handler_dict): + """ + Adds channel post handler + :param handler_dict: + :return: + """ + self.channel_post_handlers.append(handler_dict) + + def register_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) + + def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + """ + Edit channel post handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param kwargs: + :return: + """ + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + return handler + + return decorator + + def add_edited_channel_post_handler(self, handler_dict): + """ + Adds the edit channel post handler + :param handler_dict: + :return: + """ + self.edited_channel_post_handlers.append(handler_dict) + + def register_edited_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers edited channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + + def inline_handler(self, func, **kwargs): + """ + Inline call handler decorator + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_inline_handler(handler_dict) + return handler + + return decorator + + def add_inline_handler(self, handler_dict): + """ + Adds inline call handler + :param handler_dict: + :return: + """ + self.inline_handlers.append(handler_dict) + + def register_inline_handler(self, callback, func, **kwargs): + """ + Registers inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_inline_handler(handler_dict) + + def chosen_inline_handler(self, func, **kwargs): + """ + Description: TBD + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chosen_inline_handler(handler_dict) + return handler + + return decorator + + def add_chosen_inline_handler(self, handler_dict): + """ + Description: TBD + :param handler_dict: + :return: + """ + self.chosen_inline_handlers.append(handler_dict) + + def register_chosen_inline_handler(self, callback, func, **kwargs): + """ + Registers chosen inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chosen_inline_handler(handler_dict) + + def callback_query_handler(self, func, **kwargs): + """ + Callback request handler decorator + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_callback_query_handler(handler_dict) + return handler + + return decorator + + def add_callback_query_handler(self, handler_dict): + """ + Adds a callback request handler + :param handler_dict: + :return: + """ + self.callback_query_handlers.append(handler_dict) + + def register_callback_query_handler(self, callback, func, **kwargs): + """ + Registers callback query handler.. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_callback_query_handler(handler_dict) + + def shipping_query_handler(self, func, **kwargs): + """ + Shipping request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_shipping_query_handler(handler_dict) + return handler + + return decorator + + def add_shipping_query_handler(self, handler_dict): + """ + Adds a shipping request handler + :param handler_dict: + :return: + """ + self.shipping_query_handlers.append(handler_dict) + + def register_shipping_query_handler(self, callback, func, **kwargs): + """ + Registers shipping query handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_shipping_query_handler(handler_dict) + + def pre_checkout_query_handler(self, func, **kwargs): + """ + Pre-checkout request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_pre_checkout_query_handler(handler_dict) + return handler + + return decorator + + def add_pre_checkout_query_handler(self, handler_dict): + """ + Adds a pre-checkout request handler + :param handler_dict: + :return: + """ + self.pre_checkout_query_handlers.append(handler_dict) + + def register_pre_checkout_query_handler(self, callback, func, **kwargs): + """ + Registers pre-checkout request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_pre_checkout_query_handler(handler_dict) + + def poll_handler(self, func, **kwargs): + """ + Poll request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_poll_handler(handler_dict) + return handler + + return decorator + + def add_poll_handler(self, handler_dict): + """ + Adds a poll request handler + :param handler_dict: + :return: + """ + self.poll_handlers.append(handler_dict) + + def register_poll_handler(self, callback, func, **kwargs): + """ + Registers poll handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_poll_handler(handler_dict) + + def poll_answer_handler(self, func=None, **kwargs): + """ + Poll_answer request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_poll_answer_handler(handler_dict) + return handler + + return decorator + + def add_poll_answer_handler(self, handler_dict): + """ + Adds a poll_answer request handler + :param handler_dict: + :return: + """ + self.poll_answer_handlers.append(handler_dict) + + def register_poll_answer_handler(self, callback, func, **kwargs): + """ + Registers poll answer handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_poll_answer_handler(handler_dict) + + def my_chat_member_handler(self, func=None, **kwargs): + """ + my_chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_my_chat_member_handler(self, handler_dict): + """ + Adds a my_chat_member handler + :param handler_dict: + :return: + """ + self.my_chat_member_handlers.append(handler_dict) + + def register_my_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers my chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + + def chat_member_handler(self, func=None, **kwargs): + """ + chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_chat_member_handler(self, handler_dict): + """ + Adds a chat_member handler + :param handler_dict: + :return: + """ + self.chat_member_handlers.append(handler_dict) + + def register_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + + def chat_join_request_handler(self, func=None, **kwargs): + """ + chat_join_request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + return handler + + return decorator + + def add_chat_join_request_handler(self, handler_dict): + """ + Adds a chat_join_request handler + :param handler_dict: + :return: + """ + self.chat_join_request_handlers.append(handler_dict) + + def register_chat_join_request_handler(self, callback, func=None, **kwargs): + """ + Registers chat join request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + + @staticmethod + def _build_handler_dict(handler, **filters): + """ + Builds a dictionary for a handler + :param handler: + :param filters: + :return: + """ + return { + 'function': handler, + 'filters': {ftype: fvalue for ftype, fvalue in filters.items() if fvalue is not None} + # Remove None values, they are skipped in _test_filter anyway + #'filters': filters + } + + async def skip_updates(self): + await self.get_updates(-1) + return True + + # all methods begin here + + async def get_me(self) -> types.User: + """ + Returns basic information about the bot in form of a User object. + """ + result = await asyncio_helper.get_me(self.token) + return types.User.de_json(result) + + async def get_file(self, file_id: str) -> types.File: + """ + Use this method to get basic info about a file and prepare it for downloading. + For the moment, bots can download files of up to 20MB in size. + On success, a File object is returned. + It is guaranteed that the link will be valid for at least 1 hour. + When the link expires, a new one can be requested by calling get_file again. + """ + return types.File.de_json(await asyncio_helper.get_file(self.token, file_id)) + + async def get_file_url(self, file_id: str) -> str: + return await asyncio_helper.get_file_url(self.token, file_id) + + async def download_file(self, file_path: str) -> bytes: + return await asyncio_helper.download_file(self.token, file_path) + + async def log_out(self) -> bool: + """ + Use this method to log out from the cloud Bot API server before launching the bot locally. + You MUST log out the bot before running it locally, otherwise there is no guarantee + that the bot will receive updates. + After a successful call, you can immediately log in on a local server, + but will not be able to log in back to the cloud Bot API server for 10 minutes. + Returns True on success. + """ + return await asyncio_helper.log_out(self.token) + + async def close(self) -> bool: + """ + Use this method to close the bot instance before moving it from one local server to another. + You need to delete the webhook before calling this method to ensure that the bot isn't launched again + after server restart. + The method will return error 429 in the first 10 minutes after the bot is launched. + Returns True on success. + """ + return await asyncio_helper.close(self.token) + + async def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): + """ + Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an + update for the bot, we will send an HTTPS POST request to the specified url, + containing a JSON-serialized Update. + In case of an unsuccessful request, we will give up after a reasonable amount of attempts. + Returns True on success. + + :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration + :param certificate: Upload your public key certificate so that the root certificate in use can be checked. + See our self-signed guide for details. + :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook + for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, + and higher values to increase your bot's throughput. + :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates + of these types. See Update for a complete list of available update types. + Specify an empty list to receive all updates regardless of type (default). + If not specified, the previous setting will be used. + :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address + resolved through DNS + :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout + :return: + """ + return await asyncio_helper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, + drop_pending_updates, timeout) + + async def delete_webhook(self, drop_pending_updates=None, timeout=None): + """ + Use this method to remove webhook integration if you decide to switch back to getUpdates. + + :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout + :return: bool + """ + return await asyncio_helper.delete_webhook(self.token, drop_pending_updates, timeout) + + async def get_webhook_info(self, timeout=None): + """ + Use this method to get current webhook status. Requires no parameters. + If the bot is using getUpdates, will return an object with the url field empty. + + :param timeout: Integer. Request connection timeout + :return: On success, returns a WebhookInfo object. + """ + result = await asyncio_helper.get_webhook_info(self.token, timeout) + return types.WebhookInfo.de_json(result) + + async def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None, + limit: Optional[int]=None) -> types.UserProfilePhotos: + """ + Retrieves the user profile photos of the person with 'user_id' + See https://core.telegram.org/bots/api#getuserprofilephotos + :param user_id: + :param offset: + :param limit: + :return: API reply. + """ + result = await asyncio_helper.get_user_profile_photos(self.token, user_id, offset, limit) + return types.UserProfilePhotos.de_json(result) + + async def get_chat(self, chat_id: Union[int, str]) -> types.Chat: + """ + Use this method to get up to date information about the chat (current name of the user for one-on-one + conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.get_chat(self.token, chat_id) + return types.Chat.de_json(result) + + async def leave_chat(self, chat_id: Union[int, str]) -> bool: + """ + Use this method for your bot to leave a group, supergroup or channel. Returns True on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.leave_chat(self.token, chat_id) + return result + + async def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: + """ + Use this method to get a list of administrators in a chat. + On success, returns an Array of ChatMember objects that contains + information about all chat administrators except other bots. + :param chat_id: Unique identifier for the target chat or username + of the target supergroup or channel (in the format @channelusername) + :return: + """ + result = await asyncio_helper.get_chat_administrators(self.token, chat_id) + return [types.ChatMember.de_json(r) for r in result] + + async def get_chat_members_count(self, chat_id: Union[int, str]) -> int: + """ + This function is deprecated. Use `get_chat_member_count` instead + """ + logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.') + result = await asyncio_helper.get_chat_member_count(self.token, chat_id) + return result + + async def get_chat_member_count(self, chat_id: Union[int, str]) -> int: + """ + Use this method to get the number of members in a chat. Returns Int on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.get_chat_member_count(self.token, chat_id) + return result + + async def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str) -> types.StickerSet: + """ + Use this method to set a new group sticker set for a supergroup. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + Use the field can_set_sticker_set optionally returned in getChat requests to check + if the bot can use this method. Returns True on success. + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param sticker_set_name: Name of the sticker set to be set as the group sticker set + :return: + """ + result = await asyncio_helper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) + return result + + async def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat + for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set + optionally returned in getChat requests to check if the bot can use this method. Returns True on success. + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :return: + """ + result = await asyncio_helper.delete_chat_sticker_set(self.token, chat_id) + return result + + async def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: + """ + Use this method to get information about a member of a chat. Returns a ChatMember object on success. + :param chat_id: + :param user_id: + :return: + """ + result = await asyncio_helper.get_chat_member(self.token, chat_id, user_id) + return types.ChatMember.de_json(result) + + async def send_message( + self, chat_id: Union[int, str], text: str, + disable_web_page_preview: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send text messages. + + Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error. + If you must send more than 4000 characters, + use the `split_string` or `smart_split` function in util.py. + + :param chat_id: + :param text: + :param disable_web_page_preview: + :param reply_to_message_id: + :param reply_markup: + :param parse_mode: + :param disable_notification: Boolean, Optional. Sends the message silently. + :param timeout: + :param entities: + :param allow_sending_without_reply: + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_message( + self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, + entities, allow_sending_without_reply)) + + async def forward_message( + self, chat_id: Union[int, str], from_chat_id: Union[int, str], + message_id: int, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None) -> types.Message: + """ + Use this method to forward messages of any kind. + :param disable_notification: + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param timeout: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) + + async def copy_message( + self, chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + caption: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> int: + """ + Use this method to copy messages of any kind. + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param caption: + :param parse_mode: + :param caption_entities: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: + :param timeout: + :return: API reply. + """ + return types.MessageID.de_json( + await asyncio_helper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, + disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, + timeout)) + + async def delete_message(self, chat_id: Union[int, str], message_id: int, + timeout: Optional[int]=None) -> bool: + """ + Use this method to delete message. Returns True on success. + :param chat_id: in which chat to delete + :param message_id: which message to delete + :param timeout: + :return: API reply. + """ + return await asyncio_helper.delete_message(self.token, chat_id, message_id, timeout) + + async def send_dice( + self, chat_id: Union[int, str], + emoji: Optional[str]=None, disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send dices. + :param chat_id: + :param emoji: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :return: Message + """ + return types.Message.de_json( + await asyncio_helper.send_dice( + self.token, chat_id, emoji, disable_notification, reply_to_message_id, + reply_markup, timeout, allow_sending_without_reply) + ) + + async def send_photo( + self, chat_id: Union[int, str], photo: Union[Any, str], + caption: Optional[str]=None, reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send photos. + :param chat_id: + :param photo: + :param caption: + :param parse_mode: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param caption_entities: + :param allow_sending_without_reply: + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_photo( + self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) + + async def send_audio( + self, chat_id: Union[int, str], audio: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + performer: Optional[str]=None, title: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send audio files, if you want Telegram clients to display them in the music player. + Your audio must be in the .mp3 format. + :param chat_id:Unique identifier for the message recipient + :param audio:Audio file to send. + :param caption: + :param duration:Duration of the audio in seconds + :param performer:Performer + :param title:Track name + :param reply_to_message_id:If the message is a reply, ID of the original message + :param reply_markup: + :param parse_mode + :param disable_notification: + :param timeout: + :param thumb: + :param caption_entities: + :param allow_sending_without_reply: + :return: Message + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_audio( + self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) + + async def send_voice( + self, chat_id: Union[int, str], voice: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send audio files, if you want Telegram clients to display the file + as a playable voice message. + :param chat_id:Unique identifier for the message recipient. + :param voice: + :param caption: + :param duration:Duration of sent audio in seconds + :param reply_to_message_id: + :param reply_markup: + :param parse_mode + :param disable_notification: + :param timeout: + :param caption_entities: + :param allow_sending_without_reply: + :return: Message + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_voice( + self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) + + async def send_document( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + caption: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None, + visible_file_name: Optional[str]=None, + disable_content_type_detection: Optional[bool]=None) -> types.Message: + """ + Use this method to send general files. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param data: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data + :param reply_to_message_id: If the message is a reply, ID of the original message + :param caption: Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing + :param reply_markup: + :param parse_mode: Mode for parsing entities in the document caption + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under + :param caption_entities: + :param allow_sending_without_reply: + :param visible_file_name: allows to async define file name that will be visible in the Telegram instead of original file name + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_data( + self.token, chat_id, data, 'document', + reply_to_message_id = reply_to_message_id, reply_markup = reply_markup, parse_mode = parse_mode, + disable_notification = disable_notification, timeout = timeout, caption = caption, thumb = thumb, + caption_entities = caption_entities, allow_sending_without_reply = allow_sending_without_reply, + disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name)) + + async def send_sticker( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send .webp stickers. + :param chat_id: + :param data: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: to disable the notification + :param timeout: timeout + :param allow_sending_without_reply: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.send_data( + self.token, chat_id, data, 'sticker', + reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, + disable_notification=disable_notification, timeout=timeout, + allow_sending_without_reply=allow_sending_without_reply)) + + async def send_video( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + supports_streaming: Optional[bool]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + width: Optional[int]=None, + height: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send video files, Telegram clients support mp4 videos. + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param caption: String : Video caption (may also be used when resending videos by file_id). + :param parse_mode: + :param supports_streaming: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param width: + :param height: + :param caption_entities: + :param allow_sending_without_reply: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_video( + self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, + parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height, + caption_entities, allow_sending_without_reply)) + + async def send_animation( + self, chat_id: Union[int, str], animation: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param animation: InputFile or String : Animation to send. You can either pass a file_id as String to resend an + animation that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param caption: String : Animation caption (may also be used when resending animation by file_id). + :param parse_mode: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param caption_entities: + :param allow_sending_without_reply: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_animation( + self.token, chat_id, animation, duration, caption, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) + + async def send_video_note( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + length: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send + video messages. + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param length: Integer : Video width and height, Can't be None and should be in range of (0, 640) + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param allow_sending_without_reply: + :return: + """ + return types.Message.de_json( + await asyncio_helper.send_video_note( + self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, + disable_notification, timeout, thumb, allow_sending_without_reply)) + + async def send_media_group( + self, chat_id: Union[int, str], + media: List[Union[ + types.InputMediaAudio, types.InputMediaDocument, + types.InputMediaPhoto, types.InputMediaVideo]], + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> List[types.Message]: + """ + send a group of photos or videos as an album. On success, an array of the sent Messages is returned. + :param chat_id: + :param media: + :param disable_notification: + :param reply_to_message_id: + :param timeout: + :param allow_sending_without_reply: + :return: + """ + result = await asyncio_helper.send_media_group( + self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, + allow_sending_without_reply) + return [types.Message.de_json(msg) for msg in result] + + async def send_location( + self, chat_id: Union[int, str], + latitude: float, longitude: float, + live_period: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + + + """ + Use this method to send point on the map. + :param chat_id: + :param latitude: + :param longitude: + :param live_period: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :param allow_sending_without_reply: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.send_location( + self.token, chat_id, latitude, longitude, live_period, + reply_to_message_id, reply_markup, disable_notification, timeout, + horizontal_accuracy, heading, proximity_alert_radius, + allow_sending_without_reply)) + + async def edit_message_live_location( + self, latitude: float, longitude: float, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None) -> types.Message: + """ + Use this method to edit live location + :param latitude: + :param longitude: + :param chat_id: + :param message_id: + :param reply_markup: + :param timeout: + :param inline_message_id: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :return: + """ + return types.Message.de_json( + await asyncio_helper.edit_message_live_location( + self.token, latitude, longitude, chat_id, message_id, + inline_message_id, reply_markup, timeout, + horizontal_accuracy, heading, proximity_alert_radius)) + + async def stop_message_live_location( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> types.Message: + """ + Use this method to stop updating a live location message sent by the bot + or via the bot (for inline bots) before live_period expires + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :param timeout: + :return: + """ + return types.Message.de_json( + await asyncio_helper.stop_message_live_location( + self.token, chat_id, message_id, inline_message_id, reply_markup, timeout)) + + async def send_venue( + self, chat_id: Union[int, str], + latitude: float, longitude: float, + title: str, address: str, + foursquare_id: Optional[str]=None, + foursquare_type: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + google_place_id: Optional[str]=None, + google_place_type: Optional[str]=None) -> types.Message: + """ + Use this method to send information about a venue. + :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel + :param latitude: Float : Latitude of the venue + :param longitude: Float : Longitude of the venue + :param title: String : Name of the venue + :param address: String : Address of the venue + :param foursquare_id: String : Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, “arts_entertainment/async default”, + “arts_entertainment/aquarium” or “food/icecream”.) + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :param google_place_id: + :param google_place_type: + :return: + """ + return types.Message.de_json( + await asyncio_helper.send_venue( + self.token, chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply, google_place_id, google_place_type) + ) + + async def send_contact( + self, chat_id: Union[int, str], phone_number: str, + first_name: str, last_name: Optional[str]=None, + vcard: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + return types.Message.de_json( + await asyncio_helper.send_contact( + self.token, chat_id, phone_number, first_name, last_name, vcard, + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) + ) + + async def send_chat_action( + self, chat_id: Union[int, str], action: str, timeout: Optional[int]=None) -> bool: + """ + Use this method when you need to tell the user that something is happening on the bot's side. + The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear + its typing status). + :param chat_id: + :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', + 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', + 'upload_video_note'. + :param timeout: + :return: API reply. :type: boolean + """ + return await asyncio_helper.send_chat_action(self.token, chat_id, action, timeout) + + async def kick_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + This function is deprecated. Use `ban_chat_member` instead + """ logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') - return TeleBot.ban_chat_member(self, *args, **kwargs) + return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + + async def ban_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + Use this method to ban a user in a group, a supergroup or a channel. + In the case of supergroups and channels, the user will not be able to return to the chat on their + own using invite links, etc., unless unbanned first. + Returns True on success. + :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or + less than 30 seconds from the current time they are considered to be banned forever + :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. + If False, the user will be able to see messages in the group that were sent before the user was removed. + Always True for supergroups and channels. + :return: boolean + """ + return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + + async def unban_chat_member( + self, chat_id: Union[int, str], user_id: int, + only_if_banned: Optional[bool]=False) -> bool: + """ + Use this method to unban a previously kicked user in a supergroup or channel. + The user will not return to the group or channel automatically, but will be able to join via link, etc. + The bot must be an administrator for this to work. By async default, this method guarantees that after the call + the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat + they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. + + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel + (in the format @username) + :param user_id: Unique identifier of the target user + :param only_if_banned: Do nothing if the user is not banned + :return: True on success + """ + return await asyncio_helper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) + + async def restrict_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date: Optional[Union[int, datetime]]=None, + can_send_messages: Optional[bool]=None, + can_send_media_messages: Optional[bool]=None, + can_send_polls: Optional[bool]=None, + can_send_other_messages: Optional[bool]=None, + can_add_web_page_previews: Optional[bool]=None, + can_change_info: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_pin_messages: Optional[bool]=None) -> bool: + """ + Use this method to restrict a user in a supergroup. + The bot must be an administrator in the supergroup for this to work and must have + the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. + + :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup + or channel (in the format @channelusername) + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when restrictions will be lifted for the user, unix time. + If user is restricted for more than 366 days or less than 30 seconds from the current time, + they are considered to be restricted forever + :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues + :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes + and voice notes, implies can_send_messages + :param can_send_polls: Pass True, if the user is allowed to send polls, implies can_send_messages + :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and + use inline bots, implies can_send_media_messages + :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, + implies can_send_media_messages + :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. + Ignored in public supergroups + :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, + implies can_invite_users + :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups + :return: True on success + """ + return await asyncio_helper.restrict_chat_member( + self.token, chat_id, user_id, until_date, + can_send_messages, can_send_media_messages, + can_send_polls, can_send_other_messages, + can_add_web_page_previews, can_change_info, + can_invite_users, can_pin_messages) + + async def promote_chat_member( + self, chat_id: Union[int, str], user_id: int, + can_change_info: Optional[bool]=None, + can_post_messages: Optional[bool]=None, + can_edit_messages: Optional[bool]=None, + can_delete_messages: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_restrict_members: Optional[bool]=None, + can_pin_messages: Optional[bool]=None, + can_promote_members: Optional[bool]=None, + is_anonymous: Optional[bool]=None, + can_manage_chat: Optional[bool]=None, + can_manage_voice_chats: Optional[bool]=None) -> bool: + """ + Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + Pass False for all boolean parameters to demote a user. + + :param chat_id: Unique identifier for the target chat or username of the target channel ( + in the format @channelusername) + :param user_id: Int : Unique identifier of the target user + :param can_change_info: Bool: Pass True, if the administrator can change chat title, photo and other settings + :param can_post_messages: Bool : Pass True, if the administrator can create channel posts, channels only + :param can_edit_messages: Bool : Pass True, if the administrator can edit messages of other users, channels only + :param can_delete_messages: Bool : Pass True, if the administrator can delete messages of other users + :param can_invite_users: Bool : Pass True, if the administrator can invite new users to the chat + :param can_restrict_members: Bool: Pass True, if the administrator can restrict, ban or unban chat members + :param can_pin_messages: Bool: Pass True, if the administrator can pin messages, supergroups only + :param can_promote_members: Bool: Pass True, if the administrator can add new administrators with a subset + of his own privileges or demote administrators that he has promoted, directly or indirectly + (promoted by administrators that were appointed by him) + :param is_anonymous: Bool: Pass True, if the administrator's presence in the chat is hidden + :param can_manage_chat: Bool: Pass True, if the administrator can access the chat event log, chat statistics, + message statistics in channels, see channel members, + see anonymous administrators in supergroups and ignore slow mode. + Implied by any other administrator privilege + :param can_manage_voice_chats: Bool: Pass True, if the administrator can manage voice chats + For now, bots can use this privilege only for passing to other administrators. + :return: True on success. + """ + return await asyncio_helper.promote_chat_member( + self.token, chat_id, user_id, can_change_info, can_post_messages, + can_edit_messages, can_delete_messages, can_invite_users, + can_restrict_members, can_pin_messages, can_promote_members, + is_anonymous, can_manage_chat, can_manage_voice_chats) + + async def set_chat_administrator_custom_title( + self, chat_id: Union[int, str], user_id: int, custom_title: str) -> bool: + """ + Use this method to set a custom title for an administrator + in a supergroup promoted by the bot. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :param custom_title: New custom title for the administrator; + 0-16 characters, emoji are not allowed + :return: True on success. + """ + return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) + + async def set_chat_permissions( + self, chat_id: Union[int, str], permissions: types.ChatPermissions) -> bool: + """ + Use this method to set async default chat permissions for all members. + The bot must be an administrator in the group or a supergroup for this to work + and must have the can_restrict_members admin rights. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param permissions: New async default chat permissions + :return: True on success + """ + return await asyncio_helper.set_chat_permissions(self.token, chat_id, permissions) + + async def create_chat_invite_link( + self, chat_id: Union[int, str], + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: + """ + Use this method to create an additional invite link for a chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request) + ) + + async def edit_chat_invite_link( + self, chat_id: Union[int, str], + invite_link: Optional[str] = None, + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: + """ + Use this method to edit a non-primary invite link created by the bot. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param name: Invite link name; 0-32 characters + :param invite_link: The invite link to edit + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.edit_chat_invite_link(self.token, chat_id, name, invite_link, expire_date, member_limit, creates_join_request) + ) + + async def revoke_chat_invite_link( + self, chat_id: Union[int, str], invite_link: str) -> types.ChatInviteLink: + """ + Use this method to revoke an invite link created by the bot. + Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param invite_link: The invite link to revoke + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.revoke_chat_invite_link(self.token, chat_id, invite_link) + ) + + async def export_chat_invite_link(self, chat_id: Union[int, str]) -> str: + """ + Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :return: exported invite link as String on success. + """ + return await asyncio_helper.export_chat_invite_link(self.token, chat_id) + + + async def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to approve a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return await asyncio_helper.approve_chat_join_request(self.token, chat_id, user_id) + + async def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to decline a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return await asyncio_helper.decline_chat_join_request(self.token, chat_id, user_id) + + async def set_chat_photo(self, chat_id: Union[int, str], photo: Any) -> bool: + """ + Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param photo: InputFile: New chat photo, uploaded using multipart/form-data + :return: + """ + return await asyncio_helper.set_chat_photo(self.token, chat_id, photo) + + async def delete_chat_photo(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to delete a chat photo. Photos can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + """ + return await asyncio_helper.delete_chat_photo(self.token, chat_id) - @util.async_dec() - def ban_chat_member(self, *args, **kwargs): - return TeleBot.ban_chat_member(self, *args, **kwargs) + async def get_my_commands(self, scope: Optional[types.BotCommandScope], + language_code: Optional[str]) -> List[types.BotCommand]: + """ + Use this method to get the current list of the bot's commands. + Returns List of BotCommand on success. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + """ + result = await asyncio_helper.get_my_commands(self.token, scope, language_code) + return [types.BotCommand.de_json(cmd) for cmd in result] - @util.async_dec() - def unban_chat_member(self, *args, **kwargs): - return TeleBot.unban_chat_member(self, *args, **kwargs) - - @util.async_dec() - def restrict_chat_member(self, *args, **kwargs): - return TeleBot.restrict_chat_member(self, *args, **kwargs) - - @util.async_dec() - def promote_chat_member(self, *args, **kwargs): - return TeleBot.promote_chat_member(self, *args, **kwargs) + async def set_my_commands(self, commands: List[types.BotCommand], + scope: Optional[types.BotCommandScope]=None, + language_code: Optional[str]=None) -> bool: + """ + Use this method to change the list of the bot's commands. + :param commands: List of BotCommand. At most 100 commands can be specified. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + :return: + """ + return await asyncio_helper.set_my_commands(self.token, commands, scope, language_code) - @util.async_dec() - def set_chat_administrator_custom_title(self, *args, **kwargs): - return TeleBot.set_chat_administrator_custom_title(self, *args, **kwargs) + async def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None, + language_code: Optional[int]=None) -> bool: + """ + Use this method to delete the list of the bot's commands for the given scope and user language. + After deletion, higher level commands will be shown to affected users. + Returns True on success. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + """ + return await asyncio_helper.delete_my_commands(self.token, scope, language_code) - @util.async_dec() - def set_chat_permissions(self, *args, **kwargs): - return TeleBot.set_chat_permissions(self, *args, **kwargs) + async def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: + """ + Use this method to change the title of a chat. Titles can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param title: New chat title, 1-255 characters + :return: + """ + return await asyncio_helper.set_chat_title(self.token, chat_id, title) - @util.async_dec() - def create_chat_invite_link(self, *args, **kwargs): - return TeleBot.create_chat_invite_link(self, *args, **kwargs) - - @util.async_dec() - def edit_chat_invite_link(self, *args, **kwargs): - return TeleBot.edit_chat_invite_link(self, *args, **kwargs) - - @util.async_dec() - def revoke_chat_invite_link(self, *args, **kwargs): - return TeleBot.revoke_chat_invite_link(self, *args, **kwargs) - - @util.async_dec() - def export_chat_invite_link(self, *args): - return TeleBot.export_chat_invite_link(self, *args) + async def set_chat_description(self, chat_id: Union[int, str], description: Optional[str]=None) -> bool: + """ + Use this method to change the description of a supergroup or a channel. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - @util.async_dec() - def set_chat_photo(self, *args): - return TeleBot.set_chat_photo(self, *args) + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param description: Str: New chat description, 0-255 characters + :return: True on success. + """ + return await asyncio_helper.set_chat_description(self.token, chat_id, description) - @util.async_dec() - def delete_chat_photo(self, *args): - return TeleBot.delete_chat_photo(self, *args) + async def pin_chat_message( + self, chat_id: Union[int, str], message_id: int, + disable_notification: Optional[bool]=False) -> bool: + """ + Use this method to pin a message in a supergroup. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to pin + :param disable_notification: Bool: Pass True, if it is not necessary to send a notification + to all group members about the new pinned message + :return: + """ + return await asyncio_helper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - @util.async_dec() - def set_chat_title(self, *args): - return TeleBot.set_chat_title(self, *args) + async def unpin_chat_message(self, chat_id: Union[int, str], message_id: Optional[int]=None) -> bool: + """ + Use this method to unpin specific pinned message in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to unpin + :return: + """ + return await asyncio_helper.unpin_chat_message(self.token, chat_id, message_id) - @util.async_dec() - def set_chat_description(self, *args): - return TeleBot.set_chat_description(self, *args) + async def unpin_all_chat_messages(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to unpin a all pinned messages in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :return: + """ + return await asyncio_helper.unpin_all_chat_messages(self.token, chat_id) - @util.async_dec() - def pin_chat_message(self, *args, **kwargs): - return TeleBot.pin_chat_message(self, *args, **kwargs) + async def edit_message_text( + self, text: str, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + entities: Optional[List[types.MessageEntity]]=None, + disable_web_page_preview: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit text and game messages. + :param text: + :param chat_id: + :param message_id: + :param inline_message_id: + :param parse_mode: + :param entities: + :param disable_web_page_preview: + :param reply_markup: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - @util.async_dec() - def unpin_chat_message(self, *args): - return TeleBot.unpin_chat_message(self, *args) + result = await asyncio_helper.edit_message_text(self.token, text, chat_id, message_id, inline_message_id, parse_mode, + entities, disable_web_page_preview, reply_markup) + if type(result) == bool: # if edit inline message return is bool not Message. + return result + return types.Message.de_json(result) - @util.async_dec() - def unpin_all_chat_messages(self, *args): - return TeleBot.unpin_all_chat_messages(self, *args) + async def edit_message_media( + self, media: Any, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit animation, audio, document, photo, or video messages. + If a message is a part of a message album, then it can be edited only to a photo or a video. + Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. + Use previously uploaded file via its file_id or specify a URL. + :param media: + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :return: + """ + result = await asyncio_helper.edit_message_media(self.token, media, chat_id, message_id, inline_message_id, reply_markup) + if type(result) == bool: # if edit inline message return is bool not Message. + return result + return types.Message.de_json(result) - @util.async_dec() - def edit_message_text(self, *args, **kwargs): - return TeleBot.edit_message_text(self, *args, **kwargs) + async def edit_message_reply_markup( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit only the reply markup of messages. + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :return: + """ + result = await asyncio_helper.edit_message_reply_markup(self.token, chat_id, message_id, inline_message_id, reply_markup) + if type(result) == bool: + return result + return types.Message.de_json(result) - @util.async_dec() - def edit_message_media(self, *args, **kwargs): - return TeleBot.edit_message_media(self, *args, **kwargs) + async def send_game( + self, chat_id: Union[int, str], game_short_name: str, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Used to send the game + :param chat_id: + :param game_short_name: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :return: + """ + result = await asyncio_helper.send_game( + self.token, chat_id, game_short_name, disable_notification, + reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) + return types.Message.de_json(result) - @util.async_dec() - def edit_message_reply_markup(self, *args, **kwargs): - return TeleBot.edit_message_reply_markup(self, *args, **kwargs) + async def set_game_score( + self, user_id: Union[int, str], score: int, + force: Optional[bool]=None, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + disable_edit_message: Optional[bool]=None) -> Union[types.Message, bool]: + """ + Sets the value of points in the game to a specific user + :param user_id: + :param score: + :param force: + :param chat_id: + :param message_id: + :param inline_message_id: + :param disable_edit_message: + :return: + """ + result = await asyncio_helper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, + message_id, inline_message_id) + if type(result) == bool: + return result + return types.Message.de_json(result) - @util.async_dec() - def send_game(self, *args, **kwargs): - return TeleBot.send_game(self, *args, **kwargs) + async def get_game_high_scores( + self, user_id: int, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: + """ + Gets top points and game play + :param user_id: + :param chat_id: + :param message_id: + :param inline_message_id: + :return: + """ + result = await asyncio_helper.get_game_high_scores(self.token, user_id, chat_id, message_id, inline_message_id) + return [types.GameHighScore.de_json(r) for r in result] - @util.async_dec() - def set_game_score(self, *args, **kwargs): - return TeleBot.set_game_score(self, *args, **kwargs) + async def send_invoice( + self, chat_id: Union[int, str], title: str, description: str, + invoice_payload: str, provider_token: str, currency: str, + prices: List[types.LabeledPrice], start_parameter: Optional[str]=None, + photo_url: Optional[str]=None, photo_size: Optional[int]=None, + photo_width: Optional[int]=None, photo_height: Optional[int]=None, + need_name: Optional[bool]=None, need_phone_number: Optional[bool]=None, + need_email: Optional[bool]=None, need_shipping_address: Optional[bool]=None, + send_phone_number_to_provider: Optional[bool]=None, + send_email_to_provider: Optional[bool]=None, + is_flexible: Optional[bool]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + provider_data: Optional[str]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]]=None) -> types.Message: + """ + Sends invoice + :param chat_id: Unique identifier for the target private chat + :param title: Product name + :param description: Product description + :param invoice_payload: Bot-async defined invoice payload, 1-128 bytes. This will not be displayed to the user, + use for your internal processes. + :param provider_token: Payments provider token, obtained via @Botfather + :param currency: Three-letter ISO 4217 currency code, + see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components + (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice + when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods + or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass True, if you require the user's full name to complete the order + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :param need_email: Pass True, if you require the user's email to complete the order + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param reply_to_message_id: If the message is a reply, ID of the original message + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, + one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. + A detailed description of required fields should be provided by the payment provider. + :param timeout: + :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest + units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip + amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + :return: + """ + result = await asyncio_helper.send_invoice( + self.token, chat_id, title, description, invoice_payload, provider_token, + currency, prices, start_parameter, photo_url, photo_size, photo_width, + photo_height, need_name, need_phone_number, need_email, need_shipping_address, + send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, + reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply, + max_tip_amount, suggested_tip_amounts) + return types.Message.de_json(result) - @util.async_dec() - def get_game_high_scores(self, *args, **kwargs): - return TeleBot.get_game_high_scores(self, *args, **kwargs) + # noinspection PyShadowingBuiltins + async def send_poll( + self, chat_id: Union[int, str], question: str, options: List[str], + is_anonymous: Optional[bool]=None, type: Optional[str]=None, + allows_multiple_answers: Optional[bool]=None, + correct_option_id: Optional[int]=None, + explanation: Optional[str]=None, + explanation_parse_mode: Optional[str]=None, + open_period: Optional[int]=None, + close_date: Optional[Union[int, datetime]]=None, + is_closed: Optional[bool]=None, + disable_notification: Optional[bool]=False, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + allow_sending_without_reply: Optional[bool]=None, + timeout: Optional[int]=None, + explanation_entities: Optional[List[types.MessageEntity]]=None) -> types.Message: + """ + Send polls + :param chat_id: + :param question: + :param options: array of str with answers + :param is_anonymous: + :param type: + :param allows_multiple_answers: + :param correct_option_id: + :param explanation: + :param explanation_parse_mode: + :param open_period: + :param close_date: + :param is_closed: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: + :param timeout: + :param explanation_entities: + :return: + """ - @util.async_dec() - def send_invoice(self, *args, **kwargs): - return TeleBot.send_invoice(self, *args, **kwargs) + if isinstance(question, types.Poll): + raise RuntimeError("The send_poll signature was changed, please see send_poll function details.") - @util.async_dec() - def answer_shipping_query(self, *args, **kwargs): - return TeleBot.answer_shipping_query(self, *args, **kwargs) + return types.Message.de_json( + await asyncio_helper.send_poll( + self.token, chat_id, + question, options, + is_anonymous, type, allows_multiple_answers, correct_option_id, + explanation, explanation_parse_mode, open_period, close_date, is_closed, + disable_notification, reply_to_message_id, allow_sending_without_reply, + reply_markup, timeout, explanation_entities)) - @util.async_dec() - def answer_pre_checkout_query(self, *args, **kwargs): - return TeleBot.answer_pre_checkout_query(self, *args, **kwargs) + async def stop_poll( + self, chat_id: Union[int, str], message_id: int, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Poll: + """ + Stops poll + :param chat_id: + :param message_id: + :param reply_markup: + :return: + """ + return types.Poll.de_json(await asyncio_helper.stop_poll(self.token, chat_id, message_id, reply_markup)) - @util.async_dec() - def edit_message_caption(self, *args, **kwargs): - return TeleBot.edit_message_caption(self, *args, **kwargs) + async def answer_shipping_query( + self, shipping_query_id: str, ok: bool, + shipping_options: Optional[List[types.ShippingOption]]=None, + error_message: Optional[str]=None) -> bool: + """ + Asks for an answer to a shipping question + :param shipping_query_id: + :param ok: + :param shipping_options: + :param error_message: + :return: + """ + return await asyncio_helper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) - @util.async_dec() - def answer_inline_query(self, *args, **kwargs): - return TeleBot.answer_inline_query(self, *args, **kwargs) + async def answer_pre_checkout_query( + self, pre_checkout_query_id: int, ok: bool, + error_message: Optional[str]=None) -> bool: + """ + Response to a request for pre-inspection + :param pre_checkout_query_id: + :param ok: + :param error_message: + :return: + """ + return await asyncio_helper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) - @util.async_dec() - def answer_callback_query(self, *args, **kwargs): - return TeleBot.answer_callback_query(self, *args, **kwargs) + async def edit_message_caption( + self, caption: str, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit captions of messages + :param caption: + :param chat_id: + :param message_id: + :param inline_message_id: + :param parse_mode: + :param caption_entities: + :param reply_markup: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - @util.async_dec() - def get_sticker_set(self, *args, **kwargs): - return TeleBot.get_sticker_set(self, *args, **kwargs) + result = await asyncio_helper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, + parse_mode, caption_entities, reply_markup) + if type(result) == bool: + return result + return types.Message.de_json(result) - @util.async_dec() - def upload_sticker_file(self, *args, **kwargs): - return TeleBot.upload_sticker_file(self, *args, **kwargs) + async def reply_to(self, message: types.Message, text: str, **kwargs) -> types.Message: + """ + Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` + :param message: + :param text: + :param kwargs: + :return: + """ + return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) - @util.async_dec() - def create_new_sticker_set(self, *args, **kwargs): - return TeleBot.create_new_sticker_set(self, *args, **kwargs) + async def answer_inline_query( + self, inline_query_id: str, + results: List[Any], + cache_time: Optional[int]=None, + is_personal: Optional[bool]=None, + next_offset: Optional[str]=None, + switch_pm_text: Optional[str]=None, + switch_pm_parameter: Optional[str]=None) -> bool: + """ + Use this method to send answers to an inline query. On success, True is returned. + No more than 50 results per query are allowed. + :param inline_query_id: Unique identifier for the answered query + :param results: Array of results for the inline query + :param cache_time: The maximum amount of time in seconds that the result of the inline query + may be cached on the server. + :param is_personal: Pass True, if results may be cached on the server side only for + the user that sent the query. + :param next_offset: Pass the offset that a client should send in the next query with the same text + to receive more results. + :param switch_pm_parameter: If passed, clients will display a button with specified text that switches the user + to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter + :param switch_pm_text: Parameter for the start message sent to the bot when user presses the switch button + :return: True means success. + """ + return await asyncio_helper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset, + switch_pm_text, switch_pm_parameter) - @util.async_dec() - def add_sticker_to_set(self, *args, **kwargs): - return TeleBot.add_sticker_to_set(self, *args, **kwargs) + async def answer_callback_query( + self, callback_query_id: int, + text: Optional[str]=None, show_alert: Optional[bool]=None, + url: Optional[str]=None, cache_time: Optional[int]=None) -> bool: + """ + Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to + the user as a notification at the top of the chat screen or as an alert. + :param callback_query_id: + :param text: + :param show_alert: + :param url: + :param cache_time: + :return: + """ + return await asyncio_helper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) - @util.async_dec() - def set_sticker_position_in_set(self, *args, **kwargs): - return TeleBot.set_sticker_position_in_set(self, *args, **kwargs) + async def set_sticker_set_thumb( + self, name: str, user_id: int, thumb: Union[Any, str]=None): + """ + Use this method to set the thumbnail of a sticker set. + Animated thumbnails can be set for animated sticker sets only. Returns True on success. + """ + return await asyncio_helper.set_sticker_set_thumb(self.token, name, user_id, thumb) - @util.async_dec() - def delete_sticker_from_set(self, *args, **kwargs): - return TeleBot.delete_sticker_from_set(self, *args, **kwargs) - - @util.async_dec() - def set_sticker_set_thumb(self, *args, **kwargs): - return TeleBot.set_sticker_set_thumb(self, *args, **kwargs) + async def get_sticker_set(self, name: str) -> types.StickerSet: + """ + Use this method to get a sticker set. On success, a StickerSet object is returned. + :param name: + :return: + """ + result = await asyncio_helper.get_sticker_set(self.token, name) + return types.StickerSet.de_json(result) - @util.async_dec() - def send_poll(self, *args, **kwargs): - return TeleBot.send_poll(self, *args, **kwargs) + async def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: + """ + Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet + methods (can be used multiple times). Returns the uploaded File on success. + :param user_id: + :param png_sticker: + :return: + """ + result = await asyncio_helper.upload_sticker_file(self.token, user_id, png_sticker) + return types.File.de_json(result) - @util.async_dec() - def stop_poll(self, *args, **kwargs): - return TeleBot.stop_poll(self, *args, **kwargs) + async def create_new_sticker_set( + self, user_id: int, name: str, title: str, + emojis: str, + png_sticker: Union[Any, str], + tgs_sticker: Union[Any, str], + contains_masks: Optional[bool]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to create new sticker set owned by a user. + The bot will be able to edit the created sticker set. + Returns True on success. + :param user_id: + :param name: + :param title: + :param emojis: + :param png_sticker: + :param tgs_sticker: + :param contains_masks: + :param mask_position: + :return: + """ + return await asyncio_helper.create_new_sticker_set( + self.token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks, mask_position) + + + async def add_sticker_to_set( + self, user_id: int, name: str, emojis: str, + png_sticker: Optional[Union[Any, str]]=None, + tgs_sticker: Optional[Union[Any, str]]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to add a new sticker to a set created by the bot. + It's required to pass `png_sticker` or `tgs_sticker`. + Returns True on success. + :param user_id: + :param name: + :param emojis: + :param png_sticker: Required if `tgs_sticker` is None + :param tgs_sticker: Required if `png_sticker` is None + :param mask_position: + :return: + """ + return await asyncio_helper.add_sticker_to_set( + self.token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position) + + + async def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: + """ + Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. + :param sticker: + :param position: + :return: + """ + return await asyncio_helper.set_sticker_position_in_set(self.token, sticker, position) + + async def delete_sticker_from_set(self, sticker: str) -> bool: + """ + Use this method to delete a sticker from a set created by the bot. Returns True on success. + :param sticker: + :return: + """ + return await asyncio_helper.delete_sticker_from_set(self.token, sticker) + + async def register_for_reply( + self, message: types.Message, callback: Callable, *args, **kwargs) -> None: + """ + Registers a callback function to be notified when a reply to `message` arrives. + + Warning: In case `callback` as lambda function, saving reply handlers will not work. + + :param message: The message for which we are awaiting a reply. + :param callback: The callback function to be called when a reply arrives. Must accept one `message` + parameter, which will contain the replied message. + """ + message_id = message.message_id + self.register_for_reply_by_message_id(message_id, callback, *args, **kwargs) + + async def register_for_reply_by_message_id( + self, message_id: int, callback: Callable, *args, **kwargs) -> None: + """ + Registers a callback function to be notified when a reply to `message` arrives. + + Warning: In case `callback` as lambda function, saving reply handlers will not work. + + :param message_id: The id of the message for which we are awaiting a reply. + :param callback: The callback function to be called when a reply arrives. Must accept one `message` + parameter, which will contain the replied message. + """ + self.reply_backend.register_handler(message_id, Handler(callback, *args, **kwargs)) + + async def _notify_reply_handlers(self, new_messages) -> None: + """ + Notify handlers of the answers + :param new_messages: + :return: + """ + for message in new_messages: + if hasattr(message, "reply_to_message") and message.reply_to_message is not None: + handlers = self.reply_backend.get_handlers(message.reply_to_message.message_id) + if handlers: + for handler in handlers: + self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) + + async def register_next_step_handler( + self, message: types.Message, callback: Callable, *args, **kwargs) -> None: + """ + Registers a callback function to be notified when new message arrives after `message`. + + Warning: In case `callback` as lambda function, saving next step handlers will not work. + + :param message: The message for which we want to handle new message in the same chat. + :param callback: The callback function which next new message arrives. + :param args: Args to pass in callback func + :param kwargs: Args to pass in callback func + """ + chat_id = message.chat.id + self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) + + async def set_state(self, chat_id, state): + """ + Sets a new state of a user. + :param chat_id: + :param state: new state. can be string or integer. + """ + await self.current_states.add_state(chat_id, state) + + async def delete_state(self, chat_id): + """ + Delete the current state of a user. + :param chat_id: + :return: + """ + await self.current_states.delete_state(chat_id) + + def retrieve_data(self, chat_id): + return self.current_states.retrieve_data(chat_id) + + async def get_state(self, chat_id): + """ + Get current state of a user. + :param chat_id: + :return: state of a user + """ + return await self.current_states.current_state(chat_id) + + async def add_data(self, chat_id, **kwargs): + """ + Add data to states. + :param chat_id: + """ + for key, value in kwargs.items(): + await self.current_states._add_data(chat_id, key, value) + + \ No newline at end of file diff --git a/telebot/asyncio_filters.py b/telebot/asyncio_filters.py new file mode 100644 index 0000000..c8242fe --- /dev/null +++ b/telebot/asyncio_filters.py @@ -0,0 +1,176 @@ +from abc import ABC + +class SimpleCustomFilter(ABC): + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts only message, returns bool value, that is compared with given in handler. + """ + + async def check(self, message): + """ + Perform a check. + """ + pass + + +class AdvancedCustomFilter(ABC): + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts two parameters, returns bool: True - filter passed, False - filter failed. + message: Message class + text: Filter value given in handler + """ + + async def check(self, message, text): + """ + Perform a check. + """ + pass + + +class TextMatchFilter(AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + @bot.message_handler(text=['account']) + """ + + key = 'text' + + async def check(self, message, text): + if type(text) is list:return message.text in text + else: return text == message.text + +class TextContainsFilter(AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + # Will respond if any message.text contains word 'account' + @bot.message_handler(text_contains=['account']) + """ + + key = 'text_contains' + + async def check(self, message, text): + return text in message.text + +class TextStartsFilter(AdvancedCustomFilter): + """ + Filter to check whether message starts with some text. + + Example: + # Will work if message.text starts with 'Sir'. + @bot.message_handler(text_startswith='Sir') + """ + + key = 'text_startswith' + async def check(self, message, text): + return message.text.startswith(text) + +class ChatFilter(AdvancedCustomFilter): + """ + Check whether chat_id corresponds to given chat_id. + + Example: + @bot.message_handler(chat_id=[99999]) + """ + + key = 'chat_id' + async def check(self, message, text): + return message.chat.id in text + +class ForwardFilter(SimpleCustomFilter): + """ + Check whether message was forwarded from channel or group. + + Example: + + @bot.message_handler(is_forwarded=True) + """ + + key = 'is_forwarded' + + async def check(self, message): + return message.forward_from_chat is not None + +class IsReplyFilter(SimpleCustomFilter): + """ + Check whether message is a reply. + + Example: + + @bot.message_handler(is_reply=True) + """ + + key = 'is_reply' + + async def check(self, message): + return message.reply_to_message is not None + + + +class LanguageFilter(AdvancedCustomFilter): + """ + Check users language_code. + + Example: + + @bot.message_handler(language_code=['ru']) + """ + + key = 'language_code' + + async def check(self, message, text): + if type(text) is list:return message.from_user.language_code in text + else: return message.from_user.language_code == text + +class IsAdminFilter(SimpleCustomFilter): + """ + Check whether the user is administrator / owner of the chat. + + Example: + @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + """ + + key = 'is_chat_admin' + + def __init__(self, bot): + self._bot = bot + + async def check(self, message): + return self._bot.get_chat_member(message.chat.id, message.from_user.id).status in ['creator', 'administrator'] + +class StateFilter(AdvancedCustomFilter): + """ + Filter to check state. + + Example: + @bot.message_handler(state=1) + """ + def __init__(self, bot): + self.bot = bot + key = 'state' + + async def check(self, message, text): + if await self.bot.current_states.current_state(message.from_user.id) is False: return False + elif text == '*': return True + elif type(text) is list: return await self.bot.current_states.current_state(message.from_user.id) in text + return await self.bot.current_states.current_state(message.from_user.id) == text + +class IsDigitFilter(SimpleCustomFilter): + """ + Filter to check whether the string is made up of only digits. + + Example: + @bot.message_handler(is_digit=True) + """ + key = 'is_digit' + + async def check(self, message): + return message.text.isdigit() diff --git a/telebot/asyncio_handler_backends.py b/telebot/asyncio_handler_backends.py new file mode 100644 index 0000000..001f869 --- /dev/null +++ b/telebot/asyncio_handler_backends.py @@ -0,0 +1,343 @@ +import os +import pickle +import threading + +from telebot import apihelper + + +class HandlerBackend(object): + """ + Class for saving (next step|reply) handlers + """ + def __init__(self, handlers=None): + if handlers is None: + handlers = {} + self.handlers = handlers + + async def register_handler(self, handler_group_id, handler): + raise NotImplementedError() + + async def clear_handlers(self, handler_group_id): + raise NotImplementedError() + + async def get_handlers(self, handler_group_id): + raise NotImplementedError() + + +class MemoryHandlerBackend(HandlerBackend): + async def register_handler(self, handler_group_id, handler): + if handler_group_id in self.handlers: + self.handlers[handler_group_id].append(handler) + else: + self.handlers[handler_group_id] = [handler] + + async def clear_handlers(self, handler_group_id): + self.handlers.pop(handler_group_id, None) + + async def get_handlers(self, handler_group_id): + return self.handlers.pop(handler_group_id, None) + + async def load_handlers(self, filename, del_file_after_loading): + raise NotImplementedError() + + +class FileHandlerBackend(HandlerBackend): + def __init__(self, handlers=None, filename='./.handler-saves/handlers.save', delay=120): + super(FileHandlerBackend, self).__init__(handlers) + self.filename = filename + self.delay = delay + self.timer = threading.Timer(delay, self.save_handlers) + + async def register_handler(self, handler_group_id, handler): + if handler_group_id in self.handlers: + self.handlers[handler_group_id].append(handler) + else: + self.handlers[handler_group_id] = [handler] + await self.start_save_timer() + + async def clear_handlers(self, handler_group_id): + self.handlers.pop(handler_group_id, None) + await self.start_save_timer() + + async def get_handlers(self, handler_group_id): + handlers = self.handlers.pop(handler_group_id, None) + await self.start_save_timer() + return handlers + + async def start_save_timer(self): + if not self.timer.is_alive(): + if self.delay <= 0: + self.save_handlers() + else: + self.timer = threading.Timer(self.delay, self.save_handlers) + self.timer.start() + + async def save_handlers(self): + await self.dump_handlers(self.handlers, self.filename) + + async def load_handlers(self, filename=None, del_file_after_loading=True): + if not filename: + filename = self.filename + tmp = await self.return_load_handlers(filename, del_file_after_loading=del_file_after_loading) + if tmp is not None: + self.handlers.update(tmp) + + @staticmethod + async def dump_handlers(handlers, filename, file_mode="wb"): + dirs = filename.rsplit('/', maxsplit=1)[0] + os.makedirs(dirs, exist_ok=True) + + with open(filename + ".tmp", file_mode) as file: + if (apihelper.CUSTOM_SERIALIZER is None): + pickle.dump(handlers, file) + else: + apihelper.CUSTOM_SERIALIZER.dump(handlers, file) + + if os.path.isfile(filename): + os.remove(filename) + + os.rename(filename + ".tmp", filename) + + @staticmethod + async def return_load_handlers(filename, del_file_after_loading=True): + if os.path.isfile(filename) and os.path.getsize(filename) > 0: + with open(filename, "rb") as file: + if (apihelper.CUSTOM_SERIALIZER is None): + handlers = pickle.load(file) + else: + handlers = apihelper.CUSTOM_SERIALIZER.load(file) + + if del_file_after_loading: + os.remove(filename) + + return handlers + + +class RedisHandlerBackend(HandlerBackend): + def __init__(self, handlers=None, host='localhost', port=6379, db=0, prefix='telebot', password=None): + super(RedisHandlerBackend, self).__init__(handlers) + from redis import Redis + self.prefix = prefix + self.redis = Redis(host, port, db, password) + + async def _key(self, handle_group_id): + return ':'.join((self.prefix, str(handle_group_id))) + + async def register_handler(self, handler_group_id, handler): + handlers = [] + value = self.redis.get(self._key(handler_group_id)) + if value: + handlers = pickle.loads(value) + handlers.append(handler) + self.redis.set(self._key(handler_group_id), pickle.dumps(handlers)) + + async def clear_handlers(self, handler_group_id): + self.redis.delete(self._key(handler_group_id)) + + async def get_handlers(self, handler_group_id): + handlers = None + value = self.redis.get(self._key(handler_group_id)) + if value: + handlers = pickle.loads(value) + self.clear_handlers(handler_group_id) + return handlers + + +class StateMemory: + def __init__(self): + self._states = {} + + async def add_state(self, chat_id, state): + """ + Add a state. + :param chat_id: + :param state: new state + """ + if chat_id in self._states: + + self._states[chat_id]['state'] = state + else: + self._states[chat_id] = {'state': state,'data': {}} + + async def current_state(self, chat_id): + """Current state""" + if chat_id in self._states: return self._states[chat_id]['state'] + else: return False + + async def delete_state(self, chat_id): + """Delete a state""" + self._states.pop(chat_id) + + def _get_data(self, chat_id): + return self._states[chat_id]['data'] + + async def set(self, chat_id, new_state): + """ + Set a new state for a user. + :param chat_id: + :param new_state: new_state of a user + """ + await self.add_state(chat_id,new_state) + + async def _add_data(self, chat_id, key, value): + result = self._states[chat_id]['data'][key] = value + return result + + async def finish(self, chat_id): + """ + Finish(delete) state of a user. + :param chat_id: + """ + await self.delete_state(chat_id) + + def retrieve_data(self, chat_id): + """ + Save input text. + + Usage: + with bot.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + Also, at the end of your 'Form' you can get the name: + data['name'] + """ + return StateContext(self, chat_id) + + +class StateFile: + """ + Class to save states in a file. + """ + def __init__(self, filename): + self.file_path = filename + + async def add_state(self, chat_id, state): + """ + Add a state. + :param chat_id: + :param state: new state + """ + states_data = self._read_data() + if chat_id in states_data: + states_data[chat_id]['state'] = state + return await self._save_data(states_data) + else: + new_data = states_data[chat_id] = {'state': state,'data': {}} + return await self._save_data(states_data) + + + async def current_state(self, chat_id): + """Current state.""" + states_data = self._read_data() + if chat_id in states_data: return states_data[chat_id]['state'] + else: return False + + async def delete_state(self, chat_id): + """Delete a state""" + states_data = await self._read_data() + states_data.pop(chat_id) + await self._save_data(states_data) + + async def _read_data(self): + """ + Read the data from file. + """ + file = open(self.file_path, 'rb') + states_data = pickle.load(file) + file.close() + return states_data + + async def _create_dir(self): + """ + Create directory .save-handlers. + """ + dirs = self.file_path.rsplit('/', maxsplit=1)[0] + os.makedirs(dirs, exist_ok=True) + if not os.path.isfile(self.file_path): + with open(self.file_path,'wb') as file: + pickle.dump({}, file) + + async def _save_data(self, new_data): + """ + Save data after editing. + :param new_data: + """ + with open(self.file_path, 'wb+') as state_file: + pickle.dump(new_data, state_file, protocol=pickle.HIGHEST_PROTOCOL) + return True + + def _get_data(self, chat_id): + return self._read_data()[chat_id]['data'] + + async def set(self, chat_id, new_state): + """ + Set a new state for a user. + :param chat_id: + :param new_state: new_state of a user + + """ + await self.add_state(chat_id,new_state) + + async def _add_data(self, chat_id, key, value): + states_data = self._read_data() + result = states_data[chat_id]['data'][key] = value + await self._save_data(result) + + return result + + async def finish(self, chat_id): + """ + Finish(delete) state of a user. + :param chat_id: + """ + await self.delete_state(chat_id) + + async def retrieve_data(self, chat_id): + """ + Save input text. + + Usage: + with bot.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + Also, at the end of your 'Form' you can get the name: + data['name'] + """ + return StateFileContext(self, chat_id) + + +class StateContext: + """ + Class for data. + """ + def __init__(self , obj: StateMemory, chat_id) -> None: + self.obj = obj + self.chat_id = chat_id + self.data = obj._get_data(chat_id) + + async def __aenter__(self): + return self.data + + async def __aexit__(self, exc_type, exc_val, exc_tb): + return + +class StateFileContext: + """ + Class for data. + """ + def __init__(self , obj: StateFile, chat_id) -> None: + self.obj = obj + self.chat_id = chat_id + self.data = None + + async def __aenter__(self): + self.data = self.obj._get_data(self.chat_id) + return self.data + + async def __aexit__(self, exc_type, exc_val, exc_tb): + old_data = await self.obj._read_data() + for i in self.data: + old_data[self.chat_id]['data'][i] = self.data.get(i) + await self.obj._save_data(old_data) + + return diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py new file mode 100644 index 0000000..7bb649e --- /dev/null +++ b/telebot/asyncio_helper.py @@ -0,0 +1,1607 @@ +import asyncio +from time import time +import aiohttp +from telebot import types +import json +import logging + +try: + import ujson as json +except ImportError: + import json + +import requests +from requests.exceptions import HTTPError, ConnectionError, Timeout + +try: + # noinspection PyUnresolvedReferences + from requests.packages.urllib3 import fields + format_header_param = fields.format_header_param +except ImportError: + format_header_param = None + +API_URL = 'https://api.telegram.org/bot{0}/{1}' + +from datetime import datetime +from telebot import util + +class SessionBase: + def __init__(self) -> None: + self.session = None + async def _get_new_session(self): + self.session = aiohttp.ClientSession() + return self.session + +session_manager = SessionBase() + +proxy = None +session = None + +FILE_URL = None + +CONNECT_TIMEOUT = 15 +READ_TIMEOUT = 30 + +LONG_POLLING_TIMEOUT = 10 # Should be positive, short polling should be used for testing purposes only (https://core.telegram.org/bots/api#getupdates) + + +RETRY_ON_ERROR = False +RETRY_TIMEOUT = 2 +MAX_RETRIES = 15 + +CUSTOM_SERIALIZER = None +CUSTOM_REQUEST_SENDER = None + +ENABLE_MIDDLEWARE = False + +async def _process_request(token, url, method='get', params=None, files=None): + async with await session_manager._get_new_session() as session: + async with session.get(API_URL.format(token, url), params=params, data=files) as response: + json_result = await _check_result(url, response) + if json_result: + return json_result['result'] + + +async def _convert_markup(markup): + if isinstance(markup, types.JsonSerializable): + return markup.to_json() + return markup + + + +async def get_me(token): + method_url = r'getMe' + return await _process_request(token, method_url) + + +async def log_out(token): + method_url = r'logOut' + return await _process_request(token, method_url) + + +async def close(token): + method_url = r'close' + return await _process_request(token, method_url) + + +async def get_file(token, file_id): + method_url = r'getFile' + return await _process_request(token, method_url, params={'file_id': file_id}) + + +async def get_file_url(token, file_id): + if FILE_URL is None: + return "https://api.telegram.org/file/bot{0}/{1}".format(token, get_file(token, file_id)['file_path']) + else: + # noinspection PyUnresolvedReferences + return FILE_URL.format(token, get_file(token, file_id)['file_path']) + + +async def download_file(token, file_path): + if FILE_URL is None: + url = "https://api.telegram.org/file/bot{0}/{1}".format(token, file_path) + else: + # noinspection PyUnresolvedReferences + url = FILE_URL.format(token, file_path) + # TODO: rewrite this method + async with await session_manager._get_new_session() as session: + async with session.get(url, proxy=proxy) as response: + result = await response.read() + if response.status != 200: + raise ApiHTTPException('Download file', result) + + return result + + +async def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): + method_url = r'setWebhook' + payload = { + 'url': url if url else "", + } + files = None + if certificate: + files = {'certificate': certificate} + if max_connections: + payload['max_connections'] = max_connections + if allowed_updates is not None: # Empty lists should pass + payload['allowed_updates'] = json.dumps(allowed_updates) + if ip_address is not None: # Empty string should pass + payload['ip_address'] = ip_address + if drop_pending_updates is not None: # Any bool value should pass + payload['drop_pending_updates'] = drop_pending_updates + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload, files=files) + + +async def delete_webhook(token, drop_pending_updates=None, timeout=None): + method_url = r'deleteWebhook' + payload = {} + if drop_pending_updates is not None: # Any bool value should pass + payload['drop_pending_updates'] = drop_pending_updates + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def get_webhook_info(token, timeout=None): + method_url = r'getWebhookInfo' + payload = {} + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + + +async def get_updates(token, offset=None, limit=None, + timeout=None, allowed_updates=None, long_polling_timeout=None): + method_name = 'getUpdates' + params = {} + if offset: + params['offset'] = offset + elif limit: + params['limit'] = limit + elif timeout: + params['timeout'] = timeout + elif allowed_updates: + params['allowed_updates'] = allowed_updates + params['long_polling_timeout'] = long_polling_timeout if long_polling_timeout else LONG_POLLING_TIMEOUT + return await _process_request(token, method_name, params=params) + +async def _check_result(method_name, result): + """ + Checks whether `result` is a valid API response. + A result is considered invalid if: + - The server returned an HTTP response code other than 200 + - The content of the result is invalid JSON. + - The method call was unsuccessful (The JSON 'ok' field equals False) + + :raises ApiException: if one of the above listed cases is applicable + :param method_name: The name of the method called + :param result: The returned result of the method request + :return: The result parsed to a JSON dictionary. + """ + try: + result_json = await result.json(encoding="utf-8") + except: + if result.status_code != 200: + raise ApiHTTPException(method_name, result) + else: + raise ApiInvalidJSONException(method_name, result) + else: + if not result_json['ok']: + raise ApiTelegramException(method_name, result, result_json) + + return result_json + + +async def send_message( + token, chat_id, text, + disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, + entities=None, allow_sending_without_reply=None): + """ + Use this method to send text messages. On success, the sent Message is returned. + :param token: + :param chat_id: + :param text: + :param disable_web_page_preview: + :param reply_to_message_id: + :param reply_markup: + :param parse_mode: + :param disable_notification: + :param timeout: + :param entities: + :param allow_sending_without_reply: + :return: + """ + method_name = 'sendMessage' + params = {'chat_id': str(chat_id), 'text': text} + if disable_web_page_preview is not None: + params['disable_web_page_preview'] = disable_web_page_preview + if reply_to_message_id: + params['reply_to_message_id'] = reply_to_message_id + if reply_markup: + params['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + params['parse_mode'] = parse_mode + if disable_notification is not None: + params['disable_notification'] = disable_notification + if timeout: + params['timeout'] = timeout + if entities: + params['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) + if allow_sending_without_reply is not None: + params['allow_sending_without_reply'] = allow_sending_without_reply + + return await _process_request(token, method_name, params=params) + +# here shit begins + +async def get_user_profile_photos(token, user_id, offset=None, limit=None): + method_url = r'getUserProfilePhotos' + payload = {'user_id': user_id} + if offset: + payload['offset'] = offset + if limit: + payload['limit'] = limit + return await _process_request(token, method_url, params=payload) + + +async def get_chat(token, chat_id): + method_url = r'getChat' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def leave_chat(token, chat_id): + method_url = r'leaveChat' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def get_chat_administrators(token, chat_id): + method_url = r'getChatAdministrators' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def get_chat_member_count(token, chat_id): + method_url = r'getChatMemberCount' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def set_sticker_set_thumb(token, name, user_id, thumb): + method_url = r'setStickerSetThumb' + payload = {'name': name, 'user_id': user_id} + files = {} + if thumb: + if not isinstance(thumb, str): + files['thumb'] = thumb + else: + payload['thumb'] = thumb + return await _process_request(token, method_url, params=payload, files=files or None) + + +async def set_chat_sticker_set(token, chat_id, sticker_set_name): + method_url = r'setChatStickerSet' + payload = {'chat_id': chat_id, 'sticker_set_name': sticker_set_name} + return await _process_request(token, method_url, params=payload) + + +async def delete_chat_sticker_set(token, chat_id): + method_url = r'deleteChatStickerSet' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def get_chat_member(token, chat_id, user_id): + method_url = r'getChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + return await _process_request(token, method_url, params=payload) + + +async def forward_message( + token, chat_id, from_chat_id, message_id, + disable_notification=None, timeout=None): + method_url = r'forwardMessage' + payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, + disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None): + method_url = r'copyMessage' + payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} + if caption is not None: + payload['caption'] = caption + if parse_mode: + payload['parse_mode'] = parse_mode + if caption_entities is not None: + payload['caption_entities'] = await _convert_entites(caption_entities) + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup is not None: + payload['reply_markup'] = await _convert_markup(reply_markup) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def send_dice( + token, chat_id, + emoji=None, disable_notification=None, reply_to_message_id=None, + reply_markup=None, timeout=None, allow_sending_without_reply=None): + method_url = r'sendDice' + payload = {'chat_id': chat_id} + if emoji: + payload['emoji'] = emoji + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload) + + +async def send_photo( + token, chat_id, photo, + caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, + caption_entities=None, allow_sending_without_reply=None): + method_url = r'sendPhoto' + payload = {'chat_id': chat_id} + files = None + if util.is_string(photo): + payload['photo'] = photo + elif util.is_pil_image(photo): + files = {'photo': util.pil_image_to_file(photo)} + else: + files = {'photo': photo} + if caption: + payload['caption'] = caption + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_media_group( + token, chat_id, media, + disable_notification=None, reply_to_message_id=None, + timeout=None, allow_sending_without_reply=None): + method_url = r'sendMediaGroup' + media_json, files = await convert_input_media_array(media) + payload = {'chat_id': chat_id, 'media': media_json} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request( + token, method_url, params=payload, + method='post' if files else 'get', + files=files if files else None) + + +async def send_location( + token, chat_id, latitude, longitude, + live_period=None, reply_to_message_id=None, + reply_markup=None, disable_notification=None, + timeout=None, horizontal_accuracy=None, heading=None, + proximity_alert_radius=None, allow_sending_without_reply=None): + method_url = r'sendLocation' + payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude} + if live_period: + payload['live_period'] = live_period + if horizontal_accuracy: + payload['horizontal_accuracy'] = horizontal_accuracy + if heading: + payload['heading'] = heading + if proximity_alert_radius: + payload['proximity_alert_radius'] = proximity_alert_radius + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def edit_message_live_location( + token, latitude, longitude, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None, timeout=None, + horizontal_accuracy=None, heading=None, proximity_alert_radius=None): + method_url = r'editMessageLiveLocation' + payload = {'latitude': latitude, 'longitude': longitude} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if horizontal_accuracy: + payload['horizontal_accuracy'] = horizontal_accuracy + if heading: + payload['heading'] = heading + if proximity_alert_radius: + payload['proximity_alert_radius'] = proximity_alert_radius + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def stop_message_live_location( + token, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None, timeout=None): + method_url = r'stopMessageLiveLocation' + payload = {} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def send_venue( + token, chat_id, latitude, longitude, title, address, + foursquare_id=None, foursquare_type=None, disable_notification=None, + reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None, google_place_id=None, + google_place_type=None): + method_url = r'sendVenue' + payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address} + if foursquare_id: + payload['foursquare_id'] = foursquare_id + if foursquare_type: + payload['foursquare_type'] = foursquare_type + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if google_place_id: + payload['google_place_id'] = google_place_id + if google_place_type: + payload['google_place_type'] = google_place_type + return await _process_request(token, method_url, params=payload) + + +async def send_contact( + token, chat_id, phone_number, first_name, last_name=None, vcard=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None): + method_url = r'sendContact' + payload = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name} + if last_name: + payload['last_name'] = last_name + if vcard: + payload['vcard'] = vcard + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload) + + +async def send_chat_action(token, chat_id, action, timeout=None): + method_url = r'sendChatAction' + payload = {'chat_id': chat_id, 'action': action} + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def send_video(token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, + thumb=None, width=None, height=None, caption_entities=None, allow_sending_without_reply=None): + method_url = r'sendVideo' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + files = {'video': data} + else: + payload['video'] = data + if duration: + payload['duration'] = duration + if caption: + payload['caption'] = caption + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if supports_streaming is not None: + payload['supports_streaming'] = supports_streaming + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if width: + payload['width'] = width + if height: + payload['height'] = height + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_animation( + token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, thumb=None, caption_entities=None, + allow_sending_without_reply=None): + method_url = r'sendAnimation' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + files = {'animation': data} + else: + payload['animation'] = data + if duration: + payload['duration'] = duration + if caption: + payload['caption'] = caption + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, caption_entities=None, + allow_sending_without_reply=None): + method_url = r'sendVoice' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(voice): + files = {'voice': voice} + else: + payload['voice'] = voice + if caption: + payload['caption'] = caption + if duration: + payload['duration'] = duration + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, + disable_notification=None, timeout=None, thumb=None, allow_sending_without_reply=None): + method_url = r'sendVideoNote' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + files = {'video_note': data} + else: + payload['video_note'] = data + if duration: + payload['duration'] = duration + if length and (str(length).isdigit() and int(length) <= 639): + payload['length'] = length + else: + payload['length'] = 639 # seems like it is MAX length size + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_audio(token, chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, + reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, thumb=None, + caption_entities=None, allow_sending_without_reply=None): + method_url = r'sendAudio' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(audio): + files = {'audio': audio} + else: + payload['audio'] = audio + if caption: + payload['caption'] = caption + if duration: + payload['duration'] = duration + if performer: + payload['performer'] = performer + if title: + payload['title'] = title + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, + disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, + allow_sending_without_reply=None, disable_content_type_detection=None, visible_file_name=None): + method_url = get_method_by_type(data_type) + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + file_data = data + if visible_file_name: + file_data = (visible_file_name, data) + files = {data_type: file_data} + else: + payload[data_type] = data + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode and data_type == 'document': + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if caption: + payload['caption'] = caption + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if method_url == 'sendDocument' and disable_content_type_detection is not None: + payload['disable_content_type_detection'] = disable_content_type_detection + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def get_method_by_type(data_type): + if data_type == 'document': + return r'sendDocument' + if data_type == 'sticker': + return r'sendSticker' + + +async def ban_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=None): + method_url = 'banChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if isinstance(until_date, datetime): + payload['until_date'] = until_date.timestamp() + else: + payload['until_date'] = until_date + if revoke_messages is not None: + payload['revoke_messages'] = revoke_messages + return await _process_request(token, method_url, params=payload, method='post') + + +async def unban_chat_member(token, chat_id, user_id, only_if_banned): + method_url = 'unbanChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if only_if_banned is not None: # None / True / False + payload['only_if_banned'] = only_if_banned + return await _process_request(token, method_url, params=payload, method='post') + + +async def restrict_chat_member( + token, chat_id, user_id, until_date=None, + can_send_messages=None, can_send_media_messages=None, + can_send_polls=None, can_send_other_messages=None, + can_add_web_page_previews=None, can_change_info=None, + can_invite_users=None, can_pin_messages=None): + method_url = 'restrictChatMember' + permissions = {} + if can_send_messages is not None: + permissions['can_send_messages'] = can_send_messages + if can_send_media_messages is not None: + permissions['can_send_media_messages'] = can_send_media_messages + if can_send_polls is not None: + permissions['can_send_polls'] = can_send_polls + if can_send_other_messages is not None: + permissions['can_send_other_messages'] = can_send_other_messages + if can_add_web_page_previews is not None: + permissions['can_add_web_page_previews'] = can_add_web_page_previews + if can_change_info is not None: + permissions['can_change_info'] = can_change_info + if can_invite_users is not None: + permissions['can_invite_users'] = can_invite_users + if can_pin_messages is not None: + permissions['can_pin_messages'] = can_pin_messages + permissions_json = json.dumps(permissions) + payload = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions_json} + if until_date is not None: + if isinstance(until_date, datetime): + payload['until_date'] = until_date.timestamp() + else: + payload['until_date'] = until_date + return await _process_request(token, method_url, params=payload, method='post') + + +async def promote_chat_member( + token, chat_id, user_id, can_change_info=None, can_post_messages=None, + can_edit_messages=None, can_delete_messages=None, can_invite_users=None, + can_restrict_members=None, can_pin_messages=None, can_promote_members=None, + is_anonymous=None, can_manage_chat=None, can_manage_voice_chats=None): + method_url = 'promoteChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if can_change_info is not None: + payload['can_change_info'] = can_change_info + if can_post_messages is not None: + payload['can_post_messages'] = can_post_messages + if can_edit_messages is not None: + payload['can_edit_messages'] = can_edit_messages + if can_delete_messages is not None: + payload['can_delete_messages'] = can_delete_messages + if can_invite_users is not None: + payload['can_invite_users'] = can_invite_users + if can_restrict_members is not None: + payload['can_restrict_members'] = can_restrict_members + if can_pin_messages is not None: + payload['can_pin_messages'] = can_pin_messages + if can_promote_members is not None: + payload['can_promote_members'] = can_promote_members + if is_anonymous is not None: + payload['is_anonymous'] = is_anonymous + if can_manage_chat is not None: + payload['can_manage_chat'] = can_manage_chat + if can_manage_voice_chats is not None: + payload['can_manage_voice_chats'] = can_manage_voice_chats + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_administrator_custom_title(token, chat_id, user_id, custom_title): + method_url = 'setChatAdministratorCustomTitle' + payload = { + 'chat_id': chat_id, 'user_id': user_id, 'custom_title': custom_title + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_permissions(token, chat_id, permissions): + method_url = 'setChatPermissions' + payload = { + 'chat_id': chat_id, + 'permissions': permissions.to_json() + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def create_chat_invite_link(token, chat_id, name, expire_date, member_limit, creates_join_request): + method_url = 'createChatInviteLink' + payload = { + 'chat_id': chat_id + } + + if expire_date is not None: + if isinstance(expire_date, datetime): + payload['expire_date'] = expire_date.timestamp() + else: + payload['expire_date'] = expire_date + if member_limit: + payload['member_limit'] = member_limit + if creates_join_request is not None: + payload['creates_join_request'] = creates_join_request + if name: + payload['name'] = name + + return await _process_request(token, method_url, params=payload, method='post') + + +async def edit_chat_invite_link(token, chat_id, invite_link, name, expire_date, member_limit, creates_join_request): + method_url = 'editChatInviteLink' + payload = { + 'chat_id': chat_id, + 'invite_link': invite_link + } + + if expire_date is not None: + if isinstance(expire_date, datetime): + payload['expire_date'] = expire_date.timestamp() + else: + payload['expire_date'] = expire_date + + if member_limit is not None: + payload['member_limit'] = member_limit + if name: + payload['name'] = name + if creates_join_request is not None: + payload['creates_join_request'] = creates_join_request + + return await _process_request(token, method_url, params=payload, method='post') + +async def revoke_chat_invite_link(token, chat_id, invite_link): + method_url = 'revokeChatInviteLink' + payload = { + 'chat_id': chat_id, + 'invite_link': invite_link + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def export_chat_invite_link(token, chat_id): + method_url = 'exportChatInviteLink' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload, method='post') + +async def approve_chat_join_request(token, chat_id, user_id): + method_url = 'approveChatJoinRequest' + payload = { + 'chat_id': chat_id, + 'user_id': user_id + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def decline_chat_join_request(token, chat_id, user_id): + method_url = 'declineChatJoinRequest' + payload = { + 'chat_id': chat_id, + 'user_id': user_id + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_photo(token, chat_id, photo): + method_url = 'setChatPhoto' + payload = {'chat_id': chat_id} + files = None + if util.is_string(photo): + payload['photo'] = photo + elif util.is_pil_image(photo): + files = {'photo': util.pil_image_to_file(photo)} + else: + files = {'photo': photo} + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def delete_chat_photo(token, chat_id): + method_url = 'deleteChatPhoto' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_title(token, chat_id, title): + method_url = 'setChatTitle' + payload = {'chat_id': chat_id, 'title': title} + return await _process_request(token, method_url, params=payload, method='post') + + +async def get_my_commands(token, scope=None, language_code=None): + method_url = r'getMyCommands' + payload = {} + if scope: + payload['scope'] = scope.to_json() + if language_code: + payload['language_code'] = language_code + return await _process_request(token, method_url, params=payload) + + +async def set_my_commands(token, commands, scope=None, language_code=None): + method_url = r'setMyCommands' + payload = {'commands': await _convert_list_json_serializable(commands)} + if scope: + payload['scope'] = scope.to_json() + if language_code: + payload['language_code'] = language_code + return await _process_request(token, method_url, params=payload, method='post') + + +async def delete_my_commands(token, scope=None, language_code=None): + method_url = r'deleteMyCommands' + payload = {} + if scope: + payload['scope'] = scope.to_json() + if language_code: + payload['language_code'] = language_code + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_description(token, chat_id, description): + method_url = 'setChatDescription' + payload = {'chat_id': chat_id} + if description is not None: # Allow empty strings + payload['description'] = description + return await _process_request(token, method_url, params=payload, method='post') + + +async def pin_chat_message(token, chat_id, message_id, disable_notification=None): + method_url = 'pinChatMessage' + payload = {'chat_id': chat_id, 'message_id': message_id} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + return await _process_request(token, method_url, params=payload, method='post') + + +async def unpin_chat_message(token, chat_id, message_id): + method_url = 'unpinChatMessage' + payload = {'chat_id': chat_id} + if message_id: + payload['message_id'] = message_id + return await _process_request(token, method_url, params=payload, method='post') + + +async def unpin_all_chat_messages(token, chat_id): + method_url = 'unpinAllChatMessages' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload, method='post') + + +# Updating messages + +async def edit_message_text(token, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, + entities = None, disable_web_page_preview=None, reply_markup=None): + method_url = r'editMessageText' + payload = {'text': text} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if parse_mode: + payload['parse_mode'] = parse_mode + if entities: + payload['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) + if disable_web_page_preview is not None: + payload['disable_web_page_preview'] = disable_web_page_preview + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, method='post') + + +async def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_message_id=None, + parse_mode=None, caption_entities=None,reply_markup=None): + method_url = r'editMessageCaption' + payload = {'caption': caption} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if parse_mode: + payload['parse_mode'] = parse_mode + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, method='post') + + +async def edit_message_media(token, media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + method_url = r'editMessageMedia' + media_json, file = convert_input_media(media) + payload = {'media': media_json} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, files=file, method='post' if file else 'get') + + +async def edit_message_reply_markup(token, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + method_url = r'editMessageReplyMarkup' + payload = {} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, method='post') + + +async def delete_message(token, chat_id, message_id, timeout=None): + method_url = r'deleteMessage' + payload = {'chat_id': chat_id, 'message_id': message_id} + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload, method='post') + + +# Game + +async def send_game( + token, chat_id, game_short_name, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None): + method_url = r'sendGame' + payload = {'chat_id': chat_id, 'game_short_name': game_short_name} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload) + + +# https://core.telegram.org/bots/api#setgamescore +async def set_game_score(token, user_id, score, force=None, disable_edit_message=None, chat_id=None, message_id=None, + inline_message_id=None): + """ + Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. + :param token: Bot's token (you don't need to fill this) + :param user_id: User identifier + :param score: New score, must be non-negative + :param force: (Optional) Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters + :param disable_edit_message: (Optional) Pass True, if the game message should not be automatically edited to include the current scoreboard + :param chat_id: (Optional, required if inline_message_id is not specified) Unique identifier for the target chat (or username of the target channel in the format @channelusername) + :param message_id: (Optional, required if inline_message_id is not specified) Unique identifier of the sent message + :param inline_message_id: (Optional, required if chat_id and message_id are not specified) Identifier of the inline message + :return: + """ + method_url = r'setGameScore' + payload = {'user_id': user_id, 'score': score} + if force is not None: + payload['force'] = force + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if disable_edit_message is not None: + payload['disable_edit_message'] = disable_edit_message + return await _process_request(token, method_url, params=payload) + + +# https://core.telegram.org/bots/api#getgamehighscores +async def get_game_high_scores(token, user_id, chat_id=None, message_id=None, inline_message_id=None): + """ + Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. + This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. + :param token: Bot's token (you don't need to fill this) + :param user_id: Target user id + :param chat_id: (Optional, required if inline_message_id is not specified) Unique identifier for the target chat (or username of the target channel in the format @channelusername) + :param message_id: (Optional, required if inline_message_id is not specified) Unique identifier of the sent message + :param inline_message_id: (Optional, required if chat_id and message_id are not specified) Identifier of the inline message + :return: + """ + method_url = r'getGameHighScores' + payload = {'user_id': user_id} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + return await _process_request(token, method_url, params=payload) + + +# Payments (https://core.telegram.org/bots/api#payments) + +async def send_invoice( + token, chat_id, title, description, invoice_payload, provider_token, currency, prices, + start_parameter = None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, + need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, + send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, + timeout=None, allow_sending_without_reply=None, max_tip_amount=None, suggested_tip_amounts=None): + """ + Use this method to send invoices. On success, the sent Message is returned. + :param token: Bot's token (you don't need to fill this) + :param chat_id: Unique identifier for the target private chat + :param title: Product name + :param description: Product description + :param invoice_payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param provider_token: Payments provider token, obtained via @Botfather + :param currency: Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass True, if you require the user's full name to complete the order + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :param need_email: Pass True, if you require the user's email to complete the order + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param reply_to_message_id: If the message is a reply, ID of the original message + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param timeout: + :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest units of the currency. + At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + :return: + """ + method_url = r'sendInvoice' + payload = {'chat_id': chat_id, 'title': title, 'description': description, 'payload': invoice_payload, + 'provider_token': provider_token, 'currency': currency, + 'prices': await _convert_list_json_serializable(prices)} + if start_parameter: + payload['start_parameter'] = start_parameter + if photo_url: + payload['photo_url'] = photo_url + if photo_size: + payload['photo_size'] = photo_size + if photo_width: + payload['photo_width'] = photo_width + if photo_height: + payload['photo_height'] = photo_height + if need_name is not None: + payload['need_name'] = need_name + if need_phone_number is not None: + payload['need_phone_number'] = need_phone_number + if need_email is not None: + payload['need_email'] = need_email + if need_shipping_address is not None: + payload['need_shipping_address'] = need_shipping_address + if send_phone_number_to_provider is not None: + payload['send_phone_number_to_provider'] = send_phone_number_to_provider + if send_email_to_provider is not None: + payload['send_email_to_provider'] = send_email_to_provider + if is_flexible is not None: + payload['is_flexible'] = is_flexible + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if provider_data: + payload['provider_data'] = provider_data + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if max_tip_amount is not None: + payload['max_tip_amount'] = max_tip_amount + if suggested_tip_amounts is not None: + payload['suggested_tip_amounts'] = json.dumps(suggested_tip_amounts) + return await _process_request(token, method_url, params=payload) + + +async def answer_shipping_query(token, shipping_query_id, ok, shipping_options=None, error_message=None): + """ + If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. + :param token: Bot's token (you don't need to fill this) + :param shipping_query_id: Unique identifier for the query to be answered + :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) + :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options. + :param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. + :return: + """ + method_url = 'answerShippingQuery' + payload = {'shipping_query_id': shipping_query_id, 'ok': ok} + if shipping_options: + payload['shipping_options'] = await _convert_list_json_serializable(shipping_options) + if error_message: + payload['error_message'] = error_message + return await _process_request(token, method_url, params=payload) + + +async def answer_pre_checkout_query(token, pre_checkout_query_id, ok, error_message=None): + """ + Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + :param token: Bot's token (you don't need to fill this) + :param pre_checkout_query_id: Unique identifier for the query to be answered + :param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. + :param error_message: Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. + :return: + """ + method_url = 'answerPreCheckoutQuery' + payload = {'pre_checkout_query_id': pre_checkout_query_id, 'ok': ok} + if error_message: + payload['error_message'] = error_message + return await _process_request(token, method_url, params=payload) + + +# InlineQuery + +async def answer_callback_query(token, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): + """ + Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. + Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via BotFather and accept the terms. Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter. + :param token: Bot's token (you don't need to fill this) + :param callback_query_id: Unique identifier for the query to be answered + :param text: (Optional) Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + :param show_alert: (Optional) If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. + :param url: (Optional) URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button. + Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter. + :param cache_time: (Optional) The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. + :return: + """ + method_url = 'answerCallbackQuery' + payload = {'callback_query_id': callback_query_id} + if text: + payload['text'] = text + if show_alert is not None: + payload['show_alert'] = show_alert + if url: + payload['url'] = url + if cache_time is not None: + payload['cache_time'] = cache_time + return await _process_request(token, method_url, params=payload, method='post') + + +async def answer_inline_query(token, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, + switch_pm_text=None, switch_pm_parameter=None): + method_url = 'answerInlineQuery' + payload = {'inline_query_id': inline_query_id, 'results': await _convert_list_json_serializable(results)} + if cache_time is not None: + payload['cache_time'] = cache_time + if is_personal is not None: + payload['is_personal'] = is_personal + if next_offset is not None: + payload['next_offset'] = next_offset + if switch_pm_text: + payload['switch_pm_text'] = switch_pm_text + if switch_pm_parameter: + payload['switch_pm_parameter'] = switch_pm_parameter + return await _process_request(token, method_url, params=payload, method='post') + + +async def get_sticker_set(token, name): + method_url = 'getStickerSet' + return await _process_request(token, method_url, params={'name': name}) + + +async def upload_sticker_file(token, user_id, png_sticker): + method_url = 'uploadStickerFile' + payload = {'user_id': user_id} + files = {'png_sticker': png_sticker} + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def create_new_sticker_set( + token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks=None, mask_position=None): + method_url = 'createNewStickerSet' + payload = {'user_id': user_id, 'name': name, 'title': title, 'emojis': emojis} + stype = 'png_sticker' if png_sticker else 'tgs_sticker' + sticker = png_sticker or tgs_sticker + files = None + if not util.is_string(sticker): + files = {stype: sticker} + else: + payload[stype] = sticker + if contains_masks is not None: + payload['contains_masks'] = contains_masks + if mask_position: + payload['mask_position'] = mask_position.to_json() + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def add_sticker_to_set(token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position): + method_url = 'addStickerToSet' + payload = {'user_id': user_id, 'name': name, 'emojis': emojis} + stype = 'png_sticker' if png_sticker else 'tgs_sticker' + sticker = png_sticker or tgs_sticker + files = None + if not util.is_string(sticker): + files = {stype: sticker} + else: + payload[stype] = sticker + if mask_position: + payload['mask_position'] = mask_position.to_json() + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def set_sticker_position_in_set(token, sticker, position): + method_url = 'setStickerPositionInSet' + payload = {'sticker': sticker, 'position': position} + return await _process_request(token, method_url, params=payload, method='post') + + +async def delete_sticker_from_set(token, sticker): + method_url = 'deleteStickerFromSet' + payload = {'sticker': sticker} + return await _process_request(token, method_url, params=payload, method='post') + + +# noinspection PyShadowingBuiltins +async def send_poll( + token, chat_id, + question, options, + is_anonymous = None, type = None, allows_multiple_answers = None, correct_option_id = None, + explanation = None, explanation_parse_mode=None, open_period = None, close_date = None, is_closed = None, + disable_notification=False, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None, explanation_entities=None): + method_url = r'sendPoll' + payload = { + 'chat_id': str(chat_id), + 'question': question, + 'options': json.dumps(await _convert_poll_options(options))} + + if is_anonymous is not None: + payload['is_anonymous'] = is_anonymous + if type is not None: + payload['type'] = type + if allows_multiple_answers is not None: + payload['allows_multiple_answers'] = allows_multiple_answers + if correct_option_id is not None: + payload['correct_option_id'] = correct_option_id + if explanation is not None: + payload['explanation'] = explanation + if explanation_parse_mode is not None: + payload['explanation_parse_mode'] = explanation_parse_mode + if open_period is not None: + payload['open_period'] = open_period + if close_date is not None: + if isinstance(close_date, datetime): + payload['close_date'] = close_date.timestamp() + else: + payload['close_date'] = close_date + if is_closed is not None: + payload['is_closed'] = is_closed + + if disable_notification: + payload['disable_notification'] = disable_notification + if reply_to_message_id is not None: + payload['reply_to_message_id'] = reply_to_message_id + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if reply_markup is not None: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if explanation_entities: + payload['explanation_entities'] = json.dumps( + types.MessageEntity.to_list_of_dicts(explanation_entities)) + return await _process_request(token, method_url, params=payload) + +async def _convert_list_json_serializable(results): + ret = '' + for r in results: + if isinstance(r, types.JsonSerializable): + ret = ret + r.to_json() + ',' + if len(ret) > 0: + ret = ret[:-1] + return '[' + ret + ']' + + + +async def _convert_entites(entites): + if entites is None: + return None + elif len(entites) == 0: + return [] + elif isinstance(entites[0], types.JsonSerializable): + return [entity.to_json() for entity in entites] + else: + return entites + + +async def _convert_poll_options(poll_options): + if poll_options is None: + return None + elif len(poll_options) == 0: + return [] + elif isinstance(poll_options[0], str): + # Compatibility mode with previous bug when only list of string was accepted as poll_options + return poll_options + elif isinstance(poll_options[0], types.PollOption): + return [option.text for option in poll_options] + else: + return poll_options + + +async def convert_input_media(media): + if isinstance(media, types.InputMedia): + return media.convert_input_media() + return None, None + + +async def convert_input_media_array(array): + media = [] + files = {} + for input_media in array: + if isinstance(input_media, types.InputMedia): + media_dict = input_media.to_dict() + if media_dict['media'].startswith('attach://'): + key = media_dict['media'].replace('attach://', '') + files[key] = input_media.media + media.append(media_dict) + return json.dumps(media), files + + +async def _no_encode(func): + def wrapper(key, val): + if key == 'filename': + return u'{0}={1}'.format(key, val) + else: + return func(key, val) + + return wrapper + +async def stop_poll(token, chat_id, message_id, reply_markup=None): + method_url = r'stopPoll' + payload = {'chat_id': str(chat_id), 'message_id': message_id} + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload) + +# exceptions +class ApiException(Exception): + """ + This class represents a base Exception thrown when a call to the Telegram API fails. + In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively + contain the name of the failed function and the returned result that made the function to be considered as + failed. + """ + + def __init__(self, msg, function_name, result): + super(ApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg)) + self.function_name = function_name + self.result = result + +class ApiHTTPException(ApiException): + """ + This class represents an Exception thrown when a call to the + Telegram API server returns HTTP code that is not 200. + """ + def __init__(self, function_name, result): + super(ApiHTTPException, self).__init__( + "The server returned HTTP {0} {1}. Response body:\n[{2}]" \ + .format(result.status_code, result.reason, result), + function_name, + result) + +class ApiInvalidJSONException(ApiException): + """ + This class represents an Exception thrown when a call to the + Telegram API server returns invalid json. + """ + def __init__(self, function_name, result): + super(ApiInvalidJSONException, self).__init__( + "The server returned an invalid JSON response. Response body:\n[{0}]" \ + .format(result), + function_name, + result) + +class ApiTelegramException(ApiException): + """ + This class represents an Exception thrown when a Telegram API returns error code. + """ + def __init__(self, function_name, result, result_json): + super(ApiTelegramException, self).__init__( + "Error code: {0}. Description: {1}" \ + .format(result_json['error_code'], result_json['description']), + function_name, + result) + self.result_json = result_json + self.error_code = result_json['error_code'] \ No newline at end of file