diff --git a/docs/source/async_version/index.rst b/docs/source/async_version/index.rst index 88b382417..2d0130155 100644 --- a/docs/source/async_version/index.rst +++ b/docs/source/async_version/index.rst @@ -46,4 +46,12 @@ Asyncio handler backends :show-inheritance: +Extensions +------------------------ + + +.. automodule:: telebot.ext.aio.webhooks + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/sync_version/index.rst b/docs/source/sync_version/index.rst index 8b805dc52..9bcd3b26d 100644 --- a/docs/source/sync_version/index.rst +++ b/docs/source/sync_version/index.rst @@ -37,3 +37,13 @@ handler_backends file :undoc-members: :show-inheritance: + +Extensions +------------------------ + + + +.. automodule:: telebot.ext.aio.webhooks + :members: + :undoc-members: + :show-inheritance: \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index 21a05ca1e..da3bf26f8 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -84,10 +84,13 @@ class TeleBot: Usage: - .. code-block:: python + .. code-block:: python3 + :caption: Creating instance of TeleBot from telebot import TeleBot bot = TeleBot('token') # get token from @BotFather + # now you can register other handlers/update listeners, + # and use bot methods. See more examples in examples/ directory: https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples @@ -243,7 +246,7 @@ def enable_saving_states(self, filename: Optional[str]="./.state-save/states.pkl Enable saving states (by default saving disabled) .. note:: - It is recommended to pass a :class:`~telebot.storage.StateMemoryStorage` instance as state_storage + It is recommended to pass a :class:`~telebot.storage.StatePickleStorage` instance as state_storage to TeleBot class. :param filename: Filename of saving file, defaults to "./.state-save/states.pkl" @@ -547,8 +550,6 @@ def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, Telegram documentation: https://core.telegram.org/bots/api#getupdates - :param allowed_updates: Array of string. List the types of updates you want your bot to receive. - :type allowed_updates: :obj:`list`, optional :param offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset @@ -562,6 +563,9 @@ def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, :param timeout: Request connection timeout :type timeout: :obj:`int`, optional + :param allowed_updates: Array of string. List the types of updates you want your bot to receive. + :type allowed_updates: :obj:`list`, optional + :param long_polling_timeout: Timeout in seconds for long polling. :type long_polling_timeout: :obj:`int`, optional @@ -604,6 +608,9 @@ def process_new_updates(self, updates: List[types.Update]): Processes new updates. Just pass list of subclasses of Update to this method. :param updates: List of :class:`telebot.types.Update` objects. + :type updates: :obj:`list` of :class:`telebot.types.Update` + + :return None: """ upd_count = len(updates) logger.debug('Received {0} new updates'.format(upd_count)) @@ -885,11 +892,11 @@ def polling(self, non_stop: Optional[bool]=False, skip_pending: Optional[bool]=F none_stop: Optional[bool]=None): """ This function creates a new Thread that calls an internal __retrieve_updates function. - This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly. + This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly. Warning: Do not call this function more than once! - Always get updates. + Always gets updates. .. deprecated:: 4.1.1 Use :meth:`infinity_polling` instead. @@ -921,7 +928,7 @@ def polling(self, non_stop: Optional[bool]=False, skip_pending: Optional[bool]=F 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. - :type allowed_updates: :obj:`list`] of :obj:`str` + :type allowed_updates: :obj:`list` of :obj:`str` :param none_stop: Deprecated, use non_stop. Old typo, kept for backward compatibility. :type none_stop: :obj:`bool` @@ -1104,6 +1111,8 @@ def _exec_task(self, task, *args, **kwargs): def stop_polling(self): """ Stops polling. + + Does not accept any arguments. """ self.__stop_polling.set() @@ -1170,6 +1179,15 @@ def get_file_url(self, file_id: Optional[str]) -> str: def download_file(self, file_path: str) -> bytes: + """ + Downloads file. + + :param file_path: Path where the file should be downloaded. + :type file_path: str + + :return: bytes + :rtype: :obj:`bytes` + """ return apihelper.download_file(self.token, file_path) @@ -1209,7 +1227,7 @@ def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None, limit: Optional[int]=None) -> types.UserProfilePhotos: """ Use this method to get a list of profile pictures for a user. - Returns a UserProfilePhotos object. + Returns a :class:`telebot.types.UserProfilePhotos` object. Telegram documentation: https://core.telegram.org/bots/api#getuserprofilephotos @@ -1240,7 +1258,7 @@ def get_chat(self, chat_id: Union[int, str]) -> types.Chat: :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) :type chat_id: :obj:`int` or :obj:`str` - :return: :class:`telebot.types.Chat` + :return: Chat information :rtype: :class:`telebot.types.Chat` """ result = apihelper.get_chat(self.token, chat_id) @@ -1384,8 +1402,8 @@ def send_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, + Warning: Do not send more than about 4096 characters each message, otherwise you'll risk an HTTP 414 error. + If you must send more than 4096 characters, use the `split_string` or `smart_split` function in util.py. Telegram documentation: https://core.telegram.org/bots/api#sendmessage @@ -3552,7 +3570,12 @@ def get_game_high_scores( message_id: Optional[int]=None, inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: """ - Gets top points and game play. + Use this method to get data for high score tables. Will return the score of the specified user and several of + their 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 their closest neighbors on each side. + Will also return the top three users if the user and their neighbors are not among them. + Please note that this behavior is subject to change. Telegram documentation: https://core.telegram.org/bots/api#getgamehighscores @@ -4430,10 +4453,16 @@ def setup_middleware(self, middleware: BaseMiddleware): self.middlewares.append(middleware) - def set_state(self, user_id: int, state: Union[int, str, State], chat_id: int=None) -> None: + def set_state(self, user_id: int, state: Union[int, str, State], chat_id: Optional[int]=None) -> None: """ Sets a new state of a user. + .. note:: + + You should set both user id and chat id in order to set state for a user in a chat. + Otherwise, if you only set user_id, chat_id will equal to user_id, this means that + state will be set for the user in his private chat with a bot. + :param user_id: User's identifier :type user_id: :obj:`int` @@ -4449,7 +4478,7 @@ def set_state(self, user_id: int, state: Union[int, str, State], chat_id: int=No chat_id = user_id self.current_states.set_state(chat_id, user_id, state) - def reset_data(self, user_id: int, chat_id: int=None): + def reset_data(self, user_id: int, chat_id: Optional[int]=None): """ Reset data for a user in chat. @@ -4465,7 +4494,7 @@ def reset_data(self, user_id: int, chat_id: int=None): chat_id = user_id self.current_states.reset_data(chat_id, user_id) - def delete_state(self, user_id: int, chat_id: int=None) -> None: + def delete_state(self, user_id: int, chat_id: Optional[int]=None) -> None: """ Delete the current state of a user. @@ -4481,12 +4510,24 @@ def delete_state(self, user_id: int, chat_id: int=None) -> None: chat_id = user_id self.current_states.delete_state(chat_id, user_id) - def retrieve_data(self, user_id: int, chat_id: int=None) -> Optional[Any]: + def retrieve_data(self, user_id: int, chat_id: Optional[int]=None) -> Optional[Any]: + """ + Returns context manager with data for a user in chat. + + :param user_id: User identifier + :type user_id: int + + :param chat_id: Chat's unique identifier, defaults to user_id + :type chat_id: int, optional + + :return: Context manager with data for a user in chat + :rtype: Optional[Any] + """ if chat_id is None: chat_id = user_id return self.current_states.get_interactive_data(chat_id, user_id) - def get_state(self, user_id: int, chat_id: int=None) -> Optional[Union[int, str, State]]: + def get_state(self, user_id: int, chat_id: Optional[int]=None) -> Optional[Union[int, str, State]]: """ Gets current state of a user. Not recommended to use this method. But it is ok for debugging. @@ -4504,7 +4545,7 @@ def get_state(self, user_id: int, chat_id: int=None) -> Optional[Union[int, str, chat_id = user_id return self.current_states.get_state(chat_id, user_id) - def add_data(self, user_id: int, chat_id:int=None, **kwargs): + def add_data(self, user_id: int, chat_id: Optional[int]=None, **kwargs): """ Add data to states. @@ -4635,6 +4676,7 @@ def middleware_handler(self, update_types: Optional[List[str]]=None): Example: .. code-block:: python3 + :caption: Usage of middleware_handler bot = TeleBot('TOKEN') @@ -4728,13 +4770,14 @@ def check_regexp_input(regexp, method_name): def message_handler(self, commands: Optional[List[str]]=None, regexp: Optional[str]=None, func: Optional[Callable]=None, content_types: Optional[List[str]]=None, chat_types: Optional[List[str]]=None, **kwargs): """ - Message handler decorator. - This decorator can be used to decorate functions that must handle certain types of messages. + Handles New incoming message of any kind - text, photo, sticker, etc. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. All message handlers are tested in the order they were added. Example: - .. code-block:: python + .. code-block:: python3 + :caption: Usage of message_handler bot = TeleBot('TOKEN') @@ -4768,8 +4811,17 @@ def default_command(message): :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. + :type func: :obj:`lambda` + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + :param chat_types: list of chat types + :type chat_types: :obj:`list` of :obj:`str` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: decorated function """ if content_types is None: content_types = ["text"] @@ -4871,7 +4923,8 @@ def register_message_handler(self, callback: Callable, content_types: Optional[L def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ - Edit message handler decorator + Handles new version of a message that is known to the bot and was edited. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. :param commands: Optional list of strings (commands to handle). :type commands: :obj:`list` of :obj:`str` @@ -4889,6 +4942,7 @@ def edited_message_handler(self, commands=None, regexp=None, func=None, content_ :type chat_types: :obj:`list` of :obj:`str` :param kwargs: Optional keyword arguments(custom filters) + :return: None """ if content_types is None: @@ -4960,6 +5014,8 @@ def register_edited_message_handler(self, callback: Callable, content_types: Opt :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ method_name = "register_edited_message_handler" @@ -4988,7 +5044,8 @@ def register_edited_message_handler(self, callback: Callable, content_types: Opt def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ - Channel post handler decorator. + Handles new incoming channel post of any kind - text, photo, sticker, etc. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. :param commands: Optional list of strings (commands to handle). :type commands: :obj:`list` of :obj:`str` @@ -5003,6 +5060,7 @@ def channel_post_handler(self, commands=None, regexp=None, func=None, content_ty :type content_types: :obj:`list` of :obj:`str` :param kwargs: Optional keyword arguments(custom filters) + :return: None """ if content_types is None: @@ -5069,6 +5127,8 @@ def register_channel_post_handler(self, callback: Callable, content_types: Optio :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ method_name = "register_channel_post_handler" @@ -5096,7 +5156,8 @@ def register_channel_post_handler(self, callback: Callable, content_types: Optio def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ - Edit channel post handler decorator + Handles new version of a channel post that is known to the bot and was edited. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. :param commands: Optional list of strings (commands to handle). :type commands: :obj:`list` of :obj:`str` @@ -5178,6 +5239,8 @@ def register_edited_channel_post_handler(self, callback: Callable, content_types :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: decorated function """ method_name = "register_edited_channel_post_handler" @@ -5205,7 +5268,8 @@ def register_edited_channel_post_handler(self, callback: Callable, content_types def inline_handler(self, func, **kwargs): """ - Inline call handler decorator + Handles new incoming inline query. + As a parameter to the decorator function, it passes :class:`telebot.types.InlineQuery` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5246,6 +5310,8 @@ def register_inline_handler(self, callback: Callable, func: Callable, pass_bot: :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: decorated function """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5253,7 +5319,9 @@ def register_inline_handler(self, callback: Callable, func: Callable, pass_bot: def chosen_inline_handler(self, func, **kwargs): """ - Description: The result of an inline query that was chosen by a user and sent to their chat partner. + Handles the result of an inline query that was chosen by a user and sent to their chat partner. + Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. + As a parameter to the decorator function, it passes :class:`telebot.types.ChosenInlineResult` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5294,6 +5362,8 @@ def register_chosen_inline_handler(self, callback: Callable, func: Callable, pas :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5301,7 +5371,8 @@ def register_chosen_inline_handler(self, callback: Callable, func: Callable, pas def callback_query_handler(self, func, **kwargs): """ - Callback request handler decorator + Handles new incoming callback query. + As a parameter to the decorator function, it passes :class:`telebot.types.CallbackQuery` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5342,6 +5413,8 @@ def register_callback_query_handler(self, callback: Callable, func: Callable, pa :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5349,7 +5422,8 @@ def register_callback_query_handler(self, callback: Callable, func: Callable, pa def shipping_query_handler(self, func, **kwargs): """ - Shipping request handler + Handles new incoming shipping query. Only for invoices with flexible price. + As a parameter to the decorator function, it passes :class:`telebot.types.ShippingQuery` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5390,6 +5464,8 @@ def register_shipping_query_handler(self, callback: Callable, func: Callable, pa :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5397,7 +5473,8 @@ def register_shipping_query_handler(self, callback: Callable, func: Callable, pa def pre_checkout_query_handler(self, func, **kwargs): """ - Pre-checkout request handler + New incoming pre-checkout query. Contains full information about checkout. + As a parameter to the decorator function, it passes :class:`telebot.types.PreCheckoutQuery` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5437,6 +5514,8 @@ def register_pre_checkout_query_handler(self, callback: Callable, func: Callable :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: decorated function """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5444,7 +5523,8 @@ def register_pre_checkout_query_handler(self, callback: Callable, func: Callable def poll_handler(self, func, **kwargs): """ - Poll request handler + Handles new state of a poll. Bots receive only updates about stopped polls and polls, which are sent by the bot + As a parameter to the decorator function, it passes :class:`telebot.types.Poll` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5484,6 +5564,8 @@ def register_poll_handler(self, callback: Callable, func: Callable, pass_bot: Op :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5491,7 +5573,9 @@ def register_poll_handler(self, callback: Callable, func: Callable, pass_bot: Op def poll_answer_handler(self, func=None, **kwargs): """ - Poll_answer request handler + Handles change of user's answer in a non-anonymous poll(when user changes the vote). + Bots receive new votes only in polls that were sent by the bot itself. + As a parameter to the decorator function, it passes :class:`telebot.types.PollAnswer` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5532,6 +5616,8 @@ def register_poll_answer_handler(self, callback: Callable, func: Callable, pass_ :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5539,8 +5625,9 @@ def register_poll_answer_handler(self, callback: Callable, func: Callable, pass_ def my_chat_member_handler(self, func=None, **kwargs): """ - The bot's chat member status was updated in a chat. For private chats, + Handles update in a status of a bot. For private chats, this update is received only when the bot is blocked or unblocked by the user. + As a parameter to the decorator function, it passes :class:`telebot.types.ChatMemberUpdated` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5581,6 +5668,8 @@ def register_my_chat_member_handler(self, callback: Callable, func: Optional[Cal :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5588,8 +5677,10 @@ def register_my_chat_member_handler(self, callback: Callable, func: Optional[Cal def chat_member_handler(self, func=None, **kwargs): """ - A chat member's status was updated in a chat. The bot must be an administrator - in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. + Handles update in a status of a user in a chat. + The bot must be an administrator in the chat and must explicitly specify “chat_member” + in the list of allowed_updates to receive these updates. + As a parameter to the decorator function, it passes :class:`telebot.types.ChatMemberUpdated` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5639,8 +5730,9 @@ def register_chat_member_handler(self, callback: Callable, func: Optional[Callab def chat_join_request_handler(self, func=None, **kwargs): """ - A request to join the chat has been sent. The bot must have the can_invite_users + Handles a request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. + As a parameter to the decorator function, it passes :class:`telebot.types.ChatJoinRequest` object. :param func: Function executed as a filter :type func: :obj:`function` @@ -5681,6 +5773,8 @@ def register_chat_join_request_handler(self, callback: Callable, func: Optional[ :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) :type pass_bot: :obj:`bool` + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -5707,6 +5801,15 @@ def add_custom_filter(self, custom_filter: Union[SimpleCustomFilter, AdvancedCus """ Create custom filter. + .. code-block:: python3 + :caption: Example on checking the text of a message + + class TextMatchFilter(AdvancedCustomFilter): + key = 'text' + + async def check(self, message, text): + return text == message.text + :param custom_filter: Class with check(message) method. :param custom_filter: Custom filter class with key. """ diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 2241316ae..1ae0de574 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -5,7 +5,7 @@ import re import time import traceback -from typing import Any, List, Optional, Union +from typing import Any, Awaitable, Callable, List, Optional, Union # this imports are used to avoid circular import error import telebot.util @@ -13,7 +13,7 @@ # storages -from telebot.asyncio_storage import StateMemoryStorage, StatePickleStorage +from telebot.asyncio_storage import StateMemoryStorage, StatePickleStorage, StateStorageBase from telebot.asyncio_handler_backends import BaseMiddleware, CancelUpdate, SkipHandler, State from inspect import signature @@ -71,18 +71,38 @@ class AsyncTeleBot: Usage: - .. code-block:: python + .. code-block:: python3 + :caption: Using asynchronous implementation of TeleBot. from telebot.async_telebot import AsyncTeleBot bot = AsyncTeleBot('token') # get token from @BotFather + # now you can register other handlers/update listeners, + # and use bot methods. + # Remember to use async/await keywords when necessary. See more examples in examples/ directory: https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples + + :param token: Token of a bot, obtained from @BotFather + :type token: :obj:`str` + + :param parse_mode: Default parse mode, defaults to None + :type parse_mode: :obj:`str`, optional + + :param offset: Offset used in get_updates, defaults to None + :type offset: :obj:`int`, optional + + :param exception_handler: Exception handler, which will handle the exception occured, defaults to None + :type exception_handler: Optional[ExceptionHandler], optional + + :param state_storage: Storage for states, defaults to StateMemoryStorage() + :type state_storage: :class:`telebot.asyncio_storage.StateMemoryStorage`, optional + """ - def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, - exception_handler=None, state_storage=StateMemoryStorage()) -> None: # TODO: ADD TYPEHINTS + def __init__(self, token: str, parse_mode: Optional[str]=None, offset: Optional[int]=None, + exception_handler: Optional[ExceptionHandler]=None, state_storage: Optional[StateStorageBase]=StateMemoryStorage()) -> None: self.token = token self.offset = offset @@ -118,43 +138,73 @@ def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, async def close_session(self): """ Closes existing session of aiohttp. - Use this function if you stop polling. + Use this function if you stop polling/webhooks. """ await asyncio_helper.session_manager.session.close() async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, timeout: Optional[int]=20, allowed_updates: Optional[List]=None, request_timeout: Optional[int]=None) -> List[types.Update]: """ - Use this method to receive incoming updates using long polling (wiki). - An Array of Update objects is returned. + Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. + + Telegram documentation: https://core.telegram.org/bots/api#getupdates + - Telegram documentation: https://core.telegram.org/bots/api#making-requests + :param offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. + By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset + higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. + All previous updates will forgotten. + :type offset: :obj:`int`, optional + + :param limit: Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. + :type limit: :obj:`int`, optional + + :param timeout: Request connection timeout + :type timeout: :obj:`int`, optional :param allowed_updates: Array of string. List the types of updates you want your bot to receive. - :param offset: Integer. Identifier of the first update to be returned. - :param limit: Integer. Limits the number of updates to be retrieved. - :param timeout: Integer. Request connection timeout - :param request_timeout: Timeout in seconds for a request. - :return: array of Updates + :type allowed_updates: :obj:`list`, optional + + :param long_polling_timeout: Timeout in seconds for long polling. + :type long_polling_timeout: :obj:`int`, optional + + :return: An Array of Update objects is returned. + :rtype: :obj:`list` of :class:`telebot.types.Update` """ json_updates = await asyncio_helper.get_updates(self.token, offset, limit, timeout, allowed_updates, request_timeout) return [types.Update.de_json(ju) for ju in json_updates] async def polling(self, non_stop: bool=False, skip_pending=False, interval: int=0, timeout: int=20, - request_timeout: int=None, allowed_updates: Optional[List[str]]=None, + request_timeout: Optional[int]=None, 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. + Runs bot in long-polling mode in a main loop. + This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly. Warning: Do not call this function more than once! - Always get updates. + Always gets updates. + + .. note:: + + Set non_stop=True if you want your bot to continue receiving updates + if there is an error. - :param interval: Delay between two update retrivals :param non_stop: Do not stop polling when an ApiException occurs. - :param timeout: Request connection timeout + :type non_stop: :obj:`bool` + :param skip_pending: skip old updates - :param request_timeout: Timeout in seconds for a request. + :type skip_pending: :obj:`bool` + + :param interval: Delay between two update retrivals + :type interval: :obj:`int` + + :param timeout: Request connection timeout + :type timeout: :obj:`int` + + :param request_timeout: Timeout in seconds for get_updates(Defaults to None) + :type request_timeout: :obj:`int` + :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. @@ -163,7 +213,11 @@ async def polling(self, non_stop: bool=False, skip_pending=False, interval: int= 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 + :type allowed_updates: :obj:`list` of :obj:`str` + + :param none_stop: Deprecated, use non_stop. Old typo, kept for backward compatibility. + :type none_stop: :obj:`bool` + :return: """ if none_stop is not None: @@ -174,16 +228,24 @@ async def polling(self, non_stop: bool=False, skip_pending=False, interval: int= await self.skip_updates() await self._process_polling(non_stop, interval, timeout, request_timeout, allowed_updates) - async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, request_timeout: int=None, logger_level=logging.ERROR, - allowed_updates: Optional[List[str]]=None, *args, **kwargs): + async def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Optional[bool]=False, request_timeout: Optional[int]=None, + logger_level: Optional[int]=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 request_timeout: Timeout in seconds for long polling (see API docs) + :param timeout: Timeout in seconds for get_updates(Defaults to None) + :type timeout: :obj:`int` + :param skip_pending: skip old updates + :type skip_pending: :obj:`bool` + + :param request_timeout: Aiohttp's request timeout. Defaults to 5 minutes(aiohttp.ClientTimeout). + :type request_timeout: :obj:`int` + :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging + :type logger_level: :obj:`int` + :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. @@ -192,13 +254,16 @@ async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, requ 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. + :type allowed_updates: :obj:`list` of :obj:`str` + + :return: None """ if skip_pending: await self.skip_updates() self._polling = True while self._polling: try: - await self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout, + await self._process_polling(non_stop=False, timeout=timeout, request_timeout=request_timeout, allowed_updates=allowed_updates, *args, **kwargs) except Exception as e: if logger_level and logger_level >= logging.ERROR: @@ -370,13 +435,16 @@ async def _run_middlewares_and_handlers(self, handlers, message, middlewares, up logger.error('Middleware {} does not have post_process_{} method. post_process function execution was skipped.'.format(middleware.__class__.__name__, update_type)) else: await middleware.post_process(message, data, handler_error) # update handling - async def process_new_updates(self, updates): + async def process_new_updates(self, updates: List[types.Update]): """ Process new updates. Just pass list of updates - each update should be instance of Update object. :param updates: list of updates + :type updates: :obj:`list` of :obj:`telebot.types.Update` + + :return: None """ upd_count = len(updates) logger.info('Received {0} new updates'.format(upd_count)) @@ -471,49 +539,94 @@ async def process_new_updates(self, updates): await self.process_chat_join_request(chat_join_request) async def process_new_messages(self, new_messages): + """ + :meta private: + """ await self.__notify_update(new_messages) await self._process_updates(self.message_handlers, new_messages, 'message') async def process_new_edited_messages(self, edited_message): + """ + :meta private: + """ await self._process_updates(self.edited_message_handlers, edited_message, 'edited_message') async def process_new_channel_posts(self, channel_post): + """ + :meta private: + """ await self._process_updates(self.channel_post_handlers, channel_post , 'channel_post') async def process_new_edited_channel_posts(self, edited_channel_post): + """ + :meta private: + """ await self._process_updates(self.edited_channel_post_handlers, edited_channel_post, 'edited_channel_post') async def process_new_inline_query(self, new_inline_querys): + """ + :meta private: + """ await self._process_updates(self.inline_handlers, new_inline_querys, 'inline_query') async def process_new_chosen_inline_query(self, new_chosen_inline_querys): + """ + :meta private: + """ await self._process_updates(self.chosen_inline_handlers, new_chosen_inline_querys, 'chosen_inline_query') async def process_new_callback_query(self, new_callback_querys): + """ + :meta private: + """ await self._process_updates(self.callback_query_handlers, new_callback_querys, 'callback_query') async def process_new_shipping_query(self, new_shipping_querys): + """ + :meta private: + """ await self._process_updates(self.shipping_query_handlers, new_shipping_querys, 'shipping_query') async def process_new_pre_checkout_query(self, pre_checkout_querys): + """ + :meta private: + """ await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys, 'pre_checkout_query') async def process_new_poll(self, polls): + """ + :meta private: + """ await self._process_updates(self.poll_handlers, polls, 'poll') async def process_new_poll_answer(self, poll_answers): + """ + :meta private: + """ await self._process_updates(self.poll_answer_handlers, poll_answers, 'poll_answer') async def process_new_my_chat_member(self, my_chat_members): + """ + :meta private: + """ await self._process_updates(self.my_chat_member_handlers, my_chat_members, 'my_chat_member') async def process_new_chat_member(self, chat_members): + """ + :meta private: + """ await self._process_updates(self.chat_member_handlers, chat_members, 'chat_member') async def process_chat_join_request(self, chat_join_request): + """ + :meta private: + """ await self._process_updates(self.chat_join_request_handlers, chat_join_request, 'chat_join_request') async def process_middlewares(self, update_type): + """ + :meta private: + """ if self.middlewares: middlewares = [middleware for middleware in self.middlewares if update_type in middleware.update_types] return middlewares @@ -542,19 +655,43 @@ async def _test_message_handler(self, message_handler, message): return True - def set_update_listener(self, func): + def set_update_listener(self, func: Awaitable): """ Update listener is a function that gets any update. :param func: function that should get update. + :type func: :obj:`Awaitable` + + .. code-block:: python3 + :caption: Example on asynchronous update listeners. + + async def update_listener(new_messages): + for message in new_messages: + print(message.text) # Prints message text + + bot.set_update_listener(update_listener) + + :return: None """ self.update_listener.append(func) - def add_custom_filter(self, custom_filter): + def add_custom_filter(self, custom_filter: Union[asyncio_filters.SimpleCustomFilter, asyncio_filters.AdvancedCustomFilter]): """ Create custom filter. - custom_filter: Class with check(message) method. + .. code-block:: python3 + :caption: Example on checking the text of a message + + class TextMatchFilter(AdvancedCustomFilter): + key = 'text' + + async def check(self, message, text): + return text == message.text + + :param custom_filter: Class with check(message) method. + :type custom_filter: :class:`telebot.asyncio_filters.SimpleCustomFilter` or :class:`telebot.asyncio_filters.AdvancedCustomFilter` + + :return: None """ self.custom_filters[custom_filter.key] = custom_filter @@ -613,8 +750,14 @@ def setup_middleware(self, middleware: BaseMiddleware): """ Setup middleware. + .. note:: + + Take a look at the :class:`telebot.asyncio_handler_backends.BaseMiddleware` section for more. + :param middleware: Middleware-class. - :return: + :type middleware: :class:`telebot.asyncio_handler_backends.BaseMiddleware` + + :return: None """ if not hasattr(middleware, 'update_types'): logger.error('Middleware has no update_types parameter. Please add list of updates to handle.') @@ -628,44 +771,58 @@ def setup_middleware(self, middleware: BaseMiddleware): 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. + Handles ew incoming message of any kind - text, photo, sticker, etc. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. All message handlers are tested in the order they were added. Example: - .. code-block:: python + .. code-block:: python3 + :caption: Usage of message_handler bot = TeleBot('TOKEN') # 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?') + await bot.send_message(message.chat.id, 'Did someone call for help?') # 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!') + await bot.send_message(message.chat.id, 'Private chat detected, sir!') # 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!') + await 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.") + async def default_command(message): + await bot.send_message(message.chat.id, "This is the default command handler.") :param commands: Optional list of strings (commands to handle). + :type commands: :obj:`list` of :obj:`str` + :param regexp: Optional regular expression. + :type regexp: :obj:`str` + :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 content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + :param chat_types: list of chat types + :type chat_types: :obj:`list` of :obj:`str` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: decorated function """ if content_types is None: @@ -696,24 +853,43 @@ def add_message_handler(self, handler_dict): """ Adds a message handler. Note that you should use register_message_handler to add message_handler. + + :meta private: :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, pass_bot=False, **kwargs): + def register_message_handler(self, callback: Awaitable, content_types: Optional[List[str]]=None, commands: Optional[List[str]]=None, + regexp: Optional[str]=None, func: Optional[Callable]=None, chat_types: Optional[List[str]]=None, pass_bot: Optional[bool]=False, **kwargs): """ Registers message handler. :param callback: function to be called - :param content_types: list of content_types + :type callback: :obj:`Awaitable` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + :param commands: list of commands + :type commands: :obj:`list` of :obj:`str` + :param regexp: - :param func: - :param chat_types: True for private chat - :param pass_bot: True if you want to get TeleBot instance in your handler - :return: decorated function + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param chat_types: List of chat types + :type chat_types: :obj:`list` of :obj:`str` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ if content_types is None: content_types = ["text"] @@ -737,15 +913,28 @@ def register_message_handler(self, callback, content_types=None, commands=None, def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ - Edit message handler decorator. + Handles new version of a message that is known to the bot and was edited. + + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. + + :param commands: Optional list of strings (commands to handle). + :type commands: :obj:`list` of :obj:`str` + + :param regexp: Optional regular expression. + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` - :param commands: - :param regexp: - :param func: - :param content_types: :param chat_types: list of chat types - :param kwargs: - :return: + :type chat_types: :obj:`list` of :obj:`str` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ if content_types is None: @@ -777,23 +966,43 @@ def add_edited_message_handler(self, handler_dict): Adds the edit message handler. Note that you should use register_edited_message_handler to add edited_message_handler. + :meta private: + :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, pass_bot=False, **kwargs): + def register_edited_message_handler(self, callback: Awaitable, content_types: Optional[List[str]]=None, + commands: Optional[List[str]]=None, regexp: Optional[str]=None, func: Optional[Callable]=None, + chat_types: Optional[List[str]]=None, pass_bot: Optional[bool]=False, **kwargs): """ Registers edited message handler. - :param pass_bot: :param callback: function to be called - :param content_types: list of content_types + :type callback: :obj:`Awaitable` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + :param commands: list of commands - :param regexp: - :param func: + :type commands: :obj:`list` of :obj:`str` + + :param regexp: Regular expression + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + :param chat_types: True for private chat - :return: decorated function + :type chat_types: :obj:`bool` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ if isinstance(commands, str): logger.warning("register_edited_message_handler: 'commands' filter should be List of strings (commands), not string.") @@ -816,14 +1025,23 @@ def register_edited_message_handler(self, callback, content_types=None, commands def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ - Channel post handler decorator. + Handles new incoming channel post of any kind - text, photo, sticker, etc. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. - :param commands: - :param regexp: - :param func: - :param content_types: - :param kwargs: - :return: + :param commands: Optional list of strings (commands to handle). + :type commands: :obj:`list` of :obj:`str` + + :param regexp: Optional regular expression. + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ if content_types is None: content_types = ["text"] @@ -853,22 +1071,39 @@ def add_channel_post_handler(self, handler_dict): Adds channel post handler. Note that you should use register_channel_post_handler to add channel_post_handler. + :meta private: + :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, pass_bot=False, **kwargs): + def register_channel_post_handler(self, callback: Awaitable, content_types: Optional[List[str]]=None, commands: Optional[List[str]]=None, + regexp: Optional[str]=None, func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs): """ Registers channel post message handler. - :param pass_bot: :param callback: function to be called - :param content_types: list of content_types + :type callback: :obj:`Awaitable` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + :param commands: list of commands - :param regexp: - :param func: - :return: decorated function + :type commands: :obj:`list` of :obj:`str` + + :param regexp: Regular expression + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ if isinstance(commands, str): logger.warning("register_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") @@ -889,13 +1124,23 @@ def register_channel_post_handler(self, callback, content_types=None, commands=N def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ - Edit channel post handler decorator. + Handles new version of a channel post that is known to the bot and was edited. + As a parameter to the decorator function, it passes :class:`telebot.types.Message` object. + + :param commands: Optional list of strings (commands to handle). + :type commands: :obj:`list` of :obj:`str` + + :param regexp: Optional regular expression. + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + + :param kwargs: Optional keyword arguments(custom filters) - :param commands: - :param regexp: - :param func: - :param content_types: - :param kwargs: :return: """ if content_types is None: @@ -926,21 +1171,38 @@ def add_edited_channel_post_handler(self, handler_dict): Adds the edit channel post handler. Note that you should use register_edited_channel_post_handler to add edited_channel_post_handler. + :meta private: + :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, pass_bot=False, **kwargs): + def register_edited_channel_post_handler(self, callback: Awaitable, content_types: Optional[List[str]]=None, + commands: Optional[List[str]]=None, regexp: Optional[str]=None, func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs): """ Registers edited channel post message handler. - :param pass_bot: :param callback: function to be called - :param content_types: list of content_types + :type callback: :obj:`Awaitable` + + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :type content_types: :obj:`list` of :obj:`str` + :param commands: list of commands - :param regexp: - :param func: + :type commands: :obj:`list` of :obj:`str` + + :param regexp: Regular expression + :type regexp: :obj:`str` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + :return: decorated function """ if isinstance(commands, str): @@ -962,11 +1224,15 @@ def register_edited_channel_post_handler(self, callback, content_types=None, com def inline_handler(self, func, **kwargs): """ - Inline call handler decorator. + Handles new incoming inline query. + As a parameter to the decorator function, it passes :class:`telebot.types.InlineQuery` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -981,18 +1247,28 @@ def add_inline_handler(self, handler_dict): Adds inline call handler. Note that you should use register_inline_handler to add inline_handler. + :meta private: + :param handler_dict: :return: """ self.inline_handlers.append(handler_dict) - def register_inline_handler(self, callback, func, pass_bot=False, **kwargs): + def register_inline_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers inline handler. - :param pass_bot: :param callback: function to be called - :param func: + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + :return: decorated function """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -1000,12 +1276,16 @@ def register_inline_handler(self, callback, func, pass_bot=False, **kwargs): def chosen_inline_handler(self, func, **kwargs): """ + The result of an inline query that was chosen by a user and sent to their chat partner. + Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. + As a parameter to the decorator function, it passes :class:`telebot.types.ChosenInlineResult` object. - Description: TBD + :param func: Function executed as a filter + :type func: :obj:`function` - :param func: - :param kwargs: - :return: + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1020,30 +1300,44 @@ def add_chosen_inline_handler(self, handler_dict): Description: TBD Note that you should use register_chosen_inline_handler to add chosen_inline_handler. + :meta private: + :param handler_dict: :return: """ self.chosen_inline_handlers.append(handler_dict) - def register_chosen_inline_handler(self, callback, func, pass_bot=False, **kwargs): + def register_chosen_inline_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers chosen inline handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_chosen_inline_handler(handler_dict) def callback_query_handler(self, func, **kwargs): """ - Callback request handler decorator. + Handles new incoming callback query. + As a parameter to the decorator function, it passes :class:`telebot.types.CallbackQuery` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1058,30 +1352,44 @@ def add_callback_query_handler(self, handler_dict): Adds a callback request handler. Note that you should use register_callback_query_handler to add callback_query_handler. + :meta private: + :param handler_dict: :return: """ self.callback_query_handlers.append(handler_dict) - def register_callback_query_handler(self, callback, func, pass_bot=False, **kwargs): + def register_callback_query_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers callback query handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_callback_query_handler(handler_dict) def shipping_query_handler(self, func, **kwargs): """ - Shipping request handler. + Handles new incoming shipping query. Only for invoices with flexible price. + As a parameter to the decorator function, it passes :class:`telebot.types.ShippingQuery` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1096,30 +1404,44 @@ def add_shipping_query_handler(self, handler_dict): Adds a shipping request handler. Note that you should use register_shipping_query_handler to add shipping_query_handler. + :meta private: + :param handler_dict: :return: """ self.shipping_query_handlers.append(handler_dict) - def register_shipping_query_handler(self, callback, func, pass_bot=False, **kwargs): + def register_shipping_query_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers shipping query handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_shipping_query_handler(handler_dict) def pre_checkout_query_handler(self, func, **kwargs): """ - Pre-checkout request handler. + New incoming pre-checkout query. Contains full information about checkout. + As a parameter to the decorator function, it passes :class:`telebot.types.PreCheckoutQuery` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1134,18 +1456,27 @@ def add_pre_checkout_query_handler(self, handler_dict): Adds a pre-checkout request handler. Note that you should use register_pre_checkout_query_handler to add pre_checkout_query_handler. + :meta private: + :param handler_dict: :return: """ self.pre_checkout_query_handlers.append(handler_dict) - def register_pre_checkout_query_handler(self, callback, func, pass_bot=False, **kwargs): + def register_pre_checkout_query_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers pre-checkout request handler. - :param pass_bot: :param callback: function to be called - :param func: + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + :return: decorated function """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) @@ -1153,11 +1484,14 @@ def register_pre_checkout_query_handler(self, callback, func, pass_bot=False, ** def poll_handler(self, func, **kwargs): """ - Poll request handler. + Handles new state of a poll. Bots receive only updates about stopped polls and polls, which are sent by the bot + As a parameter to the decorator function, it passes :class:`telebot.types.Poll` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + :return: None """ def decorator(handler): @@ -1172,30 +1506,45 @@ def add_poll_handler(self, handler_dict): Adds a poll request handler. Note that you should use register_poll_handler to add poll_handler. + :meta private: + :param handler_dict: :return: """ self.poll_handlers.append(handler_dict) - def register_poll_handler(self, callback, func, pass_bot=False, **kwargs): + def register_poll_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers poll handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_poll_handler(handler_dict) def poll_answer_handler(self, func=None, **kwargs): """ - Poll_answer request handler. + Handles change of user's answer in a non-anonymous poll(when user changes the vote). + Bots receive new votes only in polls that were sent by the bot itself. + As a parameter to the decorator function, it passes :class:`telebot.types.PollAnswer` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1210,30 +1559,45 @@ def add_poll_answer_handler(self, handler_dict): Adds a poll_answer request handler. Note that you should use register_poll_answer_handler to add poll_answer_handler. + :meta private: + :param handler_dict: :return: """ self.poll_answer_handlers.append(handler_dict) - def register_poll_answer_handler(self, callback, func, pass_bot=False, **kwargs): + def register_poll_answer_handler(self, callback: Awaitable, func: Callable, pass_bot: Optional[bool]=False, **kwargs): """ Registers poll answer handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_poll_answer_handler(handler_dict) def my_chat_member_handler(self, func=None, **kwargs): """ - my_chat_member handler. + Handles update in a status of a bot. For private chats, + this update is received only when the bot is blocked or unblocked by the user. + As a parameter to the decorator function, it passes :class:`telebot.types.ChatMemberUpdated` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1248,30 +1612,46 @@ def add_my_chat_member_handler(self, handler_dict): Adds a my_chat_member handler. Note that you should use register_my_chat_member_handler to add my_chat_member_handler. + :meta private: + :param handler_dict: :return: """ self.my_chat_member_handlers.append(handler_dict) - def register_my_chat_member_handler(self, callback, func=None, pass_bot=False, **kwargs): + def register_my_chat_member_handler(self, callback: Awaitable, func: Optional[Callable]=None, pass_bot: Optional[Callable]=False, **kwargs): """ Registers my chat member handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_my_chat_member_handler(handler_dict) def chat_member_handler(self, func=None, **kwargs): """ - chat_member handler. + Handles update in a status of a user in a chat. + The bot must be an administrator in the chat and must explicitly specify “chat_member” + in the list of allowed_updates to receive these updates. + As a parameter to the decorator function, it passes :class:`telebot.types.ChatMemberUpdated` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1286,30 +1666,45 @@ def add_chat_member_handler(self, handler_dict): Adds a chat_member handler. Note that you should use register_chat_member_handler to add chat_member_handler. + :meta private: + :param handler_dict: :return: """ self.chat_member_handlers.append(handler_dict) - def register_chat_member_handler(self, callback, func=None, pass_bot=False, **kwargs): + def register_chat_member_handler(self, callback: Awaitable, func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs): """ Registers chat member handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable`` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return:None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_chat_member_handler(handler_dict) def chat_join_request_handler(self, func=None, **kwargs): """ - chat_join_request handler. + Handles a request to join the chat has been sent. The bot must have the can_invite_users + administrator right in the chat to receive these updates. + As a parameter to the decorator function, it passes :class:`telebot.types.ChatJoinRequest` object. - :param func: - :param kwargs: - :return: + :param func: Function executed as a filter + :type func: :obj:`function` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ def decorator(handler): @@ -1324,19 +1719,29 @@ def add_chat_join_request_handler(self, handler_dict): Adds a chat_join_request handler. Note that you should use register_chat_join_request_handler to add chat_join_request_handler. + :meta private: + :param handler_dict: :return: """ self.chat_join_request_handlers.append(handler_dict) - def register_chat_join_request_handler(self, callback, func=None, pass_bot=False, **kwargs): + def register_chat_join_request_handler(self, callback: Awaitable, func: Optional[Callable]=None, pass_bot:Optional[bool]=False, **kwargs): """ Registers chat join request handler. - :param pass_bot: :param callback: function to be called - :param func: - :return: decorated function + :type callback: :obj:`Awaitable` + + :param func: Function executed as a filter + :type func: :obj:`function` + + :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files) + :type pass_bot: :obj:`bool` + + :param kwargs: Optional keyword arguments(custom filters) + + :return: None """ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs) self.add_chat_join_request_handler(handler_dict) @@ -1377,7 +1782,7 @@ async def get_me(self) -> types.User: result = await asyncio_helper.get_me(self.token) return types.User.de_json(result) - async def get_file(self, file_id: str) -> types.File: + async def get_file(self, file_id: Optional[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. @@ -1387,15 +1792,35 @@ async def get_file(self, file_id: str) -> types.File: Telegram documentation: https://core.telegram.org/bots/api#getfile - :param file_id: + :param file_id: File identifier + :type file_id: :obj:`str` + + :return: :class:`telebot.types.File` """ return types.File.de_json(await asyncio_helper.get_file(self.token, file_id)) - async def get_file_url(self, file_id: str) -> str: - + async def get_file_url(self, file_id: Optional[str]) -> str: + """ + Get a valid URL for downloading a file. + + :param file_id: File identifier to get download URL for. + :type file_id: :obj:`str` + + :return: URL for downloading the file. + :rtype: :obj:`str` + """ return await asyncio_helper.get_file_url(self.token, file_id) - async def download_file(self, file_path: str) -> bytes: + async def download_file(self, file_path: Optional[str]) -> bytes: + """ + Downloads file. + + :param file_path: Path where the file should be downloaded. + :type file_path: str + + :return: bytes + :rtype: :obj:`bytes` + """ return await asyncio_helper.download_file(self.token, file_path) async def log_out(self) -> bool: @@ -1408,6 +1833,9 @@ async def log_out(self) -> bool: Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#logout + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.log_out(self.token) @@ -1420,6 +1848,8 @@ async def close(self) -> bool: Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#close + + :return: :obj:`bool` """ return await asyncio_helper.close(self.token) @@ -1427,39 +1857,68 @@ def enable_saving_states(self, filename="./.state-save/states.pkl"): """ Enable saving states (by default saving disabled) - :param filename: Filename of saving file + .. note:: + It is recommended to pass a :class:`~telebot.asyncio_storage.StatePickleStorage` instance as state_storage + to TeleBot class. + + :param filename: Filename of saving file, defaults to "./.state-save/states.pkl" + :type filename: :obj:`str`, optional """ self.current_states = StatePickleStorage(file_path=filename) - async def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, - drop_pending_updates = None, timeout=None, secret_token=None): + async def set_webhook(self, url: Optional[str]=None, certificate: Optional[Union[str, Any]]=None, max_connections: Optional[int]=None, + allowed_updates: Optional[List[str]]=None, ip_address: Optional[str]=None, + drop_pending_updates: Optional[bool] = None, timeout: Optional[int]=None, + secret_token: Optional[str]=None) -> bool: """ - 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. + 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. + + If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. + If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content. + + Telegram Documentation: https://core.telegram.org/bots/api#setwebhook + + :param url: HTTPS URL to send updates to. Use an empty string to remove webhook integration, defaults to None + :type url: :obj:`str`, optional + + :param certificate: Upload your public key certificate so that the root certificate in use can be checked, defaults to None + :type certificate: :class:`str`, optional + + :param max_connections: The 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, + defaults to None + :type max_connections: :obj:`int`, optional + + :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 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 setWebhook, so unwanted updates may be received + for a short period of time. Defaults to None + + :type allowed_updates: :obj:`list`, optional - Telegram documentation: https://core.telegram.org/bots/api#setwebhook - - :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 - :param secret_token: Secret token to be used to verify the webhook - :return: + resolved through DNS, defaults to None + :type ip_address: :obj:`str`, optional + + :param drop_pending_updates: Pass True to drop all pending updates, defaults to None + :type drop_pending_updates: :obj:`bool`, optional + + :param timeout: Timeout of a request, defaults to None + :type timeout: :obj:`int`, optional + + :param secret_token: A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. + Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. Defaults to None + :type secret_token: :obj:`str`, optional + + :return: True on success. + :rtype: :obj:`bool` if the request was successful. """ return await asyncio_helper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, drop_pending_updates, timeout, secret_token) @@ -1545,33 +2004,43 @@ async def run_webhooks(self, - async def delete_webhook(self, drop_pending_updates=None, timeout=None): + async def delete_webhook(self, drop_pending_updates: Optional[bool]=None, timeout: Optional[int]=None) -> bool: """ Use this method to remove webhook integration if you decide to switch back to getUpdates. + Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#deletewebhook - :param drop_pending_updates: Pass True to drop all pending updates - :param timeout: Integer. Request connection timeout - :return: bool + :param drop_pending_updates: Pass True to drop all pending updates, defaults to None + :type drop_pending_updates: :obj: `bool`, optional + + :param timeout: Request connection timeout, defaults to None + :type timeout: :obj:`int`, optional + + :return: Returns True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.delete_webhook(self.token, drop_pending_updates, timeout) - async def remove_webhook(self): + async def remove_webhook(self) -> bool: """ Alternative for delete_webhook but uses set_webhook """ - await self.set_webhook() + result = await self.set_webhook() + return result - async def get_webhook_info(self, timeout=None): + async def get_webhook_info(self, timeout: Optional[int]=None) -> types.WebhookInfo: """ 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. + On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. Telegram documentation: https://core.telegram.org/bots/api#getwebhookinfo - :param timeout: Integer. Request connection timeout + :param timeout: Request connection timeout + :type timeout: :obj:`int`, optional + :return: On success, returns a WebhookInfo object. + :rtype: :class:`telebot.types.WebhookInfo` """ result = await asyncio_helper.get_webhook_info(self.token, timeout) return types.WebhookInfo.de_json(result) @@ -1579,14 +2048,23 @@ async def get_webhook_info(self, timeout=None): 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' + Use this method to get a list of profile pictures for a user. + Returns a :class:`telebot.types.UserProfilePhotos` object. Telegram documentation: https://core.telegram.org/bots/api#getuserprofilephotos - :param user_id: - :param offset: - :param limit: - :return: API reply. + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + + :param offset: Sequential number of the first photo to be returned. By default, all photos are returned. + :type offset: :obj:`int` + + :param limit: Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. + :type limit: :obj:`int` + + :return: `UserProfilePhotos `_ + :rtype: :class:`telebot.types.UserProfilePhotos` + """ result = await asyncio_helper.get_user_profile_photos(self.token, user_id, offset, limit) return types.UserProfilePhotos.de_json(result) @@ -1598,8 +2076,11 @@ async def get_chat(self, chat_id: Union[int, str]) -> types.Chat: Telegram documentation: https://core.telegram.org/bots/api#getchat - :param chat_id: - :return: + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: Chat information + :rtype: :class:`telebot.types.Chat` """ result = await asyncio_helper.get_chat(self.token, chat_id) return types.Chat.de_json(result) @@ -1610,8 +2091,10 @@ async def leave_chat(self, chat_id: Union[int, str]) -> bool: Telegram documentation: https://core.telegram.org/bots/api#leavechat - :param chat_id: - :return: + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: :obj:`bool` """ result = await asyncio_helper.leave_chat(self.token, chat_id) return result @@ -1622,10 +2105,12 @@ async def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. - Telegram documentation: https://core.telegram.org/bots/api#getchatadministrators + Telegram documentation: https://core.telegram.org/bots/api#getchatadministrators - :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) - :return: API reply. + :param chat_id: Unique identifier for the target chat or username + of the target supergroup or channel (in the format @channelusername) + :return: List made of ChatMember objects. + :rtype: :obj:`list` of :class:`telebot.types.ChatMember` """ result = await asyncio_helper.get_chat_administrators(self.token, chat_id) return [types.ChatMember.de_json(r) for r in result] @@ -1633,35 +2118,55 @@ async def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types. @util.deprecated(deprecation_text="Use get_chat_member_count instead") async def get_chat_members_count(self, chat_id: Union[int, str]) -> int: """ - This function is deprecated. Use `get_chat_member_count` instead + This function is deprecated. Use `get_chat_member_count` instead. + + .. deprecated:: 4.0.0 + This function is deprecated. Use `get_chat_member_count` instead. + + Use this method to get the number of members in a chat. + + Telegram documentation: https://core.telegram.org/bots/api#getchatmembercount + + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: Number of members in the chat. + :rtype: :obj:`int` """ 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. + Use this method to get the number of members in a chat. Telegram documentation: https://core.telegram.org/bots/api#getchatmembercount - :param chat_id: - :return: + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: Number of members in the chat. + :rtype: :obj:`int` """ 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. - + 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 administrator 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. + Telegram documentation: https://core.telegram.org/bots/api#setchatstickerset :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + :param sticker_set_name: Name of the sticker set to be set as the group sticker set - :return: API reply. + :type sticker_set_name: :obj:`str` + + :return: StickerSet object + :rtype: :class:`telebot.types.StickerSet` """ result = await asyncio_helper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) return result @@ -1673,9 +2178,12 @@ async def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool: optionally returned in getChat requests to check if the bot can use this method. Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#deletechatstickerset - + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) - :return: API reply. + :type chat_id: :obj:`int` or :obj:`str` + + :return: Returns True on success. + :rtype: :obj:`bool` """ result = await asyncio_helper.delete_chat_sticker_set(self.token, chat_id) return result @@ -1690,8 +2198,13 @@ async def answer_web_app_query(self, web_app_query_id: str, result: types.Inline Telegram Documentation: https://core.telegram.org/bots/api#answerwebappquery :param web_app_query_id: Unique identifier for the query to be answered + :type web_app_query_id: :obj:`str` + :param result: A JSON-serialized object describing the message to be sent - :return: + :type result: :class:`telebot.types.InlineQueryResultBase` + + :return: On success, a SentWebAppMessage object is returned. + :rtype: :class:`telebot.types.SentWebAppMessage` """ return await asyncio_helper.answer_web_app_query(self.token, web_app_query_id, result) @@ -1699,12 +2212,17 @@ async def answer_web_app_query(self, web_app_query_id: str, result: types.Inline 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. - + Telegram documentation: https://core.telegram.org/bots/api#getchatmember - :param chat_id: - :param user_id: - :return: API reply. + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + + :return: Returns ChatMember object on success. + :rtype: :class:`telebot.types.ChatMember` """ result = await asyncio_helper.get_chat_member(self.token, chat_id, user_id) return types.ChatMember.de_json(result) @@ -1723,24 +2241,48 @@ async def send_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, + Warning: Do not send more than about 4096 characters each message, otherwise you'll risk an HTTP 414 error. + If you must send more than 4096 characters, use the `split_string` or `smart_split` function in util.py. Telegram documentation: https://core.telegram.org/bots/api#sendmessage - :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: - :param protect_content: - :return: API reply. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param text: Text of the message to be sent + :type text: :obj:`str` + + :param parse_mode: Mode for parsing entities in the message text. + :type parse_mode: :obj:`str` + + :param entities: List of special entities that appear in message text, which can be specified instead of parse_mode + :type entities: Array of :class:`telebot.types.MessageEntity` + + :param disable_web_page_preview: Disables link previews for links in this message + :type disable_web_page_preview: :obj:`bool` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param protect_content: If True, the message content will be hidden for all users except for the target user + :type protect_content: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1760,13 +2302,26 @@ async def forward_message( Telegram documentation: https://core.telegram.org/bots/api#forwardmessage - :param disable_notification: - :param chat_id: which chat to forward - :param from_chat_id: which chat message from - :param message_id: message id - :param protect_content: - :param timeout: - :return: API reply. + :param disable_notification: Sends the message silently. Users will receive a notification with no sound + :type disable_notification: :obj:`bool` + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param from_chat_id: Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) + :type from_chat_id: :obj:`int` or :obj:`str` + + :param message_id: Message identifier in the chat specified in from_chat_id + :type message_id: :obj:`int` + + :param protect_content: Protects the contents of the forwarded message from forwarding and saving + :type protect_content: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return types.Message.de_json( await asyncio_helper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout, protect_content)) @@ -1789,19 +2344,45 @@ async def copy_message( Telegram documentation: https://core.telegram.org/bots/api#copymessage - :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: - :param protect_content: - :return: API reply. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param from_chat_id: Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) + :type from_chat_id: :obj:`int` or :obj:`str` + :param message_id: Message identifier in the chat specified in from_chat_id + :type message_id: :obj:`int` + + :param caption: New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept + :type caption: :obj:`str` + + :param parse_mode: Mode for parsing entities in the new caption. + :type parse_mode: :obj:`str` + + :param caption_entities: A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode + :type caption_entities: Array of :class:`telebot.types.MessageEntity` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1813,14 +2394,29 @@ async def copy_message( 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. + Use this method to delete a message, including service messages, with the following limitations: + - A message can only be deleted if it was sent less than 48 hours ago. + - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. + - Bots can delete outgoing messages in private chats, groups, and supergroups. + - Bots can delete incoming messages in private chats. + - Bots granted can_post_messages permissions can delete outgoing messages in channels. + - If the bot is an administrator of a group, it can delete any message there. + - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. + Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#deletemessage - :param chat_id: in which chat to delete - :param message_id: which message to delete - :param timeout: - :return: API reply. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Identifier of the message to delete + :type message_id: :obj:`int` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: Returns True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.delete_message(self.token, chat_id, message_id, timeout) @@ -1833,19 +2429,39 @@ async def send_dice( allow_sending_without_reply: Optional[bool]=None, protect_content: Optional[bool]=None) -> types.Message: """ - Use this method to send dices. + Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#senddice - :param chat_id: - :param emoji: - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param timeout: - :param allow_sending_without_reply: - :param protect_content: - :return: Message + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. + Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲” + :type emoji: :obj:`str` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions + to remove reply keyboard or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return types.Message.de_json( await asyncio_helper.send_dice( @@ -1864,22 +2480,49 @@ async def send_photo( reply_markup: Optional[REPLY_MARKUP_TYPES]=None, timeout: Optional[int]=None,) -> types.Message: """ - Use this method to send photos. + Use this method to send photos. On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#sendphoto + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` - :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: - :param protect_content: - :return: API reply. + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), + pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. + The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. + :type photo: :obj:`str` or :class:`telebot.types.InputFile` + + :param caption: Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Mode for parsing entities in the photo caption. + :type parse_mode: :obj:`str` + + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions + to remove reply keyboard or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1904,26 +2547,66 @@ async def send_audio( protect_content: 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. + Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, + this limit may be changed in the future. + + For sending voice messages, use the send_voice method instead. Telegram documentation: https://core.telegram.org/bots/api#sendaudio + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), + pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. + Audio must be in the .MP3 or .M4A format. + :type audio: :obj:`str` or :class:`telebot.types.InputFile` + + :param caption: Audio caption, 0-1024 characters after entities parsing + :type caption: :obj:`str` - :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 + :type duration: :obj:`int` + :param performer: Performer + :type performer: :obj:`str` + :param title: Track name + :type title: :obj:`str` + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + :param reply_markup: - :param parse_mode: - :param disable_notification: - :param timeout: - :param thumb: - :param caption_entities: - :param allow_sending_without_reply: - :param protect_content: - :return: Message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param parse_mode: Mode for parsing entities in the audio caption. See formatting options for more details. + :type parse_mode: :obj:`str` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param thumb: 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 + :type thumb: :obj:`str` + + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1945,24 +2628,52 @@ async def send_voice( allow_sending_without_reply: Optional[bool]=None, protect_content: 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. + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. + For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). + On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. Telegram documentation: https://core.telegram.org/bots/api#sendvoice + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` - :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: - :param protect_content: - :return: Message + :param voice: Audio 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. + :type voice: :obj:`str` or :class:`telebot.types.InputFile` + + :param caption: Voice message caption, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param duration: Duration of the voice message in seconds + :type duration: :obj:`int` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions + to remove reply keyboard or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param parse_mode: Mode for parsing entities in the voice message caption. See formatting options for more details. + :type parse_mode: :obj:`str` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1991,23 +2702,57 @@ async def send_document( Use this method to send general files. Telegram documentation: https://core.telegram.org/bots/api#senddocument - + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) - :param document: (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 + :type chat_id: :obj:`int` or :obj:`str` + + :param document: (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 + :type document: :obj:`str` or :class:`telebot.types.InputFile` + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + :param caption: Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing - :param reply_markup: + :type caption: :obj:`str` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + :param parse_mode: Mode for parsing entities in the document caption + :type parse_mode: :obj:`str` + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. - :param timeout: + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + :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 + :type thumb: :obj:`str` or :class:`telebot.types.InputFile` + + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param visible_file_name: allows to define file name that will be visible in the Telegram instead of original file name + :type visible_file_name: :obj:`str` + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data - :param data: function typo compatibility: do not use it - :param protect_content: - :return: API reply. + :type disable_content_type_detection: :obj:`bool` + + :param data: function typo miss compatibility: do not use it + :type data: :obj:`str` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode if data and not(document): @@ -2032,20 +2777,43 @@ async def send_sticker( protect_content: Optional[bool]=None, data: Union[Any, str]=None) -> types.Message: """ - Use this method to send .webp stickers. + Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. + On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#sendsticker - :param chat_id: - :param sticker: - :param reply_to_message_id: - :param reply_markup: + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param sticker: Sticker 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 .webp file from the Internet, or upload a new one using multipart/form-data. + :type sticker: :obj:`str` or :class:`telebot.types.InputFile` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + :param disable_notification: to disable the notification - :param timeout: timeout - :param allow_sending_without_reply: - :param protect_content: - :param data: deprecated, for backward compatibility - :return: API reply. + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :param data: function typo miss compatibility: do not use it + :type data: :obj:`str` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ if data and not(sticker): # function typo miss compatibility @@ -2082,22 +2850,60 @@ async def send_video( Telegram documentation: https://core.telegram.org/bots/api#sendvideo :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param video: Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file using multipart/form-data. + :type video: :obj:`str` or :class:`telebot.types.InputFile` + :param duration: Duration of sent video in seconds + :type duration: :obj:`int` + :param width: Video width + :type width: :obj:`int` + :param height: Video height + :type height: :obj:`int` + :param thumb: 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 . + :type thumb: :obj:`str` or :class:`telebot.types.InputFile` + :param caption: Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing + :type caption: :obj:`str` + :param parse_mode: Mode for parsing entities in the video caption - :param caption_entities: + :type parse_mode: :obj:`str` + + :param caption_entities: List of special entities that appear in the caption, which can be specified instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + :param supports_streaming: Pass True, if the uploaded video is suitable for streaming + :type supports_streaming: :obj:`bool` + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. - :param protect_content: + :type disable_notification: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + :param reply_to_message_id: If the message is a reply, ID of the original message - :param allow_sending_without_reply: - :param reply_markup: - :param timeout: - :param data: deprecated, for backward compatibility + :type reply_to_message_id: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param data: function typo miss compatibility: do not use it + :type data: :obj:`str` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode if data and not(video): @@ -2128,26 +2934,63 @@ async def send_animation( timeout: Optional[int]=None, ) -> types.Message: """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). + On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. Telegram documentation: https://core.telegram.org/bots/api#sendanimation + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), + pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. + :type animation: :obj:`str` or :class:`telebot.types.InputFile` + + :param duration: Duration of sent animation in seconds + :type duration: :obj:`int` + + :param width: Animation width + :type width: :obj:`int` + + :param height: Animation height + :type height: :obj:`int` - :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 width: Integer : Video width - :param height: Integer : Video height - :param thumb: InputFile or String : Thumbnail of the file sent - :param caption: String : Animation caption (may also be used when resending animation by file_id). - :param parse_mode: - :param protect_content: - :param reply_to_message_id: - :param reply_markup: - :param disable_notification: - :param timeout: - :param caption_entities: - :param allow_sending_without_reply: - :return: + :param thumb: 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 . + :type thumb: :obj:`str` or :class:`telebot.types.InputFile` + + :param caption: Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Mode for parsing entities in the animation caption + :type parse_mode: :obj:`str` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param caption_entities: List of special entities that appear in the caption, which can be specified instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -2169,24 +3012,52 @@ async def send_video_note( allow_sending_without_reply: Optional[bool]=None, protect_content: 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. + As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. + Use this method to send video messages. On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#sendvideonote + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param data: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) + or upload a new video using multipart/form-data. Sending video notes by a URL is currently unsupported + :type data: :obj:`str` or :class:`telebot.types.InputFile` - :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: - :param protect_content: - :return: + :param duration: Duration of sent video in seconds + :type duration: :obj:`int` + + :param length: Video width and height, i.e. diameter of the video message + :type length: :obj:`int` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param thumb: 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 . + :type thumb: :obj:`str` or :class:`telebot.types.InputFile` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return types.Message.de_json( await asyncio_helper.send_video_note( @@ -2204,18 +3075,34 @@ async def send_media_group( 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. + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files + can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. Telegram documentation: https://core.telegram.org/bots/api#sendmediagroup - - :param chat_id: - :param media: - :param disable_notification: - :param reply_to_message_id: - :param timeout: - :param allow_sending_without_reply: - :param protect_content: - :return: + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :type media: :obj:`list` of :obj:`types.InputMedia` + + :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :return: On success, an array of Messages that were sent is returned. + :rtype: List[types.Message] """ result = await asyncio_helper.send_media_group( self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, @@ -2235,27 +3122,54 @@ async def send_location( proximity_alert_radius: Optional[int]=None, allow_sending_without_reply: Optional[bool]=None, protect_content: Optional[bool]=None) -> types.Message: - - """ - Use this method to send point on the map. + Use this method to send point on the map. On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#sendlocation - :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: - :param protect_content: - :return: API reply. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param latitude: Latitude of the location + :type latitude: :obj:`float` + + :param longitude: Longitude of the location + :type longitude: :obj:`float` + + :param live_period: Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400. + :type live_period: :obj:`int` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard + or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :type horizontal_accuracy: :obj:`float` + + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :type heading: :obj:`int` + + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :type proximity_alert_radius: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return types.Message.de_json( await asyncio_helper.send_location( @@ -2275,21 +3189,45 @@ async def edit_message_live_location( heading: Optional[int]=None, proximity_alert_radius: Optional[int]=None) -> types.Message: """ - Use this method to edit live location. + Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly + disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message + is returned, otherwise True is returned. Telegram documentation: https://core.telegram.org/bots/api#editmessagelivelocation - :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: + :param latitude: Latitude of new location + :type latitude: :obj:`float` + + :param longitude: Longitude of new location + :type longitude: :obj:`float` + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Required if inline_message_id is not specified. Identifier of the message to edit + :type message_id: :obj:`int` + + :param reply_markup: A JSON-serialized object for a new inline keyboard. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message + :type inline_message_id: :obj:`str` + + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :type horizontal_accuracy: :obj:`float` + + :param heading: Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :type heading: :obj:`int` + + :param proximity_alert_radius: The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :type proximity_alert_radius: :obj:`int` + + :return: On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + :rtype: :class:`telebot.types.Message` or bool """ return types.Message.de_json( await asyncio_helper.edit_message_live_location( @@ -2304,17 +3242,29 @@ async def stop_message_live_location( 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. + Use this method to stop updating a live location message before live_period expires. + On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. Telegram documentation: https://core.telegram.org/bots/api#stopmessagelivelocation + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` - :param chat_id: - :param message_id: - :param inline_message_id: - :param reply_markup: - :param timeout: - :return: + :param message_id: Required if inline_message_id is not specified. Identifier of the message with live location to stop + :type message_id: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message with live location to stop + :type inline_message_id: :obj:`str` + + :param reply_markup: A JSON-serialized object for a new inline keyboard. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + :rtype: :class:`telebot.types.Message` or bool """ return types.Message.de_json( await asyncio_helper.stop_message_live_location( @@ -2335,27 +3285,61 @@ async def send_venue( google_place_type: Optional[str]=None, protect_content: Optional[bool]=None) -> types.Message: """ - Use this method to send information about a venue. - + Use this method to send information about a venue. On success, the sent Message is returned. + Telegram documentation: https://core.telegram.org/bots/api#sendvenue - :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”, + :param chat_id: Unique identifier for the target chat or username of the target channel + :type chat_id: :obj:`int` or :obj:`str` + + :param latitude: Latitude of the venue + :type latitude: :obj:`float` + + :param longitude: Longitude of the venue + :type longitude: :obj:`float` + + :param title: Name of the venue + :type title: :obj:`str` + + :param address: Address of the venue + :type address: :obj:`str` + + :param foursquare_id: Foursquare identifier of the venue + :type foursquare_id: :obj:`str` + + :param foursquare_type: Foursquare type of the venue, if known. (For example, “arts_entertainment/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: - :param protect_content: - :return: + :type foursquare_type: :obj:`str` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, + custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if one of the specified + replied-to messages is not found. + :type allow_sending_without_reply: :obj:`bool` + + :param google_place_id: Google Places identifier of the venue + :type google_place_id: :obj:`str` + + :param google_place_type: Google Places type of the venue. + :type google_place_type: :obj:`str` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return types.Message.de_json( await asyncio_helper.send_venue( @@ -2375,21 +3359,48 @@ async def send_contact( allow_sending_without_reply: Optional[bool]=None, protect_content: Optional[bool]=None) -> types.Message: """ - Use this method to send phone contacts. + Use this method to send phone contacts. On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#sendcontact - :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel - :param phone_number: String : Contact's phone number - :param first_name: String : Contact's first name - :param last_name: String : Contact's last name - :param vcard: String : Additional data about the contact in the form of a vCard, 0-2048 bytes - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param timeout: - :param allow_sending_without_reply: - :param protect_content: + :param chat_id: Unique identifier for the target chat or username of the target channel + :type chat_id: :obj:`int` or :obj:`str` + + :param phone_number: Contact's phone number + :type phone_number: :obj:`str` + + :param first_name: Contact's first name + :type first_name: :obj:`str` + + :param last_name: Contact's last name + :type last_name: :obj:`str` + + :param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes + :type vcard: :obj:`str` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, + custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove` + or :class:`telebot.types.ForceReply` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if one of the specified + replied-to messages is not found. + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return types.Message.de_json( await asyncio_helper.send_contact( @@ -2402,17 +3413,28 @@ 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). + The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). + Returns True on success. + + Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of + “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot. Telegram documentation: https://core.telegram.org/bots/api#sendchataction - :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 + :param chat_id: Unique identifier for the target chat or username of the target channel + :type chat_id: :obj:`int` or :obj:`str` + + :param action: Type of action to broadcast. Choose one, depending on what the user is about + to receive: typing for text messages, upload_photo for photos, record_video or upload_video + for videos, record_voice or upload_voice for voice notes, upload_document for general files, + choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes. + :type action: :obj:`str` + + :param timeout: Timeout in seconds for the request. + :type timeout: :obj:`int` + + :return: Returns True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.send_chat_action(self.token, chat_id, action, timeout) @@ -2438,14 +3460,24 @@ async def ban_chat_member( Telegram documentation: https://core.telegram.org/bots/api#banchatmember - :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 chat_id: Unique identifier for the target group or username of the target supergroup + or channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + :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 + :type until_date: :obj:`int` or :obj:`datetime` + :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 + 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. + :type revoke_messages: :obj:`bool` + + :return: Returns True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) @@ -2455,7 +3487,7 @@ async def unban_chat_member( """ 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 bot must be an administrator for this to work. By 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. @@ -2463,9 +3495,16 @@ async def unban_chat_member( :param chat_id: Unique identifier for the target group or username of the target supergroup or channel (in the format @username) + :type chat_id: :obj:`int` or :obj:`str` + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + :param only_if_banned: Do nothing if the user is not banned + :type only_if_banned: :obj:`bool` + :return: True on success + :rtype: :obj:`bool` """ return await asyncio_helper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) @@ -2487,22 +3526,48 @@ async def restrict_chat_member( Telegram documentation: https://core.telegram.org/bots/api#restrictchatmember - :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 chat_id: Unique identifier for the target group or username of the target supergroup + or channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + :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 + :type until_date: :obj:`int` or :obj:`datetime` + :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues + :type can_send_messages: :obj:`bool` + :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 + :type can_send_media_messages: :obj:`bool` + :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 + :type can_send_polls: :obj:`bool` + + :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages + :type can_send_other_messages: :obj:`bool` + + :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, + implies can_send_media_messages + :type can_add_web_page_previews: :obj:`bool` + + :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. + Ignored in public supergroups + :type can_change_info: :obj:`bool` + + :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, + implies can_invite_users + :type can_invite_users: :obj:`bool` + :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups + :type can_pin_messages: :obj:`bool` + :return: True on success + :rtype: :obj:`bool` """ return await asyncio_helper.restrict_chat_member( self.token, chat_id, user_id, until_date, @@ -2534,26 +3599,55 @@ async def promote_chat_member( :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 + :type chat_id: :obj:`int` or :obj:`str` + + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + + :param can_change_info: Pass True, if the administrator can change chat title, photo and other settings + :type can_change_info: :obj:`bool` + + :param can_post_messages: Pass True, if the administrator can create channel posts, channels only + :type can_post_messages: :obj:`bool` + + :param can_edit_messages: Pass True, if the administrator can edit messages of other users, channels only + :type can_edit_messages: :obj:`bool` + + :param can_delete_messages: Pass True, if the administrator can delete messages of other users + :type can_delete_messages: :obj:`bool` + + :param can_invite_users: Pass True, if the administrator can invite new users to the chat + :type can_invite_users: :obj:`bool` + + :param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members + :type can_restrict_members: :obj:`bool` + + :param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only + :type can_pin_messages: :obj:`bool` + + :param can_promote_members: 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, + :type can_promote_members: :obj:`bool` + + :param is_anonymous: Pass True, if the administrator's presence in the chat is hidden + :type is_anonymous: :obj:`bool` + + :param can_manage_chat: 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_video_chats: Bool: Pass True, if the administrator can manage voice chats + :type can_manage_chat: :obj:`bool` + + :param can_manage_video_chats: Pass True, if the administrator can manage voice chats For now, bots can use this privilege only for passing to other administrators. - :param can_manage_voice_chats: Deprecated, use can_manage_video_chats + :type can_manage_video_chats: :obj:`bool` + + :param can_manage_voice_chats: Deprecated, use can_manage_video_chats. + :type can_manage_voice_chats: :obj:`bool` + :return: True on success. + :rtype: :obj:`bool` """ if can_manage_voice_chats is not None: @@ -2570,17 +3664,24 @@ async def promote_chat_member( 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. + Use this method to set a custom title for an administrator in a supergroup promoted by the bot. + Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#setchatadministratorcustomtitle :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + :param custom_title: New custom title for the administrator; 0-16 characters, emoji are not allowed + :type custom_title: :obj:`str` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) @@ -2597,8 +3698,13 @@ async def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: U Telegram documentation: https://core.telegram.org/bots/api#banchatsenderchat :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param sender_chat_id: Unique identifier of the target sender chat + :type sender_chat_id: :obj:`int` or :obj:`str` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id) @@ -2611,17 +3717,21 @@ async def unban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Telegram documentation: https://core.telegram.org/bots/api#unbanchatsenderchat - :params: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) - :param sender_chat_id: Unique identifier of the target sender chat + :type chat_id: :obj:`int` or :obj:`str` + + :param sender_chat_id: Unique identifier of the target sender chat. + :type sender_chat_id: :obj:`int` or :obj:`str` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.unban_chat_sender_chat(self.token, chat_id, sender_chat_id) 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. + Use this method to set 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. @@ -2629,8 +3739,13 @@ async def set_chat_permissions( :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 + :type chat_id: :obj:`int` or :obj:`str` + + :param permissions: New default chat permissions + :type permissions: :class:`telebot.types..ChatPermissions` + :return: True on success + :rtype: :obj:`bool` """ return await asyncio_helper.set_chat_permissions(self.token, chat_id, permissions) @@ -2641,18 +3756,31 @@ async def create_chat_invite_link( 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. + 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 administrator rights. + The link can be revoked using the method revokeChatInviteLink. + Returns the new invite link as ChatInviteLink object. Telegram documentation: https://core.telegram.org/bots/api#createchatinvitelink :param chat_id: Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param name: Invite link name; 0-32 characters + :type name: :obj:`str` + :param expire_date: Point in time (Unix timestamp) when the link will expire + :type expire_date: :obj:`int` or :obj:`datetime` + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :type member_limit: :obj:`int` + :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: + :type creates_join_request: :obj:`bool` + + :return: Returns the new invite link as ChatInviteLink object. + :rtype: :class:`telebot.types.ChatInviteLink` """ return types.ChatInviteLink.de_json( await asyncio_helper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request) @@ -2673,12 +3801,25 @@ async def edit_chat_invite_link( :param chat_id: Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param name: Invite link name; 0-32 characters + :type name: :obj:`str` + :param invite_link: The invite link to edit + :type invite_link: :obj:`str` + :param expire_date: Point in time (Unix timestamp) when the link will expire + :type expire_date: :obj:`int` or :obj:`datetime` + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :type member_limit: :obj:`int` + :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: + :type creates_join_request: :obj:`bool` + + :return: Returns the new invite link as ChatInviteLink object. + :rtype: :class:`telebot.types.ChatInviteLink` """ 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) @@ -2693,9 +3834,15 @@ async def revoke_chat_invite_link( Telegram documentation: https://core.telegram.org/bots/api#revokechatinvitelink - :param chat_id: Id: Unique identifier for the target chat or username of the target channel(in the format @channelusername) + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param invite_link: The invite link to revoke - :return: API reply. + :type invite_link: :obj:`str` + + :return: Returns the new invite link as ChatInviteLink object. + :rtype: :class:`telebot.types.ChatInviteLink` """ return types.ChatInviteLink.de_json( await asyncio_helper.revoke_chat_invite_link(self.token, chat_id, invite_link) @@ -2710,7 +3857,10 @@ async def export_chat_invite_link(self, chat_id: Union[int, str]) -> str: :param chat_id: Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :return: exported invite link as String on success. + :rtype: :obj:`str` """ return await asyncio_helper.export_chat_invite_link(self.token, chat_id) @@ -2725,8 +3875,13 @@ async def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Uni :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` or :obj:`str` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.approve_chat_join_request(self.token, chat_id, user_id) @@ -2740,8 +3895,13 @@ async def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Uni :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` or :obj:`str` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.decline_chat_join_request(self.token, chat_id, user_id) @@ -2750,13 +3910,19 @@ 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. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. Telegram documentation: https://core.telegram.org/bots/api#setchatphoto - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param photo: InputFile: New chat photo, uploaded using multipart/form-data - :return: + :type photo: :obj:`typing.Union[file_like, str]` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_chat_photo(self.token, chat_id, photo) @@ -2765,13 +3931,16 @@ 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. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. Telegram documentation: https://core.telegram.org/bots/api#deletechatphoto :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.delete_chat_photo(self.token, chat_id) @@ -2784,10 +3953,16 @@ async def get_my_commands(self, scope: Optional[types.BotCommandScope], Telegram documentation: https://core.telegram.org/bots/api#getmycommands :param scope: The scope of users for which the commands are relevant. - async defaults to BotCommandScopeasync default. + Defaults to BotCommandScopeDefault. + :type scope: :class:`telebot.types.BotCommandScope` + :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 + :type language_code: :obj:`str` + + :return: List of BotCommand on success. + :rtype: :obj:`list` of :class:`telebot.types.BotCommand` """ result = await asyncio_helper.get_my_commands(self.token, scope, language_code) return [types.BotCommand.de_json(cmd) for cmd in result] @@ -2803,8 +3978,13 @@ async def set_chat_menu_button(self, chat_id: Union[int, str]=None, :param chat_id: Unique identifier for the target private chat. If not specified, default bot's menu button will be changed. + :type chat_id: :obj:`int` or :obj:`str` + :param menu_button: A JSON-serialized object for the new bot's menu button. Defaults to MenuButtonDefault + :type menu_button: :class:`telebot.types.MenuButton` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_chat_menu_button(self.token, chat_id, menu_button) @@ -2819,8 +3999,10 @@ async def get_chat_menu_button(self, chat_id: Union[int, str]=None) -> types.Men :param chat_id: Unique identifier for the target private chat. If not specified, default bot's menu button will be returned. - :return: types.MenuButton + :type chat_id: :obj:`int` or :obj:`str` + :return: types.MenuButton + :rtype: :class:`telebot.types.MenuButton` """ return types.MenuButton.de_json(await asyncio_helper.get_chat_menu_button(self.token, chat_id)) @@ -2836,8 +4018,16 @@ async def set_my_default_administrator_rights(self, rights: types.ChatAdministra Telegram documentation: https://core.telegram.org/bots/api#setmydefaultadministratorrights - :param rights: A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared. - :param for_channels: Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. + :param rights: A JSON-serialized object describing new default administrator rights. If not specified, + the default administrator rights will be cleared. + :type rights: :class:`telebot.types.ChatAdministratorRights` + + :param for_channels: Pass True to change the default administrator rights of the bot in channels. + Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. + :type for_channels: :obj:`bool` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_my_default_administrator_rights(self.token, rights, for_channels) @@ -2851,7 +4041,10 @@ async def get_my_default_administrator_rights(self, for_channels: bool=None) -> Telegram documentation: https://core.telegram.org/bots/api#getmydefaultadministratorrights :param for_channels: Pass True to get the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be returned. - :return: types.ChatAdministratorRights + :type for_channels: :obj:`bool` + + :return: Returns ChatAdministratorRights on success. + :rtype: :class:`telebot.types.ChatAdministratorRights` """ return types.ChatAdministratorRights.de_json(await asyncio_helper.get_my_default_administrator_rights(self.token, for_channels)) @@ -2865,12 +4058,19 @@ async def set_my_commands(self, commands: List[types.BotCommand], Telegram documentation: https://core.telegram.org/bots/api#setmycommands :param commands: List of BotCommand. At most 100 commands can be specified. + :type commands: :obj:`list` of :class:`telebot.types.BotCommand` + :param scope: The scope of users for which the commands are relevant. - async defaults to BotCommandScopeasync default. + Defaults to BotCommandScopeDefault. + :type scope: :class:`telebot.types.BotCommandScope` + :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: + :type language_code: :obj:`str` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_my_commands(self.token, commands, scope, language_code) @@ -2882,12 +4082,18 @@ async def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None, Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#deletemycommands - + :param scope: The scope of users for which the commands are relevant. - async defaults to BotCommandScopeasync default. + Defaults to BotCommandScopeDefault. + :type scope: :class:`telebot.types.BotCommandScope` + :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 + :type language_code: :obj:`str` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.delete_my_commands(self.token, scope, language_code) @@ -2901,10 +4107,15 @@ async def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: Telegram documentation: https://core.telegram.org/bots/api#setchattitle - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param title: New chat title, 1-255 characters - :return: + :type title: :obj:`str` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_chat_title(self.token, chat_id, title) @@ -2915,10 +4126,15 @@ async def set_chat_description(self, chat_id: Union[int, str], description: Opti Telegram documentation: https://core.telegram.org/bots/api#setchatdescription - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param description: Str: New chat description, 0-255 characters + :type description: :obj:`str` + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.set_chat_description(self.token, chat_id, description) @@ -2932,12 +4148,19 @@ async def pin_chat_message( Telegram documentation: https://core.telegram.org/bots/api#pinchatmessage - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + :param chat_id: 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 + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Identifier of a message to pin + :type message_id: :obj:`int` + + :param disable_notification: Pass True, if it is not necessary to send a notification to all group members about the new pinned message - :return: + :type disable_notification: :obj:`bool` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.pin_chat_message(self.token, chat_id, message_id, disable_notification) @@ -2949,10 +4172,15 @@ async def unpin_chat_message(self, chat_id: Union[int, str], message_id: Optiona Telegram documentation: https://core.telegram.org/bots/api#unpinchatmessage - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + :param message_id: Int: Identifier of a message to unpin - :return: + :type message_id: :obj:`int` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.unpin_chat_message(self.token, chat_id, message_id) @@ -2963,10 +4191,13 @@ async def unpin_all_chat_messages(self, chat_id: Union[int, str]) -> bool: Returns True on success. Telegram documentation: https://core.telegram.org/bots/api#unpinallchatmessages - + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername) - :return: + :type chat_id: :obj:`int` or :obj:`str` + + :return: True on success. + :rtype: :obj:`bool` """ return await asyncio_helper.unpin_all_chat_messages(self.token, chat_id) @@ -2984,15 +4215,32 @@ async def edit_message_text( Telegram documentation: https://core.telegram.org/bots/api#editmessagetext - :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: + :param text: New text of the message, 1-4096 characters after entities parsing + :type text: :obj:`str` + + :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Required if inline_message_id is not specified. Identifier of the sent message + :type message_id: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message + :type inline_message_id: :obj:`str` + + :param parse_mode: Mode for parsing entities in the message text. + :type parse_mode: :obj:`str` + + :param entities: List of special entities that appear in the message text, which can be specified instead of parse_mode + :type entities: List of :obj:`telebot.types.MessageEntity` + + :param disable_web_page_preview: Disables link previews for links in this message + :type disable_web_page_preview: :obj:`bool` + + :param reply_markup: A JSON-serialized object for an inline keyboard. + :type reply_markup: :obj:`InlineKeyboardMarkup` + + :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + :rtype: :obj:`types.Message` or :obj:`bool` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -3012,15 +4260,25 @@ async def edit_message_media( 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. - + Telegram documentation: https://core.telegram.org/bots/api#editmessagemedia - :param media: - :param chat_id: - :param message_id: - :param inline_message_id: - :param reply_markup: - :return: + :param media: A JSON-serialized object for a new media content of the message + :type media: :obj:`InputMedia` + :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Required if inline_message_id is not specified. Identifier of the sent message + :type message_id: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message + :type inline_message_id: :obj:`str` + + :param reply_markup: A JSON-serialized object for an inline keyboard. + :type reply_markup: :obj:`telebot.types.InlineKeyboardMarkup` or :obj:`ReplyKeyboardMarkup` or :obj:`ReplyKeyboardRemove` or :obj:`ForceReply` + + :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + :rtype: :obj:`types.Message` or :obj:`bool` """ 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. @@ -3037,11 +4295,20 @@ async def edit_message_reply_markup( Telegram documentation: https://core.telegram.org/bots/api#editmessagereplymarkup - :param chat_id: - :param message_id: - :param inline_message_id: - :param reply_markup: - :return: + :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Required if inline_message_id is not specified. Identifier of the sent message + :type message_id: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message + :type inline_message_id: :obj:`str` + + :param reply_markup: A JSON-serialized object for an inline keyboard. + :type reply_markup: :obj:`InlineKeyboardMarkup` or :obj:`ReplyKeyboardMarkup` or :obj:`ReplyKeyboardRemove` or :obj:`ForceReply` + + :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + :rtype: :obj:`types.Message` or :obj:`bool` """ result = await asyncio_helper.edit_message_reply_markup(self.token, chat_id, message_id, inline_message_id, reply_markup) if type(result) == bool: @@ -3061,15 +4328,32 @@ async def send_game( Telegram documentation: https://core.telegram.org/bots/api#sendgame - :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: - :param protect_content: - :return: + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. + :type game_short_name: :obj:`str` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + :type reply_markup: :obj:`InlineKeyboardMarkup` or :obj:`ReplyKeyboardMarkup` or :obj:`ReplyKeyboardRemove` or :obj:`ForceReply` + + :param timeout: Timeout in seconds for waiting for a response from the bot. + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if one of the specified replied-to messages is not found. + :type allow_sending_without_reply: :obj:`bool` + + :param protect_content: Pass True, if content of the message needs to be protected from being viewed by the bot. + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :obj:`types.Message` """ result = await asyncio_helper.send_game( self.token, chat_id, game_short_name, disable_notification, @@ -3089,14 +4373,29 @@ async def set_game_score( Telegram documentation: https://core.telegram.org/bots/api#setgamescore - :param user_id: - :param score: - :param force: - :param chat_id: - :param message_id: - :param inline_message_id: - :param disable_edit_message: - :return: + :param user_id: User identifier + :type user_id: :obj:`int` or :obj:`str` + + :param score: New score, must be non-negative + :type score: :obj:`int` + + :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters + :type force: :obj:`bool` + + :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Required if inline_message_id is not specified. Identifier of the sent message + :type message_id: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message + :type inline_message_id: :obj:`str` + + :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard + :type disable_edit_message: :obj:`bool` + + :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. + :rtype: :obj:`types.Message` or :obj:`bool` """ result = await asyncio_helper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, message_id, inline_message_id) @@ -3109,15 +4408,29 @@ async def get_game_high_scores( message_id: Optional[int]=None, inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: """ - Gets top points and game play. + Use this method to get data for high score tables. Will return the score of the specified user and several of + their 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 their closest neighbors on each side. + Will also return the top three users if the user and their neighbors are not among them. + Please note that this behavior is subject to change. Telegram documentation: https://core.telegram.org/bots/api#getgamehighscores - :param user_id: - :param chat_id: - :param message_id: - :param inline_message_id: - :return: + :param user_id: User identifier + :type user_id: :obj:`int` + + :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param message_id: Required if inline_message_id is not specified. Identifier of the sent message + :type message_id: :obj:`int` + + :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message + :type inline_message_id: :obj:`str` + + :return: On success, returns an Array of GameHighScore objects. + :rtype: List[types.GameHighScore] """ 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] @@ -3148,43 +4461,100 @@ async def send_invoice( Telegram documentation: https://core.telegram.org/bots/api#sendinvoice :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, + :type chat_id: :obj:`int` or :obj:`str` + + :param title: Product name, 1-32 characters + :type title: :obj:`str` + + :param description: Product description, 1-255 characters + :type description: :obj:`str` + + :param invoice_payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :type invoice_payload: :obj:`str` + :param provider_token: Payments provider token, obtained via @Botfather + :type provider_token: :obj:`str` + :param currency: Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies + :type currency: :obj:`str` + :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :type prices: List[:obj:`types.LabeledPrice`] + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter + :type start_parameter: :obj:`str` + :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 + :type photo_url: :obj:`str` + + :param photo_size: Photo size in bytes + :type photo_size: :obj:`int` + + :param photo_width: Photo width + :type photo_width: :obj:`int` + :param photo_height: Photo height + :type photo_height: :obj:`int` + :param need_name: Pass True, if you require the user's full name to complete the order + :type need_name: :obj:`bool` + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :type need_phone_number: :obj:`bool` + :param need_email: Pass True, if you require the user's email to complete the order + :type need_email: :obj:`bool` + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :type need_shipping_address: :obj:`bool` + :param is_flexible: Pass True, if the final price depends on the shipping method + :type is_flexible: :obj:`bool` + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :type send_phone_number_to_provider: :obj:`bool` + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :type send_email_to_provider: :obj:`bool` + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + :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 + :type reply_markup: :obj:`str` + :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: + :type provider_data: :obj:`str` + + :param timeout: Timeout of a request, defaults to None + :type timeout: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the message should be sent even if the specified replied-to message is not found + :type allow_sending_without_reply: :obj:`bool` + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :type max_tip_amount: :obj:`int` + :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. - :param protect_content: - :return: + :type suggested_tip_amounts: :obj:`list` of :obj:`int` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :obj:`types.Message` """ result = await asyncio_helper.send_invoice( self.token, chat_id, title, description, invoice_payload, provider_token, @@ -3222,31 +4592,74 @@ async def create_invoice_link(self, https://core.telegram.org/bots/api#createinvoicelink :param title: Product name, 1-32 characters + :type title: :obj:`str` + :param description: Product description, 1-255 characters + :type description: :obj:`str` + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :type payload: :obj:`str` + :param provider_token: Payments provider token, obtained via @Botfather + :type provider_token: :obj:`str` + :param currency: Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies + :type currency: :obj:`str` + :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :type prices: :obj:`list` of :obj:`types.LabeledPrice` + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :type max_tip_amount: :obj:`int` + :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. + :type suggested_tip_amounts: :obj:`list` of :obj:`int` + :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. + :type provider_data: :obj:`str` + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods + or a photo of the invoice. People like it better when they see a photo of what they are paying for. + :type photo_url: :obj:`str` + :param photo_size: Photo size in bytes + :type photo_size: :obj:`int` + :param photo_width: Photo width + :type photo_width: :obj:`int` + :param photo_height: Photo height + :type photo_height: :obj:`int` + :param need_name: Pass True, if you require the user's full name to complete the order + :type need_name: :obj:`bool` + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :type need_phone_number: :obj:`bool` + :param need_email: Pass True, if you require the user's email to complete the order + :type need_email: :obj:`bool` + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :type need_shipping_address: :obj:`bool` + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :type send_phone_number_to_provider: :obj:`bool` + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :type send_email_to_provider: :obj:`bool` + :param is_flexible: Pass True, if the final price depends on the shipping method + :type is_flexible: :obj:`bool` :return: Created invoice link as String on success. + :rtype: :obj:`str` """ result = await asyncio_helper.create_invoice_link( self.token, title, description, payload, provider_token, @@ -3275,30 +4688,74 @@ async def send_poll( explanation_entities: Optional[List[types.MessageEntity]]=None, protect_content: Optional[bool]=None) -> types.Message: """ - Send polls. + Use this method to send a native poll. + On success, the sent Message is returned. Telegram documentation: https://core.telegram.org/bots/api#sendpoll - :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: - :param protect_content: - :return: + :param chat_id: Unique identifier for the target chat or username of the target channel + :type chat_id: :obj:`int` | :obj:`str` + + :param question: Poll question, 1-300 characters + :type question: :obj:`str` + + :param options: A JSON-serialized list of answer options, 2-10 strings 1-100 characters each + :type options: :obj:`list` of :obj:`str` + + :param is_anonymous: True, if the poll needs to be anonymous, defaults to True + :type is_anonymous: :obj:`bool` + + :param type: Poll type, “quiz” or “regular”, defaults to “regular” + :type type: :obj:`str` + + :param allows_multiple_answers: True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False + :type allows_multiple_answers: :obj:`bool` + + :param correct_option_id: 0-based identifier of the correct answer option. Available only for polls in quiz mode, + defaults to None + :type correct_option_id: :obj:`int` + + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, + 0-200 characters with at most 2 line feeds after entities parsing + :type explanation: :obj:`str` + + :param explanation_parse_mode: Mode for parsing entities in the explanation. See formatting options for more details. + :type explanation_parse_mode: :obj:`str` + + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. + :type open_period: :obj:`int` + + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. + :type close_date: :obj:`int` | :obj:`datetime` + + :param is_closed: Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. + :type is_closed: :obj:`bool` + + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :type disable_notification: :obj:`bool` + + :param reply_to_message_id: If the message is a reply, ID of the original message + :type reply_to_message_id: :obj:`int` + + :param allow_sending_without_reply: Pass True, if the poll allows multiple options to be voted simultaneously. + :type allow_sending_without_reply: :obj:`bool` + + :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, + instructions to remove reply keyboard or to force a reply from the user. + :type reply_markup: :obj:`InlineKeyboardMarkup` | :obj:`ReplyKeyboardMarkup` | :obj:`ReplyKeyboardRemove` | :obj:`ForceReply` + + :param timeout: Timeout in seconds for waiting for a response from the user. + :type timeout: :obj:`int` + + :param explanation_entities: A JSON-serialized list of special entities that appear in the explanation, + which can be specified instead of parse_mode + :type explanation_entities: :obj:`list` of :obj:`MessageEntity` + + :param protect_content: Protects the contents of the sent message from forwarding and saving + :type protect_content: :obj:`bool` + + :return: On success, the sent Message is returned. + :rtype: :obj:`types.Message` """ if isinstance(question, types.Poll): @@ -3319,14 +4776,21 @@ async def stop_poll( self, chat_id: Union[int, str], message_id: int, reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Poll: """ - Stops poll. + Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned. Telegram documentation: https://core.telegram.org/bots/api#stoppoll - :param chat_id: - :param message_id: - :param reply_markup: - :return: + :param chat_id: Unique identifier for the target chat or username of the target channel + :type chat_id: :obj:`int` | :obj:`str` + + :param message_id: Identifier of the original message with the poll + :type message_id: :obj:`int` + + :param reply_markup: A JSON-serialized object for a new message markup. + :type reply_markup: :obj:`InlineKeyboardMarkup` | :obj:`ReplyKeyboardMarkup` | :obj:`ReplyKeyboardRemove` | :obj:`ForceReply` + + :return: On success, the stopped Poll is returned. + :rtype: :obj:`types.Poll` """ return types.Poll.de_json(await asyncio_helper.stop_poll(self.token, chat_id, message_id, reply_markup)) @@ -3339,11 +4803,21 @@ async def answer_shipping_query( Telegram documentation: https://core.telegram.org/bots/api#answershippingquery - :param shipping_query_id: - :param ok: - :param shipping_options: - :param error_message: - :return: + :param shipping_query_id: Unique identifier for the query to be answered + :type shipping_query_id: :obj:`str` + + :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) + :type ok: :obj:`bool` + + :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options. + :type shipping_options: :obj:`list` of :obj:`ShippingOption` + + :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. + :type error_message: :obj:`str` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) @@ -3351,14 +4825,28 @@ 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. + 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. Telegram documentation: https://core.telegram.org/bots/api#answerprecheckoutquery - :param pre_checkout_query_id: - :param ok: - :param error_message: - :return: + :param pre_checkout_query_id: Unique identifier for the query to be answered + :type pre_checkout_query_id: :obj:`int` + + :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. + :type ok: :obj:`bool` + + :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. + :type error_message: :obj:`str` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) @@ -3374,14 +4862,29 @@ async def edit_message_caption( Telegram documentation: https://core.telegram.org/bots/api#editmessagecaption - :param caption: - :param chat_id: - :param message_id: - :param inline_message_id: - :param parse_mode: - :param caption_entities: - :param reply_markup: - :return: + :param caption: New caption of the message + :type caption: :obj:`str` + + :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel + :type chat_id: :obj:`int` | :obj:`str` + + :param message_id: Required if inline_message_id is not specified. + :type message_id: :obj:`int` + + :param inline_message_id: Required if inline_message_id is not specified. Identifier of the inline message. + :type inline_message_id: :obj:`str` + + :param parse_mode: New caption of the message, 0-1024 characters after entities parsing + :type parse_mode: :obj:`str` + + :param caption_entities: A JSON-serialized array of objects that describe how the caption should be parsed. + :type caption_entities: :obj:`list` of :obj:`types.MessageEntity` + + :param reply_markup: A JSON-serialized object for an inline keyboard. + :type reply_markup: :obj:`InlineKeyboardMarkup` + + :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + :rtype: :obj:`types.Message` | :obj:`bool` """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -3395,10 +4898,16 @@ async def reply_to(self, message: types.Message, text: str, **kwargs) -> types.M """ Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` - :param message: - :param text: - :param kwargs: - :return: + :param message: Instance of :class:`telebot.types.Message` + :type message: :obj:`types.Message` + + :param text: Text of the message. + :type text: :obj:`str` + + :param kwargs: Additional keyword arguments which are passed to :meth:`telebot.TeleBot.send_message` + + :return: On success, the sent Message is returned. + :rtype: :class:`telebot.types.Message` """ return await self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) @@ -3413,21 +4922,40 @@ async def answer_inline_query( """ Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. - + Telegram documentation: https://core.telegram.org/bots/api#answerinlinequery - + :param inline_query_id: Unique identifier for the answered query + :type inline_query_id: :obj:`str` + :param results: Array of results for the inline query + :type results: :obj:`list` of :obj:`types.InlineQueryResult` + :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. + :type cache_time: :obj:`int` + :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. + :type is_personal: :obj:`bool` + :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. + :type next_offset: :obj:`str` + + :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, + only A-Z, a-z, 0-9, _ and - are allowed. + Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. + To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a + private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline + button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. + :type switch_pm_parameter: :obj:`str` + + :param switch_pm_text: Parameter for the start message sent to the bot when user presses the switch button + :type switch_pm_text: :obj:`str` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ 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) @@ -3439,15 +4967,27 @@ async def answer_callback_query( """ 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. - + Telegram documentation: https://core.telegram.org/bots/api#answercallbackquery - :param callback_query_id: - :param text: - :param show_alert: - :param url: - :param cache_time: - :return: + :param callback_query_id: Unique identifier for the query to be answered + :type callback_query_id: :obj:`int` + + :param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + :type text: :obj:`str` + + :param show_alert: If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. + :type show_alert: :obj:`bool` + + :param url: 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. + :type url: :obj:`str` + + :param cache_time: 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: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) @@ -3460,22 +5000,30 @@ async def set_sticker_set_thumb( Telegram documentation: https://core.telegram.org/bots/api#setstickersetthumb :param name: Sticker set name - :param user_id: User identifier - :param thumb: A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height - exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; - see https://core.telegram.org/animated_stickers#technical-requirements - + :type name: :obj:`str` + + :param user_id: User identifier + :type user_id: :obj:`int` + + :param thumb: + :type thumb: :obj:`filelike object` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.set_sticker_set_thumb(self.token, name, user_id, thumb) 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. - + Telegram documentation: https://core.telegram.org/bots/api#getstickerset - :param name: - :return: + :param name: Sticker set name + :type name: :obj:`str` + + :return: On success, a StickerSet object is returned. + :rtype: :class:`telebot.types.StickerSet` """ result = await asyncio_helper.get_sticker_set(self.token, name) return types.StickerSet.de_json(result) @@ -3485,12 +5033,17 @@ async def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) 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. - Telegram documentation: https://core.telegram.org/bots/api#uploadstickerfile - :param user_id: - :param png_sticker: - :return: + :param user_id: User identifier of sticker set owner + :type user_id: :obj:`int` + + :param png_sticker: PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, + and either width or height must be exactly 512px. + :type png_sticker: :obj:`filelike object` + + :return: On success, the sent file is returned. + :rtype: :class:`telebot.types.File` """ result = await asyncio_helper.upload_sticker_file(self.token, user_id, png_sticker) return types.File.de_json(result) @@ -3510,16 +5063,39 @@ async def create_new_sticker_set( Telegram documentation: https://core.telegram.org/bots/api#createnewstickerset - :param user_id: - :param name: - :param title: - :param emojis: - :param png_sticker: - :param tgs_sticker: - :webm_sticker: - :param contains_masks: - :param mask_position: - :return: + :param user_id: User identifier of created sticker set owner + :type user_id: :obj:`int` + + :param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, + digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "_by_". + is case insensitive. 1-64 characters. + :type name: :obj:`str` + + :param title: Sticker set title, 1-64 characters + :type title: :obj:`str` + + :param emojis: One or more emoji corresponding to the sticker + :type emojis: :obj:`str` + + :param png_sticker: PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width + or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, 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. + :type png_sticker: :obj:`str` + + :param tgs_sticker: TGS animation with the sticker, uploaded using multipart/form-data. + :type tgs_sticker: :obj:`str` + + :param webm_sticker: WebM animation with the sticker, uploaded using multipart/form-data. + :type webm_sticker: :obj:`str` + + :param contains_masks: Pass True, if a set of mask stickers should be created + :type contains_masks: :obj:`bool` + + :param mask_position: A JSON-serialized object for position where the mask should be placed on faces + :type mask_position: :class:`telebot.types.MaskPosition` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.create_new_sticker_set( self.token, user_id, name, title, emojis, png_sticker, tgs_sticker, @@ -3539,14 +5115,31 @@ async def add_sticker_to_set( Telegram documentation: https://core.telegram.org/bots/api#addstickertoset - :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 - :webm_sticker: - :param mask_position: - :return: + :param user_id: User identifier of created sticker set owner + :type user_id: :obj:`int` + + :param name: Sticker set name + :type name: :obj:`str` + + :param emojis: One or more emoji corresponding to the sticker + :type emojis: :obj:`str` + + :param png_sticker: PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either + width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, + 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. + :type png_sticker: :obj:`str` or :obj:`filelike object` + + :param tgs_sticker: TGS animation with the sticker, uploaded using multipart/form-data. + :type tgs_sticker: :obj:`str` or :obj:`filelike object` + + :param webm_sticker: WebM animation with the sticker, uploaded using multipart/form-data. + :type webm_sticker: :obj:`str` or :obj:`filelike object` + + :param mask_position: A JSON-serialized object for position where the mask should be placed on faces + :type mask_position: :class:`telebot.types.MaskPosition` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.add_sticker_to_set( self.token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position, webm_sticker) @@ -3555,85 +5148,137 @@ async def add_sticker_to_set( 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. - + Telegram documentation: https://core.telegram.org/bots/api#setstickerpositioninset - :param sticker: - :param position: - :return: + :param sticker: File identifier of the sticker + :type sticker: :obj:`str` + + :param position: New sticker position in the set, zero-based + :type position: :obj:`int` + + :return: On success, True is returned. + :rtype: :obj:`bool` """ 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. - + Telegram documentation: https://core.telegram.org/bots/api#deletestickerfromset - :param sticker: - :return: + :param sticker: File identifier of the sticker + :return: On success, True is returned. + :rtype: :obj:`bool` """ return await asyncio_helper.delete_sticker_from_set(self.token, sticker) - async def set_state(self, user_id: int, state: Union[State, int, str], chat_id: int=None): + async def set_state(self, user_id: int, state: Union[State, int, str], chat_id: Optional[int]=None): """ Sets a new state of a user. - :param user_id: - :param chat_id: - :param state: new state. can be string or integer. + .. note:: + + You should set both user id and chat id in order to set state for a user in a chat. + Otherwise, if you only set user_id, chat_id will equal to user_id, this means that + state will be set for the user in his private chat with a bot. + + :param user_id: User's identifier + :type user_id: :obj:`int` + + :param state: new state. can be string, integer, or :class:`telebot.types.State` + :type state: :obj:`int` or :obj:`str` or :class:`telebot.types.State` + + :param chat_id: Chat's identifier + :type chat_id: :obj:`int` + + :return: None """ if not chat_id: chat_id = user_id await self.current_states.set_state(chat_id, user_id, state) - async def reset_data(self, user_id: int, chat_id: int=None): + async def reset_data(self, user_id: int, chat_id: Optional[int]=None): """ Reset data for a user in chat. - :param user_id: - :param chat_id: + :param user_id: User's identifier + :type user_id: :obj:`int` + + :param chat_id: Chat's identifier + :type chat_id: :obj:`int` + + :return: None """ if chat_id is None: chat_id = user_id await self.current_states.reset_data(chat_id, user_id) - async def delete_state(self, user_id: int, chat_id:int=None): + async def delete_state(self, user_id: int, chat_id: Optional[int]=None): """ Delete the current state of a user. - :param user_id: - :param chat_id: - :return: + :param user_id: User's identifier + :type user_id: :obj:`int` + + :param chat_id: Chat's identifier + :type chat_id: :obj:`int` + + :return: None """ if not chat_id: chat_id = user_id await self.current_states.delete_state(chat_id, user_id) - def retrieve_data(self, user_id: int, chat_id: int=None): + def retrieve_data(self, user_id: int, chat_id: Optional[int]=None): + """ + Returns context manager with data for a user in chat. + + :param user_id: User identifier + :type user_id: int + + :param chat_id: Chat's unique identifier, defaults to user_id + :type chat_id: int, optional + + :return: Context manager with data for a user in chat + :rtype: Optional[Any] + """ if not chat_id: chat_id = user_id return self.current_states.get_interactive_data(chat_id, user_id) - async def get_state(self, user_id, chat_id: int=None): + async def get_state(self, user_id, chat_id: Optional[int]=None): """ - Get current state of a user. + Gets current state of a user. + Not recommended to use this method. But it is ok for debugging. + + :param user_id: User's identifier + :type user_id: :obj:`int` + + :param chat_id: Chat's identifier + :type chat_id: :obj:`int` - :param user_id: - :param chat_id: :return: state of a user + :rtype: :obj:`int` or :obj:`str` or :class:`telebot.types.State` """ if not chat_id: chat_id = user_id return await self.current_states.get_state(chat_id, user_id) - async def add_data(self, user_id: int, chat_id: int=None, **kwargs): + async def add_data(self, user_id: int, chat_id: Optional[int]=None, **kwargs): """ Add data to states. - :param user_id: - :param chat_id: + :param user_id: User's identifier + :type user_id: :obj:`int` + + :param chat_id: Chat's identifier + :type chat_id: :obj:`int` + + :param kwargs: Data to add + :return: None """ if not chat_id: chat_id = user_id diff --git a/telebot/asyncio_filters.py b/telebot/asyncio_filters.py index 8cce1bb04..f1384557c 100644 --- a/telebot/asyncio_filters.py +++ b/telebot/asyncio_filters.py @@ -10,8 +10,19 @@ 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. - + Child classes should have .key property. + + .. code-block:: python3 + :caption: Example on creating a simple custom filter. + + class ForwardFilter(SimpleCustomFilter): + # Check whether message was forwarded from channel or group. + key = 'is_forwarded' + + def check(self, message): + return message.forward_date is not None + """ key: str = None @@ -25,13 +36,23 @@ async def check(self, message): class AdvancedCustomFilter(ABC): """ - Simple Custom Filter base class. + Advanced 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 Child classes should have .key property. + + .. code-block:: python3 + :caption: Example on creating an advanced custom filter. + + class TextStartsFilter(AdvancedCustomFilter): + # Filter to check whether message starts with some text. + key = 'text_startswith' + + def check(self, message, text): + return message.text.startswith(text) """ key: str = None @@ -48,6 +69,25 @@ class TextFilter: Advanced text filter to check (types.Message, types.CallbackQuery, types.InlineQuery, types.Poll) example of usage is in examples/asynchronous_telebot/custom_filters/advanced_text_filter.py + + :param equals: string, True if object's text is equal to passed string + :type equals: :obj:`str` + + :param contains: list[str] or tuple[str], True if any string element of iterable is in text + :type contains: list[str] or tuple[str] + + :param starts_with: string, True if object's text starts with passed string + :type starts_with: :obj:`str` + + :param ends_with: string, True if object's text starts with passed string + :type ends_with: :obj:`str` + + :param ignore_case: bool (default False), case insensitive + :type ignore_case: :obj:`bool` + + :raises ValueError: if incorrect value for a parameter was supplied + + :return: None """ def __init__(self, @@ -56,13 +96,25 @@ def __init__(self, starts_with: Optional[Union[str, list, tuple]] = None, ends_with: Optional[Union[str, list, tuple]] = None, ignore_case: bool = False): - """ :param equals: string, True if object's text is equal to passed string + :type equals: :obj:`str` + :param contains: list[str] or tuple[str], True if any string element of iterable is in text + :type contains: list[str] or tuple[str] + :param starts_with: string, True if object's text starts with passed string + :type starts_with: :obj:`str` + :param ends_with: string, True if object's text starts with passed string + :type ends_with: :obj:`str` + :param ignore_case: bool (default False), case insensitive + :type ignore_case: :obj:`bool` + + :raises ValueError: if incorrect value for a parameter was supplied + + :return: None """ to_check = sum((pattern is not None for pattern in (equals, contains, starts_with, ends_with))) @@ -87,7 +139,9 @@ def _check_iterable(self, iterable, filter_name): return iterable async def check(self, obj: Union[types.Message, types.CallbackQuery, types.InlineQuery, types.Poll]): - + """ + :meta private: + """ if isinstance(obj, types.Poll): text = obj.question elif isinstance(obj, types.Message): @@ -135,15 +189,20 @@ async def check(self, obj: Union[types.Message, types.CallbackQuery, types.Inlin class TextMatchFilter(AdvancedCustomFilter): """ Filter to check Text message. - key: text - Example: - @bot.message_handler(text=['account']) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(text=['account']) + # your function """ key = 'text' async def check(self, message, text): + """ + :meta private: + """ if isinstance(text, TextFilter): return await text.check(message) elif type(text) is list: @@ -157,14 +216,21 @@ 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']) + + .. code-block:: python3 + :caption: Example on using this filter: + + # Will respond if any message.text contains word 'account' + @bot.message_handler(text_contains=['account']) + # your function """ key = 'text_contains' async def check(self, message, text): + """ + :meta private: + """ if not isinstance(text, str) and not isinstance(text, list) and not isinstance(text, tuple): raise ValueError("Incorrect text_contains value") elif isinstance(text, str): @@ -179,14 +245,20 @@ 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') + .. code-block:: python3 + :caption: Example on using this filter: + + # Will work if message.text starts with 'sir'. + @bot.message_handler(text_startswith='sir') + # your function """ key = 'text_startswith' async def check(self, message, text): + """ + :meta private: + """ return message.text.startswith(text) @@ -194,13 +266,19 @@ class ChatFilter(AdvancedCustomFilter): """ Check whether chat_id corresponds to given chat_id. - Example: - @bot.message_handler(chat_id=[99999]) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(chat_id=[99999]) + # your function """ key = 'chat_id' async def check(self, message, text): + """ + :meta private: + """ if isinstance(message, types.CallbackQuery): return message.message.chat.id in text return message.chat.id in text @@ -210,14 +288,19 @@ class ForwardFilter(SimpleCustomFilter): """ Check whether message was forwarded from channel or group. - Example: + .. code-block:: python3 + :caption: Example on using this filter: - @bot.message_handler(is_forwarded=True) + @bot.message_handler(is_forwarded=True) + # your function """ key = 'is_forwarded' async def check(self, message): + """ + :meta private: + """ return message.forward_date is not None @@ -225,14 +308,19 @@ class IsReplyFilter(SimpleCustomFilter): """ Check whether message is a reply. - Example: + .. code-block:: python3 + :caption: Example on using this filter: - @bot.message_handler(is_reply=True) + @bot.message_handler(is_reply=True) + # your function """ key = 'is_reply' async def check(self, message): + """ + :meta private: + """ if isinstance(message, types.CallbackQuery): return message.message.reply_to_message is not None return message.reply_to_message is not None @@ -242,14 +330,19 @@ class LanguageFilter(AdvancedCustomFilter): """ Check users language_code. - Example: + .. code-block:: python3 + :caption: Example on using this filter: - @bot.message_handler(language_code=['ru']) + @bot.message_handler(language_code=['ru']) + # your function """ key = 'language_code' async def check(self, message, text): + """ + :meta private: + """ if type(text) is list: return message.from_user.language_code in text else: @@ -260,8 +353,11 @@ class IsAdminFilter(SimpleCustomFilter): """ Check whether the user is administrator / owner of the chat. - Example: - @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + # your function """ key = 'is_chat_admin' @@ -270,6 +366,9 @@ def __init__(self, bot): self._bot = bot async def check(self, message): + """ + :meta private: + """ if isinstance(message, types.CallbackQuery): result = await self._bot.get_chat_member(message.message.chat.id, message.from_user.id) return result.status ('creator', 'administrator') @@ -281,8 +380,11 @@ class StateFilter(AdvancedCustomFilter): """ Filter to check state. - Example: - @bot.message_handler(state=1) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(state=1) + # your function """ def __init__(self, bot): @@ -291,6 +393,9 @@ def __init__(self, bot): key = 'state' async def check(self, message, text): + """ + :meta private: + """ if text == '*': return True # needs to work with callbackquery @@ -334,10 +439,16 @@ class IsDigitFilter(SimpleCustomFilter): """ Filter to check whether the string is made up of only digits. - Example: - @bot.message_handler(is_digit=True) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(is_digit=True) + # your function """ key = 'is_digit' async def check(self, message): + """ + :meta private: + """ return message.text.isdigit() diff --git a/telebot/asyncio_handler_backends.py b/telebot/asyncio_handler_backends.py index 4f0d1743f..34cc19a77 100644 --- a/telebot/asyncio_handler_backends.py +++ b/telebot/asyncio_handler_backends.py @@ -1,3 +1,10 @@ +""" +File with all middleware classes, states. +""" + + + + class BaseMiddleware: """ Base class for middleware. @@ -9,23 +16,25 @@ class BaseMiddleware: so on. Same applies to post_process. .. code-block:: python + :caption: Example of class-based middlewares + class MyMiddleware(BaseMiddleware): def __init__(self): self.update_sensitive = True self.update_types = ['message', 'edited_message'] - def pre_process_message(self, message, data): + async def pre_process_message(self, message, data): # only message update here pass - def post_process_message(self, message, data, exception): + async def post_process_message(self, message, data, exception): pass # only message update here for post_process - def pre_process_edited_message(self, message, data): + async def pre_process_edited_message(self, message, data): # only edited_message update here pass - def post_process_edited_message(self, message, data, exception): + async def post_process_edited_message(self, message, data, exception): pass # only edited_message update here for post_process """ @@ -42,6 +51,14 @@ async def post_process(self, message, data, exception): class State: + """ + Class representing a state. + + .. code-block:: python3 + + class MyStates(StatesGroup): + my_state = State() # returns my_state:State string. + """ def __init__(self) -> None: self.name = None @@ -50,6 +67,14 @@ def __str__(self) -> str: class StatesGroup: + """ + Class representing common states. + + .. code-block:: python3 + + class MyStates(StatesGroup): + my_state = State() # returns my_state:State string. + """ def __init_subclass__(cls) -> None: for name, value in cls.__dict__.items(): diff --git a/telebot/callback_data.py b/telebot/callback_data.py index 58fa0d511..57e4833da 100644 --- a/telebot/callback_data.py +++ b/telebot/callback_data.py @@ -1,3 +1,7 @@ +""" +Callback data factory's file. +""" + """ Copyright (c) 2017-2018 Alex Root Junior @@ -29,17 +33,23 @@ class CallbackDataFilter: + """ + Filter for CallbackData. + """ def __init__(self, factory, config: typing.Dict[str, str]): self.config = config self.factory = factory - def check(self, query): + def check(self, query) -> bool: """ Checks if query.data appropriates to specified config :param query: telebot.types.CallbackQuery - :return: bool + :type query: telebot.types.CallbackQuery + + :return: True if query.data appropriates to specified config + :rtype: bool """ try: @@ -135,7 +145,7 @@ def filter(self, **config) -> CallbackDataFilter: """ Generate filter - :param config: specified named parameters will be checked with CallbackQury.data + :param config: specified named parameters will be checked with CallbackQuery.data :return: CallbackDataFilter class """ diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 161c74ad7..dd6a27fe5 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -14,6 +14,17 @@ class SimpleCustomFilter(ABC): Accepts only message, returns bool value, that is compared with given in handler. Child classes should have .key property. + + .. code-block:: python3 + :caption: Example on creating a simple custom filter. + + class ForwardFilter(SimpleCustomFilter): + # Check whether message was forwarded from channel or group. + key = 'is_forwarded' + + def check(self, message): + return message.forward_date is not None + """ key: str = None @@ -27,13 +38,23 @@ def check(self, message): class AdvancedCustomFilter(ABC): """ - Simple Custom Filter base class. + Advanced 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 Child classes should have .key property. + + .. code-block:: python3 + :caption: Example on creating an advanced custom filter. + + class TextStartsFilter(AdvancedCustomFilter): + # Filter to check whether message starts with some text. + key = 'text_startswith' + + def check(self, message, text): + return message.text.startswith(text) """ key: str = None @@ -50,6 +71,25 @@ class TextFilter: Advanced text filter to check (types.Message, types.CallbackQuery, types.InlineQuery, types.Poll) example of usage is in examples/custom_filters/advanced_text_filter.py + + :param equals: string, True if object's text is equal to passed string + :type equals: :obj:`str` + + :param contains: list[str] or tuple[str], True if any string element of iterable is in text + :type contains: list[str] or tuple[str] + + :param starts_with: string, True if object's text starts with passed string + :type starts_with: :obj:`str` + + :param ends_with: string, True if object's text starts with passed string + :type ends_with: :obj:`str` + + :param ignore_case: bool (default False), case insensitive + :type ignore_case: :obj:`bool` + + :raises ValueError: if incorrect value for a parameter was supplied + + :return: None """ def __init__(self, @@ -58,15 +98,27 @@ def __init__(self, starts_with: Optional[Union[str, list, tuple]] = None, ends_with: Optional[Union[str, list, tuple]] = None, ignore_case: bool = False): - """ :param equals: string, True if object's text is equal to passed string + :type equals: :obj:`str` + :param contains: list[str] or tuple[str], True if any string element of iterable is in text + :type contains: list[str] or tuple[str] + :param starts_with: string, True if object's text starts with passed string + :type starts_with: :obj:`str` + :param ends_with: string, True if object's text starts with passed string + :type ends_with: :obj:`str` + :param ignore_case: bool (default False), case insensitive - """ + :type ignore_case: :obj:`bool` + :raises ValueError: if incorrect value for a parameter was supplied + + :return: None + """ + to_check = sum((pattern is not None for pattern in (equals, contains, starts_with, ends_with))) if to_check == 0: raise ValueError('None of the check modes was specified') @@ -89,6 +141,9 @@ def _check_iterable(self, iterable, filter_name: str): return iterable def check(self, obj: Union[types.Message, types.CallbackQuery, types.InlineQuery, types.Poll]): + """ + :meta private: + """ if isinstance(obj, types.Poll): text = obj.question @@ -142,15 +197,20 @@ def check(self, obj: Union[types.Message, types.CallbackQuery, types.InlineQuery class TextMatchFilter(AdvancedCustomFilter): """ Filter to check Text message. - key: text - Example: - @bot.message_handler(text=['account']) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(text=['account']) + # your function """ key = 'text' def check(self, message, text): + """ + :meta private: + """ if isinstance(text, TextFilter): return text.check(message) elif type(text) is list: @@ -164,14 +224,21 @@ 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']) + + .. code-block:: python3 + :caption: Example on using this filter: + + # Will respond if any message.text contains word 'account' + @bot.message_handler(text_contains=['account']) + # your function """ key = 'text_contains' def check(self, message, text): + """ + :meta private: + """ if not isinstance(text, str) and not isinstance(text, list) and not isinstance(text, tuple): raise ValueError("Incorrect text_contains value") elif isinstance(text, str): @@ -186,14 +253,20 @@ 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') + .. code-block:: python3 + :caption: Example on using this filter: + + # Will work if message.text starts with 'sir'. + @bot.message_handler(text_startswith='sir') + # your function """ key = 'text_startswith' def check(self, message, text): + """ + :meta private: + """ return message.text.startswith(text) @@ -201,13 +274,19 @@ class ChatFilter(AdvancedCustomFilter): """ Check whether chat_id corresponds to given chat_id. - Example: - @bot.message_handler(chat_id=[99999]) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(chat_id=[99999]) + # your function """ key = 'chat_id' def check(self, message, text): + """ + :meta private: + """ if isinstance(message, types.CallbackQuery): return message.message.chat.id in text return message.chat.id in text @@ -217,14 +296,19 @@ class ForwardFilter(SimpleCustomFilter): """ Check whether message was forwarded from channel or group. - Example: + .. code-block:: python3 + :caption: Example on using this filter: - @bot.message_handler(is_forwarded=True) + @bot.message_handler(is_forwarded=True) + # your function """ key = 'is_forwarded' def check(self, message): + """ + :meta private: + """ return message.forward_date is not None @@ -232,14 +316,19 @@ class IsReplyFilter(SimpleCustomFilter): """ Check whether message is a reply. - Example: + .. code-block:: python3 + :caption: Example on using this filter: - @bot.message_handler(is_reply=True) + @bot.message_handler(is_reply=True) + # your function """ key = 'is_reply' def check(self, message): + """ + :meta private: + """ if isinstance(message, types.CallbackQuery): return message.message.reply_to_message is not None return message.reply_to_message is not None @@ -249,14 +338,19 @@ class LanguageFilter(AdvancedCustomFilter): """ Check users language_code. - Example: + .. code-block:: python3 + :caption: Example on using this filter: - @bot.message_handler(language_code=['ru']) + @bot.message_handler(language_code=['ru']) + # your function """ key = 'language_code' def check(self, message, text): + """ + :meta private: + """ if type(text) is list: return message.from_user.language_code in text else: @@ -267,8 +361,11 @@ class IsAdminFilter(SimpleCustomFilter): """ Check whether the user is administrator / owner of the chat. - Example: - @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + # your function """ key = 'is_chat_admin' @@ -277,6 +374,9 @@ def __init__(self, bot): self._bot = bot def check(self, message): + """ + :meta private: + """ if isinstance(message, types.CallbackQuery): return self._bot.get_chat_member(message.message.chat.id, message.from_user.id).status in ['creator', 'administrator'] return self._bot.get_chat_member(message.chat.id, message.from_user.id).status in ['creator', 'administrator'] @@ -286,8 +386,11 @@ class StateFilter(AdvancedCustomFilter): """ Filter to check state. - Example: - @bot.message_handler(state=1) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(state=1) + # your function """ def __init__(self, bot): @@ -296,6 +399,9 @@ def __init__(self, bot): key = 'state' def check(self, message, text): + """ + :meta private: + """ if text == '*': return True # needs to work with callbackquery @@ -341,10 +447,16 @@ class IsDigitFilter(SimpleCustomFilter): """ Filter to check whether the string is made up of only digits. - Example: - @bot.message_handler(is_digit=True) + .. code-block:: python3 + :caption: Example on using this filter: + + @bot.message_handler(is_digit=True) + # your function """ key = 'is_digit' def check(self, message): + """ + :meta private: + """ return message.text.isdigit() diff --git a/telebot/ext/aio/webhooks.py b/telebot/ext/aio/webhooks.py index 13e28aba4..03c456616 100644 --- a/telebot/ext/aio/webhooks.py +++ b/telebot/ext/aio/webhooks.py @@ -34,14 +34,34 @@ def __init__(self, bot, """ Aynchronous implementation of webhook listener for asynchronous version of telebot. + Not supposed to be used manually by user. + Use AsyncTeleBot.run_webhooks() instead. + + :param bot: AsyncTeleBot instance. + :type bot: telebot.async_telebot.AsyncTeleBot - :param bot: TeleBot instance :param secret_token: Telegram secret token + :type secret_token: str + :param host: Webhook host + :type host: str + :param port: Webhook port + :type port: int + :param ssl_context: SSL context + :type ssl_context: tuple + :param url_path: Webhook url path + :type url_path: str + :param debug: Debug mode + :type debug: bool + + :raises ImportError: If FastAPI or uvicorn is not installed. + :raises ImportError: If Starlette version is too old. + + :return: None """ self._check_dependencies() @@ -73,6 +93,8 @@ def _prepare_endpoint_urls(self): async def process_update(self, request: Request, update: dict): """ Processes updates. + + :meta private: """ # header containsX-Telegram-Bot-Api-Secret-Token if request.headers.get('X-Telegram-Bot-Api-Secret-Token') != self._secret_token: @@ -88,7 +110,10 @@ async def process_update(self, request: Request, update: dict): async def run_app(self): """ - Run app with the given parameters. + Run app with the given parameters to init. + Not supposed to be used manually by user. + + :return: None """ config = Config(app=self.app, diff --git a/telebot/ext/sync/webhooks.py b/telebot/ext/sync/webhooks.py index 89a3ec928..6e1714b13 100644 --- a/telebot/ext/sync/webhooks.py +++ b/telebot/ext/sync/webhooks.py @@ -1,8 +1,7 @@ """ -This file is used by TeleBot.run_webhooks() & -AsyncTeleBot.run_webhooks() functions. +This file is used by TeleBot.run_webhooks() function. -Flask/fastapi is required to run this script. +Fastapi is required to run this script. """ # modules required for running this script @@ -34,16 +33,36 @@ def __init__(self, bot, debug: Optional[bool]=False ) -> None: """ - Synchronous implementation of webhook listener - for synchronous version of telebot. + Aynchronous implementation of webhook listener + for asynchronous version of telebot. + Not supposed to be used manually by user. + Use AsyncTeleBot.run_webhooks() instead. + + :param bot: AsyncTeleBot instance. + :type bot: telebot.async_telebot.AsyncTeleBot - :param bot: TeleBot instance :param secret_token: Telegram secret token + :type secret_token: str + :param host: Webhook host + :type host: str + :param port: Webhook port + :type port: int + :param ssl_context: SSL context + :type ssl_context: tuple + :param url_path: Webhook url path + :type url_path: str + :param debug: Debug mode + :type debug: bool + + :raises ImportError: If FastAPI or uvicorn is not installed. + :raises ImportError: If Starlette version is too old. + + :return: None """ self._check_dependencies() @@ -75,6 +94,8 @@ def _prepare_endpoint_urls(self): def process_update(self, request: Request, update: dict): """ Processes updates. + + :meta private: """ # header containsX-Telegram-Bot-Api-Secret-Token if request.headers.get('X-Telegram-Bot-Api-Secret-Token') != self._secret_token: @@ -89,7 +110,10 @@ def process_update(self, request: Request, update: dict): def run_app(self): """ - Run app with the given parameters. + Run app with the given parameters to init. + Not supposed to be used manually by user. + + :return: None """ uvicorn.run(app=self.app, diff --git a/telebot/formatting.py b/telebot/formatting.py index abec962d7..7b6a9f3f9 100644 --- a/telebot/formatting.py +++ b/telebot/formatting.py @@ -5,14 +5,17 @@ """ import html + import re +from typing import Optional + def format_text(*args, separator="\n"): """ Formats a list of strings into a single string. - .. code:: python + .. code:: python3 format_text( # just an example mbold('Hello'), @@ -20,7 +23,13 @@ def format_text(*args, separator="\n"): ) :param args: Strings to format. + :type args: :obj:`str` + :param separator: The separator to use between each string. + :type separator: :obj:`str` + + :return: The formatted string. + :rtype: :obj:`str` """ return separator.join(args) @@ -31,6 +40,10 @@ def escape_html(content: str) -> str: Escapes HTML characters in a string of HTML. :param content: The string of HTML to escape. + :type content: :obj:`str` + + :return: The escaped string. + :rtype: :obj:`str` """ return html.escape(content) @@ -39,9 +52,13 @@ def escape_markdown(content: str) -> str: """ Escapes Markdown characters in a string of Markdown. - Credits: simonsmh + Credits to: simonsmh :param content: The string of Markdown to escape. + :type content: :obj:`str` + + :return: The escaped string. + :rtype: :obj:`str` """ parse = re.sub(r"([_*\[\]()~`>\#\+\-=|\.!])", r"\\\1", content) @@ -49,154 +66,249 @@ def escape_markdown(content: str) -> str: return reparse -def mbold(content: str, escape: bool=True) -> str: +def mbold(content: str, escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted bold string. :param content: The string to bold. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '*{}*'.format(escape_markdown(content) if escape else content) -def hbold(content: str, escape: bool=True) -> str: +def hbold(content: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted bold string. :param content: The string to bold. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '{}'.format(escape_html(content) if escape else content) -def mitalic(content: str, escape: bool=True) -> str: +def mitalic(content: str, escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted italic string. :param content: The string to italicize. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '_{}_\r'.format(escape_markdown(content) if escape else content) -def hitalic(content: str, escape: bool=True) -> str: +def hitalic(content: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted italic string. :param content: The string to italicize. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '{}'.format(escape_html(content) if escape else content) -def munderline(content: str, escape: bool=True) -> str: +def munderline(content: str, escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted underline string. :param content: The string to underline. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '__{}__'.format(escape_markdown(content) if escape else content) -def hunderline(content: str, escape: bool=True) -> str: +def hunderline(content: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted underline string. :param content: The string to underline. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` + """ return '{}'.format(escape_html(content) if escape else content) -def mstrikethrough(content: str, escape: bool=True) -> str: +def mstrikethrough(content: str, escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted strikethrough string. :param content: The string to strikethrough. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '~{}~'.format(escape_markdown(content) if escape else content) -def hstrikethrough(content: str, escape: bool=True) -> str: +def hstrikethrough(content: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted strikethrough string. :param content: The string to strikethrough. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '{}'.format(escape_html(content) if escape else content) -def mspoiler(content: str, escape: bool=True) -> str: +def mspoiler(content: str, escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted spoiler string. :param content: The string to spoiler. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '||{}||'.format(escape_markdown(content) if escape else content) -def hspoiler(content: str, escape: bool=True) -> str: +def hspoiler(content: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted spoiler string. :param content: The string to spoiler. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '{}'.format(escape_html(content) if escape else content) -def mlink(content: str, url: str, escape: bool=True) -> str: +def mlink(content: str, url: str, escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted link string. :param content: The string to link. + :type content: :obj:`str` + :param url: The URL to link to. - :param escape: True if you need to escape special characters. + :type url: str + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '[{}]({})'.format(escape_markdown(content), escape_markdown(url) if escape else content) -def hlink(content: str, url: str, escape: bool=True) -> str: +def hlink(content: str, url: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted link string. :param content: The string to link. + :type content: :obj:`str` + :param url: The URL to link to. - :param escape: True if you need to escape special characters. + :type url: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '{}'.format(escape_html(url), escape_html(content) if escape else content) -def mcode(content: str, language: str="", escape: bool=True) -> str: +def mcode(content: str, language: str="", escape: Optional[bool]=True) -> str: """ Returns a Markdown-formatted code string. :param content: The string to code. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '```{}\n{}```'.format(language, escape_markdown(content) if escape else content) -def hcode(content: str, escape: bool=True) -> str: +def hcode(content: str, escape: Optional[bool]=True) -> str: """ Returns an HTML-formatted code string. :param content: The string to code. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '{}'.format(escape_html(content) if escape else content) -def hpre(content: str, escape: bool=True, language: str="") -> str: +def hpre(content: str, escape: Optional[bool]=True, language: str="") -> str: """ Returns an HTML-formatted preformatted string. :param content: The string to preformatted. - :param escape: True if you need to escape special characters. + :type content: :obj:`str` + + :param escape: True if you need to escape special characters. Defaults to True. + :type escape: :obj:`bool` + + :return: The formatted string. + :rtype: :obj:`str` """ return '
{}
'.format(language, escape_html(content) if escape else content) @@ -205,7 +317,10 @@ def hide_link(url: str) -> str: """ Hide url of an image. - :param url: - :return: str + :param url: The url of the image. + :type url: :obj:`str` + + :return: The hidden url. + :rtype: :obj:`str` """ return f'' \ No newline at end of file diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index 9f4a3a952..42c5804de 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -12,7 +12,9 @@ class HandlerBackend(object): """ - Class for saving (next step|reply) handlers + Class for saving (next step|reply) handlers. + + :meta private: """ def __init__(self, handlers=None): if handlers is None: @@ -30,6 +32,9 @@ def get_handlers(self, handler_group_id): class MemoryHandlerBackend(HandlerBackend): + """ + :meta private: + """ def register_handler(self, handler_group_id, handler): if handler_group_id in self.handlers: self.handlers[handler_group_id].append(handler) @@ -47,6 +52,9 @@ def load_handlers(self, filename, del_file_after_loading): class FileHandlerBackend(HandlerBackend): + """ + :meta private: + """ def __init__(self, handlers=None, filename='./.handler-saves/handlers.save', delay=120): super(FileHandlerBackend, self).__init__(handlers) self.filename = filename @@ -119,6 +127,9 @@ def return_load_handlers(filename, del_file_after_loading=True): class RedisHandlerBackend(HandlerBackend): + """ + :meta private: + """ def __init__(self, handlers=None, host='localhost', port=6379, db=0, prefix='telebot', password=None): super(RedisHandlerBackend, self).__init__(handlers) if not redis_installed: @@ -150,6 +161,14 @@ def get_handlers(self, handler_group_id): class State: + """ + Class representing a state. + + .. code-block:: python3 + + class MyStates(StatesGroup): + my_state = State() # returns my_state:State string. + """ def __init__(self) -> None: self.name = None def __str__(self) -> str: @@ -158,6 +177,14 @@ def __str__(self) -> str: class StatesGroup: + """ + Class representing common states. + + .. code-block:: python3 + + class MyStates(StatesGroup): + my_state = State() # returns my_state:State string. + """ def __init_subclass__(cls) -> None: for name, value in cls.__dict__.items(): if not name.startswith('__') and not callable(value) and isinstance(value, State): @@ -179,8 +206,13 @@ class BaseMiddleware: message update, then you will have to create pre_process_message function, and so on. Same applies to post_process. - .. code-block:: python - + .. note:: + If you want to use middleware, you have to set use_class_middlewares=True in your + TeleBot instance. + + .. code-block:: python3 + :caption: Example of class-based middlewares. + class MyMiddleware(BaseMiddleware): def __init__(self): self.update_sensitive = True diff --git a/telebot/types.py b/telebot/types.py index 5bab9c4cd..6c5a1f085 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -20,12 +20,15 @@ class JsonSerializable(object): """ Subclasses of this class are guaranteed to be able to be converted to JSON format. All subclasses of this class must override to_json. + """ def to_json(self): """ Returns a JSON string representation of this class. + :meta private: + This function must be overridden by subclasses. :return: a JSON formatted string. """ @@ -36,12 +39,15 @@ class Dictionaryable(object): """ Subclasses of this class are guaranteed to be able to be converted to dictionary. All subclasses of this class must override to_dict. + """ def to_dict(self): """ Returns a DICT with class field values + :meta private: + This function must be overridden by subclasses. :return: a DICT """ @@ -59,6 +65,8 @@ def de_json(cls, json_string): """ Returns an instance of this class from the given json dict or string. + :meta private: + This function must be overridden by subclasses. :return: an instance of this class created from the given json dict or string. """ @@ -69,6 +77,8 @@ def check_json(json_type, dict_copy = True): """ Checks whether json_type is a dict or a string. If it is already a dict, it is returned as-is. If it is not, it is converted to a dict by means of json.loads(json_type) + + :meta private: :param json_type: input json or parsed dict :param dict_copy: if dict is passed and it is changed outside - should be True! @@ -90,6 +100,71 @@ def __str__(self): class Update(JsonDeserializable): + """ + This object represents an incoming update.At most one of the optional parameters can be present in any given update. + + Telegram Documentation: https://core.telegram.org/bots/api#update + + :param update_id: The update's unique identifier. Update identifiers start from a certain positive number and + increase sequentially. This ID becomes especially handy if you're using webhooks, since it allows you to ignore + repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates + for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. + :type update_id: :obj:`int` + + :param message: Optional. New incoming message of any kind - text, photo, sticker, etc. + :type message: :class:`telebot.types.Message` + + :param edited_message: Optional. New version of a message that is known to the bot and was edited + :type edited_message: :class:`telebot.types.Message` + + :param channel_post: Optional. New incoming channel post of any kind - text, photo, sticker, etc. + :type channel_post: :class:`telebot.types.Message` + + :param edited_channel_post: Optional. New version of a channel post that is known to the bot and was edited + :type edited_channel_post: :class:`telebot.types.Message` + + :param inline_query: Optional. New incoming inline query + :type inline_query: :class:`telebot.types.InlineQuery` + + :param chosen_inline_result: Optional. The result of an inline query that was chosen by a user and sent to their chat + partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your + bot. + :type chosen_inline_result: :class:`telebot.types.ChosenInlineResult` + + :param callback_query: Optional. New incoming callback query + :type callback_query: :class:`telebot.types.CallbackQuery` + + :param shipping_query: Optional. New incoming shipping query. Only for invoices with flexible price + :type shipping_query: :class:`telebot.types.ShippingQuery` + + :param pre_checkout_query: Optional. New incoming pre-checkout query. Contains full information about + checkout + :type pre_checkout_query: :class:`telebot.types.PreCheckoutQuery` + + :param poll: Optional. New poll state. Bots receive only updates about stopped polls and polls, which are sent by the + bot + :type poll: :class:`telebot.types.Poll` + + :param poll_answer: Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in + polls that were sent by the bot itself. + :type poll_answer: :class:`telebot.types.PollAnswer` + + :param my_chat_member: Optional. The bot's chat member status was updated in a chat. For private chats, this update + is received only when the bot is blocked or unblocked by the user. + :type my_chat_member: :class:`telebot.types.ChatMemberUpdated` + + :param chat_member: Optional. A chat member's status was updated in a chat. The bot must be an administrator in the + chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. + :type chat_member: :class:`telebot.types.ChatMemberUpdated` + + :param chat_join_request: Optional. A request to join the chat has been sent. The bot must have the + can_invite_users administrator right in the chat to receive these updates. + :type chat_join_request: :class:`telebot.types.ChatJoinRequest` + + :return: Instance of the class + :rtype: :class:`telebot.types.Update` + + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -134,6 +209,33 @@ def __init__(self, update_id, message, edited_message, channel_post, edited_chan class ChatMemberUpdated(JsonDeserializable): + """ + This object represents changes in the status of a chat member. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmemberupdated + + :param chat: Chat the user belongs to + :type chat: :class:`telebot.types.Chat` + + :param from_user: Performer of the action, which resulted in the change + :type from_user: :class:`telebot.types.User` + + :param date: Date the change was done in Unix time + :type date: :obj:`int` + + :param old_chat_member: Previous information about the chat member + :type old_chat_member: :class:`telebot.types.ChatMember` + + :param new_chat_member: New information about the chat member + :type new_chat_member: :class:`telebot.types.ChatMember` + + :param invite_link: Optional. Chat invite link, which was used by the user to join the chat; for joining by invite + link events only. + :type invite_link: :class:`telebot.types.ChatInviteLink` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberUpdated` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -158,7 +260,11 @@ def difference(self) -> Dict[str, List]: """ Get the difference between `old_chat_member` and `new_chat_member` as a dict in the following format {'parameter': [old_value, new_value]} - E.g {'status': ['member', 'kicked'], 'until_date': [None, 1625055092]} + E.g {'status': ['member', 'kicked'], 'until_date': [None, 1625055092]} + + + :return: Dict of differences + :rtype: Dict[str, List] """ old: Dict = self.old_chat_member.__dict__ new: Dict = self.new_chat_member.__dict__ @@ -168,8 +274,32 @@ def difference(self) -> Dict[str, List]: if new[key] != old[key]: dif[key] = [old[key], new[key]] return dif + class ChatJoinRequest(JsonDeserializable): + """ + Represents a join request sent to a chat. + + Telegram Documentation: https://core.telegram.org/bots/api#chatjoinrequest + + :param chat: Chat to which the request was sent + :type chat: :class:`telebot.types.Chat` + + :param from: User that sent the join request + :type from_user: :class:`telebot.types.User` + + :param date: Date the request was sent in Unix time + :type date: :obj:`int` + + :param bio: Optional. Bio of the user. + :type bio: :obj:`str` + + :param invite_link: Optional. Chat invite link that was used by the user to send the join request + :type invite_link: :class:`telebot.types.ChatInviteLink` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatJoinRequest` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -187,6 +317,46 @@ def __init__(self, chat, from_user, date, bio=None, invite_link=None, **kwargs): self.invite_link = invite_link class WebhookInfo(JsonDeserializable): + """ + Describes the current status of a webhook. + + Telegram Documentation: https://core.telegram.org/bots/api#webhookinfo + + :param url: Webhook URL, may be empty if webhook is not set up + :type url: :obj:`str` + + :param has_custom_certificate: True, if a custom certificate was provided for webhook certificate checks + :type has_custom_certificate: :obj:`bool` + + :param pending_update_count: Number of updates awaiting delivery + :type pending_update_count: :obj:`int` + + :param ip_address: Optional. Currently used webhook IP address + :type ip_address: :obj:`str` + + :param last_error_date: Optional. Unix time for the most recent error that happened when trying to deliver an + update via webhook + :type last_error_date: :obj:`int` + + :param last_error_message: Optional. Error message in human-readable format for the most recent error that + happened when trying to deliver an update via webhook + :type last_error_message: :obj:`str` + + :param last_synchronization_error_date: Optional. Unix time of the most recent error that happened when trying + to synchronize available updates with Telegram datacenters + :type last_synchronization_error_date: :obj:`int` + + :param max_connections: Optional. The maximum allowed number of simultaneous HTTPS connections to the webhook + for update delivery + :type max_connections: :obj:`int` + + :param allowed_updates: Optional. A list of update types the bot is subscribed to. Defaults to all update types + except chat_member + :type allowed_updates: :obj:`list` of :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.WebhookInfo` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -208,6 +378,50 @@ def __init__(self, url, has_custom_certificate, pending_update_count, ip_address class User(JsonDeserializable, Dictionaryable, JsonSerializable): + """ + This object represents a Telegram user or bot. + + Telegram Documentation: https://core.telegram.org/bots/api#user + + :param id: Unique identifier for this user or bot. This number may have more than 32 significant bits and some + programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant + bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + :type id: :obj:`int` + + :param is_bot: True, if this user is a bot + :type is_bot: :obj:`bool` + + :param first_name: User's or bot's first name + :type first_name: :obj:`str` + + :param last_name: Optional. User's or bot's last name + :type last_name: :obj:`str` + + :param username: Optional. User's or bot's username + :type username: :obj:`str` + + :param language_code: Optional. IETF language tag of the user's language + :type language_code: :obj:`str` + + :param is_premium: Optional. :obj:`bool`, if this user is a Telegram Premium user + :type is_premium: :obj:`bool` + + :param added_to_attachment_menu: Optional. :obj:`bool`, if this user added the bot to the attachment menu + :type added_to_attachment_menu: :obj:`bool` + + :param can_join_groups: Optional. True, if the bot can be invited to groups. Returned only in getMe. + :type can_join_groups: :obj:`bool` + + :param can_read_all_group_messages: Optional. True, if privacy mode is disabled for the bot. Returned only in + getMe. + :type can_read_all_group_messages: :obj:`bool` + + :param supports_inline_queries: Optional. True, if the bot supports inline queries. Returned only in getMe. + :type supports_inline_queries: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.User` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -232,6 +446,9 @@ def __init__(self, id, is_bot, first_name, last_name=None, username=None, langua @property def full_name(self): + """ + :return: User's full name + """ full_name = self.first_name if self.last_name: full_name += ' {0}'.format(self.last_name) @@ -249,10 +466,15 @@ def to_dict(self): 'language_code': self.language_code, 'can_join_groups': self.can_join_groups, 'can_read_all_group_messages': self.can_read_all_group_messages, - 'supports_inline_queries': self.supports_inline_queries} + 'supports_inline_queries': self.supports_inline_queries, + 'is_premium': self.is_premium, + 'added_to_attachment_menu': self.added_to_attachment_menu} class GroupChat(JsonDeserializable): + """ + :meta private: + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -265,6 +487,95 @@ def __init__(self, id, title, **kwargs): class Chat(JsonDeserializable): + """ + This object represents a chat. + + Telegram Documentation: https://core.telegram.org/bots/api#chat + + :param id: Unique identifier for this chat. This number may have more than 32 significant bits and some programming + languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed + 64-bit integer or double-precision float type are safe for storing this identifier. + :type id: :obj:`int` + + :param type: Type of chat, can be either “private”, “group”, “supergroup” or “channel” + :type type: :obj:`str` + + :param title: Optional. Title, for supergroups, channels and group chats + :type title: :obj:`str` + + :param username: Optional. Username, for private chats, supergroups and channels if available + :type username: :obj:`str` + + :param first_name: Optional. First name of the other party in a private chat + :type first_name: :obj:`str` + + :param last_name: Optional. Last name of the other party in a private chat + :type last_name: :obj:`str` + + :param photo: Optional. Chat photo. Returned only in getChat. + :type photo: :class:`telebot.types.ChatPhoto` + + :param bio: Optional. Bio of the other party in a private chat. Returned only in getChat. + :type bio: :obj:`str` + + :param has_private_forwards: Optional. :obj:`bool`, if privacy settings of the other party in the private chat + allows to use tg://user?id= links only in chats with the user. Returned only in getChat. + :type has_private_forwards: :obj:`bool` + + :param join_to_send_messages: Optional. :obj:`bool`, if users need to join the supergroup before they can send + messages. Returned only in getChat. + :type join_to_send_messages: :obj:`bool` + + :param join_by_request: Optional. :obj:`bool`, if all users directly joining the supergroup need to be approved + by supergroup administrators. Returned only in getChat. + :type join_by_request: :obj:`bool` + + :param description: Optional. Description, for groups, supergroups and channel chats. Returned only in getChat. + :type description: :obj:`str` + + :param invite_link: Optional. Primary invite link, for groups, supergroups and channel chats. Returned only in + getChat. + :type invite_link: :obj:`str` + + :param pinned_message: Optional. The most recent pinned message (by sending date). Returned only in getChat. + :type pinned_message: :class:`telebot.types.Message` + + :param permissions: Optional. Default chat member permissions, for groups and supergroups. Returned only in + getChat. + :type permissions: :class:`telebot.types.ChatPermissions` + + :param slow_mode_delay: Optional. For supergroups, the minimum allowed delay between consecutive messages sent + by each unpriviledged user; in seconds. Returned only in getChat. + :type slow_mode_delay: :obj:`int` + + :param message_auto_delete_time: Optional. The time after which all messages sent to the chat will be + automatically deleted; in seconds. Returned only in getChat. + :type message_auto_delete_time: :obj:`int` + + :param has_protected_content: Optional. :obj:`bool`, if messages from the chat can't be forwarded to other + chats. Returned only in getChat. + :type has_protected_content: :obj:`bool` + + :param sticker_set_name: Optional. For supergroups, name of group sticker set. Returned only in getChat. + :type sticker_set_name: :obj:`str` + + :param can_set_sticker_set: Optional. :obj:`bool`, if the bot can change the group sticker set. Returned only in + getChat. + :type can_set_sticker_set: :obj:`bool` + + :param linked_chat_id: Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for + a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some + programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a + signed 64 bit integer or double-precision float type are safe for storing this identifier. Returned only in getChat. + :type linked_chat_id: :obj:`int` + + :param location: Optional. For supergroups, the location to which the supergroup is connected. Returned only in + getChat. + :type location: :class:`telebot.types.ChatLocation` + + :return: Instance of the class + :rtype: :class:`telebot.types.Chat` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -311,6 +622,17 @@ def __init__(self, id, type, title=None, username=None, first_name=None, class MessageID(JsonDeserializable): + """ + This object represents a unique message identifier. + + Telegram Documentation: https://core.telegram.org/bots/api#messageid + + :param message_id: Unique message identifier + :type message_id: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.MessageId` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -321,7 +643,23 @@ def __init__(self, message_id, **kwargs): self.message_id = message_id -class WebAppData(JsonDeserializable): +class WebAppData(JsonDeserializable, Dictionaryable): + """ + Describes data sent from a Web App to the bot. + + Telegram Documentation: https://core.telegram.org/bots/api#webappdata + + :param data: The data. Be aware that a bad client can send arbitrary data in this field. + :type data: :obj:`str` + + :param button_text: Text of the web_app keyboard button from which the Web App was opened. Be aware that a bad client + can send arbitrary data in this field. + :type button_text: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.WebAppData` + """ + def __init__(self, data, button_text): self.data = data self.button_text = button_text @@ -336,6 +674,224 @@ def de_json(cls, json_string): class Message(JsonDeserializable): + """ + This object represents a message. + + Telegram Documentation: https://core.telegram.org/bots/api#message + + :param message_id: Unique message identifier inside this chat + :type message_id: :obj:`int` + + :param from_user: Optional. Sender of the message; empty for messages sent to channels. For backward compatibility, the + field contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat. + :type from_user: :class:`telebot.types.User` + + :param sender_chat: Optional. Sender of the message, sent on behalf of a chat. For example, the channel itself for + channel posts, the supergroup itself for messages from anonymous group administrators, the linked channel for + messages automatically forwarded to the discussion group. For backward compatibility, the field from contains a + fake sender user in non-channel chats, if the message was sent on behalf of a chat. + :type sender_chat: :class:`telebot.types.Chat` + + :param date: Date the message was sent in Unix time + :type date: :obj:`int` + + :param chat: Conversation the message belongs to + :type chat: :class:`telebot.types.Chat` + + :param forward_from: Optional. For forwarded messages, sender of the original message + :type forward_from: :class:`telebot.types.User` + + :param forward_from_chat: Optional. For messages forwarded from channels or from anonymous administrators, + information about the original sender chat + :type forward_from_chat: :class:`telebot.types.Chat` + + :param forward_from_message_id: Optional. For messages forwarded from channels, identifier of the original + message in the channel + :type forward_from_message_id: :obj:`int` + + :param forward_signature: Optional. For forwarded messages that were originally sent in channels or by an + anonymous chat administrator, signature of the message sender if present + :type forward_signature: :obj:`str` + + :param forward_sender_name: Optional. Sender's name for messages forwarded from users who disallow adding a link + to their account in forwarded messages + :type forward_sender_name: :obj:`str` + + :param forward_date: Optional. For forwarded messages, date the original message was sent in Unix time + :type forward_date: :obj:`int` + + :param is_automatic_forward: Optional. :obj:`bool`, if the message is a channel post that was automatically + forwarded to the connected discussion group + :type is_automatic_forward: :obj:`bool` + + :param reply_to_message: Optional. For replies, the original message. Note that the Message object in this field + will not contain further reply_to_message fields even if it itself is a reply. + :type reply_to_message: :class:`telebot.types.Message` + + :param via_bot: Optional. Bot through which the message was sent + :type via_bot: :class:`telebot.types.User` + + :param edit_date: Optional. Date the message was last edited in Unix time + :type edit_date: :obj:`int` + + :param has_protected_content: Optional. :obj:`bool`, if the message can't be forwarded + :type has_protected_content: :obj:`bool` + + :param media_group_id: Optional. The unique identifier of a media message group this message belongs to + :type media_group_id: :obj:`str` + + :param author_signature: Optional. Signature of the post author for messages in channels, or the custom title of an + anonymous group administrator + :type author_signature: :obj:`str` + + :param text: Optional. For text messages, the actual UTF-8 text of the message + :type text: :obj:`str` + + :param entities: Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that + appear in the text + :type entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param animation: Optional. Message is an animation, information about the animation. For backward + compatibility, when this field is set, the document field will also be set + :type animation: :class:`telebot.types.Animation` + + :param audio: Optional. Message is an audio file, information about the file + :type audio: :class:`telebot.types.Audio` + + :param document: Optional. Message is a general file, information about the file + :type document: :class:`telebot.types.Document` + + :param photo: Optional. Message is a photo, available sizes of the photo + :type photo: :obj:`list` of :class:`telebot.types.PhotoSize` + + :param sticker: Optional. Message is a sticker, information about the sticker + :type sticker: :class:`telebot.types.Sticker` + + :param video: Optional. Message is a video, information about the video + :type video: :class:`telebot.types.Video` + + :param video_note: Optional. Message is a video note, information about the video message + :type video_note: :class:`telebot.types.VideoNote` + + :param voice: Optional. Message is a voice message, information about the file + :type voice: :class:`telebot.types.Voice` + + :param caption: Optional. Caption for the animation, audio, document, photo, video or voice + :type caption: :obj:`str` + + :param caption_entities: Optional. For messages with a caption, special entities like usernames, URLs, bot + commands, etc. that appear in the caption + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param contact: Optional. Message is a shared contact, information about the contact + :type contact: :class:`telebot.types.Contact` + + :param dice: Optional. Message is a dice with random value + :type dice: :class:`telebot.types.Dice` + + :param game: Optional. Message is a game, information about the game. More about games » + :type game: :class:`telebot.types.Game` + + :param poll: Optional. Message is a native poll, information about the poll + :type poll: :class:`telebot.types.Poll` + + :param venue: Optional. Message is a venue, information about the venue. For backward compatibility, when this + field is set, the location field will also be set + :type venue: :class:`telebot.types.Venue` + + :param location: Optional. Message is a shared location, information about the location + :type location: :class:`telebot.types.Location` + + :param new_chat_members: Optional. New members that were added to the group or supergroup and information about + them (the bot itself may be one of these members) + :type new_chat_members: :obj:`list` of :class:`telebot.types.User` + + :param left_chat_member: Optional. A member was removed from the group, information about them (this member may be + the bot itself) + :type left_chat_member: :class:`telebot.types.User` + + :param new_chat_title: Optional. A chat title was changed to this value + :type new_chat_title: :obj:`str` + + :param new_chat_photo: Optional. A chat photo was change to this value + :type new_chat_photo: :obj:`list` of :class:`telebot.types.PhotoSize` + + :param delete_chat_photo: Optional. Service message: the chat photo was deleted + :type delete_chat_photo: :obj:`bool` + + :param group_chat_created: Optional. Service message: the group has been created + :type group_chat_created: :obj:`bool` + + :param supergroup_chat_created: Optional. Service message: the supergroup has been created. This field can't be + received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can + only be found in reply_to_message if someone replies to a very first message in a directly created supergroup. + :type supergroup_chat_created: :obj:`bool` + + :param channel_chat_created: Optional. Service message: the channel has been created. This field can't be + received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only + be found in reply_to_message if someone replies to a very first message in a channel. + :type channel_chat_created: :obj:`bool` + + :param message_auto_delete_timer_changed: Optional. Service message: auto-delete timer settings changed in + the chat + :type message_auto_delete_timer_changed: :class:`telebot.types.MessageAutoDeleteTimerChanged` + + :param migrate_to_chat_id: Optional. The group has been migrated to a supergroup with the specified identifier. + This number may have more than 32 significant bits and some programming languages may have difficulty/silent + defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision + float type are safe for storing this identifier. + :type migrate_to_chat_id: :obj:`int` + + :param migrate_from_chat_id: Optional. The supergroup has been migrated from a group with the specified + identifier. This number may have more than 32 significant bits and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this identifier. + :type migrate_from_chat_id: :obj:`int` + + :param pinned_message: Optional. Specified message was pinned. Note that the Message object in this field will not + contain further reply_to_message fields even if it is itself a reply. + :type pinned_message: :class:`telebot.types.Message` + + :param invoice: Optional. Message is an invoice for a payment, information about the invoice. More about payments » + :type invoice: :class:`telebot.types.Invoice` + + :param successful_payment: Optional. Message is a service message about a successful payment, information about + the payment. More about payments » + :type successful_payment: :class:`telebot.types.SuccessfulPayment` + + :param connected_website: Optional. The domain name of the website on which the user has logged in. More about + Telegram Login » + :type connected_website: :obj:`str` + + :param passport_data: Optional. Telegram Passport data + :type passport_data: :class:`telebot.types.PassportData` + + :param proximity_alert_triggered: Optional. Service message. A user in the chat triggered another user's + proximity alert while sharing Live Location. + :type proximity_alert_triggered: :class:`telebot.types.ProximityAlertTriggered` + + :param video_chat_scheduled: Optional. Service message: video chat scheduled + :type video_chat_scheduled: :class:`telebot.types.VideoChatScheduled` + + :param video_chat_started: Optional. Service message: video chat started + :type video_chat_started: :class:`telebot.types.VideoChatStarted` + + :param video_chat_ended: Optional. Service message: video chat ended + :type video_chat_ended: :class:`telebot.types.VideoChatEnded` + + :param video_chat_participants_invited: Optional. Service message: new participants invited to a video chat + :type video_chat_participants_invited: :class:`telebot.types.VideoChatParticipantsInvited` + + :param web_app_data: Optional. Service message: data sent by a Web App + :type web_app_data: :class:`telebot.types.WebAppData` + + :param reply_markup: Optional. Inline keyboard attached to the message. login_url buttons are represented as + ordinary url buttons. + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :return: Instance of the class + :rtype: :class:`telebot.types.Message` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -507,6 +1063,9 @@ def de_json(cls, json_string): @classmethod def parse_chat(cls, chat): + """ + Parses chat. + """ if 'first_name' not in chat: return GroupChat.de_json(chat) else: @@ -514,6 +1073,9 @@ def parse_chat(cls, chat): @classmethod def parse_photo(cls, photo_size_array): + """ + Parses photo array. + """ ret = [] for ps in photo_size_array: ret.append(PhotoSize.de_json(ps)) @@ -521,6 +1083,9 @@ def parse_photo(cls, photo_size_array): @classmethod def parse_entities(cls, message_entity_array): + """ + Parses message entity array. + """ ret = [] for me in message_entity_array: ret.append(MessageEntity.de_json(me)) @@ -589,13 +1154,17 @@ def __html_text(self, text, entities): Updaters: @badiboy Message: "*Test* parse _formatting_, [url](https://example.com), [text_mention](tg://user?id=123456) and mention @username" - Example: + .. code-block:: python3 + :caption: Example: + message.html_text >> "Test parse formatting, url, text_mention and mention @username" Custom subs: You can customize the substitutes. By default, there is no substitute for the entities: hashtag, bot_command, email. You can add or modify substitute an existing entity. - Example: + .. code-block:: python3 + :caption: Example: + message.custom_subs = {"bold": "{text}", "italic": "{text}", "mention": "{text}"} message.html_text >> "Test parse formatting, url and text_mention and mention @username" @@ -655,16 +1224,56 @@ def func(upd_text, subst_type=None, url=None, user=None): @property def html_text(self): + """ + Returns html-rendered text. + """ return self.__html_text(self.text, self.entities) @property def html_caption(self): + """ + Returns html-rendered caption. + """ return self.__html_text(self.caption, self.caption_entities) class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable): + """ + This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. + + Telegram Documentation: https://core.telegram.org/bots/api#messageentity + + :param type: Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag), “cashtag” + ($USD), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” + (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), + “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “code” + (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users + without usernames) + :type type: :obj:`str` + + :param offset: Offset in UTF-16 code units to the start of the entity + :type offset: :obj:`int` + + :param length: Length of the entity in UTF-16 code units + :type length: :obj:`int` + + :param url: Optional. For “text_link” only, URL that will be opened after user taps on the text + :type url: :obj:`str` + + :param user: Optional. For “text_mention” only, the mentioned user + :type user: :class:`telebot.types.User` + + :param language: Optional. For “pre” only, the programming language of the entity text + :type language: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.MessageEntity` + """ @staticmethod def to_list_of_dicts(entity_list) -> Union[List[Dict], None]: + """ + Converts a list of MessageEntity objects to a list of dictionaries. + """ res = [] for e in entity_list: res.append(MessageEntity.to_dict(e)) @@ -699,6 +1308,20 @@ def to_dict(self): class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): + """ + This object represents an animated emoji that displays a random value. + + Telegram Documentation: https://core.telegram.org/bots/api#dice + + :param emoji: Emoji on which the dice throw animation is based + :type emoji: :obj:`str` + + :param value: Value of the dice, 1-6 for “🎲”, “🎯” and “🎳” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji + :type value: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Dice` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -718,6 +1341,30 @@ def to_dict(self): class PhotoSize(JsonDeserializable): + """ + This object represents one size of a photo or a file / sticker thumbnail. + + Telegram Documentation: https://core.telegram.org/bots/api#photosize + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param width: Photo width + :type width: :obj:`int` + + :param height: Photo height + :type height: :obj:`int` + + :param file_size: Optional. File size in bytes + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.PhotoSize` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -733,6 +1380,44 @@ def __init__(self, file_id, file_unique_id, width, height, file_size=None, **kwa class Audio(JsonDeserializable): + """ + This object represents an audio file to be treated as music by the Telegram clients. + + Telegram Documentation: https://core.telegram.org/bots/api#audio + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param duration: Duration of the audio in seconds as defined by sender + :type duration: :obj:`int` + + :param performer: Optional. Performer of the audio as defined by sender or by audio tags + :type performer: :obj:`str` + + :param title: Optional. Title of the audio as defined by sender or by audio tags + :type title: :obj:`str` + + :param file_name: Optional. Original filename as defined by sender + :type file_name: :obj:`str` + + :param mime_type: Optional. MIME type of the file as defined by sender + :type mime_type: :obj:`str` + + :param file_size: Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this value. + :type file_size: :obj:`int` + + :param thumb: Optional. Thumbnail of the album cover to which the music file belongs + :type thumb: :class:`telebot.types.PhotoSize` + + :return: Instance of the class + :rtype: :class:`telebot.types.Audio` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -757,6 +1442,32 @@ def __init__(self, file_id, file_unique_id, duration, performer=None, title=None class Voice(JsonDeserializable): + """ + This object represents a voice note. + + Telegram Documentation: https://core.telegram.org/bots/api#voice + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param duration: Duration of the audio in seconds as defined by sender + :type duration: :obj:`int` + + :param mime_type: Optional. MIME type of the file as defined by sender + :type mime_type: :obj:`str` + + :param file_size: Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this value. + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Voice` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -772,6 +1483,35 @@ def __init__(self, file_id, file_unique_id, duration, mime_type=None, file_size= class Document(JsonDeserializable): + """ + This object represents a general file (as opposed to photos, voice messages and audio files). + + Telegram Documentation: https://core.telegram.org/bots/api#document + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param thumb: Optional. Document thumbnail as defined by sender + :type thumb: :class:`telebot.types.PhotoSize` + + :param file_name: Optional. Original filename as defined by sender + :type file_name: :obj:`str` + + :param mime_type: Optional. MIME type of the file as defined by sender + :type mime_type: :obj:`str` + + :param file_size: Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this value. + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Document` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -792,10 +1532,48 @@ def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_typ class Video(JsonDeserializable): - @classmethod - def de_json(cls, json_string): - if json_string is None: return None - obj = cls.check_json(json_string) + """ + This object represents a video file. + + Telegram Documentation: https://core.telegram.org/bots/api#video + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param width: Video width as defined by sender + :type width: :obj:`int` + + :param height: Video height as defined by sender + :type height: :obj:`int` + + :param duration: Duration of the video in seconds as defined by sender + :type duration: :obj:`int` + + :param thumb: Optional. Video thumbnail + :type thumb: :class:`telebot.types.PhotoSize` + + :param file_name: Optional. Original filename as defined by sender + :type file_name: :obj:`str` + + :param mime_type: Optional. MIME type of the file as defined by sender + :type mime_type: :obj:`str` + + :param file_size: Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this value. + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Video` + """ + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) return cls(**obj) @@ -813,6 +1591,33 @@ def __init__(self, file_id, file_unique_id, width, height, duration, thumb=None, class VideoNote(JsonDeserializable): + """ + This object represents a video message (available in Telegram apps as of v.4.0). + + Telegram Documentation: https://core.telegram.org/bots/api#videonote + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param length: Video width and height (diameter of the video message) as defined by sender + :type length: :obj:`int` + + :param duration: Duration of the video in seconds as defined by sender + :type duration: :obj:`int` + + :param thumb: Optional. Video thumbnail + :type thumb: :class:`telebot.types.PhotoSize` + + :param file_size: Optional. File size in bytes + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.VideoNote` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -831,6 +1636,31 @@ def __init__(self, file_id, file_unique_id, length, duration, thumb=None, file_s class Contact(JsonDeserializable): + """ + This object represents a phone contact. + + Telegram Documentation: https://core.telegram.org/bots/api#contact + + :param phone_number: Contact's phone number + :type phone_number: :obj:`str` + + :param first_name: Contact's first name + :type first_name: :obj:`str` + + :param last_name: Optional. Contact's last name + :type last_name: :obj:`str` + + :param user_id: Optional. Contact's user identifier in Telegram. This number may have more than 32 significant bits + and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 + significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + :type user_id: :obj:`int` + + :param vcard: Optional. Additional data about the contact in the form of a vCard + :type vcard: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.Contact` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -846,6 +1676,34 @@ def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard class Location(JsonDeserializable, JsonSerializable, Dictionaryable): + """ + This object represents a point on the map. + + Telegram Documentation: https://core.telegram.org/bots/api#location + + :param longitude: Longitude as defined by sender + :type longitude: :obj:`float` + + :param latitude: Latitude as defined by sender + :type latitude: :obj:`float` + + :param horizontal_accuracy: Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + :type horizontal_accuracy: :obj:`float` number + + :param live_period: Optional. Time relative to the message sending date, during which the location can be updated; + in seconds. For active live locations only. + :type live_period: :obj:`int` + + :param heading: Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only. + :type heading: :obj:`int` + + :param proximity_alert_radius: Optional. The maximum distance for proximity alerts about approaching another + chat member, in meters. For sent live locations only. + :type proximity_alert_radius: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Location` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -876,6 +1734,36 @@ def to_dict(self): class Venue(JsonDeserializable): + """ + This object represents a venue. + + Telegram Documentation: https://core.telegram.org/bots/api#venue + + :param location: Venue location. Can't be a live location + :type location: :class:`telebot.types.Location` + + :param title: Name of the venue + :type title: :obj:`str` + + :param address: Address of the venue + :type address: :obj:`str` + + :param foursquare_id: Optional. Foursquare identifier of the venue + :type foursquare_id: :obj:`str` + + :param foursquare_type: Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, + “arts_entertainment/aquarium” or “food/icecream”.) + :type foursquare_type: :obj:`str` + + :param google_place_id: Optional. Google Places identifier of the venue + :type google_place_id: :obj:`str` + + :param google_place_type: Optional. Google Places type of the venue. (See supported types.) + :type google_place_type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.Venue` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -895,6 +1783,20 @@ def __init__(self, location, title, address, foursquare_id=None, foursquare_type class UserProfilePhotos(JsonDeserializable): + """ + This object represent a user's profile pictures. + + Telegram Documentation: https://core.telegram.org/bots/api#userprofilephotos + + :param total_count: Total number of profile pictures the target user has + :type total_count: :obj:`int` + + :param photos: Requested profile pictures (in up to 4 sizes each) + :type photos: :obj:`list` of :obj:`list` of :class:`telebot.types.PhotoSize` + + :return: Instance of the class + :rtype: :class:`telebot.types.UserProfilePhotos` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -910,6 +1812,30 @@ def __init__(self, total_count, photos=None, **kwargs): class File(JsonDeserializable): + """ + This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot/. 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 getFile. + + Telegram Documentation: https://core.telegram.org/bots/api#file + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param file_size: Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this value. + :type file_size: :obj:`int` + + :param file_path: Optional. File path. Use https://api.telegram.org/file/bot/ to get the + file. + :type file_path: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.File` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -924,6 +1850,27 @@ def __init__(self, file_id, file_unique_id, file_size=None, file_path=None, **kw class ForceReply(JsonSerializable): + """ + Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode. + + Telegram Documentation: https://core.telegram.org/bots/api#forcereply + + :param force_reply: Shows reply interface to the user, as if they manually selected the bot's message and tapped + 'Reply' + :type force_reply: :obj:`bool` + + :param input_field_placeholder: Optional. The placeholder to be shown in the input field when the reply is active; + 1-64 characters + :type input_field_placeholder: :obj:`str` + + :param selective: Optional. Use this parameter if you want to force reply from specific users only. Targets: 1) users + that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), + sender of the original message. + :type selective: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.ForceReply` + """ def __init__(self, selective: Optional[bool]=None, input_field_placeholder: Optional[str]=None): self.selective: bool = selective self.input_field_placeholder: str = input_field_placeholder @@ -938,6 +1885,27 @@ def to_json(self): class ReplyKeyboardRemove(JsonSerializable): + """ + Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). + + Telegram Documentation: https://core.telegram.org/bots/api#replykeyboardremove + + :param remove_keyboard: Requests clients to remove the custom keyboard (user will not be able to summon this + keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in + ReplyKeyboardMarkup) + Note that this parameter is set to True by default by the library. You cannot modify it. + :type remove_keyboard: :obj:`bool` + + :param selective: Optional. Use this parameter if you want to remove the keyboard for specific users only. Targets: + 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has + reply_to_message_id), sender of the original message.Example: A user votes in a poll, bot returns confirmation + message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options + to users who haven't voted yet. + :type selective: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.ReplyKeyboardRemove` + """ def __init__(self, selective=None): self.selective: bool = selective @@ -948,7 +1916,18 @@ def to_json(self): return json.dumps(json_dict) -class WebAppInfo(JsonDeserializable): +class WebAppInfo(JsonDeserializable, Dictionaryable): + """ + Describes a Web App. + + Telegram Documentation: https://core.telegram.org/bots/api#webappinfo + + :param url: An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps + :type url: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.WebAppInfo` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -963,6 +1942,51 @@ def to_dict(self): class ReplyKeyboardMarkup(JsonSerializable): + """ + This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). + + .. code-block:: python3 + :caption: Example on creating ReplyKeyboardMarkup object + + from telebot.types import ReplyKeyboardMarkup, KeyboardButton + + markup = ReplyKeyboardMarkup(resize_keyboard=True) + markup.add(KeyboardButton('Text')) + # or: + markup.add('Text') + + # display this markup: + bot.send_message(chat_id, 'Text', reply_markup=markup) + + Telegram Documentation: https://core.telegram.org/bots/api#replykeyboardmarkup + + :param keyboard: :obj:`list` of button rows, each represented by an :obj:`list` of + :class:`telebot.types.KeyboardButton` objects + :type keyboard: :obj:`list` of :obj:`list` of :class:`telebot.types.KeyboardButton` + + :param resize_keyboard: Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make + the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is + always of the same height as the app's standard keyboard. + :type resize_keyboard: :obj:`bool` + + :param one_time_keyboard: Optional. Requests clients to hide the keyboard as soon as it's been used. The keyboard + will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can + press a special button in the input field to see the custom keyboard again. Defaults to false. + :type one_time_keyboard: :obj:`bool` + + :param input_field_placeholder: Optional. The placeholder to be shown in the input field when the keyboard is + active; 1-64 characters + :type input_field_placeholder: :obj:`str` + + :param selective: Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) + users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has + reply_to_message_id), sender of the original message.Example: A user requests to change the bot's language, bot + replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard. + :type selective: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.ReplyKeyboardMarkup` + """ max_row_keys = 12 def __init__(self, resize_keyboard: Optional[bool]=None, one_time_keyboard: Optional[bool]=None, @@ -989,8 +2013,13 @@ def add(self, *args, row_width=None): See https://core.telegram.org/bots/api#replykeyboardmarkup :param args: KeyboardButton to append to the keyboard + :type args: :obj:`str` or :class:`telebot.types.KeyboardButton` + :param row_width: width of row + :type row_width: :obj:`int` + :return: self, to allow function chaining. + :rtype: :class:`telebot.types.ReplyKeyboardMarkup` """ if row_width is None: row_width = self.row_width @@ -1021,17 +2050,15 @@ def row(self, *args): See https://core.telegram.org/bots/api#replykeyboardmarkup :param args: strings + :type args: :obj:`str` + :return: self, to allow function chaining. + :rtype: :class:`telebot.types.ReplyKeyboardMarkup` """ return self.add(*args, row_width=self.max_row_keys) def to_json(self): - """ - Converts this object to its json representation following the Telegram API guidelines described here: - https://core.telegram.org/bots/api#replykeyboardmarkup - :return: - """ json_dict = {'keyboard': self.keyboard} if self.one_time_keyboard is not None: json_dict['one_time_keyboard'] = self.one_time_keyboard @@ -1045,6 +2072,18 @@ def to_json(self): class KeyboardButtonPollType(Dictionaryable): + """ + This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. + + Telegram Documentation: https://core.telegram.org/bots/api#keyboardbuttonpolltype + + :param type: Optional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is + passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type. + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.KeyboardButtonPollType` + """ def __init__(self, type=''): self.type: str = type @@ -1053,6 +2092,34 @@ def to_dict(self): class KeyboardButton(Dictionaryable, JsonSerializable): + """ + This object represents one button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields web_app, request_contact, request_location, and request_poll are mutually exclusive. + + Telegram Documentation: https://core.telegram.org/bots/api#keyboardbutton + + :param text: Text of the button. If none of the optional fields are used, it will be sent as a message when the button is + pressed + :type text: :obj:`str` + + :param request_contact: Optional. If True, the user's phone number will be sent as a contact when the button is + pressed. Available in private chats only. + :type request_contact: :obj:`bool` + + :param request_location: Optional. If True, the user's current location will be sent when the button is pressed. + Available in private chats only. + :type request_location: :obj:`bool` + + :param request_poll: Optional. If specified, the user will be asked to create a poll and send it to the bot when the + button is pressed. Available in private chats only. + :type request_poll: :class:`telebot.types.KeyboardButtonPollType` + + :param web_app: Optional. If specified, the described Web App will be launched when the button is pressed. The Web App + will be able to send a “web_app_data” service message. Available in private chats only. + :type web_app: :class:`telebot.types.WebAppInfo` + + :return: Instance of the class + :rtype: :class:`telebot.types.KeyboardButton` + """ def __init__(self, text: str, request_contact: Optional[bool]=None, request_location: Optional[bool]=None, request_poll: Optional[KeyboardButtonPollType]=None, web_app: WebAppInfo=None): @@ -1079,6 +2146,31 @@ def to_dict(self): class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable): + """ + This object represents an inline keyboard that appears right next to the message it belongs to. + + .. note:: + It is recommended to use :meth:`telebot.util.quick_markup` instead. + + .. code-block:: python3 + :caption: Example of a custom keyboard with buttons. + + from telebot.util import quick_markup + + markup = quick_markup( + {'text': 'Press me', 'callback_data': 'press'}, + {'text': 'Press me too', 'callback_data': 'press_too'} + ) + + Telegram Documentation: https://core.telegram.org/bots/api#inlinekeyboardmarkup + + :param inline_keyboard: :obj:`list` of button rows, each represented by an :obj:`list` of + :class:`telebot.types.InlineKeyboardButton` objects + :type inline_keyboard: :obj:`list` of :obj:`list` of :class:`telebot.types.InlineKeyboardButton` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineKeyboardMarkup` + """ max_row_keys = 8 @classmethod @@ -1089,12 +2181,6 @@ def de_json(cls, json_string): return cls(keyboard = keyboard) def __init__(self, keyboard=None, row_width=3): - """ - This object represents an inline keyboard that appears - right next to the message it belongs to. - - :return: None - """ if row_width > self.max_row_keys: # Todo: Will be replaced with Exception in future releases logger.error('Telegram does not support inline keyboard row width over %d.' % self.max_row_keys) @@ -1115,8 +2201,13 @@ def add(self, *args, row_width=None): See https://core.telegram.org/bots/api#inlinekeyboardmarkup :param args: Array of InlineKeyboardButton to append to the keyboard + :type args: :obj:`list` of :class:`telebot.types.InlineKeyboardButton` + :param row_width: width of row + :type row_width: :obj:`int` + :return: self, to allow function chaining. + :rtype: :class:`telebot.types.InlineKeyboardMarkup` """ if row_width is None: row_width = self.row_width @@ -1142,18 +2233,15 @@ def row(self, *args): See https://core.telegram.org/bots/api#inlinekeyboardmarkup :param args: Array of InlineKeyboardButton to append to the keyboard + :type args: :obj:`list` of :class:`telebot.types.InlineKeyboardButton` + :return: self, to allow function chaining. + :rtype: :class:`telebot.types.InlineKeyboardMarkup` """ return self.add(*args, row_width=self.max_row_keys) def to_json(self): - """ - Converts this object to its json representation - following the Telegram API guidelines described here: - https://core.telegram.org/bots/api#inlinekeyboardmarkup - :return: - """ return json.dumps(self.to_dict()) def to_dict(self): @@ -1163,6 +2251,54 @@ def to_dict(self): class InlineKeyboardButton(Dictionaryable, JsonSerializable, JsonDeserializable): + """ + This object represents one button of an inline keyboard. You must use exactly one of the optional fields. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinekeyboardbutton + + :param text: Label text on the button + :type text: :obj:`str` + + :param url: Optional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be + used to mention a user by their ID without using a username, if this is allowed by their privacy settings. + :type url: :obj:`str` + + :param callback_data: Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes + :type callback_data: :obj:`str` + + :param web_app: Optional. Description of the Web App that will be launched when the user presses the button. The Web + App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only + in private chats between a user and the bot. + :type web_app: :class:`telebot.types.WebAppInfo` + + :param login_url: Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for + the Telegram Login Widget. + :type login_url: :class:`telebot.types.LoginUrl` + + :param switch_inline_query: Optional. If set, pressing the button will prompt the user to select one of their chats, + open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which + case just the bot's username will be inserted.Note: This offers an easy way for users to start using your bot in inline + mode when they are currently in a private chat with it. Especially useful when combined with switch_pm… actions - in + this case the user will be automatically returned to the chat they switched from, skipping the chat selection screen. + :type switch_inline_query: :obj:`str` + + :param switch_inline_query_current_chat: Optional. If set, pressing the button will insert the bot's username + and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username + will be inserted.This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting + something from multiple options. + :type switch_inline_query_current_chat: :obj:`str` + + :param callback_game: Optional. Description of the game that will be launched when the user presses the + button. NOTE: This type of button must always be the first button in the first row. + :type callback_game: :class:`telebot.types.CallbackGame` + + :param pay: Optional. Specify True, to send a Pay button. NOTE: This type of button must always be the first button in + the first row and can only be used in invoice messages. + :type pay: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineKeyboardButton` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1211,6 +2347,33 @@ def to_dict(self): class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): + """ + This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in: + + Telegram Documentation: https://core.telegram.org/bots/api#loginurl + + :param url: An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. + If the user refuses to provide authorization data, the original URL without information about the user will be + opened. The data added is the same as described in Receiving authorization data. NOTE: You must always check the hash + of the received data to verify the authentication and the integrity of the data as described in Checking + authorization. + :type url: :obj:`str` + + :param forward_text: Optional. New text of the button in forwarded messages. + :type forward_text: :obj:`str` + + :param bot_username: Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for + more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the + domain linked with the bot. See Linking your domain to the bot for more details. + :type bot_username: :obj:`str` + + :param request_write_access: Optional. Pass True to request the permission for your bot to send messages to the + user. + :type request_write_access: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.LoginUrl` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1238,6 +2401,39 @@ def to_dict(self): class CallbackQuery(JsonDeserializable): + """ + This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present. + + Telegram Documentation: https://core.telegram.org/bots/api#callbackquery + + :param id: Unique identifier for this query + :type id: :obj:`str` + + :param from_user: Sender + :type from_user: :class:`telebot.types.User` + + :param message: Optional. Message with the callback button that originated the query. Note that message content and + message date will not be available if the message is too old + :type message: :class:`telebot.types.Message` + + :param inline_message_id: Optional. Identifier of the message sent via the bot in inline mode, that originated the + query. + :type inline_message_id: :obj:`str` + + :param chat_instance: Global identifier, uniquely corresponding to the chat to which the message with the callback + button was sent. Useful for high scores in games. + :type chat_instance: :obj:`str` + + :param data: Optional. Data associated with the callback button. Be aware that the message originated the query can + contain no callback buttons with this data. + :type data: :obj:`str` + + :param game_short_name: Optional. Short name of a Game to be returned, serves as the unique identifier for the game + :type game_short_name: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.CallbackQuery` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1263,6 +2459,30 @@ def __init__(self, id, from_user, data, chat_instance, json_string, message=None class ChatPhoto(JsonDeserializable): + """ + This object represents a chat photo. + + Telegram Documentation: https://core.telegram.org/bots/api#chatphoto + + :param small_file_id: File identifier of small (160x160) chat photo. This file_id can be used only for photo + download and only for as long as the photo is not changed. + :type small_file_id: :obj:`str` + + :param small_file_unique_id: Unique file identifier of small (160x160) chat photo, which is supposed to be the same + over time and for different bots. Can't be used to download or reuse the file. + :type small_file_unique_id: :obj:`str` + + :param big_file_id: File identifier of big (640x640) chat photo. This file_id can be used only for photo download and + only for as long as the photo is not changed. + :type big_file_id: :obj:`str` + + :param big_file_unique_id: Unique file identifier of big (640x640) chat photo, which is supposed to be the same over + time and for different bots. Can't be used to download or reuse the file. + :type big_file_unique_id: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatPhoto` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1277,6 +2497,20 @@ def __init__(self, small_file_id, small_file_unique_id, big_file_id, big_file_un class ChatMember(JsonDeserializable): + """ + This object contains information about one member of a chat. + Currently, the following 6 types of chat members are supported: + + * :class:`telebot.types.ChatMemberOwner` + * :class:`telebot.types.ChatMemberAdministrator` + * :class:`telebot.types.ChatMemberMember` + * :class:`telebot.types.ChatMemberRestricted` + * :class:`telebot.types.ChatMemberLeft` + * :class:`telebot.types.ChatMemberBanned` + + Telegram Documentation: https://core.telegram.org/bots/api#chatmember + """ + @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1334,41 +2568,249 @@ def __init__(self, user, status, custom_title=None, is_anonymous=None, can_be_ed class ChatMemberOwner(ChatMember): + """ + Represents a chat member that owns the chat and has all administrator privileges. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmemberowner + + :param status: The member's status in the chat, always “creator” + :type status: :obj:`str` + + :param user: Information about the user + :type user: :class:`telebot.types.User` + + :param is_anonymous: True, if the user's presence in the chat is hidden + :type is_anonymous: :obj:`bool` + + :param custom_title: Optional. Custom title for this user + :type custom_title: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberOwner` + """ pass class ChatMemberAdministrator(ChatMember): + """ + Represents a chat member that has some additional privileges. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmemberadministrator + + :param status: The member's status in the chat, always “administrator” + :type status: :obj:`str` + + :param user: Information about the user + :type user: :class:`telebot.types.User` + + :param can_be_edited: True, if the bot is allowed to edit administrator privileges of that user + :type can_be_edited: :obj:`bool` + + :param is_anonymous: True, if the user's presence in the chat is hidden + :type is_anonymous: :obj:`bool` + + :param can_manage_chat: 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 + :type can_manage_chat: :obj:`bool` + + :param can_delete_messages: True, if the administrator can delete messages of other users + :type can_delete_messages: :obj:`bool` + + :param can_manage_video_chats: True, if the administrator can manage video chats + :type can_manage_video_chats: :obj:`bool` + + :param can_restrict_members: True, if the administrator can restrict, ban or unban chat members + :type can_restrict_members: :obj:`bool` + + :param can_promote_members: True, if the administrator can add new administrators with a subset of their own + privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that + were appointed by the user) + :type can_promote_members: :obj:`bool` + + :param can_change_info: True, if the user is allowed to change the chat title, photo and other settings + :type can_change_info: :obj:`bool` + + :param can_invite_users: True, if the user is allowed to invite new users to the chat + :type can_invite_users: :obj:`bool` + + :param can_post_messages: Optional. True, if the administrator can post in the channel; channels only + :type can_post_messages: :obj:`bool` + + :param can_edit_messages: Optional. True, if the administrator can edit messages of other users and can pin + messages; channels only + :type can_edit_messages: :obj:`bool` + + :param can_pin_messages: Optional. True, if the user is allowed to pin messages; groups and supergroups only + :type can_pin_messages: :obj:`bool` + + :param custom_title: Optional. Custom title for this user + :type custom_title: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberAdministrator` + """ pass class ChatMemberMember(ChatMember): + """ + Represents a chat member that has no additional privileges or restrictions. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmembermember + + :param status: The member's status in the chat, always “member” + :type status: :obj:`str` + + :param user: Information about the user + :type user: :class:`telebot.types.User` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberMember` + """ pass class ChatMemberRestricted(ChatMember): + """ + Represents a chat member that is under certain restrictions in the chat. Supergroups only. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmemberrestricted + + :param status: The member's status in the chat, always “restricted” + :type status: :obj:`str` + + :param user: Information about the user + :type user: :class:`telebot.types.User` + + :param is_member: True, if the user is a member of the chat at the moment of the request + :type is_member: :obj:`bool` + + :param can_change_info: True, if the user is allowed to change the chat title, photo and other settings + :type can_change_info: :obj:`bool` + + :param can_invite_users: True, if the user is allowed to invite new users to the chat + :type can_invite_users: :obj:`bool` + + :param can_pin_messages: True, if the user is allowed to pin messages + :type can_pin_messages: :obj:`bool` + + :param can_send_messages: True, if the user is allowed to send text messages, contacts, locations and venues + :type can_send_messages: :obj:`bool` + + :param can_send_media_messages: True, if the user is allowed to send audios, documents, photos, videos, video + notes and voice notes + :type can_send_media_messages: :obj:`bool` + + :param can_send_polls: True, if the user is allowed to send polls + :type can_send_polls: :obj:`bool` + + :param can_send_other_messages: True, if the user is allowed to send animations, games, stickers and use inline + bots + :type can_send_other_messages: :obj:`bool` + + :param can_add_web_page_previews: True, if the user is allowed to add web page previews to their messages + :type can_add_web_page_previews: :obj:`bool` + + :param until_date: Date when restrictions will be lifted for this user; unix time. If 0, then the user is restricted + forever + :type until_date: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberRestricted` + """ pass class ChatMemberLeft(ChatMember): + """ + Represents a chat member that isn't currently a member of the chat, but may join it themselves. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmemberleft + + :param status: The member's status in the chat, always “left” + :type status: :obj:`str` + + :param user: Information about the user + :type user: :class:`telebot.types.User` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberLeft` + """ pass class ChatMemberBanned(ChatMember): + """ + Represents a chat member that was banned in the chat and can't return to the chat or view chat messages. + + Telegram Documentation: https://core.telegram.org/bots/api#chatmemberbanned + + :param status: The member's status in the chat, always “kicked” + :type status: :obj:`str` + + :param user: Information about the user + :type user: :class:`telebot.types.User` + + :param until_date: Date when restrictions will be lifted for this user; unix time. If 0, then the user is banned + forever + :type until_date: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatMemberBanned` + """ pass class ChatPermissions(JsonDeserializable, JsonSerializable, Dictionaryable): - @classmethod - def de_json(cls, json_string): - if json_string is None: return json_string - obj = cls.check_json(json_string, dict_copy=False) - return cls(**obj) + """ + Describes actions that a non-administrator user is allowed to take in a chat. - def __init__(self, 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, **kwargs): - self.can_send_messages: bool = can_send_messages + Telegram Documentation: https://core.telegram.org/bots/api#chatpermissions + + :param can_send_messages: Optional. True, if the user is allowed to send text messages, contacts, locations and + venues + :type can_send_messages: :obj:`bool` + + :param can_send_media_messages: Optional. True, if the user is allowed to send audios, documents, photos, videos, + video notes and voice notes, implies can_send_messages + :type can_send_media_messages: :obj:`bool` + + :param can_send_polls: Optional. True, if the user is allowed to send polls, implies can_send_messages + :type can_send_polls: :obj:`bool` + + :param can_send_other_messages: Optional. True, if the user is allowed to send animations, games, stickers and use + inline bots, implies can_send_media_messages + :type can_send_other_messages: :obj:`bool` + + :param can_add_web_page_previews: Optional. True, if the user is allowed to add web page previews to their + messages, implies can_send_media_messages + :type can_add_web_page_previews: :obj:`bool` + + :param can_change_info: Optional. True, if the user is allowed to change the chat title, photo and other settings. + Ignored in public supergroups + :type can_change_info: :obj:`bool` + + :param can_invite_users: Optional. True, if the user is allowed to invite new users to the chat + :type can_invite_users: :obj:`bool` + + :param can_pin_messages: Optional. True, if the user is allowed to pin messages. Ignored in public supergroups + :type can_pin_messages: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatPermissions` + """ + @classmethod + def de_json(cls, json_string): + if json_string is None: return json_string + obj = cls.check_json(json_string, dict_copy=False) + return cls(**obj) + + def __init__(self, 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, **kwargs): + self.can_send_messages: bool = can_send_messages self.can_send_media_messages: bool = can_send_media_messages self.can_send_polls: bool = can_send_polls self.can_send_other_messages: bool = can_send_other_messages @@ -1401,7 +2843,22 @@ def to_dict(self): return json_dict -class BotCommand(JsonSerializable, JsonDeserializable): +class BotCommand(JsonSerializable, JsonDeserializable, Dictionaryable): + """ + This object represents a bot command. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommand + + :param command: Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and + underscores. + :type command: :obj:`str` + + :param description: Description of the command; 1-256 characters. + :type description: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommand` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1409,13 +2866,6 @@ def de_json(cls, json_string): return cls(**obj) def __init__(self, command, description): - """ - This object represents a bot command. - :param command: Text of the command, 1-32 characters. - Can contain only lowercase English letters, digits and underscores. - :param description: Description of the command, 3-256 characters. - :return: - """ self.command: str = command self.description: str = description @@ -1429,18 +2879,48 @@ def to_dict(self): # BotCommandScopes class BotCommandScope(ABC, JsonSerializable): + """ + This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported: + + * :class:`BotCommandScopeDefault` + * :class:`BotCommandScopeAllPrivateChats` + * :class:`BotCommandScopeAllGroupChats` + * :class:`BotCommandScopeAllChatAdministrators` + * :class:`BotCommandScopeChat` + * :class:`BotCommandScopeChatAdministrators` + * :class:`BotCommandScopeChatMember` + + Determining list of commands + The following algorithm is used to determine the list of commands for a particular user viewing the bot menu. The first list of commands which is set is returned: + + Commands in the chat with the bot: + + * :class:`BotCommandScopeChat` + language_code + * :class:`BotCommandScopeChat` + * :class:`BotCommandScopeAllPrivateChats` + language_code + * :class:`BotCommandScopeAllPrivateChats` + * :class:`BotCommandScopeDefault` + language_code + * :class:`BotCommandScopeDefault` + + Commands in group and supergroup chats: + + * :class:`BotCommandScopeChatMember` + language_code + * :class:`BotCommandScopeChatMember` + * :class:`BotCommandScopeChatAdministrators` + language_code (administrators only) + * :class:`BotCommandScopeChatAdministrators` (administrators only) + * :class:`BotCommandScopeChat` + language_code + * :class:`BotCommandScopeChat` + * :class:`BotCommandScopeAllChatAdministrators` + language_code (administrators only) + * :class:`BotCommandScopeAllChatAdministrators` (administrators only) + * :class:`BotCommandScopeAllGroupChats` + language_code + * :class:`BotCommandScopeAllGroupChats` + * :class:`BotCommandScopeDefault` + language_code + * :class:`BotCommandScopeDefault` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScope` + """ def __init__(self, type='default', chat_id=None, user_id=None): - """ - Abstract class. - Use BotCommandScopeX classes to set a specific scope type: - BotCommandScopeDefault - BotCommandScopeAllPrivateChats - BotCommandScopeAllGroupChats - BotCommandScopeAllChatAdministrators - BotCommandScopeChat - BotCommandScopeChatAdministrators - BotCommandScopeChatMember - """ self.type: str = type self.chat_id: Optional[Union[int, str]] = chat_id self.user_id: Optional[Union[int, str]] = user_id @@ -1455,6 +2935,17 @@ def to_json(self): class BotCommandScopeDefault(BotCommandScope): + """ + Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopedefault + + :param type: Scope type, must be default + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeDefault` + """ def __init__(self): """ Represents the default scope of bot commands. @@ -1464,6 +2955,17 @@ def __init__(self): class BotCommandScopeAllPrivateChats(BotCommandScope): + """ + Represents the scope of bot commands, covering all private chats. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopeallprivatechats + + :param type: Scope type, must be all_private_chats + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeAllPrivateChats` + """ def __init__(self): """ Represents the scope of bot commands, covering all private chats. @@ -1472,6 +2974,17 @@ def __init__(self): class BotCommandScopeAllGroupChats(BotCommandScope): + """ + Represents the scope of bot commands, covering all group and supergroup chats. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopeallgroupchats + + :param type: Scope type, must be all_group_chats + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeAllGroupChats` + """ def __init__(self): """ Represents the scope of bot commands, covering all group and supergroup chats. @@ -1480,6 +2993,17 @@ def __init__(self): class BotCommandScopeAllChatAdministrators(BotCommandScope): + """ + Represents the scope of bot commands, covering all group and supergroup chat administrators. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopeallchatadministrators + + :param type: Scope type, must be all_chat_administrators + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeAllChatAdministrators` + """ def __init__(self): """ Represents the scope of bot commands, covering all group and supergroup chat administrators. @@ -1488,32 +3012,100 @@ def __init__(self): class BotCommandScopeChat(BotCommandScope): + """ + Represents the scope of bot commands, covering a specific chat. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopechat + + :param type: Scope type, must be chat + :type type: :obj:`str` + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format + @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeChat` + """ def __init__(self, chat_id=None): super(BotCommandScopeChat, self).__init__(type='chat', chat_id=chat_id) class BotCommandScopeChatAdministrators(BotCommandScope): + """ + Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopechatadministrators + + :param type: Scope type, must be chat_administrators + :type type: :obj:`str` + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format + @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeChatAdministrators` + """ def __init__(self, chat_id=None): - """ - Represents the scope of bot commands, covering a specific chat. - @param chat_id: Unique identifier for the target chat - """ super(BotCommandScopeChatAdministrators, self).__init__(type='chat_administrators', chat_id=chat_id) class BotCommandScopeChatMember(BotCommandScope): + """ + Represents the scope of bot commands, covering a specific member of a group or supergroup chat. + + Telegram Documentation: https://core.telegram.org/bots/api#botcommandscopechatmember + + :param type: Scope type, must be chat_member + :type type: :obj:`str` + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format + @supergroupusername) + :type chat_id: :obj:`int` or :obj:`str` + + :param user_id: Unique identifier of the target user + :type user_id: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.BotCommandScopeChatMember` + """ def __init__(self, chat_id=None, user_id=None): - """ - Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat - @param chat_id: Unique identifier for the target chat - @param user_id: Unique identifier of the target user - """ super(BotCommandScopeChatMember, self).__init__(type='chat_member', chat_id=chat_id, user_id=user_id) # InlineQuery class InlineQuery(JsonDeserializable): + """ + This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequery + + :param id: Unique identifier for this query + :type id: :obj:`str` + + :param from_user: Sender + :type from_user: :class:`telebot.types.User` + + :param query: Text of the query (up to 256 characters) + :type query: :obj:`str` + + :param offset: Offset of the results to be returned, can be controlled by the bot + :type offset: :obj:`str` + + :param chat_type: Optional. Type of the chat from which the inline query was sent. Can be either “sender” for a private + chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always + known for requests sent from official clients and most third-party clients, unless the request was sent from a secret + chat + :type chat_type: :obj:`str` + + :param location: Optional. Sender location, only for bots that request user location + :type location: :class:`telebot.types.Location` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQuery` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1524,20 +3116,6 @@ def de_json(cls, json_string): return cls(**obj) def __init__(self, id, from_user, query, offset, chat_type=None, location=None, **kwargs): - """ - This object represents an incoming inline query. - When the user sends an empty query, your bot could - return some default or trending results. - :param id: string Unique identifier for this query - :param from_user: User Sender - :param query: String Text of the query - :param chat_type: String Type of the chat, from which the inline query was sent. - Can be either “sender” for a private chat with the inline query sender, - “private”, “group”, “supergroup”, or “channel”. - :param offset: String Offset of the results to be returned, can be controlled by the bot - :param location: Sender location, only for bots that request user location - :return: InlineQuery Object - """ self.id: int = id self.from_user: User = from_user self.query: str = query @@ -1547,6 +3125,28 @@ def __init__(self, id, from_user, query, offset, chat_type=None, location=None, class InputTextMessageContent(Dictionaryable): + """ + Represents the content of a text message to be sent as the result of an inline query. + + Telegram Documentation: https://core.telegram.org/bots/api#inputtextmessagecontent + + :param message_text: Text of the message to be sent, 1-4096 characters + :type message_text: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the message text. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param entities: Optional. List of special entities that appear in message text, which can be specified instead of + parse_mode + :type entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param disable_web_page_preview: Optional. Disables link previews for links in the sent message + :type disable_web_page_preview: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputTextMessageContent` + """ def __init__(self, message_text, parse_mode=None, entities=None, disable_web_page_preview=None): self.message_text: str = message_text self.parse_mode: str = parse_mode @@ -1565,6 +3165,35 @@ def to_dict(self): class InputLocationMessageContent(Dictionaryable): + """ + Represents the content of a location message to be sent as the result of an inline query. + + Telegram Documentation: https://core.telegram.org/bots/api#inputlocationmessagecontent + + :param latitude: Latitude of the location in degrees + :type latitude: :obj:`float` + + :param longitude: Longitude of the location in degrees + :type longitude: :obj:`float` + + :param horizontal_accuracy: Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + :type horizontal_accuracy: :obj:`float` number + + :param live_period: Optional. Period in seconds for which the location can be updated, should be between 60 and + 86400. + :type live_period: :obj:`int` + + :param heading: Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 + and 360 if specified. + :type heading: :obj:`int` + + :param proximity_alert_radius: Optional. For live locations, a maximum distance for proximity alerts about + approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :type proximity_alert_radius: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputLocationMessageContent` + """ def __init__(self, latitude, longitude, horizontal_accuracy=None, live_period=None, heading=None, proximity_alert_radius=None): self.latitude: float = latitude self.longitude: float = longitude @@ -1587,6 +3216,39 @@ def to_dict(self): class InputVenueMessageContent(Dictionaryable): + """ + Represents the content of a venue message to be sent as the result of an inline query. + + Telegram Documentation: https://core.telegram.org/bots/api#inputvenuemessagecontent + + :param latitude: Latitude of the venue in degrees + :type latitude: :obj:`float` + + :param longitude: Longitude of the venue in degrees + :type longitude: :obj:`float` + + :param title: Name of the venue + :type title: :obj:`str` + + :param address: Address of the venue + :type address: :obj:`str` + + :param foursquare_id: Optional. Foursquare identifier of the venue, if known + :type foursquare_id: :obj:`str` + + :param foursquare_type: Optional. Foursquare type of the venue, if known. (For example, + “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + :type foursquare_type: :obj:`str` + + :param google_place_id: Optional. Google Places identifier of the venue + :type google_place_id: :obj:`str` + + :param google_place_type: Optional. Google Places type of the venue. (See supported types.) + :type google_place_type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputVenueMessageContent` + """ def __init__(self, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, google_place_id=None, google_place_type=None): self.latitude: float = latitude @@ -1617,6 +3279,26 @@ def to_dict(self): class InputContactMessageContent(Dictionaryable): + """ + Represents the content of a contact message to be sent as the result of an inline query. + + Telegram Documentation: https://core.telegram.org/bots/api#inputcontactmessagecontent + + :param phone_number: Contact's phone number + :type phone_number: :obj:`str` + + :param first_name: Contact's first name + :type first_name: :obj:`str` + + :param last_name: Optional. Contact's last name + :type last_name: :obj:`str` + + :param vcard: Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes + :type vcard: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputContactMessageContent` + """ def __init__(self, phone_number, first_name, last_name=None, vcard=None): self.phone_number: str = phone_number self.first_name: str = first_name @@ -1633,6 +3315,84 @@ def to_dict(self): class InputInvoiceMessageContent(Dictionaryable): + """ + Represents the content of an invoice message to be sent as the result of an inline query. + + Telegram Documentation: https://core.telegram.org/bots/api#inputinvoicemessagecontent + + :param title: Product name, 1-32 characters + :type title: :obj:`str` + + :param description: Product description, 1-255 characters + :type description: :obj:`str` + + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your + internal processes. + :type payload: :obj:`str` + + :param provider_token: Payment provider token, obtained via @BotFather + :type provider_token: :obj:`str` + + :param currency: Three-letter ISO 4217 currency code, see more on currencies + :type currency: :obj:`str` + + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery + cost, delivery tax, bonus, etc.) + :type prices: :obj:`list` of :class:`telebot.types.LabeledPrice` + + :param max_tip_amount: Optional. The maximum accepted amount for tips in the smallest units of the currency + (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp + parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the + majority of currencies). Defaults to 0 + :type max_tip_amount: :obj:`int` + + :param suggested_tip_amounts: Optional. A JSON-serialized array of suggested amounts of tip in the smallest units + of the currency (integer, not float/double). 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. + :type suggested_tip_amounts: :obj:`list` of :obj:`int` + + :param provider_data: Optional. A JSON-serialized object for data about the invoice, which will be shared with the + payment provider. A detailed description of the required fields should be provided by the payment provider. + :type provider_data: :obj:`str` + + :param photo_url: Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image + for a service. + :type photo_url: :obj:`str` + + :param photo_size: Optional. Photo size in bytes + :type photo_size: :obj:`int` + + :param photo_width: Optional. Photo width + :type photo_width: :obj:`int` + + :param photo_height: Optional. Photo height + :type photo_height: :obj:`int` + + :param need_name: Optional. Pass True, if you require the user's full name to complete the order + :type need_name: :obj:`bool` + + :param need_phone_number: Optional. Pass True, if you require the user's phone number to complete the order + :type need_phone_number: :obj:`bool` + + :param need_email: Optional. Pass True, if you require the user's email address to complete the order + :type need_email: :obj:`bool` + + :param need_shipping_address: Optional. Pass True, if you require the user's shipping address to complete the + order + :type need_shipping_address: :obj:`bool` + + :param send_phone_number_to_provider: Optional. Pass True, if the user's phone number should be sent to provider + :type send_phone_number_to_provider: :obj:`bool` + + :param send_email_to_provider: Optional. Pass True, if the user's email address should be sent to provider + :type send_email_to_provider: :obj:`bool` + + :param is_flexible: Optional. Pass True, if the final price depends on the shipping method + :type is_flexible: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputInvoiceMessageContent` + """ def __init__(self, title, description, payload, provider_token, currency, prices, max_tip_amount=None, suggested_tip_amounts=None, provider_data=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, @@ -1701,6 +3461,30 @@ def to_dict(self): class ChosenInlineResult(JsonDeserializable): + """ + Represents a result of an inline query that was chosen by the user and sent to their chat partner. + + Telegram Documentation: https://core.telegram.org/bots/api#choseninlineresult + + :param result_id: The unique identifier for the result that was chosen + :type result_id: :obj:`str` + + :param from: The user that chose the result + :type from: :class:`telebot.types.User` + + :param location: Optional. Sender location, only for bots that require user location + :type location: :class:`telebot.types.Location` + + :param inline_message_id: Optional. Identifier of the sent inline message. Available only if there is an inline + keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. + :type inline_message_id: :obj:`str` + + :param query: The query that was used to obtain the result + :type query: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChosenInlineResult` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1711,14 +3495,6 @@ def de_json(cls, json_string): return cls(**obj) def __init__(self, result_id, from_user, query, location=None, inline_message_id=None, **kwargs): - """ - This object represents a result of an inline query - that was chosen by the user and sent to their chat partner. - :param result_id: string The unique identifier for the result that was chosen. - :param from_user: User The user that chose the result. - :param query: String The query that was used to obtain the result. - :return: ChosenInlineResult Object. - """ self.result_id: str = result_id self.from_user: User = from_user self.location: Location = location @@ -1727,6 +3503,32 @@ def __init__(self, result_id, from_user, query, location=None, inline_message_id class InlineQueryResultBase(ABC, Dictionaryable, JsonSerializable): + """ + This object represents one result of an inline query. Telegram clients currently support results of the following 20 types: + + * :class:`InlineQueryResultCachedAudio` + * :class:`InlineQueryResultCachedDocument` + * :class:`InlineQueryResultCachedGif` + * :class:`InlineQueryResultCachedMpeg4Gif` + * :class:`InlineQueryResultCachedPhoto` + * :class:`InlineQueryResultCachedSticker` + * :class:`InlineQueryResultCachedVideo` + * :class:`InlineQueryResultCachedVoice` + * :class:`InlineQueryResultArticle` + * :class:`InlineQueryResultAudio` + * :class:`InlineQueryResultContact` + * :class:`InlineQueryResultGame` + * :class:`InlineQueryResultDocument` + * :class:`InlineQueryResultGif` + * :class:`InlineQueryResultLocation` + * :class:`InlineQueryResultMpeg4Gif` + * :class:`InlineQueryResultPhoto` + * :class:`InlineQueryResultVenue` + * :class:`InlineQueryResultVideo` + * :class:`InlineQueryResultVoice` + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresult + """ # noinspection PyShadowingBuiltins def __init__(self, type, id, title = None, caption = None, input_message_content = None, reply_markup = None, caption_entities = None, parse_mode = None): @@ -1762,7 +3564,19 @@ def to_dict(self): return json_dict -class SentWebAppMessage(JsonDeserializable): +class SentWebAppMessage(JsonDeserializable, Dictionaryable): + """ + Describes an inline message sent by a Web App on behalf of a user. + + Telegram Documentation: https://core.telegram.org/bots/api#sentwebappmessage + + :param inline_message_id: Optional. Identifier of the sent inline message. Available only if there is an inline + keyboard attached to the message. + :type inline_message_id: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.SentWebAppMessage` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -1778,27 +3592,51 @@ def to_dict(self): json_dict['inline_message_id'] = self.inline_message_id return json_dict - +class InlineQueryResultArticle(InlineQueryResultBase): + """ + Represents a link to an article or web page. + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultarticle -class InlineQueryResultArticle(InlineQueryResultBase): + :param type: Type of the result, must be article + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 Bytes + :type id: :obj:`str` + + :param title: Title of the result + :type title: :obj:`str` + + :param input_message_content: Content of the message to be sent + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param url: Optional. URL of the result + :type url: :obj:`str` + + :param hide_url: Optional. Pass True, if you don't want the URL to be shown in the message + :type hide_url: :obj:`bool` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param thumb_url: Optional. Url of the thumbnail for the result + :type thumb_url: :obj:`str` + + :param thumb_width: Optional. Thumbnail width + :type thumb_width: :obj:`int` + + :param thumb_height: Optional. Thumbnail height + :type thumb_height: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultArticle` + """ def __init__(self, id, title, input_message_content, reply_markup=None, url=None, hide_url=None, description=None, thumb_url=None, thumb_width=None, thumb_height=None): - """ - Represents a link to an article or web page. - :param id: Unique identifier for this result, 1-64 Bytes. - :param title: Title of the result. - :param input_message_content: InputMessageContent : Content of the message to be sent - :param reply_markup: InlineKeyboardMarkup : Inline keyboard attached to the message - :param url: URL of the result. - :param hide_url: Pass True, if you don't want the URL to be shown in the message. - :param description: Short description of the result. - :param thumb_url: Url of the thumbnail for the result. - :param thumb_width: Thumbnail width. - :param thumb_height: Thumbnail height - :return: - """ super().__init__('article', id, title = title, input_message_content = input_message_content, reply_markup = reply_markup) self.url = url self.hide_url = hide_url @@ -1825,24 +3663,57 @@ def to_dict(self): class InlineQueryResultPhoto(InlineQueryResultBase): + """ + Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultphoto + + :param type: Type of the result, must be photo + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param photo_url: A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB + :type photo_url: :obj:`str` + + :param thumb_url: URL of the thumbnail for the photo + :type thumb_url: :obj:`str` + + :param photo_width: Optional. Width of the photo + :type photo_width: :obj:`int` + + :param photo_height: Optional. Height of the photo + :type photo_height: :obj:`int` + + :param title: Optional. Title for the result + :type title: :obj:`str` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param caption: Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the photo caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the photo + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultPhoto` + """ def __init__(self, id, photo_url, thumb_url, photo_width=None, photo_height=None, title=None, description=None, caption=None, caption_entities=None, parse_mode=None, reply_markup=None, input_message_content=None): - """ - Represents a link to a photo. - :param id: Unique identifier for this result, 1-64 bytes - :param photo_url: A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB - :param thumb_url: URL of the thumbnail for the photo - :param photo_width: Width of the photo. - :param photo_height: Height of the photo. - :param title: Title for the result. - :param description: Short description of the result. - :param caption: Caption of the photo to be sent, 0-200 characters. - :param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or - inline URLs in the media caption. - :param reply_markup: InlineKeyboardMarkup : Inline keyboard attached to the message - :param input_message_content: InputMessageContent : Content of the message to be sent instead of the photo - :return: - """ super().__init__('photo', id, title = title, caption = caption, input_message_content = input_message_content, reply_markup = reply_markup, parse_mode = parse_mode, caption_entities = caption_entities) @@ -1866,23 +3737,62 @@ def to_dict(self): class InlineQueryResultGif(InlineQueryResultBase): + """ + Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultgif + + :param type: Type of the result, must be gif + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param gif_url: A valid URL for the GIF file. File size must not exceed 1MB + :type gif_url: :obj:`str` + + :param gif_width: Optional. Width of the GIF + :type gif_width: :obj:`int` + + :param gif_height: Optional. Height of the GIF + :type gif_height: :obj:`int` + + :param gif_duration: Optional. Duration of the GIF in seconds + :type gif_duration: :obj:`int` + + :param thumb_url: URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result + :type thumb_url: :obj:`str` + + :param thumb_mime_type: Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or + “video/mp4”. Defaults to “image/jpeg” + :type thumb_mime_type: :obj:`str` + + :param title: Optional. Title for the result + :type title: :obj:`str` + + :param caption: Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the caption. See formatting options for more details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the GIF animation + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultGif` + """ def __init__(self, id, gif_url, thumb_url, gif_width=None, gif_height=None, title=None, caption=None, caption_entities=None, reply_markup=None, input_message_content=None, gif_duration=None, parse_mode=None, thumb_mime_type=None): - """ - Represents a link to an animated GIF file. - :param id: Unique identifier for this result, 1-64 bytes. - :param gif_url: A valid URL for the GIF file. File size must not exceed 1MB - :param thumb_url: URL of the static thumbnail (jpeg or gif) for the result. - :param gif_width: Width of the GIF. - :param gif_height: Height of the GIF. - :param title: Title for the result. - :param caption: Caption of the GIF file to be sent, 0-200 characters - :param reply_markup: InlineKeyboardMarkup : Inline keyboard attached to the message - :param input_message_content: InputMessageContent : Content of the message to be sent instead of the photo - :return: - """ super().__init__('gif', id, title = title, caption = caption, input_message_content = input_message_content, reply_markup = reply_markup, parse_mode = parse_mode, caption_entities = caption_entities) @@ -1909,25 +3819,62 @@ def to_dict(self): class InlineQueryResultMpeg4Gif(InlineQueryResultBase): + """ + Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif + + :param type: Type of the result, must be mpeg4_gif + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param mpeg4_url: A valid URL for the MPEG4 file. File size must not exceed 1MB + :type mpeg4_url: :obj:`str` + + :param mpeg4_width: Optional. Video width + :type mpeg4_width: :obj:`int` + + :param mpeg4_height: Optional. Video height + :type mpeg4_height: :obj:`int` + + :param mpeg4_duration: Optional. Video duration in seconds + :type mpeg4_duration: :obj:`int` + + :param thumb_url: URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result + :type thumb_url: :obj:`str` + + :param thumb_mime_type: Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or + “video/mp4”. Defaults to “image/jpeg” + :type thumb_mime_type: :obj:`str` + + :param title: Optional. Title for the result + :type title: :obj:`str` + + :param caption: Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the caption. See formatting options for more details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the video animation + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultMpeg4Gif` + """ def __init__(self, id, mpeg4_url, thumb_url, mpeg4_width=None, mpeg4_height=None, title=None, caption=None, caption_entities=None, parse_mode=None, reply_markup=None, input_message_content=None, mpeg4_duration=None, thumb_mime_type=None): - """ - Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). - :param id: Unique identifier for this result, 1-64 bytes - :param mpeg4_url: A valid URL for the MP4 file. File size must not exceed 1MB - :param thumb_url: URL of the static thumbnail (jpeg or gif) for the result - :param mpeg4_width: Video width - :param mpeg4_height: Video height - :param title: Title for the result - :param caption: Caption of the MPEG-4 file to be sent, 0-200 characters - :param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text - or inline URLs in the media caption. - :param reply_markup: InlineKeyboardMarkup : Inline keyboard attached to the message - :param input_message_content: InputMessageContent : Content of the message to be sent instead of the photo - :return: - """ super().__init__('mpeg4_gif', id, title = title, caption = caption, input_message_content = input_message_content, reply_markup = reply_markup, parse_mode = parse_mode, caption_entities = caption_entities) @@ -1954,30 +3901,71 @@ def to_dict(self): class InlineQueryResultVideo(InlineQueryResultBase): - def __init__(self, id, video_url, mime_type, thumb_url, - title, caption=None, caption_entities=None, parse_mode=None, - video_width=None, video_height=None, video_duration=None, - description=None, reply_markup=None, input_message_content=None): - """ - Represents link to a page containing an embedded video player or a video file. - :param id: Unique identifier for this result, 1-64 bytes - :param video_url: A valid URL for the embedded video player or video file - :param mime_type: Mime type of the content of video url, “text/html” or “video/mp4” - :param thumb_url: URL of the thumbnail (jpeg only) for the video - :param title: Title for the result - :param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or - inline URLs in the media caption. - :param video_width: Video width - :param video_height: Video height - :param video_duration: Video duration in seconds - :param description: Short description of the result - :return: - """ - super().__init__('video', id, title = title, caption = caption, - input_message_content = input_message_content, reply_markup = reply_markup, - parse_mode = parse_mode, caption_entities = caption_entities) - self.video_url = video_url - self.mime_type = mime_type + """ + Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultvideo + + :param type: Type of the result, must be video + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param video_url: A valid URL for the embedded video player or video file + :type video_url: :obj:`str` + + :param mime_type: MIME type of the content of the video URL, “text/html” or “video/mp4” + :type mime_type: :obj:`str` + + :param thumb_url: URL of the thumbnail (JPEG only) for the video + :type thumb_url: :obj:`str` + + :param title: Title for the result + :type title: :obj:`str` + + :param caption: Optional. Caption of the video to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the video caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param video_width: Optional. Video width + :type video_width: :obj:`int` + + :param video_height: Optional. Video height + :type video_height: :obj:`int` + + :param video_duration: Optional. Video duration in seconds + :type video_duration: :obj:`int` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the video. This field is + required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video). + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultVideo` + """ + def __init__(self, id, video_url, mime_type, thumb_url, + title, caption=None, caption_entities=None, parse_mode=None, + video_width=None, video_height=None, video_duration=None, + description=None, reply_markup=None, input_message_content=None): + super().__init__('video', id, title = title, caption = caption, + input_message_content = input_message_content, reply_markup = reply_markup, + parse_mode = parse_mode, caption_entities = caption_entities) + self.video_url = video_url + self.mime_type = mime_type self.thumb_url = thumb_url self.video_width = video_width self.video_height = video_height @@ -1999,6 +3987,49 @@ def to_dict(self): class InlineQueryResultAudio(InlineQueryResultBase): + """ + Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultaudio + + :param type: Type of the result, must be audio + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param audio_url: A valid URL for the audio file + :type audio_url: :obj:`str` + + :param title: Title + :type title: :obj:`str` + + :param caption: Optional. Caption, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the audio caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param performer: Optional. Performer + :type performer: :obj:`str` + + :param audio_duration: Optional. Audio duration in seconds + :type audio_duration: :obj:`int` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the audio + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultAudio` + """ def __init__(self, id, audio_url, title, caption=None, caption_entities=None, parse_mode=None, performer=None, audio_duration=None, reply_markup=None, input_message_content=None): @@ -2020,6 +4051,46 @@ def to_dict(self): class InlineQueryResultVoice(InlineQueryResultBase): + """ + Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultvoice + + :param type: Type of the result, must be voice + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param voice_url: A valid URL for the voice recording + :type voice_url: :obj:`str` + + :param title: Recording title + :type title: :obj:`str` + + :param caption: Optional. Caption, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the voice message caption. See formatting options for + more details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param voice_duration: Optional. Recording duration in seconds + :type voice_duration: :obj:`int` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the voice recording + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultVoice` + """ def __init__(self, id, voice_url, title, caption=None, caption_entities=None, parse_mode=None, voice_duration=None, reply_markup=None, input_message_content=None): super().__init__('voice', id, title = title, caption = caption, @@ -2037,6 +4108,58 @@ def to_dict(self): class InlineQueryResultDocument(InlineQueryResultBase): + """ + Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultdocument + + :param type: Type of the result, must be document + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param title: Title for the result + :type title: :obj:`str` + + :param caption: Optional. Caption of the document to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the document caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param document_url: A valid URL for the file + :type document_url: :obj:`str` + + :param mime_type: MIME type of the content of the file, either “application/pdf” or “application/zip” + :type mime_type: :obj:`str` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the file + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :param thumb_url: Optional. URL of the thumbnail (JPEG only) for the file + :type thumb_url: :obj:`str` + + :param thumb_width: Optional. Thumbnail width + :type thumb_width: :obj:`int` + + :param thumb_height: Optional. Thumbnail height + :type thumb_height: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultDocument` + """ def __init__(self, id, title, document_url, mime_type, caption=None, caption_entities=None, parse_mode=None, description=None, reply_markup=None, input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None): @@ -2066,6 +4189,59 @@ def to_dict(self): class InlineQueryResultLocation(InlineQueryResultBase): + """ + Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultlocation + + :param type: Type of the result, must be location + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 Bytes + :type id: :obj:`str` + + :param latitude: Location latitude in degrees + :type latitude: :obj:`float` number + + :param longitude: Location longitude in degrees + :type longitude: :obj:`float` number + + :param title: Location title + :type title: :obj:`str` + + :param horizontal_accuracy: Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + :type horizontal_accuracy: :obj:`float` number + + :param live_period: Optional. Period in seconds for which the location can be updated, should be between 60 and + 86400. + :type live_period: :obj:`int` + + :param heading: Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 + and 360 if specified. + :type heading: :obj:`int` + + :param proximity_alert_radius: Optional. For live locations, a maximum distance for proximity alerts about + approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :type proximity_alert_radius: :obj:`int` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the location + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :param thumb_url: Optional. Url of the thumbnail for the result + :type thumb_url: :obj:`str` + + :param thumb_width: Optional. Thumbnail width + :type thumb_width: :obj:`int` + + :param thumb_height: Optional. Thumbnail height + :type thumb_height: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultLocation` + """ def __init__(self, id, title, latitude, longitude, horizontal_accuracy, live_period=None, reply_markup=None, input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None, heading=None, proximity_alert_radius = None): super().__init__('location', id, title = title, @@ -2102,6 +4278,60 @@ def to_dict(self): class InlineQueryResultVenue(InlineQueryResultBase): + """ + Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultvenue + + :param type: Type of the result, must be venue + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 Bytes + :type id: :obj:`str` + + :param latitude: Latitude of the venue location in degrees + :type latitude: :obj:`float` + + :param longitude: Longitude of the venue location in degrees + :type longitude: :obj:`float` + + :param title: Title of the venue + :type title: :obj:`str` + + :param address: Address of the venue + :type address: :obj:`str` + + :param foursquare_id: Optional. Foursquare identifier of the venue if known + :type foursquare_id: :obj:`str` + + :param foursquare_type: Optional. Foursquare type of the venue, if known. (For example, + “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + :type foursquare_type: :obj:`str` + + :param google_place_id: Optional. Google Places identifier of the venue + :type google_place_id: :obj:`str` + + :param google_place_type: Optional. Google Places type of the venue. (See supported types.) + :type google_place_type: :obj:`str` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the venue + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :param thumb_url: Optional. Url of the thumbnail for the result + :type thumb_url: :obj:`str` + + :param thumb_width: Optional. Thumbnail width + :type thumb_width: :obj:`int` + + :param thumb_height: Optional. Thumbnail height + :type thumb_height: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultVenue` + """ def __init__(self, id, title, latitude, longitude, address, foursquare_id=None, foursquare_type=None, reply_markup=None, input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None, google_place_id=None, google_place_type=None): @@ -2141,6 +4371,47 @@ def to_dict(self): class InlineQueryResultContact(InlineQueryResultBase): + """ + Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcontact + + :param type: Type of the result, must be contact + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 Bytes + :type id: :obj:`str` + + :param phone_number: Contact's phone number + :type phone_number: :obj:`str` + + :param first_name: Contact's first name + :type first_name: :obj:`str` + + :param last_name: Optional. Contact's last name + :type last_name: :obj:`str` + + :param vcard: Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes + :type vcard: :obj:`str` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the contact + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :param thumb_url: Optional. Url of the thumbnail for the result + :type thumb_url: :obj:`str` + + :param thumb_width: Optional. Thumbnail width + :type thumb_width: :obj:`int` + + :param thumb_height: Optional. Thumbnail height + :type thumb_height: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultContact` + """ def __init__(self, id, phone_number, first_name, last_name=None, vcard=None, reply_markup=None, input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None): @@ -2172,6 +4443,26 @@ def to_dict(self): class InlineQueryResultGame(InlineQueryResultBase): + """ + Represents a Game. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultgame + + :param type: Type of the result, must be game + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param game_short_name: Short name of the game + :type game_short_name: :obj:`str` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultGame` + """ def __init__(self, id, game_short_name, reply_markup=None): super().__init__('game', id, reply_markup = reply_markup) self.game_short_name = game_short_name @@ -2183,6 +4474,9 @@ def to_dict(self): class InlineQueryResultCachedBase(ABC, JsonSerializable): + """ + Base class of all InlineQueryResultCached* classes. + """ def __init__(self): self.type = None self.id = None @@ -2217,6 +4511,46 @@ def to_json(self): class InlineQueryResultCachedPhoto(InlineQueryResultCachedBase): + """ + Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedphoto + + :param type: Type of the result, must be photo + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param photo_file_id: A valid file identifier of the photo + :type photo_file_id: :obj:`str` + + :param title: Optional. Title for the result + :type title: :obj:`str` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param caption: Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the photo caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the photo + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedPhoto` + """ def __init__(self, id, photo_file_id, title=None, description=None, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, input_message_content=None): @@ -2235,6 +4569,42 @@ def __init__(self, id, photo_file_id, title=None, description=None, class InlineQueryResultCachedGif(InlineQueryResultCachedBase): + """ + Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedgif + + :param type: Type of the result, must be gif + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param gif_file_id: A valid file identifier for the GIF file + :type gif_file_id: :obj:`str` + + :param title: Optional. Title for the result + :type title: :obj:`str` + + :param caption: Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the caption. See formatting options for more details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the GIF animation + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedGif` + """ def __init__(self, id, gif_file_id, title=None, description=None, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, input_message_content=None): @@ -2253,6 +4623,42 @@ def __init__(self, id, gif_file_id, title=None, description=None, class InlineQueryResultCachedMpeg4Gif(InlineQueryResultCachedBase): + """ + Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedmpeg4gif + + :param type: Type of the result, must be mpeg4_gif + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param mpeg4_file_id: A valid file identifier for the MPEG4 file + :type mpeg4_file_id: :obj:`str` + + :param title: Optional. Title for the result + :type title: :obj:`str` + + :param caption: Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the caption. See formatting options for more details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the video animation + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedMpeg4Gif` + """ def __init__(self, id, mpeg4_file_id, title=None, description=None, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, input_message_content=None): @@ -2271,6 +4677,29 @@ def __init__(self, id, mpeg4_file_id, title=None, description=None, class InlineQueryResultCachedSticker(InlineQueryResultCachedBase): + """ + Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedsticker + + :param type: Type of the result, must be sticker + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param sticker_file_id: A valid file identifier of the sticker + :type sticker_file_id: :obj:`str` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the sticker + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedSticker` + """ def __init__(self, id, sticker_file_id, reply_markup=None, input_message_content=None): InlineQueryResultCachedBase.__init__(self) self.type = 'sticker' @@ -2282,6 +4711,46 @@ def __init__(self, id, sticker_file_id, reply_markup=None, input_message_content class InlineQueryResultCachedDocument(InlineQueryResultCachedBase): + """ + Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcacheddocument + + :param type: Type of the result, must be document + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param title: Title for the result + :type title: :obj:`str` + + :param document_file_id: A valid file identifier for the file + :type document_file_id: :obj:`str` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param caption: Optional. Caption of the document to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the document caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the file + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedDocument` + """ def __init__(self, id, document_file_id, title, description=None, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, input_message_content=None): @@ -2300,6 +4769,46 @@ def __init__(self, id, document_file_id, title, description=None, class InlineQueryResultCachedVideo(InlineQueryResultCachedBase): + """ + Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedvideo + + :param type: Type of the result, must be video + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param video_file_id: A valid file identifier for the video file + :type video_file_id: :obj:`str` + + :param title: Title for the result + :type title: :obj:`str` + + :param description: Optional. Short description of the result + :type description: :obj:`str` + + :param caption: Optional. Caption of the video to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the video caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the video + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedVideo` + """ def __init__(self, id, video_file_id, title, description=None, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, @@ -2319,6 +4828,43 @@ def __init__(self, id, video_file_id, title, description=None, class InlineQueryResultCachedVoice(InlineQueryResultCachedBase): + """ + Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedvoice + + :param type: Type of the result, must be voice + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param voice_file_id: A valid file identifier for the voice message + :type voice_file_id: :obj:`str` + + :param title: Voice message title + :type title: :obj:`str` + + :param caption: Optional. Caption, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the voice message caption. See formatting options for + more details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the voice message + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedVoice` + """ def __init__(self, id, voice_file_id, title, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, input_message_content=None): InlineQueryResultCachedBase.__init__(self) @@ -2335,6 +4881,40 @@ def __init__(self, id, voice_file_id, title, caption=None, caption_entities = No class InlineQueryResultCachedAudio(InlineQueryResultCachedBase): + """ + Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio. + + Telegram Documentation: https://core.telegram.org/bots/api#inlinequeryresultcachedaudio + + :param type: Type of the result, must be audio + :type type: :obj:`str` + + :param id: Unique identifier for this result, 1-64 bytes + :type id: :obj:`str` + + :param audio_file_id: A valid file identifier for the audio file + :type audio_file_id: :obj:`str` + + :param caption: Optional. Caption, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the audio caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param reply_markup: Optional. Inline keyboard attached to the message + :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` + + :param input_message_content: Optional. Content of the message to be sent instead of the audio + :type input_message_content: :class:`telebot.types.InputMessageContent` + + :return: Instance of the class + :rtype: :class:`telebot.types.InlineQueryResultCachedAudio` + """ def __init__(self, id, audio_file_id, caption=None, caption_entities = None, parse_mode=None, reply_markup=None, input_message_content=None): InlineQueryResultCachedBase.__init__(self) @@ -2352,6 +4932,34 @@ def __init__(self, id, audio_file_id, caption=None, caption_entities = None, # Games class Game(JsonDeserializable): + """ + This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers. + + Telegram Documentation: https://core.telegram.org/bots/api#game + + :param title: Title of the game + :type title: :obj:`str` + + :param description: Description of the game + :type description: :obj:`str` + + :param photo: Photo that will be displayed in the game message in chats. + :type photo: :obj:`list` of :class:`telebot.types.PhotoSize` + + :param text: Optional. Brief description of the game or high scores included in the game message. Can be + automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited + using editMessageText. 0-4096 characters. + :type text: :obj:`str` + + :param text_entities: Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc. + :type text_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param animation: Optional. Animation that will be displayed in the game message in chats. Upload via BotFather + :type animation: :class:`telebot.types.Animation` + + :return: Instance of the class + :rtype: :class:`telebot.types.Game` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2365,6 +4973,9 @@ def de_json(cls, json_string): @classmethod def parse_photo(cls, photo_size_array): + """ + Parse the photo array into a list of PhotoSize objects + """ ret = [] for ps in photo_size_array: ret.append(PhotoSize.de_json(ps)) @@ -2372,6 +4983,9 @@ def parse_photo(cls, photo_size_array): @classmethod def parse_entities(cls, message_entity_array): + """ + Parse the message entity array into a list of MessageEntity objects + """ ret = [] for me in message_entity_array: ret.append(MessageEntity.de_json(me)) @@ -2387,6 +5001,44 @@ def __init__(self, title, description, photo, text=None, text_entities=None, ani class Animation(JsonDeserializable): + """ + This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). + + Telegram Documentation: https://core.telegram.org/bots/api#animation + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param width: Video width as defined by sender + :type width: :obj:`int` + + :param height: Video height as defined by sender + :type height: :obj:`int` + + :param duration: Duration of the video in seconds as defined by sender + :type duration: :obj:`int` + + :param thumb: Optional. Animation thumbnail as defined by sender + :type thumb: :class:`telebot.types.PhotoSize` + + :param file_name: Optional. Original animation filename as defined by sender + :type file_name: :obj:`str` + + :param mime_type: Optional. MIME type of the file as defined by sender + :type mime_type: :obj:`str` + + :param file_size: Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have + difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or + double-precision float type are safe for storing this value. + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Animation` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2411,6 +5063,23 @@ def __init__(self, file_id, file_unique_id, width=None, height=None, duration=No class GameHighScore(JsonDeserializable): + """ + This object represents one row of the high scores table for a game. + + Telegram Documentation: https://core.telegram.org/bots/api#gamehighscore + + :param position: Position in high score table for the game + :type position: :obj:`int` + + :param user: User + :type user: :class:`telebot.types.User` + + :param score: Score + :type score: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.GameHighScore` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2426,7 +5095,23 @@ def __init__(self, position, user, score, **kwargs): # Payments -class LabeledPrice(JsonSerializable): +class LabeledPrice(JsonSerializable, Dictionaryable): + """ + This object represents a portion of the price for goods or services. + + Telegram Documentation: https://core.telegram.org/bots/api#labeledprice + + :param label: Portion label + :type label: :obj:`str` + + :param amount: Price of the product in the smallest units of the currency (integer, not float/double). For example, + for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past + the decimal point for each currency (2 for the majority of currencies). + :type amount: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.LabeledPrice` + """ def __init__(self, label, amount): self.label: str = label self.amount: int = amount @@ -2441,6 +5126,31 @@ def to_json(self): class Invoice(JsonDeserializable): + """ + This object contains basic information about an invoice. + + Telegram Documentation: https://core.telegram.org/bots/api#invoice + + :param title: Product name + :type title: :obj:`str` + + :param description: Product description + :type description: :obj:`str` + + :param start_parameter: Unique bot deep-linking parameter that can be used to generate this invoice + :type start_parameter: :obj:`str` + + :param currency: Three-letter ISO 4217 currency code + :type currency: :obj:`str` + + :param total_amount: Total price in the smallest units of the currency (integer, not float/double). For example, + for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past + the decimal point for each currency (2 for the majority of currencies). + :type total_amount: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Invoice` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2456,6 +5166,32 @@ def __init__(self, title, description, start_parameter, currency, total_amount, class ShippingAddress(JsonDeserializable): + """ + This object represents a shipping address. + + Telegram Documentation: https://core.telegram.org/bots/api#shippingaddress + + :param country_code: Two-letter ISO 3166-1 alpha-2 country code + :type country_code: :obj:`str` + + :param state: State, if applicable + :type state: :obj:`str` + + :param city: City + :type city: :obj:`str` + + :param street_line1: First line for the address + :type street_line1: :obj:`str` + + :param street_line2: Second line for the address + :type street_line2: :obj:`str` + + :param post_code: Address post code + :type post_code: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.ShippingAddress` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2472,6 +5208,26 @@ def __init__(self, country_code, state, city, street_line1, street_line2, post_c class OrderInfo(JsonDeserializable): + """ + This object represents information about an order. + + Telegram Documentation: https://core.telegram.org/bots/api#orderinfo + + :param name: Optional. User name + :type name: :obj:`str` + + :param phone_number: Optional. User's phone number + :type phone_number: :obj:`str` + + :param email: Optional. User email + :type email: :obj:`str` + + :param shipping_address: Optional. User shipping address + :type shipping_address: :class:`telebot.types.ShippingAddress` + + :return: Instance of the class + :rtype: :class:`telebot.types.OrderInfo` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2487,6 +5243,23 @@ def __init__(self, name=None, phone_number=None, email=None, shipping_address=No class ShippingOption(JsonSerializable): + """ + This object represents one shipping option. + + Telegram Documentation: https://core.telegram.org/bots/api#shippingoption + + :param id: Shipping option identifier + :type id: :obj:`str` + + :param title: Option title + :type title: :obj:`str` + + :param prices: List of price portions + :type prices: :obj:`list` of :class:`telebot.types.LabeledPrice` + + :return: Instance of the class + :rtype: :class:`telebot.types.ShippingOption` + """ def __init__(self, id, title): self.id: str = id self.title: str = title @@ -2497,6 +5270,9 @@ def add_price(self, *args): Add LabeledPrice to ShippingOption :param args: LabeledPrices + :type args: :obj:`LabeledPrice` + + :return: None """ for price in args: self.prices.append(price) @@ -2510,7 +5286,38 @@ def to_json(self): return json_dict -class SuccessfulPayment(JsonDeserializable): +class SuccessfulPayment(JsonDeserializable): + """ + This object contains basic information about a successful payment. + + Telegram Documentation: https://core.telegram.org/bots/api#successfulpayment + + :param currency: Three-letter ISO 4217 currency code + :type currency: :obj:`str` + + :param total_amount: Total price in the smallest units of the currency (integer, not float/double). For example, + for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past + the decimal point for each currency (2 for the majority of currencies). + :type total_amount: :obj:`int` + + :param invoice_payload: Bot specified invoice payload + :type invoice_payload: :obj:`str` + + :param shipping_option_id: Optional. Identifier of the shipping option chosen by the user + :type shipping_option_id: :obj:`str` + + :param order_info: Optional. Order information provided by the user + :type order_info: :class:`telebot.types.OrderInfo` + + :param telegram_payment_charge_id: Telegram payment identifier + :type telegram_payment_charge_id: :obj:`str` + + :param provider_payment_charge_id: Provider payment identifier + :type provider_payment_charge_id: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.SuccessfulPayment` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2530,6 +5337,26 @@ def __init__(self, currency, total_amount, invoice_payload, shipping_option_id=N class ShippingQuery(JsonDeserializable): + """ + This object contains information about an incoming shipping query. + + Telegram Documentation: https://core.telegram.org/bots/api#shippingquery + + :param id: Unique query identifier + :type id: :obj:`str` + + :param from: User who sent the query + :type from: :class:`telebot.types.User` + + :param invoice_payload: Bot specified invoice payload + :type invoice_payload: :obj:`str` + + :param shipping_address: User specified shipping address + :type shipping_address: :class:`telebot.types.ShippingAddress` + + :return: Instance of the class + :rtype: :class:`telebot.types.ShippingQuery` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2546,6 +5373,37 @@ def __init__(self, id, from_user, invoice_payload, shipping_address, **kwargs): class PreCheckoutQuery(JsonDeserializable): + """ + This object contains information about an incoming pre-checkout query. + + Telegram Documentation: https://core.telegram.org/bots/api#precheckoutquery + + :param id: Unique query identifier + :type id: :obj:`str` + + :param from: User who sent the query + :type from: :class:`telebot.types.User` + + :param currency: Three-letter ISO 4217 currency code + :type currency: :obj:`str` + + :param total_amount: Total price in the smallest units of the currency (integer, not float/double). For example, + for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past + the decimal point for each currency (2 for the majority of currencies). + :type total_amount: :obj:`int` + + :param invoice_payload: Bot specified invoice payload + :type invoice_payload: :obj:`str` + + :param shipping_option_id: Optional. Identifier of the shipping option chosen by the user + :type shipping_option_id: :obj:`str` + + :param order_info: Optional. Order information provided by the user + :type order_info: :class:`telebot.types.OrderInfo` + + :return: Instance of the class + :rtype: :class:`telebot.types.PreCheckoutQuery` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2567,6 +5425,35 @@ def __init__(self, id, from_user, currency, total_amount, invoice_payload, shipp # Stickers class StickerSet(JsonDeserializable): + """ + This object represents a sticker set. + + Telegram Documentation: https://core.telegram.org/bots/api#stickerset + + :param name: Sticker set name + :type name: :obj:`str` + + :param title: Sticker set title + :type title: :obj:`str` + + :param is_animated: True, if the sticker set contains animated stickers + :type is_animated: :obj:`bool` + + :param is_video: True, if the sticker set contains video stickers + :type is_video: :obj:`bool` + + :param contains_masks: True, if the sticker set contains masks + :type contains_masks: :obj:`bool` + + :param stickers: List of all set stickers + :type stickers: :obj:`list` of :class:`telebot.types.Sticker` + + :param thumb: Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format + :type thumb: :class:`telebot.types.PhotoSize` + + :return: Instance of the class + :rtype: :class:`telebot.types.StickerSet` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2592,6 +5479,52 @@ def __init__(self, name, title, is_animated, is_video, contains_masks, stickers, class Sticker(JsonDeserializable): + """ + This object represents a sticker. + + Telegram Documentation: https://core.telegram.org/bots/api#sticker + + :param file_id: Identifier for this file, which can be used to download or reuse the file + :type file_id: :obj:`str` + + :param file_unique_id: Unique identifier for this file, which is supposed to be the same over time and for different + bots. Can't be used to download or reuse the file. + :type file_unique_id: :obj:`str` + + :param width: Sticker width + :type width: :obj:`int` + + :param height: Sticker height + :type height: :obj:`int` + + :param is_animated: True, if the sticker is animated + :type is_animated: :obj:`bool` + + :param is_video: True, if the sticker is a video sticker + :type is_video: :obj:`bool` + + :param thumb: Optional. Sticker thumbnail in the .WEBP or .JPG format + :type thumb: :class:`telebot.types.PhotoSize` + + :param emoji: Optional. Emoji associated with the sticker + :type emoji: :obj:`str` + + :param set_name: Optional. Name of the sticker set to which the sticker belongs + :type set_name: :obj:`str` + + :param premium_animation: Optional. Premium animation for the sticker, if the sticker is premium + :type premium_animation: :class:`telebot.types.File` + + :param mask_position: Optional. For mask stickers, the position where the mask should be placed + :type mask_position: :class:`telebot.types.MaskPosition` + + :param file_size: Optional. File size in bytes + :type file_size: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Sticker` + """ + @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2625,6 +5558,30 @@ def __init__(self, file_id, file_unique_id, width, height, is_animated, class MaskPosition(Dictionaryable, JsonDeserializable, JsonSerializable): + """ + This object describes the position on faces where a mask should be placed by default. + + Telegram Documentation: https://core.telegram.org/bots/api#maskposition + + :param point: The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or + “chin”. + :type point: :obj:`str` + + :param x_shift: Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, + choosing -1.0 will place mask just to the left of the default mask position. + :type x_shift: :obj:`float` number + + :param y_shift: Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For + example, 1.0 will place the mask just below the default mask position. + :type y_shift: :obj:`float` number + + :param scale: Mask scaling coefficient. For example, 2.0 means double size. + :type scale: :obj:`float` number + + :return: Instance of the class + :rtype: :class:`telebot.types.MaskPosition` + """ + @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2647,6 +5604,15 @@ def to_dict(self): # InputMedia class InputMedia(Dictionaryable, JsonSerializable): + """ + This object represents the content of a media message to be sent. It should be one of + + * :class:`InputMediaAnimation` + * :class:`InputMediaDocument` + * :class:`InputMediaAudio` + * :class:`InputMediaPhoto` + * :class:`InputMediaVideo` + """ def __init__(self, type, media, caption=None, parse_mode=None, caption_entities=None): self.type: str = type self.media: str = media @@ -2675,6 +5641,9 @@ def to_dict(self): return json_dict def convert_input_media(self): + """ + :meta private: + """ if util.is_string(self.media): return self.to_json(), None @@ -2682,6 +5651,33 @@ def convert_input_media(self): class InputMediaPhoto(InputMedia): + """ + Represents a photo to be sent. + + Telegram Documentation: https://core.telegram.org/bots/api#inputmediaphoto + + :param type: Type of the result, must be photo + :type type: :obj:`str` + + :param media: File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an + HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using + multipart/form-data under name. More information on Sending Files » + :type media: :obj:`str` + + :param caption: Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the photo caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputMediaPhoto` + """ def __init__(self, media, caption=None, parse_mode=None): if util.is_pil_image(media): media = util.pil_image_to_file(media) @@ -2693,6 +5689,52 @@ def to_dict(self): class InputMediaVideo(InputMedia): + """ + Represents a video to be sent. + + Telegram Documentation: https://core.telegram.org/bots/api#inputmediavideo + + :param type: Type of the result, must be video + :type type: :obj:`str` + + :param media: File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an + HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using + multipart/form-data under name. More information on Sending Files » + :type media: :obj:`str` + + :param thumb: Optional. 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 . More information on Sending Files » + :type thumb: InputFile or :obj:`str` + + :param caption: Optional. Caption of the video to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the video caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param width: Optional. Video width + :type width: :obj:`int` + + :param height: Optional. Video height + :type height: :obj:`int` + + :param duration: Optional. Video duration in seconds + :type duration: :obj:`int` + + :param supports_streaming: Optional. Pass True, if the uploaded video is suitable for streaming + :type supports_streaming: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputMediaVideo` + """ def __init__(self, media, thumb=None, caption=None, parse_mode=None, width=None, height=None, duration=None, supports_streaming=None): super(InputMediaVideo, self).__init__(type="video", media=media, caption=caption, parse_mode=parse_mode) @@ -2718,6 +5760,49 @@ def to_dict(self): class InputMediaAnimation(InputMedia): + """ + Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. + + Telegram Documentation: https://core.telegram.org/bots/api#inputmediaanimation + + :param type: Type of the result, must be animation + :type type: :obj:`str` + + :param media: File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an + HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using + multipart/form-data under name. More information on Sending Files » + :type media: :obj:`str` + + :param thumb: Optional. 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 . More information on Sending Files » + :type thumb: InputFile or :obj:`str` + + :param caption: Optional. Caption of the animation to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the animation caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param width: Optional. Animation width + :type width: :obj:`int` + + :param height: Optional. Animation height + :type height: :obj:`int` + + :param duration: Optional. Animation duration in seconds + :type duration: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputMediaAnimation` + """ def __init__(self, media, thumb=None, caption=None, parse_mode=None, width=None, height=None, duration=None): super(InputMediaAnimation, self).__init__(type="animation", media=media, caption=caption, parse_mode=parse_mode) self.thumb = thumb @@ -2739,6 +5824,49 @@ def to_dict(self): class InputMediaAudio(InputMedia): + """ + Represents an audio file to be treated as music to be sent. + + Telegram Documentation: https://core.telegram.org/bots/api#inputmediaaudio + + :param type: Type of the result, must be audio + :type type: :obj:`str` + + :param media: File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an + HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using + multipart/form-data under name. More information on Sending Files » + :type media: :obj:`str` + + :param thumb: Optional. 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 . More information on Sending Files » + :type thumb: InputFile or :obj:`str` + + :param caption: Optional. Caption of the audio to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the audio caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param duration: Optional. Duration of the audio in seconds + :type duration: :obj:`int` + + :param performer: Optional. Performer of the audio + :type performer: :obj:`str` + + :param title: Optional. Title of the audio + :type title: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputMediaAudio` + """ def __init__(self, media, thumb=None, caption=None, parse_mode=None, duration=None, performer=None, title=None): super(InputMediaAudio, self).__init__(type="audio", media=media, caption=caption, parse_mode=parse_mode) self.thumb = thumb @@ -2760,6 +5888,44 @@ def to_dict(self): class InputMediaDocument(InputMedia): + """ + Represents a general file to be sent. + + Telegram Documentation: https://core.telegram.org/bots/api#inputmediadocument + + :param type: Type of the result, must be document + :type type: :obj:`str` + + :param media: File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an + HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using + multipart/form-data under name. More information on Sending Files » + :type media: :obj:`str` + + :param thumb: Optional. 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 . More information on Sending Files » + :type thumb: InputFile or :obj:`str` + + :param caption: Optional. Caption of the document to be sent, 0-1024 characters after entities parsing + :type caption: :obj:`str` + + :param parse_mode: Optional. Mode for parsing entities in the document caption. See formatting options for more + details. + :type parse_mode: :obj:`str` + + :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified + instead of parse_mode + :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param disable_content_type_detection: Optional. Disables automatic server-side content type detection for + files uploaded using multipart/form-data. Always True, if the document is sent as part of an album. + :type disable_content_type_detection: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.InputMediaDocument` + """ def __init__(self, media, thumb=None, caption=None, parse_mode=None, disable_content_type_detection=None): super(InputMediaDocument, self).__init__(type="document", media=media, caption=caption, parse_mode=parse_mode) self.thumb = thumb @@ -2775,6 +5941,20 @@ def to_dict(self): class PollOption(JsonDeserializable): + """ + This object contains information about one answer option in a poll. + + Telegram Documentation: https://core.telegram.org/bots/api#polloption + + :param text: Option text, 1-100 characters + :type text: :obj:`str` + + :param voter_count: Number of users that voted for this option + :type voter_count: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.PollOption` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2791,6 +5971,56 @@ def __init__(self, text, voter_count = 0, **kwargs): class Poll(JsonDeserializable): + """ + This object contains information about a poll. + + Telegram Documentation: https://core.telegram.org/bots/api#poll + + :param id: Unique poll identifier + :type id: :obj:`str` + + :param question: Poll question, 1-300 characters + :type question: :obj:`str` + + :param options: List of poll options + :type options: :obj:`list` of :class:`telebot.types.PollOption` + + :param total_voter_count: Total number of users that voted in the poll + :type total_voter_count: :obj:`int` + + :param is_closed: True, if the poll is closed + :type is_closed: :obj:`bool` + + :param is_anonymous: True, if the poll is anonymous + :type is_anonymous: :obj:`bool` + + :param type: Poll type, currently can be “regular” or “quiz” + :type type: :obj:`str` + + :param allows_multiple_answers: True, if the poll allows multiple answers + :type allows_multiple_answers: :obj:`bool` + + :param correct_option_id: Optional. 0-based identifier of the correct answer option. Available only for polls in + the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot. + :type correct_option_id: :obj:`int` + + :param explanation: Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a + quiz-style poll, 0-200 characters + :type explanation: :obj:`str` + + :param explanation_entities: Optional. Special entities like usernames, URLs, bot commands, etc. that appear in + the explanation + :type explanation_entities: :obj:`list` of :class:`telebot.types.MessageEntity` + + :param open_period: Optional. Amount of time in seconds the poll will be active after creation + :type open_period: :obj:`int` + + :param close_date: Optional. Point in time (Unix timestamp) when the poll will be automatically closed + :type close_date: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.Poll` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2831,6 +6061,12 @@ def __init__( self.close_date: int = close_date def add(self, option): + """ + Add an option to the poll. + + :param option: Option to add + :type option: :class:`telebot.types.PollOption` or :obj:`str` + """ if type(option) is PollOption: self.options.append(option) else: @@ -2838,6 +6074,24 @@ def add(self, option): class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): + """ + This object represents an answer of a user in a non-anonymous poll. + + Telegram Documentation: https://core.telegram.org/bots/api#pollanswer + + :param poll_id: Unique poll identifier + :type poll_id: :obj:`str` + + :param user: The user, who changed the answer to the poll + :type user: :class:`telebot.types.User` + + :param option_ids: 0-based identifiers of answer options, chosen by the user. May be empty if the user retracted + their vote. + :type option_ids: :obj:`list` of :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.PollAnswer` + """ @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2860,6 +6114,20 @@ def to_dict(self): class ChatLocation(JsonSerializable, JsonDeserializable, Dictionaryable): + """ + Represents a location to which a chat is connected. + + Telegram Documentation: https://core.telegram.org/bots/api#chatlocation + + :param location: The location to which the supergroup is connected. Can't be a live location. + :type location: :class:`telebot.types.Location` + + :param address: Location address; 1-64 characters, as defined by the chat owner + :type address: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatLocation` + """ @classmethod def de_json(cls, json_string): if json_string is None: return json_string @@ -2882,6 +6150,43 @@ def to_dict(self): class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): + """ + Represents an invite link for a chat. + + Telegram Documentation: https://core.telegram.org/bots/api#chatinvitelink + + :param invite_link: The invite link. If the link was created by another chat administrator, then the second part of + the link will be replaced with “…”. + :type invite_link: :obj:`str` + + :param creator: Creator of the link + :type creator: :class:`telebot.types.User` + + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators + :type creates_join_request: :obj:`bool` + + :param is_primary: True, if the link is primary + :type is_primary: :obj:`bool` + + :param is_revoked: True, if the link is revoked + :type is_revoked: :obj:`bool` + + :param name: Optional. Invite link name + :type name: :obj:`str` + + :param expire_date: Optional. Point in time (Unix timestamp) when the link will expire or has been expired + :type expire_date: :obj:`int` + + :param member_limit: Optional. The maximum number of users that can be members of the chat simultaneously after + joining the chat via this invite link; 1-99999 + :type member_limit: :obj:`int` + + :param pending_join_request_count: Optional. Number of pending join requests created using this link + :type pending_join_request_count: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatInviteLink` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -2924,6 +6229,23 @@ def to_dict(self): class ProximityAlertTriggered(JsonDeserializable): + """ + This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user. + + Telegram Documentation: https://core.telegram.org/bots/api#proximityalerttriggered + + :param traveler: User that triggered the alert + :type traveler: :class:`telebot.types.User` + + :param watcher: User that set the alert + :type watcher: :class:`telebot.types.User` + + :param distance: The distance between the users + :type distance: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.ProximityAlertTriggered` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -2937,24 +6259,39 @@ def __init__(self, traveler, watcher, distance, **kwargs): class VideoChatStarted(JsonDeserializable): + """ + This object represents a service message about a video chat started in the chat. Currently holds no information. + """ @classmethod def de_json(cls, json_string): return cls() def __init__(self): - """ - This object represents a service message about a voice chat started in the chat. - Currently holds no information. - """ pass class VoiceChatStarted(VideoChatStarted): + """ + Deprecated, use :class:`VideoChatStarted` instead. + """ + def __init__(self): logger.warning('VoiceChatStarted is deprecated. Use VideoChatStarted instead.') super().__init__() class VideoChatScheduled(JsonDeserializable): + """ + This object represents a service message about a video chat scheduled in the chat. + + Telegram Documentation: https://core.telegram.org/bots/api#videochatscheduled + + :param start_date: Point in time (Unix timestamp) when the video chat is supposed to be started by a chat + administrator + :type start_date: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.VideoChatScheduled` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -2965,12 +6302,26 @@ def __init__(self, start_date, **kwargs): self.start_date: int = start_date class VoiceChatScheduled(VideoChatScheduled): + """ + Deprecated, use :class:`VideoChatScheduled` instead. + """ def __init__(self, *args, **kwargs): logger.warning('VoiceChatScheduled is deprecated. Use VideoChatScheduled instead.') super().__init__(*args, **kwargs) class VideoChatEnded(JsonDeserializable): + """ + This object represents a service message about a video chat ended in the chat. + + Telegram Documentation: https://core.telegram.org/bots/api#videochatended + + :param duration: Video chat duration in seconds + :type duration: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.VideoChatEnded` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -2981,6 +6332,9 @@ def __init__(self, duration, **kwargs): self.duration: int = duration class VoiceChatEnded(VideoChatEnded): + """ + Deprecated, use :class:`VideoChatEnded` instead. + """ def __init__(self, *args, **kwargs): logger.warning('VoiceChatEnded is deprecated. Use VideoChatEnded instead.') super().__init__(*args, **kwargs) @@ -2988,6 +6342,17 @@ def __init__(self, *args, **kwargs): class VideoChatParticipantsInvited(JsonDeserializable): + """ + This object represents a service message about new members invited to a video chat. + + Telegram Documentation: https://core.telegram.org/bots/api#videochatparticipantsinvited + + :param users: New members that were invited to the video chat + :type users: :obj:`list` of :class:`telebot.types.User` + + :return: Instance of the class + :rtype: :class:`telebot.types.VideoChatParticipantsInvited` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -3000,12 +6365,26 @@ def __init__(self, users=None, **kwargs): self.users: List[User] = users class VoiceChatParticipantsInvited(VideoChatParticipantsInvited): + """ + Deprecated, use :class:`VideoChatParticipantsInvited` instead. + """ def __init__(self, *args, **kwargs): logger.warning('VoiceChatParticipantsInvited is deprecated. Use VideoChatParticipantsInvited instead.') super().__init__(*args, **kwargs) class MessageAutoDeleteTimerChanged(JsonDeserializable): + """ + This object represents a service message about a change in auto-delete timer settings. + + Telegram Documentation: https://core.telegram.org/bots/api#messageautodeletetimerchanged + + :param message_auto_delete_time: New auto-delete time for messages in the chat; in seconds + :type message_auto_delete_time: :obj:`int` + + :return: Instance of the class + :rtype: :class:`telebot.types.MessageAutoDeleteTimerChanged` + """ @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -3016,9 +6395,16 @@ def __init__(self, message_auto_delete_time, **kwargs): self.message_auto_delete_time = message_auto_delete_time -class MenuButton(JsonDeserializable, JsonSerializable): +class MenuButton(JsonDeserializable, JsonSerializable, Dictionaryable): """ - Base class for MenuButtons. + This object describes the bot's menu button in a private chat. It should be one of + + * :class:`MenuButtonCommands` + * :class:`MenuButtonWebApp` + * :class:`MenuButtonDefault` + + If a menu button other than MenuButtonDefault is set for a private chat, then it is applied + in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands. """ @classmethod def de_json(cls, json_string): @@ -3032,10 +6418,30 @@ def de_json(cls, json_string): return map[obj['type']](**obj) def to_json(self): + """ + :meta private: + """ + raise NotImplementedError + + def to_dict(self): + """ + :meta private: + """ raise NotImplementedError class MenuButtonCommands(MenuButton): + """ + Represents a menu button, which opens the bot's list of commands. + + Telegram Documentation: https://core.telegram.org/bots/api#menubuttoncommands + + :param type: Type of the button, must be commands + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.MenuButtonCommands` + """ def __init__(self, type): self.type = type @@ -3047,6 +6453,24 @@ def to_json(self): return json.dumps(self.to_dict()) class MenuButtonWebApp(MenuButton): + """ + Represents a menu button, which launches a Web App. + + Telegram Documentation: https://core.telegram.org/bots/api#menubuttonwebapp + + :param type: Type of the button, must be web_app + :type type: :obj:`str` + + :param text: Text on the button + :type text: :obj:`str` + + :param web_app: Description of the Web App that will be launched when the user presses the button. The Web App will be + able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. + :type web_app: :class:`telebot.types.WebAppInfo` + + :return: Instance of the class + :rtype: :class:`telebot.types.MenuButtonWebApp` + """ def __init__(self, type, text, web_app): self.type: str = type @@ -3060,7 +6484,17 @@ def to_json(self): return json.dumps(self.to_dict()) class MenuButtonDefault(MenuButton): + """ + Describes that no specific value for the menu button was set. + Telegram Documentation: https://core.telegram.org/bots/api#menubuttondefault + + :param type: Type of the button, must be default + :type type: :obj:`str` + + :return: Instance of the class + :rtype: :class:`telebot.types.MenuButtonDefault` + """ def __init__(self, type): self.type: str = type @@ -3071,10 +6505,52 @@ def to_json(self): return json.dumps(self.to_dict()) -class ChatAdministratorRights(JsonDeserializable, JsonSerializable): +class ChatAdministratorRights(JsonDeserializable, JsonSerializable, Dictionaryable): """ - Class representation of: - https://core.telegram.org/bots/api#chatadministratorrights + Represents the rights of an administrator in a chat. + + Telegram Documentation: https://core.telegram.org/bots/api#chatadministratorrights + + :param is_anonymous: True, if the user's presence in the chat is hidden + :type is_anonymous: :obj:`bool` + + :param can_manage_chat: 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 + :type can_manage_chat: :obj:`bool` + + :param can_delete_messages: True, if the administrator can delete messages of other users + :type can_delete_messages: :obj:`bool` + + :param can_manage_video_chats: True, if the administrator can manage video chats + :type can_manage_video_chats: :obj:`bool` + + :param can_restrict_members: True, if the administrator can restrict, ban or unban chat members + :type can_restrict_members: :obj:`bool` + + :param can_promote_members: True, if the administrator can add new administrators with a subset of their own + privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that + were appointed by the user) + :type can_promote_members: :obj:`bool` + + :param can_change_info: True, if the user is allowed to change the chat title, photo and other settings + :type can_change_info: :obj:`bool` + + :param can_invite_users: True, if the user is allowed to invite new users to the chat + :type can_invite_users: :obj:`bool` + + :param can_post_messages: Optional. True, if the administrator can post in the channel; channels only + :type can_post_messages: :obj:`bool` + + :param can_edit_messages: Optional. True, if the administrator can edit messages of other users and can pin + messages; channels only + :type can_edit_messages: :obj:`bool` + + :param can_pin_messages: Optional. True, if the user is allowed to pin messages; groups and supergroups only + :type can_pin_messages: :obj:`bool` + + :return: Instance of the class + :rtype: :class:`telebot.types.ChatAdministratorRights` """ @classmethod diff --git a/telebot/util.py b/telebot/util.py index b9d7f7da2..8170f676f 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -35,11 +35,13 @@ thread_local = threading.local() +#: Contains all media content types. content_type_media = [ 'text', 'audio', 'animation', 'document', 'photo', 'sticker', 'video', 'video_note', 'voice', 'contact', 'dice', 'poll', 'venue', 'location' ] +#: Contains all service content types such as `User joined the group`. content_type_service = [ 'new_chat_members', 'left_chat_member', 'new_chat_title', 'new_chat_photo', 'delete_chat_photo', 'group_chat_created', 'supergroup_chat_created', 'channel_chat_created', 'migrate_to_chat_id', 'migrate_from_chat_id', 'pinned_message', @@ -47,6 +49,7 @@ 'video_chat_participants_invited', 'message_auto_delete_timer_changed' ] +#: All update types, should be used for allowed_updates parameter in polling. update_types = [ "message", "edited_message", "channel_post", "edited_channel_post", "inline_query", "chosen_inline_result", "callback_query", "shipping_query", "pre_checkout_query", "poll", "poll_answer", @@ -55,6 +58,9 @@ class WorkerThread(threading.Thread): + """ + :meta private: + """ count = 0 def __init__(self, exception_callback=None, queue=None, name=None): @@ -118,7 +124,9 @@ def stop(self): class ThreadPool: - + """ + :meta private: + """ def __init__(self, telebot, num_threads=2): self.telebot = telebot self.tasks = Queue.Queue() @@ -156,6 +164,9 @@ def close(self): class AsyncTask: + """ + :meta private: + """ def __init__(self, target, *args, **kwargs): self.target = target self.args = args @@ -182,6 +193,9 @@ def wait(self): class CustomRequestResponse(): + """ + :meta private: + """ def __init__(self, json_text, status_code = 200, reason = ""): self.status_code = status_code self.text = json_text @@ -192,6 +206,9 @@ def json(self): def async_dec(): + """ + :meta private: + """ def decorator(fn): def wrapper(*args, **kwargs): return AsyncTask(fn, *args, **kwargs) @@ -201,19 +218,49 @@ def wrapper(*args, **kwargs): return decorator -def is_string(var): +def is_string(var) -> bool: + """ + Returns True if the given object is a string. + """ return isinstance(var, str) -def is_dict(var): +def is_dict(var) -> bool: + """ + Returns True if the given object is a dictionary. + + :param var: object to be checked + :type var: :obj:`object` + + :return: True if the given object is a dictionary. + :rtype: :obj:`bool` + """ return isinstance(var, dict) -def is_bytes(var): +def is_bytes(var) -> bool: + """ + Returns True if the given object is a bytes object. + + :param var: object to be checked + :type var: :obj:`object` + + :return: True if the given object is a bytes object. + :rtype: :obj:`bool` + """ return isinstance(var, bytes) -def is_pil_image(var): +def is_pil_image(var) -> bool: + """ + Returns True if the given object is a PIL.Image.Image object. + + :param var: object to be checked + :type var: :obj:`object` + + :return: True if the given object is a PIL.Image.Image object. + :rtype: :obj:`bool` + """ return pil_imported and isinstance(var, Image.Image) @@ -233,7 +280,10 @@ def is_command(text: str) -> bool: Checks if `text` is a command. Telegram chat commands start with the '/' character. :param text: Text to check. + :type text: :obj:`str` + :return: True if `text` is a command, else False. + :rtype: :obj:`bool` """ if text is None: return False return text.startswith('/') @@ -244,30 +294,40 @@ def extract_command(text: str) -> Union[str, None]: Extracts the command from `text` (minus the '/') if `text` is a command (see is_command). If `text` is not a command, this function returns None. - Examples: - extract_command('/help'): 'help' - extract_command('/help@BotName'): 'help' - extract_command('/search black eyed peas'): 'search' - extract_command('Good day to you'): None + .. code-block:: python3 + :caption: Examples: + + extract_command('/help'): 'help' + extract_command('/help@BotName'): 'help' + extract_command('/search black eyed peas'): 'search' + extract_command('Good day to you'): None :param text: String to extract the command from + :type text: :obj:`str` + :return: the command if `text` is a command (according to is_command), else None. + :rtype: :obj:`str` or :obj:`None` """ if text is None: return None return text.split()[0].split('@')[0][1:] if is_command(text) else None -def extract_arguments(text: str) -> str: +def extract_arguments(text: str) -> str or None: """ Returns the argument after the command. - Examples: - extract_arguments("/get name"): 'name' - extract_arguments("/get"): '' - extract_arguments("/get@botName name"): 'name' + .. code-block:: python3 + :caption: Examples: + + extract_arguments("/get name"): 'name' + extract_arguments("/get"): '' + extract_arguments("/get@botName name"): 'name' :param text: String to extract the arguments from a command + :type text: :obj:`str` + :return: the arguments if `text` is a command (according to is_command), else None. + :rtype: :obj:`str` or :obj:`None` """ regexp = re.compile(r"/\w*(@\w*)*\s*([\s\S]*)", re.IGNORECASE) result = regexp.match(text) @@ -280,8 +340,13 @@ def split_string(text: str, chars_per_string: int) -> List[str]: This is very useful for splitting one giant message into multiples. :param text: The text to split + :type text: :obj:`str` + :param chars_per_string: The number of characters per line the text is split into. + :type chars_per_string: :obj:`int` + :return: The splitted text as a list of strings. + :rtype: :obj:`list` of :obj:`str` """ return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)] @@ -294,8 +359,13 @@ def smart_split(text: str, chars_per_string: int=MAX_MESSAGE_LENGTH) -> List[str Splits by '\n', '. ' or ' ' in exactly this priority. :param text: The text to split + :type text: :obj:`str` + :param chars_per_string: The number of maximum characters per part the text is split to. + :type chars_per_string: :obj:`int` + :return: The splitted text as a list of strings. + :rtype: :obj:`list` of :obj:`str` """ def _text_before_last(substr: str) -> str: @@ -336,12 +406,25 @@ def user_link(user: types.User, include_id: bool=False) -> str: Returns an HTML user link. This is useful for reports. Attention: Don't forget to set parse_mode to 'HTML'! - Example: - bot.send_message(your_user_id, user_link(message.from_user) + ' started the bot!', parse_mode='HTML') + + .. code-block:: python3 + :caption: Example: + + bot.send_message(your_user_id, user_link(message.from_user) + ' started the bot!', parse_mode='HTML') + + .. note:: + You can use formatting.* for all other formatting options(bold, italic, links, and etc.) + This method is kept for backward compatibility, and it is recommended to use formatting.* for + more options. :param user: the user (not the user_id) + :type user: :obj:`telebot.types.User` + :param include_id: include the user_id + :type include_id: :obj:`bool` + :return: HTML user link + :rtype: :obj:`str` """ name = escape(user.first_name) return (f"{name}" @@ -355,15 +438,16 @@ def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.I Example: - .. code-block:: python + .. code-block:: python3 + :caption: Using quick_markup: quick_markup({ 'Twitter': {'url': 'https://twitter.com'}, 'Facebook': {'url': 'https://facebook.com'}, 'Back': {'callback_data': 'whatever'} }, row_width=2): - # returns an InlineKeyboardMarkup with two buttons in a row, one leading to Twitter, the other to facebook - # and a back button below + # returns an InlineKeyboardMarkup with two buttons in a row, one leading to Twitter, the other to facebook + # and a back button below # kwargs can be: { @@ -378,8 +462,13 @@ def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.I } :param values: a dict containing all buttons to create in this format: {text: kwargs} {str:} + :type values: :obj:`dict` + :param row_width: int row width + :type row_width: :obj:`int` + :return: InlineKeyboardMarkup + :rtype: :obj:`types.InlineKeyboardMarkup` """ markup = types.InlineKeyboardMarkup(row_width=row_width) buttons = [ @@ -392,16 +481,25 @@ def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.I # CREDITS TO http://stackoverflow.com/questions/12317940#answer-12320352 def or_set(self): + """ + :meta private: + """ self._set() self.changed() def or_clear(self): + """ + :meta private: + """ self._clear() self.changed() def orify(e, changed_callback): + """ + :meta private: + """ if not hasattr(e, "_set"): e._set = e.set if not hasattr(e, "_clear"): @@ -412,6 +510,9 @@ def orify(e, changed_callback): def OrEvent(*events): + """ + :meta private: + """ or_event = threading.Event() def changed(): @@ -435,6 +536,9 @@ def busy_wait(): def per_thread(key, construct_value, reset=False): + """ + :meta private: + """ if reset or not hasattr(thread_local, key): value = construct_value() setattr(thread_local, key, value) @@ -449,7 +553,13 @@ def chunks(lst, n): yield lst[i:i + n] -def generate_random_token(): +def generate_random_token() -> str: + """ + Generates a random token consisting of letters and digits, 16 characters long. + + :return: a random token + :rtype: :obj:`str` + """ return ''.join(random.sample(string.ascii_letters, 16)) @@ -457,10 +567,19 @@ def deprecated(warn: bool=True, alternative: Optional[Callable]=None, deprecatio """ Use this decorator to mark functions as deprecated. When the function is used, an info (or warning if `warn` is True) is logged. + + :meta private: :param warn: If True a warning is logged else an info + :type warn: :obj:`bool` + :param alternative: The new function to use instead + :type alternative: :obj:`Callable` + :param deprecation_text: Custom deprecation text + :type deprecation_text: :obj:`str` + + :return: The decorated function """ def decorator(function): def wrapper(*args, **kwargs): @@ -480,7 +599,17 @@ def wrapper(*args, **kwargs): # Cloud helpers def webhook_google_functions(bot, request): - """A webhook endpoint for Google Cloud Functions FaaS.""" + """ + A webhook endpoint for Google Cloud Functions FaaS. + + :param bot: The bot instance + :type bot: :obj:`telebot.TeleBot` or :obj:`telebot.async_telebot.AsyncTeleBot` + + :param request: The request object + :type request: :obj:`flask.Request` + + :return: The response object + """ if request.is_json: try: request_json = request.get_json() @@ -494,7 +623,7 @@ def webhook_google_functions(bot, request): return 'Bot ON' -def antiflood(function, *args, **kwargs): +def antiflood(function: Callable, *args, **kwargs): """ Use this function inside loops in order to avoid getting TooManyRequests error. Example: @@ -505,9 +634,15 @@ def antiflood(function, *args, **kwargs): for chat_id in chat_id_list: msg = antiflood(bot.send_message, chat_id, text) - :param function: - :param args: - :param kwargs: + :param function: The function to call + :type function: :obj:`Callable` + + :param args: The arguments to pass to the function + :type args: :obj:`tuple` + + :param kwargs: The keyword arguments to pass to the function + :type kwargs: :obj:`dict` + :return: None """ from telebot.apihelper import ApiTelegramException @@ -524,6 +659,17 @@ def antiflood(function, *args, **kwargs): def parse_web_app_data(token: str, raw_init_data: str): + """ + Parses web app data. + + :param token: The bot token + :type token: :obj:`str` + + :param raw_init_data: The raw init data + :type raw_init_data: :obj:`str` + + :return: The parsed init data + """ is_valid = validate_web_app_data(token, raw_init_data) if not is_valid: return False @@ -539,7 +685,18 @@ def parse_web_app_data(token: str, raw_init_data: str): return result -def validate_web_app_data(token, raw_init_data): +def validate_web_app_data(token: str, raw_init_data: str): + """ + Validates web app data. + + :param token: The bot token + :type token: :obj:`str` + + :param raw_init_data: The raw init data + :type raw_init_data: :obj:`str` + + :return: The parsed init data + """ try: parsed_data = dict(parse_qsl(raw_init_data)) except ValueError: