From 6049de435617a07237f9a8b7b6d80203951ae589 Mon Sep 17 00:00:00 2001 From: zeph1997 Date: Thu, 16 Jul 2020 19:07:39 +0800 Subject: [PATCH 001/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fb12d59..530641d 100644 --- a/README.md +++ b/README.md @@ -651,5 +651,6 @@ Get help. Discuss. Chat. * [FoodBot](https://t.me/ChensonUz_bot) ([source](https://github.com/Fliego/old_restaurant_telegram_chatbot)) by @Fliego - a simple bot for food ordering * [Sporty](https://t.me/SportydBot) ([source](https://github.com/0xnu/sporty)) by @0xnu - Telegram bot for displaying the latest news, sports schedules and injury updates. * [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. +* [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From bc5d9c8d6984c5565081cea601e9b2b4d8f6d3aa Mon Sep 17 00:00:00 2001 From: zeph1997 Date: Thu, 16 Jul 2020 19:09:37 +0800 Subject: [PATCH 002/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 530641d..fa33553 100644 --- a/README.md +++ b/README.md @@ -651,6 +651,6 @@ Get help. Discuss. Chat. * [FoodBot](https://t.me/ChensonUz_bot) ([source](https://github.com/Fliego/old_restaurant_telegram_chatbot)) by @Fliego - a simple bot for food ordering * [Sporty](https://t.me/SportydBot) ([source](https://github.com/0xnu/sporty)) by @0xnu - Telegram bot for displaying the latest news, sports schedules and injury updates. * [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. -* [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. +* [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From b50eb1bafb31aeee6cff6e7781ba5e7c7bfbbf1a Mon Sep 17 00:00:00 2001 From: EskiSlav Date: Fri, 17 Jul 2020 13:43:45 +0300 Subject: [PATCH 003/350] Added nested entities from Bot API 4.5 --- telebot/types.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index cb98b9f..7660b80 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -479,8 +479,11 @@ class Message(JsonDeserializable): "pre" : "
{text}
", "code" : "{text}", #"url" : "{text}", # @badiboy plain URLs have no text and do not need tags - "text_link": "{text}" - } + "text_link": "{text}", + "strikethrough": "{text}", + "underline": "{text}" + } + if hasattr(self, "custom_subs"): for key, value in self.custom_subs.items(): _subs[key] = value @@ -511,8 +514,7 @@ class Message(JsonDeserializable): html_text += func(utf16_text[offset * 2 : (offset + entity.length) * 2], entity.type, entity.url, entity.user) offset += entity.length else: - # TODO: process nested entities from Bot API 4.5 - # Now ignoring them + # For future entities pass if offset * 2 < len(utf16_text): html_text += func(utf16_text[offset * 2:]) From c533a52e39d1efd1cfd1752bec0d297e49dd17d3 Mon Sep 17 00:00:00 2001 From: EskiSlav Date: Sat, 18 Jul 2020 00:25:00 +0300 Subject: [PATCH 004/350] Restored necessary comment --- telebot/types.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 7660b80..a622d29 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -514,7 +514,8 @@ class Message(JsonDeserializable): html_text += func(utf16_text[offset * 2 : (offset + entity.length) * 2], entity.type, entity.url, entity.user) offset += entity.length else: - # For future entities + # TODO: process nested entities from Bot API 4.5 + # Now ignoring them pass if offset * 2 < len(utf16_text): html_text += func(utf16_text[offset * 2:]) From a02f499a206f503f2d92bb814d57f46208761f5f Mon Sep 17 00:00:00 2001 From: daveusa31 <41593484+daveusa31@users.noreply.github.com> Date: Sat, 18 Jul 2020 19:02:07 +0300 Subject: [PATCH 005/350] Documented the default parse_mode installation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fa33553..b106d1d 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ Then, open the file and create an instance of the TeleBot class. ```python import telebot -bot = telebot.TeleBot("TOKEN") +bot = telebot.TeleBot("TOKEN", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN ``` *Note: Make sure to actually replace TOKEN with your own API token.* From dbe9ce49dfe5c7c77a47576c77f343d599fb647a Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 21 Jul 2020 01:20:01 +0300 Subject: [PATCH 006/350] Minor updates in code --- telebot/__init__.py | 56 +++++++++++++++++++++++--------------------- telebot/apihelper.py | 25 +++++++++++++------- telebot/types.py | 2 +- 3 files changed, 47 insertions(+), 36 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index ffde7e3..14366b5 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -648,14 +648,14 @@ class TeleBot: return types.Message.de_json( apihelper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) - def delete_message(self, chat_id, message_id): + def delete_message(self, chat_id, message_id, timeout=None): """ Use this method to delete message. Returns True on success. :param chat_id: in which chat to delete :param message_id: which message to delete :return: API reply. """ - return apihelper.delete_message(self.token, chat_id, message_id) + return apihelper.delete_message(self.token, chat_id, message_id, timeout) def send_dice( self, chat_id, @@ -1252,39 +1252,41 @@ class TeleBot: def send_invoice(self, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, - is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, - provider_data=None, timeout=None): + send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, timeout=None): """ Sends invoice - :param chat_id: - :param title: - :param description: - :param invoice_payload: - :param provider_token: - :param currency: - :param prices: - :param start_parameter: - :param photo_url: - :param photo_size: - :param photo_width: - :param photo_height: - :param need_name: - :param need_phone_number: - :param need_email: - :param need_shipping_address: - :param is_flexible: - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param provider_data: + :param chat_id: Unique identifier for the target private chat + :param title: Product name + :param description: Product description + :param invoice_payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param provider_token: Payments provider token, obtained via @Botfather + :param currency: Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass True, if you require the user's full name to complete the order + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :param need_email: Pass True, if you require the user's email to complete the order + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param reply_to_message_id: If the message is a reply, ID of the original message + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. :return: """ result = apihelper.send_invoice( self.token, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url, photo_size, photo_width, photo_height, need_name, need_phone_number, need_email, need_shipping_address, - is_flexible, disable_notification, reply_to_message_id, reply_markup, - provider_data, timeout) + send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, + reply_to_message_id, reply_markup, provider_data, timeout) return types.Message.de_json(result) def send_poll( diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 8a6ae75..b3a6abf 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -320,7 +320,7 @@ def send_media_group( disable_notification=None, reply_to_message_id=None, timeout=None): method_url = r'sendMediaGroup' - media_json, files = _convert_input_media_array(media) + media_json, files = convert_input_media_array(media) payload = {'chat_id': chat_id, 'media': media_json} if disable_notification is not None: payload['disable_notification'] = disable_notification @@ -781,7 +781,7 @@ def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_m def edit_message_media(token, media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): method_url = r'editMessageMedia' - media_json, file = _convert_input_media(media) + media_json, file = convert_input_media(media) payload = {'media': media_json} if chat_id: payload['chat_id'] = chat_id @@ -808,9 +808,11 @@ def edit_message_reply_markup(token, chat_id=None, message_id=None, inline_messa return _make_request(token, method_url, params=payload, method='post') -def delete_message(token, chat_id, message_id): +def delete_message(token, chat_id, message_id, timeout=None): method_url = r'deleteMessage' payload = {'chat_id': chat_id, 'message_id': message_id} + if timeout: + payload['connect-timeout'] = timeout return _make_request(token, method_url, params=payload, method='post') @@ -890,7 +892,8 @@ def get_game_high_scores(token, user_id, chat_id=None, message_id=None, inline_m def send_invoice( token, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, - need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, + need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, + send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, timeout=None): """ @@ -913,10 +916,12 @@ def send_invoice( :param need_email: Pass True, if you require the user's email to complete the order :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :param reply_to_message_id: If the message is a reply, ID of the original message :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button - :param provider_data: + :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. :return: """ method_url = r'sendInvoice' @@ -939,6 +944,10 @@ def send_invoice( payload['need_email'] = need_email if need_shipping_address is not None: payload['need_shipping_address'] = need_shipping_address + if send_phone_number_to_provider is not None: + payload['send_phone_number_to_provider'] = send_phone_number_to_provider + if send_email_to_provider is not None: + payload['send_email_to_provider'] = send_email_to_provider if is_flexible is not None: payload['is_flexible'] = is_flexible if disable_notification is not None: @@ -1154,13 +1163,13 @@ def _convert_markup(markup): return markup -def _convert_input_media(media): +def convert_input_media(media): if isinstance(media, types.InputMedia): - return media._convert_input_media() + return media.convert_input_media() return None, None -def _convert_input_media_array(array): +def convert_input_media_array(array): media = [] files = {} for input_media in array: diff --git a/telebot/types.py b/telebot/types.py index cf3d7e9..19c6d35 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -2268,7 +2268,7 @@ class InputMedia(Dictionaryable, JsonSerializable): json_dict['parse_mode'] = self.parse_mode return json_dict - def _convert_input_media(self): + def convert_input_media(self): if util.is_string(self.media): return self.to_json(), None From 0ac64469b07600b4ce79f5edbf793551afbfdd64 Mon Sep 17 00:00:00 2001 From: mrpes <68982655+mrpes@users.noreply.github.com> Date: Thu, 30 Jul 2020 09:34:51 +0500 Subject: [PATCH 007/350] Retry on requests error Added RETRY_ON_ERROR var. If its value is true, we'll try to get proper result MAX_RETRIES times, with RETRY_TIMEOUT delay between requests. Last request will be called outside of the try block, so it will throw an exception on failure P.S. I'm actually not sure if there are better ways to solve this problem, but this was my way of solving it --- telebot/apihelper.py | 45 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 138c438..a47976b 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +import time try: import ujson as json @@ -6,6 +7,7 @@ except ImportError: import json import requests +from requests.exceptions import HTTPError, ConnectionError, Timeout try: from requests.packages.urllib3 import fields @@ -28,6 +30,10 @@ FILE_URL = None CONNECT_TIMEOUT = 3.5 READ_TIMEOUT = 9999 +RETRY_ON_ERROR = False +RETRY_TIMEOUT = 2 +MAX_RETRIES = 15 + CUSTOM_SERIALIZER = None ENABLE_MIDDLEWARE = False @@ -62,9 +68,42 @@ def _make_request(token, method_name, method='get', params=None, files=None): read_timeout = params.pop('timeout') + 10 if 'connect-timeout' in params: connect_timeout = params.pop('connect-timeout') + 10 - result = _get_req_session().request( - method, request_url, params=params, files=files, - timeout=(connect_timeout, read_timeout), proxies=proxy) + + if RETRY_ON_ERROR: + got_result = False + current_try = 0 + + while not got_result and current_try Date: Fri, 31 Jul 2020 03:10:34 +0500 Subject: [PATCH 008/350] Exception classes redesign Replacing 1 exception class with 3 more specific classes: HTTP Exception (server returned http code != 200), Invalid JSON Exception (server returned invalid json), Telegram Expection (telegram returned ok != true) All 3 classes extend BaseApiException so we can handle all API exceptions at the same time --- telebot/apihelper.py | 63 +++++++++++++++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index a47976b..a1b91a1 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -116,27 +116,22 @@ def _check_result(method_name, result): - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' field equals False) - :raises ApiException: if one of the above listed cases is applicable + :raises BaseApiException: if one of the above listed cases is applicable :param method_name: The name of the method called :param result: The returned result of the method request :return: The result parsed to a JSON dictionary. """ if result.status_code != 200: - msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]' \ - .format(result.status_code, result.reason, result.text.encode('utf8')) - raise ApiException(msg, method_name, result) + raise ApiHTTPException(method_name, result) try: result_json = result.json() except: - msg = 'The server returned an invalid JSON response. Response body:\n[{0}]' \ - .format(result.text.encode('utf8')) - raise ApiException(msg, method_name, result) + raise ApiInvalidJSONException(method_name, result) if not result_json['ok']: - msg = 'Error code: {0} Description: {1}' \ - .format(result_json['error_code'], result_json['description']) - raise ApiException(msg, method_name, result) + raise ApiTelegramException(msg, method_name, result, result_json) + return result_json @@ -165,9 +160,8 @@ def download_file(token, file_path): result = _get_req_session().get(url, proxies=proxy) if result.status_code != 200: - msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]' \ - .format(result.status_code, result.reason, result.text) - raise ApiException(msg, 'Download file', result) + raise ApiHTTPException('Download file', result) + return result.content @@ -1245,15 +1239,52 @@ def _no_encode(func): return wrapper -class ApiException(Exception): +class BaseApiException(Exception): """ - This class represents an Exception thrown when a call to the Telegram API fails. + This class represents a base Exception thrown when a call to the Telegram API fails. In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively contain the name of the failed function and the returned result that made the function to be considered as failed. """ def __init__(self, msg, function_name, result): - super(ApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg)) + super(BaseApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg)) self.function_name = function_name self.result = result + +class ApiHTTPException(BaseApiException): + """ + This class represents an Exception thrown when a call to the + Telegram API server returns HTTP code that is not 200. + """ + def __init__(self, function_name, result): + super(ApiHTTPException, self).__init__( + "The server returned HTTP {0} {1}. Response body:\n[{2}]" \ + .format(result.status_code, result.reason, result.text.encode('utf8')), + function_name, + result) + +class ApiInvalidJSONException(BaseApiException): + """ + This class represents an Exception thrown when a call to the + Telegram API server returns invalid json. + """ + def __init__(self, function_name, result): + super(ApiInvalidJSONException, self).__init__( + "The server returned an invalid JSON response. Response body:\n[{0}]" \ + .format(result.text.encode('utf8')), + function_name, + result) + +class ApiTelegramException(BaseApiException): + """ + This class represents an Exception thrown when a Telegram API returns error code. + """ + def __init__(self, function_name, result, result_json): + super(ApiTelegramException, self).__init__( + "Error code: {0} Description: {1}" \ + .format(result_json['error_code'], result_json['description']), + function_name, + result) + self.result_json = result_json + From 67536d4eec7677764657c27f2431d1e31de539fe Mon Sep 17 00:00:00 2001 From: mrpes <68982655+mrpes@users.noreply.github.com> Date: Fri, 31 Jul 2020 03:30:03 +0500 Subject: [PATCH 009/350] Fixing backward compatibility issue Just realized that renaming ApiException to BaseApiException will cause backward compatibility issue --- telebot/apihelper.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index a1b91a1..e654a72 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -116,7 +116,7 @@ def _check_result(method_name, result): - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' field equals False) - :raises BaseApiException: if one of the above listed cases is applicable + :raises ApiException: if one of the above listed cases is applicable :param method_name: The name of the method called :param result: The returned result of the method request :return: The result parsed to a JSON dictionary. @@ -1239,7 +1239,7 @@ def _no_encode(func): return wrapper -class BaseApiException(Exception): +class ApiException(Exception): """ This class represents a base Exception thrown when a call to the Telegram API fails. In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively @@ -1248,11 +1248,11 @@ class BaseApiException(Exception): """ def __init__(self, msg, function_name, result): - super(BaseApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg)) + super(ApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg)) self.function_name = function_name self.result = result -class ApiHTTPException(BaseApiException): +class ApiHTTPException(ApiException): """ This class represents an Exception thrown when a call to the Telegram API server returns HTTP code that is not 200. @@ -1264,7 +1264,7 @@ class ApiHTTPException(BaseApiException): function_name, result) -class ApiInvalidJSONException(BaseApiException): +class ApiInvalidJSONException(ApiException): """ This class represents an Exception thrown when a call to the Telegram API server returns invalid json. @@ -1276,7 +1276,7 @@ class ApiInvalidJSONException(BaseApiException): function_name, result) -class ApiTelegramException(BaseApiException): +class ApiTelegramException(ApiException): """ This class represents an Exception thrown when a Telegram API returns error code. """ From 0ab908705bef0ec46786eb545bb8ca09b52253b2 Mon Sep 17 00:00:00 2001 From: mrpes <68982655+mrpes@users.noreply.github.com> Date: Fri, 31 Jul 2020 10:39:04 +0500 Subject: [PATCH 010/350] Support for PIL images as photo argument Added autoconversion of PIL image to file-like object. PIL module is optional --- telebot/util.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index 6e581b6..b4589d4 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -19,6 +19,13 @@ except ImportError: import queue as Queue import logging +try: + import PIL + from io import BytesIO + pil_imported = True +except: + pil_imported = False + logger = logging.getLogger('TeleBot') thread_local = threading.local() @@ -159,6 +166,19 @@ def async_dec(): def is_string(var): return isinstance(var, string_types) +def is_pil_image(var): + return pil_imported and isinstance(var, PIL.Image.Image) + +def pil_image_to_file(image, extension='JPEG', quality='web_low'): + if pil_imported: + photoBuffer = BytesIO() + image.convert('RGB').save(photoBuffer, extension, quality=quality) + photoBuffer.seek(0) + + return photoBuffer + else: + raise RuntimeError('PIL module is not imported') + def is_command(text): """ Checks if `text` is a command. Telegram chat commands start with the '/' character. From 97aa9637cb4ee53fc323369150da2a226c40b744 Mon Sep 17 00:00:00 2001 From: mrpes <68982655+mrpes@users.noreply.github.com> Date: Fri, 31 Jul 2020 10:45:58 +0500 Subject: [PATCH 011/350] Update apihelper.py --- telebot/apihelper.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index e654a72..7603d17 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -329,10 +329,12 @@ def send_photo( method_url = r'sendPhoto' payload = {'chat_id': chat_id} files = None - if not util.is_string(photo): - files = {'photo': photo} - else: + if util.is_string(photo): payload['photo'] = photo + elif util.is_pil_image(photo): + files = {'photo': util.pil_image_to_file(photo)} + else: + files = {'photo': photo} if caption: payload['caption'] = caption if reply_to_message_id: @@ -743,10 +745,12 @@ def set_chat_photo(token, chat_id, photo): method_url = 'setChatPhoto' payload = {'chat_id': chat_id} files = None - if not util.is_string(photo): - files = {'photo': photo} - else: + if util.is_string(photo): payload['photo'] = photo + elif util.is_pil_image(photo): + files = {'photo': util.pil_image_to_file(photo)} + else: + files = {'photo': photo} return _make_request(token, method_url, params=payload, files=files, method='post') From 5823ca5613e29e28b881693da19301961eeaafb8 Mon Sep 17 00:00:00 2001 From: mrpes <68982655+mrpes@users.noreply.github.com> Date: Sat, 1 Aug 2020 01:28:56 +0500 Subject: [PATCH 012/350] Minor keyboard code redesign --- telebot/types.py | 96 ++++++++++++++++++++++++++---------------------- 1 file changed, 52 insertions(+), 44 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index b2d250e..4b2c8df 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -66,9 +66,9 @@ class JsonDeserializable(object): :param json_type: :return: """ - if isinstance(json_type, dict): + if util.is_dict(json_type): return json_type - elif isinstance(json_type, str): + elif util.is_string(json_type): return json.loads(json_type) else: raise ValueError("json_type should be a json dict or string.") @@ -806,36 +806,44 @@ class ReplyKeyboardRemove(JsonSerializable): class ReplyKeyboardMarkup(JsonSerializable): def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3): + if row_width>12: + raise ValueError('Telegram does not support reply keyboard row width over 12') + self.resize_keyboard = resize_keyboard self.one_time_keyboard = one_time_keyboard self.selective = selective self.row_width = row_width self.keyboard = [] - def add(self, *args): + def add(self, *args, row_width=None): """ This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the result of this function: {keyboard: [["A", "B"], ["C"]]} See https://core.telegram.org/bots/api#replykeyboardmarkup + :raises ValueError: If row_width > 12 :param args: KeyboardButton to append to the keyboard + :param row_width: width of row + :return: self, to allow function chaining. """ - i = 1 - row = [] - for button in args: - if util.is_string(button): - row.append({'text': button}) - elif isinstance(button, bytes): - row.append({'text': button.decode('utf-8')}) - else: - row.append(button.to_dict()) - if i % self.row_width == 0: - self.keyboard.append(row) - row = [] - i += 1 - if len(row) > 0: - self.keyboard.append(row) + row_width = row_width or self.row_width + + if row_width>12: + raise ValueError('Telegram does not support reply keyboard row width over 12') + + for row in util.chunks(args, row_width): + button_array = [] + for button in row: + if util.is_string(button): + button_array.append({'text': button}) + elif util.is_bytes(button): + button_array.append({'text': button.decode('utf-8')}) + else: + button_array.append(button.to_dict()) + self.keyboard.append(button_array) + + return self def row(self, *args): """ @@ -845,14 +853,8 @@ class ReplyKeyboardMarkup(JsonSerializable): :param args: strings :return: self, to allow function chaining. """ - btn_array = [] - for button in args: - if util.is_string(button): - btn_array.append({'text': button}) - else: - btn_array.append(button.to_dict()) - self.keyboard.append(btn_array) - return self + + return self.add(args, 12) def to_json(self): """ @@ -904,13 +906,17 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): """ This object represents an inline keyboard that appears right next to the message it belongs to. - + + :raises ValueError: If row_width > 8 :return: """ + if row_width>8: + raise ValueError('Telegram does not support inline keyboard row width over 8') + self.row_width = row_width self.keyboard = [] - def add(self, *args): + def add(self, *args, row_width=None): """ This method adds buttons to the keyboard without exceeding row_width. @@ -920,20 +926,23 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): When row_width is set to 2, the result: {keyboard: [["A", "B"], ["C"]]} See https://core.telegram.org/bots/api#inlinekeyboardmarkup - + + :raises ValueError: If row_width > 8 :param args: Array of InlineKeyboardButton to append to the keyboard + :param row_width: width of row + :return: self, to allow function chaining. """ - i = 1 - row = [] - for button in args: - row.append(button.to_dict()) - if i % self.row_width == 0: - self.keyboard.append(row) - row = [] - i += 1 - if len(row) > 0: - self.keyboard.append(row) - + row_width = row_width or self.row_width + + if row_width>8: + raise ValueError('Telegram does not support inline keyboard row width over 8') + + for row in util.chunks(args, row_width): + button_array = [button.to_dict() for button in row] + self.keyboard.append(button_array) + + return self + def row(self, *args): """ Adds a list of InlineKeyboardButton to the keyboard. @@ -942,13 +951,12 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): InlineKeyboardMarkup.row("A").row("B", "C").to_json() outputs: '{keyboard: [["A"], ["B", "C"]]}' See https://core.telegram.org/bots/api#inlinekeyboardmarkup - + :param args: Array of InlineKeyboardButton to append to the keyboard :return: self, to allow function chaining. """ - button_array = [button.to_dict() for button in args] - self.keyboard.append(button_array) - return self + + return self.add(args, 8) def to_json(self): """ From 317a490cf04ea5fe0a6a0ff675ee62c590b82ed6 Mon Sep 17 00:00:00 2001 From: mrpes <68982655+mrpes@users.noreply.github.com> Date: Sat, 1 Aug 2020 01:30:38 +0500 Subject: [PATCH 013/350] Type checking moved to utils --- telebot/util.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index b4589d4..7612ec4 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -166,6 +166,12 @@ def async_dec(): def is_string(var): return isinstance(var, string_types) +def is_dict(var): + return isinstance(var, dict) + +def is_bytes(var): + return isinstance(var, bytes) + def is_pil_image(var): return pil_imported and isinstance(var, PIL.Image.Image) @@ -278,6 +284,11 @@ def per_thread(key, construct_value, reset=False): return getattr(thread_local, key) +def chunks(lst, n): + """Yield successive n-sized chunks from lst.""" + # https://stackoverflow.com/a/312464/9935473 + for i in range(0, len(lst), n): + yield lst[i:i + n] def generate_random_token(): return ''.join(random.sample(string.ascii_letters, 16)) From 4e5fb59fc01dc50b64730f861ed5a21c06d57400 Mon Sep 17 00:00:00 2001 From: "Mr. Dog" <68982655+mrpes@users.noreply.github.com> Date: Sun, 2 Aug 2020 20:20:33 +0500 Subject: [PATCH 014/350] Replace exceptions with warnings Also further PIL support added --- telebot/types.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 4b2c8df..4e33277 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import logging + try: import ujson as json except ImportError: @@ -9,6 +11,7 @@ import six from telebot import util +logger = logging.getLogger('TeleBot') class JsonSerializable(object): """ @@ -807,7 +810,8 @@ class ReplyKeyboardRemove(JsonSerializable): class ReplyKeyboardMarkup(JsonSerializable): def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3): if row_width>12: - raise ValueError('Telegram does not support reply keyboard row width over 12') + logger.warning('Telegram does not support reply keyboard row width over 12') + row_width=12 self.resize_keyboard = resize_keyboard self.one_time_keyboard = one_time_keyboard @@ -822,15 +826,16 @@ class ReplyKeyboardMarkup(JsonSerializable): when row_width is set to 1. When row_width is set to 2, the following is the result of this function: {keyboard: [["A", "B"], ["C"]]} See https://core.telegram.org/bots/api#replykeyboardmarkup - :raises ValueError: If row_width > 12 :param args: KeyboardButton to append to the keyboard :param row_width: width of row :return: self, to allow function chaining. """ row_width = row_width or self.row_width + if row_width>12: - raise ValueError('Telegram does not support reply keyboard row width over 12') + logger.warning('Telegram does not support reply keyboard row width over 12') + row_width=12 for row in util.chunks(args, row_width): button_array = [] @@ -907,12 +912,12 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): This object represents an inline keyboard that appears right next to the message it belongs to. - :raises ValueError: If row_width > 8 :return: """ if row_width>8: - raise ValueError('Telegram does not support inline keyboard row width over 8') - + logger.warning('Telegram does not support inline keyboard row width over 8') + row_width=8 + self.row_width = row_width self.keyboard = [] @@ -927,7 +932,6 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): {keyboard: [["A", "B"], ["C"]]} See https://core.telegram.org/bots/api#inlinekeyboardmarkup - :raises ValueError: If row_width > 8 :param args: Array of InlineKeyboardButton to append to the keyboard :param row_width: width of row :return: self, to allow function chaining. @@ -935,7 +939,8 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): row_width = row_width or self.row_width if row_width>8: - raise ValueError('Telegram does not support inline keyboard row width over 8') + logger.warning('Telegram does not support inline keyboard row width over 8') + row_width=8 for row in util.chunks(args, row_width): button_array = [button.to_dict() for button in row] @@ -2299,6 +2304,9 @@ class InputMedia(Dictionaryable, JsonSerializable): class InputMediaPhoto(InputMedia): def __init__(self, media, caption=None, parse_mode=None): + if util.is_pil_image(media): + media = util.pil_image_to_file(media) + super(InputMediaPhoto, self).__init__(type="photo", media=media, caption=caption, parse_mode=parse_mode) def to_dict(self): From 1ba093cb02f40168afe61161a05d1908620c5414 Mon Sep 17 00:00:00 2001 From: "Mr. Dog" <68982655+mrpes@users.noreply.github.com> Date: Sun, 2 Aug 2020 20:30:58 +0500 Subject: [PATCH 015/350] Change logger level to warning --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 44119ba..ce41c6d 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -18,7 +18,7 @@ console_output_handler = logging.StreamHandler(sys.stderr) console_output_handler.setFormatter(formatter) logger.addHandler(console_output_handler) -logger.setLevel(logging.ERROR) +logger.setLevel(logging.WARNING) from telebot import apihelper, types, util from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend From cc36207992a6003c673a27e18ab7b48ffb5c87cf Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 2 Aug 2020 18:58:22 +0300 Subject: [PATCH 016/350] Minor keyboard update followup --- telebot/__init__.py | 2 +- telebot/types.py | 38 ++++++++++++++++++++++++-------------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index ce41c6d..44119ba 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -18,7 +18,7 @@ console_output_handler = logging.StreamHandler(sys.stderr) console_output_handler.setFormatter(formatter) logger.addHandler(console_output_handler) -logger.setLevel(logging.WARNING) +logger.setLevel(logging.ERROR) from telebot import apihelper, types, util from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend diff --git a/telebot/types.py b/telebot/types.py index 4e33277..3ea5e6e 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -808,10 +808,13 @@ class ReplyKeyboardRemove(JsonSerializable): class ReplyKeyboardMarkup(JsonSerializable): + max_row_keys = 12 + def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3): - if row_width>12: - logger.warning('Telegram does not support reply keyboard row width over 12') - row_width=12 + if row_width > self.max_row_keys: + # Todo: Will be replaced with Exception in future releases + logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) + row_width = self.max_row_keys self.resize_keyboard = resize_keyboard self.one_time_keyboard = one_time_keyboard @@ -830,12 +833,14 @@ class ReplyKeyboardMarkup(JsonSerializable): :param row_width: width of row :return: self, to allow function chaining. """ - row_width = row_width or self.row_width + if row_width is None: + row_width = self.row_width - if row_width>12: - logger.warning('Telegram does not support reply keyboard row width over 12') - row_width=12 + if row_width > self.max_row_keys: + # Todo: Will be replaced with Exception in future releases + logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) + row_width = self.max_row_keys for row in util.chunks(args, row_width): button_array = [] @@ -907,6 +912,8 @@ class KeyboardButtonPollType(Dictionaryable): class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): + max_row_keys = 12 + def __init__(self, row_width=3): """ This object represents an inline keyboard that appears @@ -914,9 +921,10 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): :return: """ - if row_width>8: - logger.warning('Telegram does not support inline keyboard row width over 8') - row_width=8 + 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) + row_width = self.max_row_keys self.row_width = row_width self.keyboard = [] @@ -936,11 +944,13 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): :param row_width: width of row :return: self, to allow function chaining. """ - row_width = row_width or self.row_width + if row_width is None: + row_width = self.row_width - if row_width>8: - logger.warning('Telegram does not support inline keyboard row width over 8') - row_width=8 + 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) + row_width = self.max_row_keys for row in util.chunks(args, row_width): button_array = [button.to_dict() for button in row] From c17a2379ba014d5c87352c9c0f2d48300f7f7398 Mon Sep 17 00:00:00 2001 From: "Mr. Dog" <68982655+mrpes@users.noreply.github.com> Date: Mon, 3 Aug 2020 06:39:12 +0500 Subject: [PATCH 017/350] Exceptions classes redesign followup --- telebot/apihelper.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 7603d17..3f3ddfd 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -105,7 +105,10 @@ def _make_request(token, method_name, method='get', params=None, files=None): timeout=(connect_timeout, read_timeout), proxies=proxy) logger.debug("The server returned: '{0}'".format(result.text.encode('utf8'))) - return _check_result(method_name, result)['result'] + + json_result = _check_result(method_name, result) + if json_result: + return json_result['result'] def _check_result(method_name, result): @@ -121,18 +124,18 @@ def _check_result(method_name, result): :param result: The returned result of the method request :return: The result parsed to a JSON dictionary. """ - if result.status_code != 200: - raise ApiHTTPException(method_name, result) - try: result_json = result.json() except: raise ApiInvalidJSONException(method_name, result) - - if not result_json['ok']: - raise ApiTelegramException(msg, method_name, result, result_json) - - return result_json + else: + if not result_json['ok']: + raise ApiTelegramException(method_name, result, result_json) + + elif result.status_code != 200: + raise ApiHTTPException(method_name, result) + + return result_json def get_me(token): @@ -1291,4 +1294,5 @@ class ApiTelegramException(ApiException): function_name, result) self.result_json = result_json + self.error_code = result_json['error_code'] From 1bb98483c282591766fcfccf04ec85749e4db7cc Mon Sep 17 00:00:00 2001 From: "Mr. Dog" <68982655+mrpes@users.noreply.github.com> Date: Tue, 4 Aug 2020 05:34:13 +0500 Subject: [PATCH 018/350] Update apihelper.py --- telebot/apihelper.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 3f3ddfd..964104a 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -127,14 +127,15 @@ def _check_result(method_name, result): try: result_json = result.json() except: - raise ApiInvalidJSONException(method_name, result) + if result.status_code != 200: + raise ApiHTTPException(method_name, result) + else: + raise ApiInvalidJSONException(method_name, result) + else: if not result_json['ok']: raise ApiTelegramException(method_name, result, result_json) - elif result.status_code != 200: - raise ApiHTTPException(method_name, result) - return result_json From a5fd407eb6a46608db0286ab7650665f8953087c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 4 Aug 2020 12:29:56 +0300 Subject: [PATCH 019/350] Bugfix and DISABLE_KEYLEN_ERROR Bugfix and DISABLE_KEYLEN_ERROR to supress keyboard length errors. --- telebot/apihelper.py | 3 +-- telebot/types.py | 9 +++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 7603d17..fa61fe6 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -11,7 +11,6 @@ from requests.exceptions import HTTPError, ConnectionError, Timeout try: from requests.packages.urllib3 import fields - format_header_param = fields.format_header_param except ImportError: format_header_param = None @@ -130,7 +129,7 @@ def _check_result(method_name, result): raise ApiInvalidJSONException(method_name, result) if not result_json['ok']: - raise ApiTelegramException(msg, method_name, result, result_json) + raise ApiTelegramException(method_name, result, result_json) return result_json diff --git a/telebot/types.py b/telebot/types.py index 3ea5e6e..4d35176 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -11,8 +11,11 @@ import six from telebot import util +DISABLE_KEYLEN_ERROR = False + logger = logging.getLogger('TeleBot') + class JsonSerializable(object): """ Subclasses of this class are guaranteed to be able to be converted to JSON format. @@ -813,7 +816,8 @@ class ReplyKeyboardMarkup(JsonSerializable): def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3): if row_width > self.max_row_keys: # Todo: Will be replaced with Exception in future releases - logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) + if not DISABLE_KEYLEN_ERROR: + logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) row_width = self.max_row_keys self.resize_keyboard = resize_keyboard @@ -839,7 +843,8 @@ class ReplyKeyboardMarkup(JsonSerializable): if row_width > self.max_row_keys: # Todo: Will be replaced with Exception in future releases - logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) + if not DISABLE_KEYLEN_ERROR: + logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) row_width = self.max_row_keys for row in util.chunks(args, row_width): From c6f51f6c5581cc3f60b6a2ee5c2955e39ef7523b Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 4 Aug 2020 18:28:35 +0300 Subject: [PATCH 020/350] CopyPaste bugfix --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 4d35176..8446202 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -917,7 +917,7 @@ class KeyboardButtonPollType(Dictionaryable): class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): - max_row_keys = 12 + max_row_keys = 8 def __init__(self, row_width=3): """ From ec79d1dc1ee1b5f0e377b58e2b97b45f64a46b6e Mon Sep 17 00:00:00 2001 From: "Mr. Dog" <68982655+mrpes@users.noreply.github.com> Date: Tue, 4 Aug 2020 23:45:33 +0500 Subject: [PATCH 021/350] Keyboard bugfix --- telebot/types.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 8446202..4ef068d 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -869,7 +869,7 @@ class ReplyKeyboardMarkup(JsonSerializable): :return: self, to allow function chaining. """ - return self.add(args, 12) + return self.add(*args, row_width=self.max_row_keys) def to_json(self): """ @@ -976,7 +976,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): :return: self, to allow function chaining. """ - return self.add(args, 8) + return self.add(*args, row_width=self.max_row_keys) def to_json(self): """ From 52511fce48810dbfe9ffc6eed2c05f35b0285d02 Mon Sep 17 00:00:00 2001 From: Andrea Barbagallo <66796758+barbax7@users.noreply.github.com> Date: Thu, 13 Aug 2020 12:14:57 +0200 Subject: [PATCH 022/350] Update README.md Added my bot to the list. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b106d1d..5a4a7a2 100644 --- a/README.md +++ b/README.md @@ -652,5 +652,6 @@ Get help. Discuss. Chat. * [Sporty](https://t.me/SportydBot) ([source](https://github.com/0xnu/sporty)) by @0xnu - Telegram bot for displaying the latest news, sports schedules and injury updates. * [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. * [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. +* [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 484c3a4c4829511173276959e5747681dd393be5 Mon Sep 17 00:00:00 2001 From: Akash Date: Fri, 14 Aug 2020 10:50:56 +0530 Subject: [PATCH 023/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5a4a7a2..59fa784 100644 --- a/README.md +++ b/README.md @@ -653,5 +653,6 @@ Get help. Discuss. Chat. * [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. * [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. * [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. +* [BlueProjects](https://t.me/BlueProjects) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Channel Where More Than 4 Wonderful Bots Are Listed Up!! Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 1cd36253f0872131f33be94f336a9fd4c21e6b44 Mon Sep 17 00:00:00 2001 From: Akash Date: Fri, 14 Aug 2020 11:36:04 +0530 Subject: [PATCH 024/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 59fa784..5ca5b55 100644 --- a/README.md +++ b/README.md @@ -653,6 +653,6 @@ Get help. Discuss. Chat. * [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. * [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. * [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. -* [BlueProjects](https://t.me/BlueProjects) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Channel Where More Than 4 Wonderful Bots Are Listed Up!! +* [BlueProjects](https://t.me/BlueProjects) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Channel Where More Than 4 Wonderful Bots Are Listed Up. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 2aaff09c39b2b742dd6f55d7c6a5915a790d7f88 Mon Sep 17 00:00:00 2001 From: Akash Date: Fri, 14 Aug 2020 11:38:57 +0530 Subject: [PATCH 025/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5ca5b55..66c9c09 100644 --- a/README.md +++ b/README.md @@ -653,6 +653,6 @@ Get help. Discuss. Chat. * [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. * [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. * [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. -* [BlueProjects](https://t.me/BlueProjects) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Channel Where More Than 4 Wonderful Bots Are Listed Up. +* [Blue_CC_Bot](https://t.me/Blue_CC_Bot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Checks Your Given Credit Cards And Says Which Is A Real,Card And Which Is Fake. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 3b57c288b4ca52cceb29925851e349a9688d1f29 Mon Sep 17 00:00:00 2001 From: Akash Date: Mon, 17 Aug 2020 14:08:20 +0530 Subject: [PATCH 026/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 66c9c09..6c68f84 100644 --- a/README.md +++ b/README.md @@ -654,5 +654,6 @@ Get help. Discuss. Chat. * [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. * [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. * [Blue_CC_Bot](https://t.me/Blue_CC_Bot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Checks Your Given Credit Cards And Says Which Is A Real,Card And Which Is Fake. +* [RandomInfoBot](https://t.me/RandomInfoBot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Generates Random Information Of Humans Scraped From Over 13 Websites. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 18eb8eb605a08f1a6851e9524cfcba921d65159c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 19 Aug 2020 23:57:48 +0300 Subject: [PATCH 027/350] Two None checks --- telebot/util.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index 7612ec4..67c6abf 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -191,6 +191,7 @@ def is_command(text): :param text: Text to check. :return: True if `text` is a command, else False. """ + if (text is None): return None return text.startswith('/') @@ -208,6 +209,7 @@ def extract_command(text): :param text: String to extract the command from :return: the command if `text` is a command (according to is_command), else None. """ + if (text is None): return None return text.split()[0].split('@')[0][1:] if is_command(text) else None From 8b50dc488b7131629ff4d6728a0075ee755c438f Mon Sep 17 00:00:00 2001 From: rf0x1d Date: Fri, 21 Aug 2020 11:09:43 +0300 Subject: [PATCH 028/350] added missing thumb params and more --- setup.py | 7 ++++++- telebot/__init__.py | 32 ++++++++++++++++++++------------ telebot/apihelper.py | 14 ++++++++++---- 3 files changed, 36 insertions(+), 17 deletions(-) diff --git a/setup.py b/setup.py index dc85d33..f176609 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,18 @@ #!/usr/bin/env python from setuptools import setup from io import open +import re def read(filename): with open(filename, encoding='utf-8') as file: return file.read() +with open('telebot/version.py', 'r', encoding='utf-8') as f: # Credits: LonamiWebs + version = re.search(r"^__version__\s*=\s*'(.*)'.*$", + f.read(), flags=re.MULTILINE).group(1) + setup(name='pyTelegramBotAPI', - version='3.7.2', + version=version, description='Python Telegram bot api. ', long_description=read('README.md'), long_description_content_type="text/markdown", diff --git a/telebot/__init__.py b/telebot/__init__.py index 44119ba..063163e 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -743,8 +743,8 @@ class TeleBot: apihelper.send_voice(self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout)) - def send_document(self, chat_id, data, reply_to_message_id=None, caption=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + def send_document(self, chat_id, data,reply_to_message_id=None, caption=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, thumb=None): """ Use this method to send general files. :param chat_id: @@ -755,13 +755,14 @@ class TeleBot: :param parse_mode: :param disable_notification: :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent :return: API reply. """ parse_mode = self.parse_mode if not parse_mode else parse_mode - return types.Message.de_json( + return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, caption=caption)) + parse_mode, disable_notification, timeout, caption, thumb)) def send_sticker( self, chat_id, data, reply_to_message_id=None, reply_markup=None, @@ -795,7 +796,9 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: - :param thumb: + :param thumb: InputFile or String : Thumbnail of the file sent + :param width: + :param height: :return: """ parse_mode = self.parse_mode if not parse_mode else parse_mode @@ -804,8 +807,10 @@ class TeleBot: apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height)) - def send_animation(self, chat_id, animation, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + def send_animation(self, chat_id, animation, duration=None, + caption=None, reply_to_message_id=None, + reply_markup=None, parse_mode=None, + disable_notification=None, timeout=None, thumb=None): """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -817,18 +822,20 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent :return: """ parse_mode = self.parse_mode if not parse_mode else parse_mode return types.Message.de_json( apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout)) + parse_mode, disable_notification, timeout, thumb)) - def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None): + def send_video_note(self, chat_id, data, duration=None, length=None, + reply_to_message_id=None, reply_markup=None, + disable_notification=None, timeout=None, thumb=None): """ - Use this method to send video files, Telegram clients support mp4 videos. + As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend a video that is already on the Telegram server :param duration: Integer : Duration of sent video in seconds @@ -837,11 +844,12 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent :return: """ return types.Message.de_json( apihelper.send_video_note(self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, - disable_notification, timeout)) + disable_notification, timeout, thumb)) def send_media_group( self, chat_id, media, diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 5d668ac..5561d3b 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -509,7 +509,7 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_to_messa def send_animation(token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None, thumb=None): method_url = r'sendAnimation' payload = {'chat_id': chat_id} files = None @@ -531,6 +531,8 @@ def send_animation(token, chat_id, data, duration=None, caption=None, reply_to_m payload['disable_notification'] = disable_notification if timeout: payload['connect-timeout'] = timeout + if thumb: + payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -561,7 +563,7 @@ def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_mess def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None): + disable_notification=None, timeout=None, thumb=None): method_url = r'sendVideoNote' payload = {'chat_id': chat_id} files = None @@ -571,7 +573,7 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m payload['video_note'] = data if duration: payload['duration'] = duration - if length: + if length and (str(length).isdigit() and int(length) <= 639): payload['length'] = length else: payload['length'] = 639 # seems like it is MAX length size @@ -583,6 +585,8 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m payload['disable_notification'] = disable_notification if timeout: payload['connect-timeout'] = timeout + if thumb: + payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -622,7 +626,7 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, - disable_notification=None, timeout=None, caption=None): + disable_notification=None, timeout=None, caption=None, thumb=None): method_url = get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None @@ -642,6 +646,8 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m payload['connect-timeout'] = timeout if caption: payload['caption'] = caption + if thumb: + payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') From 0ab4046a4f58bdbb2a91cc0995011b205d432098 Mon Sep 17 00:00:00 2001 From: rf0x1d Date: Fri, 21 Aug 2020 11:09:53 +0300 Subject: [PATCH 029/350] Create version.py --- telebot/version.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 telebot/version.py diff --git a/telebot/version.py b/telebot/version.py new file mode 100644 index 0000000..92aad92 --- /dev/null +++ b/telebot/version.py @@ -0,0 +1,3 @@ +# Versions should comply with PEP440. +# This line is parsed in setup.py: +__version__ = '3.7.3' From 9ca3c78c84496cae42ad665e6a2e65c6e859d91d Mon Sep 17 00:00:00 2001 From: rf0x1d Date: Fri, 21 Aug 2020 11:22:24 +0300 Subject: [PATCH 030/350] back version to 3.7.2 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 92aad92..da7bcf9 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.3' +__version__ = '3.7.2' From cab33ad0d90a3443806a8a861669543c3e080792 Mon Sep 17 00:00:00 2001 From: rf0x1d Date: Fri, 21 Aug 2020 14:09:38 +0300 Subject: [PATCH 031/350] fixed thumb processing --- telebot/apihelper.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 5561d3b..5d84add 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -532,7 +532,10 @@ def send_animation(token, chat_id, data, duration=None, caption=None, reply_to_m if timeout: payload['connect-timeout'] = timeout if thumb: - payload['thumb'] = thumb + if not util.is_string(thumb): + files['thumb'] = thumb + else: + payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -586,7 +589,10 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m if timeout: payload['connect-timeout'] = timeout if thumb: - payload['thumb'] = thumb + if not util.is_string(thumb): + files['thumb'] = thumb + else: + payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -647,7 +653,10 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m if caption: payload['caption'] = caption if thumb: - payload['thumb'] = thumb + if not util.is_string(thumb): + files['thumb'] = thumb + else: + payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') From 73487f96c4697fe3b88d4bed80a27d6386407ee4 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Fri, 21 Aug 2020 17:36:08 +0300 Subject: [PATCH 032/350] Custom exception handler for poll mode Initial beta of custom exception handler for poll mode. Use ExceptionHandler class and bot.exception_handler to proceed unhandled exceptions in poll mode. --- telebot/__init__.py | 91 +++++++++++++++++++++++++++++++++++--------- telebot/apihelper.py | 3 +- 2 files changed, 75 insertions(+), 19 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 44119ba..f7ee2ae 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -42,6 +42,15 @@ class Handler: return getattr(self, item) +class ExceptionHandler: + """ + Class for handling exceptions while Polling + """ + + def handle(self, exception): + return False + + class TeleBot: """ This is TeleBot Class Methods: @@ -86,7 +95,7 @@ class TeleBot: def __init__( self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, - next_step_backend=None, reply_backend=None + next_step_backend=None, reply_backend=None, exception_handler=None ): """ :param token: bot API token @@ -111,6 +120,8 @@ class TeleBot: if not self.reply_backend: self.reply_backend = MemoryHandlerBackend() + self.exception_handler = exception_handler + self.message_handlers = [] self.edited_message_handlers = [] self.channel_post_handlers = [] @@ -452,20 +463,41 @@ class TeleBot: error_interval = 0.25 except apihelper.ApiException as e: - logger.error(e) - if not none_stop: - self.__stop_polling.set() - logger.info("Exception occurred. Stopping.") + if self.exception_handler is not None: + handled = self.exception_handler.handle(e) + else: + handled = False + + if not handled: + logger.error(e) + if not none_stop: + self.__stop_polling.set() + logger.info("Exception occurred. Stopping.") + else: + polling_thread.clear_exceptions() + self.worker_pool.clear_exceptions() + logger.info("Waiting for {0} seconds until retry".format(error_interval)) + time.sleep(error_interval) + error_interval *= 2 else: polling_thread.clear_exceptions() self.worker_pool.clear_exceptions() - logger.info("Waiting for {0} seconds until retry".format(error_interval)) time.sleep(error_interval) - error_interval *= 2 except KeyboardInterrupt: logger.info("KeyboardInterrupt received.") self.__stop_polling.set() break + except Exception as e: + if self.exception_handler is not None: + handled = self.exception_handler.handle(e) + else: + handled = False + if not handled: + raise e + else: + polling_thread.clear_exceptions() + self.worker_pool.clear_exceptions() + time.sleep(error_interval) polling_thread.stop() logger.info('Stopped polling.') @@ -480,18 +512,35 @@ class TeleBot: self.__retrieve_updates(timeout) error_interval = 0.25 except apihelper.ApiException as e: - logger.error(e) - if not none_stop: - self.__stop_polling.set() - logger.info("Exception occurred. Stopping.") + if self.exception_handler is not None: + handled = self.exception_handler.handle(e) + else: + handled = False + + if not handled: + logger.error(e) + if not none_stop: + self.__stop_polling.set() + logger.info("Exception occurred. Stopping.") + else: + logger.info("Waiting for {0} seconds until retry".format(error_interval)) + time.sleep(error_interval) + error_interval *= 2 else: - logger.info("Waiting for {0} seconds until retry".format(error_interval)) time.sleep(error_interval) - error_interval *= 2 except KeyboardInterrupt: logger.info("KeyboardInterrupt received.") self.__stop_polling.set() break + except Exception as e: + if self.exception_handler is not None: + handled = self.exception_handler.handle(e) + else: + handled = False + if not handled: + raise e + else: + time.sleep(error_interval) logger.info('Stopped polling.') @@ -805,7 +854,7 @@ class TeleBot: parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height)) def send_animation(self, chat_id, animation, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None): """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -823,7 +872,7 @@ class TeleBot: return types.Message.de_json( apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout)) + parse_mode, disable_notification, timeout)) def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=None, timeout=None): @@ -1055,7 +1104,6 @@ class TeleBot: """ return apihelper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) - def set_chat_permissions(self, chat_id, permissions): """ Use this method to set default chat permissions for all members. @@ -1270,7 +1318,7 @@ class TeleBot: def send_invoice(self, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, - send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, + send_phone_number_to_provider=None, send_email_to_provider=None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, timeout=None): """ Sends invoice @@ -1386,7 +1434,7 @@ class TeleBot: :return: """ parse_mode = self.parse_mode if not parse_mode else parse_mode - + result = apihelper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, parse_mode, reply_markup) if type(result) == bool: @@ -1837,6 +1885,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_inline_handler(handler_dict) @@ -1859,6 +1908,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_chosen_inline_handler(handler_dict) @@ -1881,6 +1931,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_callback_query_handler(handler_dict) @@ -1903,6 +1954,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_shipping_query_handler(handler_dict) @@ -1925,6 +1977,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_pre_checkout_query_handler(handler_dict) @@ -1947,6 +2000,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_poll_handler(handler_dict) @@ -1969,6 +2023,7 @@ class TeleBot: :param kwargs: :return: """ + def decorator(handler): handler_dict = self._build_handler_dict(handler, func=func, **kwargs) self.add_poll_answer_handler(handler_dict) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 5d668ac..90c6134 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -975,6 +975,7 @@ def send_invoice( :param reply_to_message_id: If the message is a reply, ID of the original message :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param timeout: :return: """ method_url = r'sendInvoice' @@ -1288,7 +1289,7 @@ class ApiTelegramException(ApiException): """ def __init__(self, function_name, result, result_json): super(ApiTelegramException, self).__init__( - "Error code: {0} Description: {1}" \ + "Error code: {0}. Description: {1}" \ .format(result_json['error_code'], result_json['description']), function_name, result) From 5b70980bda3d6414705a4040179440ff51ce648a Mon Sep 17 00:00:00 2001 From: Badiboy Date: Fri, 21 Aug 2020 17:38:54 +0300 Subject: [PATCH 033/350] Resolve conflicts --- telebot/__init__.py | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f7ee2ae..589d443 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -792,8 +792,8 @@ class TeleBot: apihelper.send_voice(self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout)) - def send_document(self, chat_id, data, reply_to_message_id=None, caption=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + def send_document(self, chat_id, data,reply_to_message_id=None, caption=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, thumb=None): """ Use this method to send general files. :param chat_id: @@ -804,13 +804,14 @@ class TeleBot: :param parse_mode: :param disable_notification: :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent :return: API reply. """ parse_mode = self.parse_mode if not parse_mode else parse_mode - return types.Message.de_json( + return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, caption=caption)) + parse_mode, disable_notification, timeout, caption, thumb)) def send_sticker( self, chat_id, data, reply_to_message_id=None, reply_markup=None, @@ -844,7 +845,9 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: - :param thumb: + :param thumb: InputFile or String : Thumbnail of the file sent + :param width: + :param height: :return: """ parse_mode = self.parse_mode if not parse_mode else parse_mode @@ -853,8 +856,10 @@ class TeleBot: apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height)) - def send_animation(self, chat_id, animation, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + def send_animation(self, chat_id, animation, duration=None, + caption=None, reply_to_message_id=None, + reply_markup=None, parse_mode=None, + disable_notification=None, timeout=None, thumb=None): """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -866,18 +871,20 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent :return: """ parse_mode = self.parse_mode if not parse_mode else parse_mode return types.Message.de_json( apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout)) + parse_mode, disable_notification, timeout, thumb)) - def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None): + def send_video_note(self, chat_id, data, duration=None, length=None, + reply_to_message_id=None, reply_markup=None, + disable_notification=None, timeout=None, thumb=None): """ - Use this method to send video files, Telegram clients support mp4 videos. + As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend a video that is already on the Telegram server :param duration: Integer : Duration of sent video in seconds @@ -886,11 +893,12 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent :return: """ return types.Message.de_json( apihelper.send_video_note(self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, - disable_notification, timeout)) + disable_notification, timeout, thumb)) def send_media_group( self, chat_id, media, From 5e19965b0c42c55fe7561a3b94b42ca25c2d685f Mon Sep 17 00:00:00 2001 From: Florent Gallaire Date: Sat, 22 Aug 2020 16:11:52 +0200 Subject: [PATCH 034/350] Fix 'NoneType' object assignment error from #892 and #954 --- telebot/apihelper.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 5d84add..e75ed53 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -498,7 +498,10 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_to_messa payload['connect-timeout'] = timeout if thumb: if not util.is_string(thumb): - files['thumb'] = thumb + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} else: payload['thumb'] = thumb if width: @@ -533,7 +536,10 @@ def send_animation(token, chat_id, data, duration=None, caption=None, reply_to_m payload['connect-timeout'] = timeout if thumb: if not util.is_string(thumb): - files['thumb'] = thumb + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} else: payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -590,7 +596,10 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m payload['connect-timeout'] = timeout if thumb: if not util.is_string(thumb): - files['thumb'] = thumb + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} else: payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -625,7 +634,10 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non payload['connect-timeout'] = timeout if thumb: if not util.is_string(thumb): - files['thumb'] = thumb + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} else: payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') @@ -654,7 +666,10 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m payload['caption'] = caption if thumb: if not util.is_string(thumb): - files['thumb'] = thumb + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} else: payload['thumb'] = thumb return _make_request(token, method_url, params=payload, files=files, method='post') From cdd48c7aed0d2a9223e326c2e3ab0b9400f1d3f4 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 24 Aug 2020 16:02:35 +0300 Subject: [PATCH 035/350] Empty list optimization, Py2 arteacts removed, Empty list optimization: None instead of []. Py2 arteacts removed: no more six moudle used. --- requirements.txt | 1 - setup.py | 2 +- telebot/__init__.py | 129 ++++++++++++++++++++---------------- telebot/handler_backends.py | 18 +++-- telebot/types.py | 6 +- telebot/util.py | 33 ++++----- telebot/version.py | 2 +- 7 files changed, 97 insertions(+), 94 deletions(-) diff --git a/requirements.txt b/requirements.txt index 6e4ca40..a38fc09 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,4 @@ py==1.4.29 pytest==3.0.2 requests==2.20.0 -six==1.9.0 wheel==0.24.0 diff --git a/setup.py b/setup.py index f176609..b3e8158 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ setup(name='pyTelegramBotAPI', packages=['telebot'], license='GPL2', keywords='telegram bot api tools', - install_requires=['requests', 'six'], + install_requires=['requests'], extras_require={ 'json': 'ujson', 'redis': 'redis>=3.4.1' diff --git a/telebot/__init__.py b/telebot/__init__.py index 1811633..3ca0cfe 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -7,8 +7,6 @@ import sys import threading import time -import six - logger = logging.getLogger('TeleBot') formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' @@ -134,20 +132,20 @@ class TeleBot: self.poll_handlers = [] self.poll_answer_handlers = [] - self.typed_middleware_handlers = { - 'message': [], - 'edited_message': [], - 'channel_post': [], - 'edited_channel_post': [], - 'inline_query': [], - 'chosen_inline_result': [], - 'callback_query': [], - 'shipping_query': [], - 'pre_checkout_query': [], - 'poll': [], - } - - self.default_middleware_handlers = [] + if apihelper.ENABLE_MIDDLEWARE: + self.typed_middleware_handlers = { + 'message': [], + 'edited_message': [], + 'channel_post': [], + 'edited_channel_post': [], + 'inline_query': [], + 'chosen_inline_result': [], + 'callback_query': [], + 'shipping_query': [], + 'pre_checkout_query': [], + 'poll': [], + } + self.default_middleware_handlers = [] self.threaded = threaded if self.threaded: @@ -297,17 +295,22 @@ class TeleBot: self.process_new_updates(updates) def process_new_updates(self, updates): - new_messages = [] - new_edited_messages = [] - new_channel_posts = [] - new_edited_channel_posts = [] - new_inline_querys = [] - new_chosen_inline_results = [] - new_callback_querys = [] - new_shipping_querys = [] - new_pre_checkout_querys = [] - new_polls = [] - new_poll_answers = [] + upd_count = len(updates) + logger.debug('Received {0} new updates'.format(upd_count)) + if (upd_count == 0): + return + + new_messages = None + new_edited_messages = None + new_channel_posts = None + new_edited_channel_posts = None + new_inline_queries = None + new_chosen_inline_results = None + new_callback_queries = None + new_shipping_queries = None + new_pre_checkout_queries = None + new_polls = None + new_poll_answers = None for update in updates: if apihelper.ENABLE_MIDDLEWARE: @@ -316,50 +319,60 @@ class TeleBot: if update.update_id > self.last_update_id: self.last_update_id = update.update_id if update.message: + if new_messages is None: new_messages = [] new_messages.append(update.message) if update.edited_message: + if new_edited_messages is None: new_edited_messages = [] new_edited_messages.append(update.edited_message) if update.channel_post: + if new_channel_posts is None: new_channel_posts = [] new_channel_posts.append(update.channel_post) if update.edited_channel_post: + if new_edited_channel_posts is None: new_edited_channel_posts = [] new_edited_channel_posts.append(update.edited_channel_post) if update.inline_query: - new_inline_querys.append(update.inline_query) + if new_inline_queries is None: new_inline_queries = [] + new_inline_queries.append(update.inline_query) if update.chosen_inline_result: + if new_chosen_inline_results is None: new_chosen_inline_results = [] new_chosen_inline_results.append(update.chosen_inline_result) if update.callback_query: - new_callback_querys.append(update.callback_query) + if new_callback_queries is None: new_callback_queries = [] + new_callback_queries.append(update.callback_query) if update.shipping_query: - new_shipping_querys.append(update.shipping_query) + if new_shipping_queries is None: new_shipping_queries = [] + new_shipping_queries.append(update.shipping_query) if update.pre_checkout_query: - new_pre_checkout_querys.append(update.pre_checkout_query) + if new_pre_checkout_queries is None: new_pre_checkout_queries = [] + new_pre_checkout_queries.append(update.pre_checkout_query) if update.poll: + if new_polls is None: new_polls = [] new_polls.append(update.poll) if update.poll_answer: + if new_poll_answers is None: new_poll_answers = [] new_poll_answers.append(update.poll_answer) - logger.debug('Received {0} new updates'.format(len(updates))) - if len(new_messages) > 0: + if new_messages: self.process_new_messages(new_messages) - if len(new_edited_messages) > 0: + if new_edited_messages: self.process_new_edited_messages(new_edited_messages) - if len(new_channel_posts) > 0: + if new_channel_posts: self.process_new_channel_posts(new_channel_posts) - if len(new_edited_channel_posts) > 0: + if new_edited_channel_posts: self.process_new_edited_channel_posts(new_edited_channel_posts) - if len(new_inline_querys) > 0: - self.process_new_inline_query(new_inline_querys) - if len(new_chosen_inline_results) > 0: + if new_inline_queries: + self.process_new_inline_query(new_inline_queries) + if new_chosen_inline_results: self.process_new_chosen_inline_query(new_chosen_inline_results) - if len(new_callback_querys) > 0: - self.process_new_callback_query(new_callback_querys) - if len(new_shipping_querys) > 0: - self.process_new_shipping_query(new_shipping_querys) - if len(new_pre_checkout_querys) > 0: - self.process_new_pre_checkout_query(new_pre_checkout_querys) - if len(new_polls) > 0: + if new_callback_queries: + self.process_new_callback_query(new_callback_queries) + if new_shipping_queries: + self.process_new_shipping_query(new_shipping_queries) + if new_pre_checkout_queries: + self.process_new_pre_checkout_query(new_pre_checkout_queries) + if new_polls: self.process_new_poll(new_polls) - if len(new_poll_answers) > 0: + if new_poll_answers: self.process_new_poll_answer(new_poll_answers) def process_new_messages(self, new_messages): @@ -409,6 +422,8 @@ class TeleBot: default_middleware_handler(self, update) def __notify_update(self, new_messages): + if len(self.update_listener) == 0: + return for listener in self.update_listener: self._exec_task(listener, new_messages) @@ -1590,8 +1605,9 @@ class TeleBot: for message in new_messages: if hasattr(message, "reply_to_message") and message.reply_to_message is not None: handlers = self.reply_backend.get_handlers(message.reply_to_message.message_id) - for handler in handlers: - self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) + if handlers: + for handler in handlers: + self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) def register_next_step_handler(self, message, callback, *args, **kwargs): """ @@ -1663,11 +1679,12 @@ class TeleBot: for i, message in enumerate(new_messages): need_pop = False handlers = self.next_step_backend.get_handlers(message.chat.id) - for handler in handlers: - need_pop = True - self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) + if handlers: + for handler in handlers: + need_pop = True + self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) if need_pop: - new_messages.pop(i) # removing message that detects with next_step_handler + new_messages.pop(i) # removing message that was detected with next_step_handler @staticmethod def _build_handler_dict(handler, **filters): @@ -1769,9 +1786,7 @@ class TeleBot: func=func, content_types=content_types, **kwargs) - self.add_message_handler(handler_dict) - return handler return decorator @@ -2054,7 +2069,7 @@ class TeleBot: :param message: :return: """ - for message_filter, filter_value in six.iteritems(message_handler['filters']): + for message_filter, filter_value in message_handler['filters'].items(): if filter_value is None: continue @@ -2088,6 +2103,8 @@ class TeleBot: :param new_messages: :return: """ + if len(handlers) == 0: + return for message in new_messages: for message_handler in handlers: if self._test_message_handler(message_handler, message): diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index e71fb24..a10d13c 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -32,10 +32,13 @@ class MemoryHandlerBackend(HandlerBackend): self.handlers[handler_group_id] = [handler] def clear_handlers(self, handler_group_id): - self.handlers.pop(handler_group_id, []) + self.handlers.pop(handler_group_id, None) def get_handlers(self, handler_group_id): - return self.handlers.pop(handler_group_id, []) + return self.handlers.pop(handler_group_id, None) + + def load_handlers(self, filename, del_file_after_loading): + raise NotImplementedError() class FileHandlerBackend(HandlerBackend): @@ -50,19 +53,15 @@ class FileHandlerBackend(HandlerBackend): self.handlers[handler_group_id].append(handler) else: self.handlers[handler_group_id] = [handler] - self.start_save_timer() def clear_handlers(self, handler_group_id): - self.handlers.pop(handler_group_id, []) - + self.handlers.pop(handler_group_id, None) self.start_save_timer() def get_handlers(self, handler_group_id): - handlers = self.handlers.pop(handler_group_id, []) - + handlers = self.handlers.pop(handler_group_id, None) self.start_save_timer() - return handlers def start_save_timer(self): @@ -136,10 +135,9 @@ class RedisHandlerBackend(HandlerBackend): self.redis.delete(self._key(handler_group_id)) def get_handlers(self, handler_group_id): - handlers = [] + handlers = None value = self.redis.get(self._key(handler_group_id)) if value: handlers = pickle.loads(value) self.clear_handlers(handler_group_id) - return handlers diff --git a/telebot/types.py b/telebot/types.py index 4ef068d..d00cb6d 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -7,8 +7,6 @@ try: except ImportError: import json -import six - from telebot import util DISABLE_KEYLEN_ERROR = False @@ -81,13 +79,13 @@ class JsonDeserializable(object): def __str__(self): d = {} - for x, y in six.iteritems(self.__dict__): + for x, y in self.__dict__.items(): if hasattr(y, '__dict__'): d[x] = y.__dict__ else: d[x] = y - return six.text_type(d) + return str(d) class Update(JsonDeserializable): diff --git a/telebot/util.py b/telebot/util.py index 67c6abf..099828a 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -2,21 +2,12 @@ import random import re import string -import sys import threading import traceback import warnings import functools -import six -from six import string_types - -# Python3 queue support. - -try: - import Queue -except ImportError: - import queue as Queue +import queue as Queue import logging try: @@ -51,7 +42,7 @@ class WorkerThread(threading.Thread): self.continue_event = threading.Event() self.exception_callback = exception_callback - self.exc_info = None + self.exception_info = None self._running = True self.start() @@ -73,11 +64,11 @@ class WorkerThread(threading.Thread): pass except Exception as e: logger.error(type(e).__name__ + " occurred, args=" + str(e.args) + "\n" + traceback.format_exc()) - self.exc_info = sys.exc_info() + self.exception_info = e self.exception_event.set() if self.exception_callback: - self.exception_callback(self, self.exc_info) + self.exception_callback(self, self.exception_info) self.continue_event.wait() def put(self, task, *args, **kwargs): @@ -85,7 +76,7 @@ class WorkerThread(threading.Thread): def raise_exceptions(self): if self.exception_event.is_set(): - six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) + raise self.exception_info def clear_exceptions(self): self.exception_event.clear() @@ -103,19 +94,19 @@ class ThreadPool: self.num_threads = num_threads self.exception_event = threading.Event() - self.exc_info = None + self.exception_info = None def put(self, func, *args, **kwargs): self.tasks.put((func, args, kwargs)) def on_exception(self, worker_thread, exc_info): - self.exc_info = exc_info + self.exception_info = exc_info self.exception_event.set() worker_thread.continue_event.set() def raise_exceptions(self): if self.exception_event.is_set(): - six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) + raise self.exception_info def clear_exceptions(self): self.exception_event.clear() @@ -140,15 +131,15 @@ class AsyncTask: def _run(self): try: self.result = self.target(*self.args, **self.kwargs) - except: - self.result = sys.exc_info() + except Exception as e: + self.result = e self.done = True def wait(self): if not self.done: self.thread.join() if isinstance(self.result, BaseException): - six.reraise(self.result[0], self.result[1], self.result[2]) + raise self.result else: return self.result @@ -164,7 +155,7 @@ def async_dec(): def is_string(var): - return isinstance(var, string_types) + return isinstance(var, str) def is_dict(var): return isinstance(var, dict) diff --git a/telebot/version.py b/telebot/version.py index da7bcf9..92aad92 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.2' +__version__ = '3.7.3' From 48b53f6a8ec9585270ab78eed28d2ece28551e1d Mon Sep 17 00:00:00 2001 From: eternnoir Date: Mon, 24 Aug 2020 21:36:27 +0800 Subject: [PATCH 036/350] Update version.X --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index da7bcf9..92aad92 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.2' +__version__ = '3.7.3' From 8cd18945c506971e04f26c426e56c3fecb416a99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20D=C3=A1vila=20Herrero?= Date: Tue, 25 Aug 2020 15:45:08 +0200 Subject: [PATCH 037/350] Append bots to list TasksListsBot MyElizaPsychologistBot --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 6c68f84..9285c4e 100644 --- a/README.md +++ b/README.md @@ -655,5 +655,7 @@ Get help. Discuss. Chat. * [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. * [Blue_CC_Bot](https://t.me/Blue_CC_Bot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Checks Your Given Credit Cards And Says Which Is A Real,Card And Which Is Fake. * [RandomInfoBot](https://t.me/RandomInfoBot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Generates Random Information Of Humans Scraped From Over 13 Websites. +* [TasksListsBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/TasksListsBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - A (tasks) lists manager bot for Telegram. +* [MyElizaPsychologistBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/MyElizaPsychologistBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - An implementation of the famous Eliza psychologist chatbot. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From bab9b4077d159fad6607e707ce30e8c574de31f2 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 25 Aug 2020 18:18:51 +0300 Subject: [PATCH 038/350] Bot API support checked/updated up to 4.2 --- README.md | 7 +++++- telebot/__init__.py | 34 +++++++++++++++++-------- telebot/apihelper.py | 11 +++++--- telebot/types.py | 60 ++++++++++++++++++++++++++++++-------------- tests/test_types.py | 2 +- 5 files changed, 79 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 9285c4e..59a3dbf 100644 --- a/README.md +++ b/README.md @@ -539,8 +539,13 @@ apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'} _Checking is in progress..._ -✅ [Bot API 3.5](https://core.telegram.org/bots/api-changelog#november-17-2017) _- To be checked..._ +✅ [Bot API 4.3](https://core.telegram.org/bots/api-changelog#may-31-2019) _- To be checked..._ +* ✔ [Bot API 4.2](https://core.telegram.org/bots/api-changelog#april-14-2019) +* ➕ [Bot API 4.1](https://core.telegram.org/bots/api-changelog#august-27-2018) - No Passport support. +* ➕ [Bot API 4.0](https://core.telegram.org/bots/api-changelog#july-26-2018) - No Passport support. +* ✔ [Bot API 3.6](https://core.telegram.org/bots/api-changelog#february-13-2018) +* ✔ [Bot API 3.5](https://core.telegram.org/bots/api-changelog#november-17-2017) * ✔ [Bot API 3.4](https://core.telegram.org/bots/api-changelog#october-11-2017) * ✔ [Bot API 3.3](https://core.telegram.org/bots/api-changelog#august-23-2017) * ✔ [Bot API 3.2](https://core.telegram.org/bots/api-changelog#july-21-2017) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3ca0cfe..1c74d02 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -711,6 +711,7 @@ class TeleBot: :param chat_id: which chat to forward :param from_chat_id: which chat message from :param message_id: message id + :param timeout: :return: API reply. """ return types.Message.de_json( @@ -721,6 +722,7 @@ class TeleBot: Use this method to delete message. Returns True on success. :param chat_id: in which chat to delete :param message_id: which message to delete + :param timeout: :return: API reply. """ return apihelper.delete_message(self.token, chat_id, message_id, timeout) @@ -736,6 +738,7 @@ class TeleBot: :param disable_notification: :param reply_to_message_id: :param reply_markup: + :param timeout: :return: Message """ return types.Message.de_json( @@ -755,6 +758,7 @@ class TeleBot: :param parse_mode :param reply_to_message_id: :param reply_markup: + :param timeout: :return: API reply. """ parse_mode = self.parse_mode if not parse_mode else parse_mode @@ -924,6 +928,7 @@ class TeleBot: :param media: :param disable_notification: :param reply_to_message_id: + :param timeout: :return: """ result = apihelper.send_media_group( @@ -945,6 +950,7 @@ class TeleBot: :param reply_to_message_id: :param reply_markup: :param disable_notification: + :param timeout: :return: API reply. """ return types.Message.de_json( @@ -962,6 +968,7 @@ class TeleBot: :param message_id: :param inline_message_id: :param reply_markup: + :param timeout: :return: """ return types.Message.de_json( @@ -979,6 +986,7 @@ class TeleBot: :param message_id: :param inline_message_id: :param reply_markup: + :param timeout: :return: """ return types.Message.de_json( @@ -986,8 +994,8 @@ class TeleBot: self.token, chat_id, message_id, inline_message_id, reply_markup, timeout)) def send_venue( - self, chat_id, latitude, longitude, title, address, foursquare_id=None, disable_notification=None, - reply_to_message_id=None, reply_markup=None, timeout=None): + self, chat_id, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): """ Use this method to send information about a venue. :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel @@ -996,25 +1004,26 @@ class TeleBot: :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/default”, “arts_entertainment/aquarium” or “food/icecream”.) :param disable_notification: :param reply_to_message_id: :param reply_markup: + :param timeout: :return: """ return types.Message.de_json( apihelper.send_venue( - self.token, chat_id, latitude, longitude, title, address, foursquare_id, + self.token, chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, disable_notification, reply_to_message_id, reply_markup, timeout) ) def send_contact( - self, chat_id, phone_number, first_name, - last_name=None, disable_notification=None, - reply_to_message_id=None, reply_markup=None, timeout=None): + self, chat_id, phone_number, first_name, last_name=None, vcard=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): return types.Message.de_json( apihelper.send_contact( - self.token, chat_id, phone_number, first_name, last_name, disable_notification, - reply_to_message_id, reply_markup, timeout) + self.token, chat_id, phone_number, first_name, last_name, vcard, + disable_notification, reply_to_message_id, reply_markup, timeout) ) def send_chat_action(self, chat_id, action, timeout=None): @@ -1025,6 +1034,7 @@ class TeleBot: :param chat_id: :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', 'upload_video_note'. + :param timeout: :return: API reply. :type: boolean """ return apihelper.send_chat_action(self.token, chat_id, action, timeout) @@ -1297,6 +1307,7 @@ class TeleBot: :param disable_notification: :param reply_to_message_id: :param reply_markup: + :param timeout: :return: """ result = apihelper.send_game( @@ -1368,6 +1379,7 @@ class TeleBot: :param reply_to_message_id: If the message is a reply, ID of the original message :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param timeout: :return: """ result = apihelper.send_invoice( @@ -1400,6 +1412,7 @@ class TeleBot: :param disable_notifications: :param reply_to_message_id: :param reply_markup: + :param timeout: :return: """ @@ -1414,14 +1427,15 @@ class TeleBot: explanation, explanation_parse_mode, open_period, close_date, is_closed, disable_notifications, reply_to_message_id, reply_markup, timeout)) - def stop_poll(self, chat_id, message_id): + def stop_poll(self, chat_id, message_id, reply_markup=None): """ Stops poll :param chat_id: :param message_id: + :param reply_markup: :return: """ - return types.Poll.de_json(apihelper.stop_poll(self.token, chat_id, message_id)) + return types.Poll.de_json(apihelper.stop_poll(self.token, chat_id, message_id, reply_markup)) def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None): """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 70c3f26..b80a627 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -427,12 +427,14 @@ def stop_message_live_location( def send_venue( token, chat_id, latitude, longitude, title, address, - foursquare_id=None, disable_notification=None, + foursquare_id=None, foursquare_type=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): method_url = r'sendVenue' payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address} if foursquare_id: payload['foursquare_id'] = foursquare_id + if foursquare_type: + payload['foursquare_type'] = foursquare_type if disable_notification is not None: payload['disable_notification'] = disable_notification if reply_to_message_id: @@ -445,13 +447,14 @@ def send_venue( def send_contact( - token, chat_id, phone_number, first_name, - last_name=None, disable_notification=None, - reply_to_message_id=None, reply_markup=None, timeout=None): + token, chat_id, phone_number, first_name, last_name=None, vcard=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): method_url = r'sendContact' payload = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name} if last_name: payload['last_name'] = last_name + if vcard: + payload['vcard'] = vcard if disable_notification is not None: payload['disable_notification'] = disable_notification if reply_to_message_id: diff --git a/telebot/types.py b/telebot/types.py index d00cb6d..55689a6 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -274,6 +274,8 @@ class Message(JsonDeserializable): opts['forward_from_message_id'] = obj.get('forward_from_message_id') if 'forward_signature' in obj: opts['forward_signature'] = obj.get('forward_signature') + if 'forward_sender_name' in obj: + opts['forward_sender_name'] = obj.get('forward_sender_name') if 'forward_date' in obj: opts['forward_date'] = obj.get('forward_date') if 'reply_to_message' in obj: @@ -416,6 +418,7 @@ class Message(JsonDeserializable): self.forward_from_chat = None self.forward_from_message_id = None self.forward_signature = None + self.forward_sender_name = None self.forward_date = None self.reply_to_message = None self.edit_date = None @@ -544,14 +547,16 @@ class MessageEntity(JsonDeserializable): length = obj['length'] url = obj.get('url') user = User.de_json(obj.get('user')) - return cls(type, offset, length, url, user) + language = obj.get('language') + return cls(type, offset, length, url, user, language) - def __init__(self, type, offset, length, url=None, user=None): + def __init__(self, type, offset, length, url=None, user=None, language=None): self.type = type self.offset = offset self.length = length self.url = url self.user = user + self.language = language class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): @@ -711,13 +716,15 @@ class Contact(JsonDeserializable): first_name = obj['first_name'] last_name = obj.get('last_name') user_id = obj.get('user_id') - return cls(phone_number, first_name, last_name, user_id) + vcard = obj.get('vcard') + return cls(phone_number, first_name, last_name, user_id, vcard) - def __init__(self, phone_number, first_name, last_name=None, user_id=None): + def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None): self.phone_number = phone_number self.first_name = first_name self.last_name = last_name self.user_id = user_id + self.vcard = vcard class Location(JsonDeserializable): @@ -745,13 +752,15 @@ class Venue(JsonDeserializable): title = obj['title'] address = obj['address'] foursquare_id = obj.get('foursquare_id') - return cls(location, title, address, foursquare_id) + foursquare_type = obj.get('foursquare_type') + return cls(location, title, address, foursquare_id, foursquare_type) - def __init__(self, location, title, address, foursquare_id=None): + def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None): self.location = location self.title = title self.address = address self.foursquare_id = foursquare_id + self.foursquare_type = foursquare_type class UserProfilePhotos(JsonDeserializable): @@ -1281,12 +1290,13 @@ class InputLocationMessageContent(Dictionaryable): class InputVenueMessageContent(Dictionaryable): - def __init__(self, latitude, longitude, title, address, foursquare_id=None): + def __init__(self, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None): self.latitude = latitude self.longitude = longitude self.title = title self.address = address self.foursquare_id = foursquare_id + self.foursquare_type = foursquare_type def to_dict(self): json_dict = { @@ -1297,19 +1307,24 @@ class InputVenueMessageContent(Dictionaryable): } if self.foursquare_id: json_dict['foursquare_id'] = self.foursquare_id + if self.foursquare_type: + json_dict['foursquare_type'] = self.foursquare_type return json_dict class InputContactMessageContent(Dictionaryable): - def __init__(self, phone_number, first_name, last_name=None): + def __init__(self, phone_number, first_name, last_name=None, vcard=None): self.phone_number = phone_number self.first_name = first_name self.last_name = last_name + self.vcard = vcard def to_dict(self): json_dict = {'phone_numbe': self.phone_number, 'first_name': self.first_name} if self.last_name: json_dict['last_name'] = self.last_name + if self.vcard: + json_dict['vcard'] = self.vcard return json_dict @@ -1737,8 +1752,8 @@ class InlineQueryResultLocation(JsonSerializable): class InlineQueryResultVenue(JsonSerializable): - def __init__(self, id, title, latitude, longitude, address, foursquare_id=None, reply_markup=None, - input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None): + 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): self.type = 'venue' self.id = id self.title = title @@ -1746,6 +1761,7 @@ class InlineQueryResultVenue(JsonSerializable): self.longitude = longitude self.address = address self.foursquare_id = foursquare_id + self.foursquare_type = foursquare_type self.reply_markup = reply_markup self.input_message_content = input_message_content self.thumb_url = thumb_url @@ -1757,6 +1773,8 @@ class InlineQueryResultVenue(JsonSerializable): 'longitude': self.longitude, 'address': self.address} if self.foursquare_id: json_dict['foursquare_id'] = self.foursquare_id + if self.foursquare_type: + json_dict['foursquare_type'] = self.foursquare_type if self.thumb_url: json_dict['thumb_url'] = self.thumb_url if self.thumb_width: @@ -1771,13 +1789,15 @@ class InlineQueryResultVenue(JsonSerializable): class InlineQueryResultContact(JsonSerializable): - def __init__(self, id, phone_number, first_name, last_name=None, reply_markup=None, - input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None): + 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): self.type = 'contact' self.id = id self.phone_number = phone_number self.first_name = first_name self.last_name = last_name + self.vcard = vcard self.reply_markup = reply_markup self.input_message_content = input_message_content self.thumb_url = thumb_url @@ -1788,16 +1808,18 @@ class InlineQueryResultContact(JsonSerializable): json_dict = {'type': self.type, 'id': self.id, 'phone_number': self.phone_number, 'first_name': self.first_name} if self.last_name: json_dict['last_name'] = self.last_name + if self.vcard: + json_dict['vcard'] = self.vcard + if self.reply_markup: + json_dict['reply_markup'] = self.reply_markup.to_dict() + if self.input_message_content: + json_dict['input_message_content'] = self.input_message_content.to_dict() if self.thumb_url: json_dict['thumb_url'] = self.thumb_url if self.thumb_width: json_dict['thumb_width'] = self.thumb_width if self.thumb_height: json_dict['thumb_height'] = self.thumb_height - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() return json.dumps(json_dict) @@ -1976,9 +1998,10 @@ class Game(JsonDeserializable): description = obj['description'] photo = Game.parse_photo(obj['photo']) text = obj.get('text') - text_entities = None if 'text_entities' in obj: text_entities = Game.parse_entities(obj['text_entities']) + else: + text_entities = None animation = Animation.de_json(obj.get('animation')) return cls(title, description, photo, text, text_entities, animation) @@ -2446,7 +2469,6 @@ class Poll(JsonDeserializable): explanation_entities = None open_period = obj.get('open_period') close_date = obj.get('close_date') - #poll = return cls( question, options, poll_id, total_voter_count, is_closed, is_anonymous, poll_type, @@ -2469,7 +2491,7 @@ class Poll(JsonDeserializable): self.allows_multiple_answers = allows_multiple_answers self.correct_option_id = correct_option_id self.explanation = explanation - self.explanation_entities = explanation_entities if not(explanation_entities is None) else [] + self.explanation_entities = explanation_entities # Default state of entities is None. if (explanation_entities is not None) else [] self.open_period = open_period self.close_date = close_date diff --git a/tests/test_types.py b/tests/test_types.py index 742c113..d8c1403 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -110,7 +110,7 @@ def test_json_UserProfilePhotos(): def test_json_contact(): - json_string = r'{"phone_number":"00011111111","first_name":"dd","last_name":"ddl","user_id":8633}' + json_string = r'{"phone_number":"00011111111","first_name":"dd","last_name":"ddl","user_id":8633,"vcard":"SomeContactString"}' contact = types.Contact.de_json(json_string) assert contact.first_name == 'dd' assert contact.last_name == 'ddl' From c13f9a7f98f26d26748591c30d73d290c1a4effa Mon Sep 17 00:00:00 2001 From: Nikolay Korolev Date: Tue, 25 Aug 2020 21:26:28 +0300 Subject: [PATCH 039/350] Add last_update_id parameter for constructor --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3ca0cfe..33c3094 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -92,7 +92,7 @@ class TeleBot: """ def __init__( - self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, + self, token, parse_mode=None, last_update_id=0, threaded=True, skip_pending=False, num_threads=2, next_step_backend=None, reply_backend=None, exception_handler=None ): """ @@ -107,7 +107,7 @@ class TeleBot: self.skip_pending = skip_pending self.__stop_polling = threading.Event() - self.last_update_id = 0 + self.last_update_id = last_update_id self.exc_info = None self.next_step_backend = next_step_backend From 5120650774ec3a321c5532c09256dfc1193cc28e Mon Sep 17 00:00:00 2001 From: Nikolay Korolev Date: Tue, 25 Aug 2020 21:45:30 +0300 Subject: [PATCH 040/350] Move parameter to the end of list --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 33c3094..2a98812 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -92,8 +92,8 @@ class TeleBot: """ def __init__( - self, token, parse_mode=None, last_update_id=0, threaded=True, skip_pending=False, num_threads=2, - next_step_backend=None, reply_backend=None, exception_handler=None + self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, + next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0 ): """ :param token: bot API token From 309e55845cb47bf27837a04c560ddc01e5b8a6a6 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 26 Aug 2020 00:51:55 +0300 Subject: [PATCH 041/350] Minor readme update --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 59a3dbf..7953711 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ [![PyPi Package Version](https://img.shields.io/pypi/v/pyTelegramBotAPI.svg)](https://pypi.python.org/pypi/pyTelegramBotAPI) [![Supported Python versions](https://img.shields.io/pypi/pyversions/pyTelegramBotAPI.svg)](https://pypi.python.org/pypi/pyTelegramBotAPI) [![Build Status](https://travis-ci.org/eternnoir/pyTelegramBotAPI.svg?branch=master)](https://travis-ci.org/eternnoir/pyTelegramBotAPI) +[![PyPi downloads](https://img.shields.io/pypi/dm/pyTelegramBotAPI.svg)](https://pypi.org/project/pyTelegramBotAPI/) * [Getting started.](#getting-started) * [Writing your first bot](#writing-your-first-bot) @@ -39,7 +40,7 @@ ## Getting started. -This API is tested with Python 2.6, Python 2.7, Python 3.4, Pypy and Pypy 3. +This API is tested with Python Python 3.6-3.8 and Pypy 3. There are two ways to install the library: * Installation using pip (a Python package manager)*: From e811163b5f402fac1eff549480658f41dddb6917 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Sat, 29 Aug 2020 04:29:02 +0800 Subject: [PATCH 042/350] UPG: Added the field `file_unique_id` Added the field file_unique_id to the objects Animation, Audio, Document, PassportFile, PhotoSize, Sticker, Video, VideoNote, Voice, File and the fields small_file_unique_id and big_file_unique_id to the object ChatPhoto. (Bot API 4.5) --- telebot/types.py | 56 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 55689a6..8597101 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -586,13 +586,15 @@ class PhotoSize(JsonDeserializable): if (json_string is None): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] width = obj['width'] height = obj['height'] file_size = obj.get('file_size') - return cls(file_id, width, height, file_size) + return cls(file_id, file_unique_id, width, height, file_size) - def __init__(self, file_id, width, height, file_size=None): + def __init__(self, file_id, file_unique_id, width, height, file_size=None): self.file_size = file_size + self.file_unique_id = file_unique_id self.height = height self.width = width self.file_id = file_id @@ -604,15 +606,17 @@ class Audio(JsonDeserializable): if (json_string is None): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] duration = obj['duration'] performer = obj.get('performer') title = obj.get('title') mime_type = obj.get('mime_type') file_size = obj.get('file_size') - return cls(file_id, duration, performer, title, mime_type, file_size) + return cls(file_id, file_unique_id, duration, performer, title, mime_type, file_size) - def __init__(self, file_id, duration, performer=None, title=None, mime_type=None, file_size=None): + def __init__(self, file_id, file_unique_id, duration, performer=None, title=None, mime_type=None, file_size=None): self.file_id = file_id + self.file_unique_id = file_unique_id self.duration = duration self.performer = performer self.title = title @@ -626,13 +630,15 @@ class Voice(JsonDeserializable): if (json_string is None): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] duration = obj['duration'] mime_type = obj.get('mime_type') file_size = obj.get('file_size') - return cls(file_id, duration, mime_type, file_size) + return cls(file_id, file_unique_id, duration, mime_type, file_size) - def __init__(self, file_id, duration, mime_type=None, file_size=None): + def __init__(self, file_id, file_unique_id, duration, mime_type=None, file_size=None): self.file_id = file_id + self.file_unique_id = file_unique_id self.duration = duration self.mime_type = mime_type self.file_size = file_size @@ -644,16 +650,18 @@ class Document(JsonDeserializable): if (json_string is None): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] thumb = None if 'thumb' in obj and 'file_id' in obj['thumb']: thumb = PhotoSize.de_json(obj['thumb']) file_name = obj.get('file_name') mime_type = obj.get('mime_type') file_size = obj.get('file_size') - return cls(file_id, thumb, file_name, mime_type, file_size) + return cls(file_id, file_unique_id, thumb, file_name, mime_type, file_size) - def __init__(self, file_id, thumb=None, file_name=None, mime_type=None, file_size=None): + def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None): self.file_id = file_id + self.file_unique_id = file_unique_id self.thumb = thumb self.file_name = file_name self.mime_type = mime_type @@ -667,16 +675,18 @@ class Video(JsonDeserializable): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] width = obj['width'] height = obj['height'] duration = obj['duration'] thumb = PhotoSize.de_json(obj.get('thumb')) mime_type = obj.get('mime_type') file_size = obj.get('file_size') - return cls(file_id, width, height, duration, thumb, mime_type, file_size) + return cls(file_id, file_unique_id, width, height, duration, thumb, mime_type, file_size) - def __init__(self, file_id, width, height, duration, thumb=None, mime_type=None, file_size=None): + def __init__(self, file_id, file_unique_id, width, height, duration, thumb=None, mime_type=None, file_size=None): self.file_id = file_id + self.file_unique_id = file_unique_id self.width = width self.height = height self.duration = duration @@ -692,14 +702,16 @@ class VideoNote(JsonDeserializable): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] length = obj['length'] duration = obj['duration'] thumb = PhotoSize.de_json(obj.get('thumb')) file_size = obj.get('file_size') - return cls(file_id, length, duration, thumb, file_size) + return cls(file_id, file_unique_id, length, duration, thumb, file_size) - def __init__(self, file_id, length, duration, thumb=None, file_size=None): + def __init__(self, file_id, file_unique_id, length, duration, thumb=None, file_size=None): self.file_id = file_id + self.file_unique_id = file_unique_id self.length = length self.duration = duration self.thumb = thumb @@ -785,12 +797,14 @@ class File(JsonDeserializable): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] file_size = obj.get('file_size') file_path = obj.get('file_path') - return cls(file_id, file_size, file_path) + return cls(file_id, file_unique_id, file_size, file_path) - def __init__(self, file_id, file_size, file_path): + def __init__(self, file_id, file_unique_id, file_size, file_path): self.file_id = file_id + self.file_unique_id = file_unique_id self.file_size = file_size self.file_path = file_path @@ -1085,12 +1099,16 @@ class ChatPhoto(JsonDeserializable): return None obj = cls.check_json(json_string) small_file_id = obj['small_file_id'] + small_file_unique_id = obj['small_file_unique_id'] big_file_id = obj['big_file_id'] - return cls(small_file_id, big_file_id) + big_file_unique_id = obj['big_file_unique_id'] + return cls(small_file_id, small_file_unique_id, big_file_id, big_file_unique_id) - def __init__(self, small_file_id, big_file_id): + def __init__(self, small_file_id, small_file_unique_id, big_file_id, big_file_unique_id): self.small_file_id = small_file_id + self.small_file_unique_id = small_file_unique_id self.big_file_id = big_file_id + self.big_file_unique_id = big_file_unique_id class ChatMember(JsonDeserializable): @@ -2034,14 +2052,16 @@ class Animation(JsonDeserializable): if (json_string is None): return None obj = cls.check_json(json_string) file_id = obj['file_id'] + file_unique_id = obj['file_unique_id'] thumb = PhotoSize.de_json(obj.get('thumb')) file_name = obj.get('file_name') mime_type = obj.get('mime_type') file_size = obj.get('file_size') - return cls(file_id, thumb, file_name, mime_type, file_size) + return cls(file_id, file_unique_id, thumb, file_name, mime_type, file_size) - def __init__(self, file_id, thumb=None, file_name=None, mime_type=None, file_size=None): + def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None): self.file_id = file_id + self.file_unique_id = file_unique_id self.thumb = thumb self.file_name = file_name self.mime_type = mime_type From bdfb793e3421a9e35390937c57117bcd19730576 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Sat, 29 Aug 2020 12:07:38 +0800 Subject: [PATCH 043/350] test: Added file_unique_id from Bot API 4.5 --- tests/test_types.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_types.py b/tests/test_types.py index d8c1403..2f1e698 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -41,14 +41,14 @@ def test_json_GroupChat(): def test_json_Document(): - json_string = r'{"file_name":"Text File","thumb":{},"file_id":"BQADBQADMwIAAsYifgZ_CEh0u682xwI","file_size":446}' + json_string = r'{"file_name":"Text File","thumb":{},"file_id":"BQADBQADMwIAAsYifgZ_CEh0u682xwI","file_unique_id": "AgADJQEAAqfhOEY","file_size":446}' doc = types.Document.de_json(json_string) assert doc.thumb is None assert doc.file_name == 'Text File' def test_json_Message_Audio(): - json_string = r'{"message_id":131,"from":{"id":12775,"first_name":"dd","username":"dd","is_bot":true },"chat":{"id":10834,"first_name":"dd","type":"private","type":"private","last_name":"dd","username":"dd"},"date":1439978364,"audio":{"duration":1,"mime_type":"audio\/mpeg","title":"pyTelegram","performer":"eternnoir","file_id":"BQADBQADDH1JaB8-1KyWUss2-Ag","file_size":20096}}' + json_string = r'{"message_id":131,"from":{"id":12775,"first_name":"dd","username":"dd","is_bot":true },"chat":{"id":10834,"first_name":"dd","type":"private","type":"private","last_name":"dd","username":"dd"},"date":1439978364,"audio":{"duration":1,"mime_type":"audio\/mpeg","title":"pyTelegram","performer":"eternnoir","file_id":"BQADBQADDH1JaB8-1KyWUss2-Ag","file_unique_id": "AgADawEAAn8VSFY","file_size":20096}}' msg = types.Message.de_json(json_string) assert msg.audio.duration == 1 assert msg.content_type == 'audio' @@ -73,21 +73,21 @@ def test_json_Message_Sticker_without_thumb(): def test_json_Message_Document(): - json_string = r'{"message_id":97,"from":{"id":10734,"first_name":"Fd","last_name":"Wd","username":"dd","is_bot":true },"chat":{"id":10,"first_name":"Fd","type":"private","last_name":"Wd","username":"dd"},"date":1435478744,"document":{"file_name":"Text File","thumb":{},"file_id":"BQADBQADMwIAAsYifgZ_CEh0u682xwI","file_size":446}}' + json_string = r'{"message_id":97,"from":{"id":10734,"first_name":"Fd","last_name":"Wd","username":"dd","is_bot":true },"chat":{"id":10,"first_name":"Fd","type":"private","last_name":"Wd","username":"dd"},"date":1435478744,"document":{"file_name":"Text File","thumb":{},"file_id":"BQADBQADMwIAAsYifgZ_CEh0u682xwI","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":446}}' msg = types.Message.de_json(json_string) assert msg.document.file_name == 'Text File' assert msg.content_type == 'document' def test_json_Message_Photo(): - json_string = r'{"message_id":96,"from":{"id":109734,"first_name":"Fd","last_name":"Wd","username":"dd","is_bot":true },"chat":{"id":10734,"first_name":"Fd","type":"private","last_name":"dd","username":"dd"},"date":1435478191,"photo":[{"file_id":"AgADBQADIagxG8YifgYv8yLSj76i-dd","file_size":615,"width":90,"height":67},{"file_id":"AgADBQADIagxG8YifgYv8yLSj76i-dd","file_size":10174,"width":320,"height":240},{"file_id":"dd-A_LsTIABFNx-FUOaEa_3AABAQABAg","file_size":53013,"width":759,"height":570}]}' + json_string = r'{"message_id":96,"from":{"id":109734,"first_name":"Fd","last_name":"Wd","username":"dd","is_bot":true },"chat":{"id":10734,"first_name":"Fd","type":"private","last_name":"dd","username":"dd"},"date":1435478191,"photo":[{"file_id":"AgADBQADIagxG8YifgYv8yLSj76i-dd","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":615,"width":90,"height":67},{"file_id":"AgADBQADIagxG8YifgYv8yLSj76i-dd","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":10174,"width":320,"height":240},{"file_id":"dd-A_LsTIABFNx-FUOaEa_3AABAQABAg","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":53013,"width":759,"height":570}]}' msg = types.Message.de_json(json_string) assert len(msg.photo) == 3 assert msg.content_type == 'photo' def test_json_Message_Video(): - json_string = r'{"message_id":101,"from":{"id":109734,"first_name":"dd","last_name":"dd","username":"dd","is_bot":true },"chat":{"id":109734,"first_name":"dd","type":"private","last_name":"dd","username":"dd"},"date":1435481960,"video":{"duration":3,"caption":"","width":360,"height":640,"thumb":{"file_id":"AAQFABPiYnBjkDwMAAIC","file_size":1597,"width":50,"height":90},"file_id":"BAADBQADNifgb_TOPEKErGoQI","file_size":260699}}' + json_string = r'{"message_id":101,"from":{"id":109734,"first_name":"dd","last_name":"dd","username":"dd","is_bot":true },"chat":{"id":109734,"first_name":"dd","type":"private","last_name":"dd","username":"dd"},"date":1435481960,"video":{"duration":3,"caption":"","width":360,"height":640,"thumb":{"file_id":"AAQFABPiYnBjkDwMAAIC","file_unique_id": "AQADTeisa3QAAz1nAAI","file_size":1597,"width":50,"height":90},"file_id":"BAADBQADNifgb_TOPEKErGoQI","file_unique_id": "AgADbgEAAn8VSFY","file_size":260699}}' msg = types.Message.de_json(json_string) assert msg.video assert msg.video.duration == 3 @@ -103,7 +103,7 @@ def test_json_Message_Location(): def test_json_UserProfilePhotos(): - json_string = r'{"total_count":1,"photos":[[{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAATZH_SpyZjzIwdVAAIC","file_size":6150,"width":160,"height":160},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAATOiTNi_YoJMghVAAIC","file_size":13363,"width":320,"height":320},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAAQW4DyFv0-lhglVAAIC","file_size":28347,"width":640,"height":640},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAAT50RvJCg0GQApVAAIC","file_size":33953,"width":800,"height":800}]]}' + json_string = r'{"total_count":1,"photos":[[{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAATZH_SpyZjzIwdVAAIC","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":6150,"width":160,"height":160},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAATOiTNi_YoJMghVAAIC","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":13363,"width":320,"height":320},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAAQW4DyFv0-lhglVAAIC","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":28347,"width":640,"height":640},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAAT50RvJCg0GQApVAAIC","file_unique_id": "AQAD_QIfa3QAAyA4BgAB","file_size":33953,"width":800,"height":800}]]}' upp = types.UserProfilePhotos.de_json(json_string) assert upp.photos[0][0].width == 160 assert upp.photos[0][-1].height == 800 @@ -117,7 +117,7 @@ def test_json_contact(): def test_json_voice(): - json_string = r'{"duration": 0,"mime_type": "audio/ogg","file_id": "AwcccccccDH1JaB7w_gyFjYQxVAg","file_size": 10481}' + json_string = r'{"duration": 0,"mime_type": "audio/ogg","file_id": "AwcccccccDH1JaB7w_gyFjYQxVAg","file_unique_id": "AgADbAEAAn8VSFY","file_size": 10481}' voice = types.Voice.de_json(json_string) assert voice.duration == 0 assert voice.file_size == 10481 From 81100f249cbec7f89f07c0fd62e02b397399bb96 Mon Sep 17 00:00:00 2001 From: Artem Frantsiian <35114937+ArtemFrantsiian@users.noreply.github.com> Date: Sat, 29 Aug 2020 21:57:41 +0300 Subject: [PATCH 044/350] Fix an error with the is_pil_image function When I've tried to send_photo as shown in detailed_example, I got an error: "AttributeError: module 'PIL' has no attribute 'Image'". This error was described well here: https://stackoverflow.com/a/11911536/9092263. So in accordance to prescriptions, I've made changes and It works fine for me. Steps to reproduce: 1. initiate bot via TeleBot constructor 2. call function bot.send_photo(call.message.chat.id, open("some_image.jpg", "rb")) P.S. Error Environment: - python==3.8.5 - pyTelegramBotAPI==3.7.3 - PIL==7.2.0 --- telebot/util.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/util.py b/telebot/util.py index 099828a..438e8c1 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -11,7 +11,7 @@ import queue as Queue import logging try: - import PIL + from PIL import Image from io import BytesIO pil_imported = True except: @@ -164,7 +164,7 @@ def is_bytes(var): return isinstance(var, bytes) def is_pil_image(var): - return pil_imported and isinstance(var, PIL.Image.Image) + return pil_imported and isinstance(var, Image.Image) def pil_image_to_file(image, extension='JPEG', quality='web_low'): if pil_imported: From 6832c337333536f39a500c7bccc1b354633189c8 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Mon, 31 Aug 2020 12:00:56 +0000 Subject: [PATCH 045/350] feat: Added the field reply_markup to the Message Added the field `reply_markup` to the Message object --- telebot/types.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/telebot/types.py b/telebot/types.py index 8597101..e44d6b5 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -385,6 +385,9 @@ class Message(JsonDeserializable): if 'passport_data' in obj: opts['passport_data'] = obj['passport_data'] content_type = 'passport_data' + if 'reply_markup' in obj: + opts['reply_markup'] = InlineKeyboardMarkup.de_json(obj['reply_markup']) + content_type = 'reply_markup' return cls(message_id, from_user, date, chat, content_type, opts, json_string) @classmethod @@ -455,6 +458,7 @@ class Message(JsonDeserializable): self.invoice = None self.successful_payment = None self.connected_website = None + self.reply_markup = None for key in options: setattr(self, key, options[key]) self.json = json_string From cdae65116b92e1d5dbace592588e9a6b436b66e4 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Tue, 1 Sep 2020 18:03:21 +0800 Subject: [PATCH 046/350] feat: make LoginUrl JsonDeserializable feat: make LoginUrl JsonDeserializable, add de_json func --- telebot/types.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index e44d6b5..7d88a06 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1017,12 +1017,23 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): return json_dict -class LoginUrl(Dictionaryable, JsonSerializable): +class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): def __init__(self, url, forward_text=None, bot_username=None, request_write_access=None): self.url = url self.forward_text = forward_text self.bot_username = bot_username self.request_write_access = request_write_access + + @classmethod + def de_json(cls, json_string): + if (json_string is None): + return None + obj = cls.check_json(json_string) + url = obj['url'] + forward_text = obj.get('forward_text') + bot_username = obj.get('bot_username') + request_write_access = obj.get('request_write_access') + return cls(url, forward_text, bot_username, request_write_access) def to_json(self): return json.dumps(self.to_dict()) From 630a9a5b2ca653193de5b3f31672d45995a53fa4 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Tue, 1 Sep 2020 18:07:45 +0800 Subject: [PATCH 047/350] feat: make InlineKeyboardButton JsonDeserializable feat: make InlineKeyboardButton JsonDeserializable, add de_json func to InlineKeyboardButton Object --- telebot/types.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 7d88a06..adf7e18 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1049,7 +1049,7 @@ class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): return json_dict -class InlineKeyboardButton(Dictionaryable, JsonSerializable): +class InlineKeyboardButton(Dictionaryable, JsonSerializable, JsonDeserializable): def __init__(self, text, url=None, callback_data=None, switch_inline_query=None, switch_inline_query_current_chat=None, callback_game=None, pay=None, login_url=None): self.text = text @@ -1060,6 +1060,21 @@ class InlineKeyboardButton(Dictionaryable, JsonSerializable): self.callback_game = callback_game self.pay = pay self.login_url = login_url + + @classmethod + def de_json(cls, json_string): + if (json_string is None): + return None + obj = cls.check_json(json_string) + text = obj['text'] + url = obj.get('url') + callback_data = obj.get('callback_data') + switch_inline_query = obj.get('switch_inline_query') + switch_inline_query_current_chat = obj.get('switch_inline_query_current_chat') + callback_game = obj.get('callback_game') + pay = obj.get('pay') + login_url = LoginUrl.de_json(obj.get('login_url')) + return cls(text, url, callback_data, switch_inline_query, switch_inline_query_current_chat, callback_game, pay, login_url) def to_json(self): return json.dumps(self.to_dict()) From decad450d0e1fa4433f36cfbd465c7d26aee551d Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Tue, 1 Sep 2020 18:13:22 +0800 Subject: [PATCH 048/350] feat: make InlineKeyboardMarkup JsonDeserializable feat: make InlineKeyboardMarkup JsonDeserializable, add de_json func to InlineKeyboardMarkup object --- telebot/types.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index adf7e18..9ae4ccc 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -941,10 +941,18 @@ class KeyboardButtonPollType(Dictionaryable): return {'type': self.type} -class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): +class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable)): max_row_keys = 8 + + @classmethod + def de_json(cls, json_string): + if (json_string is None): + return None + obj = cls.check_json(json_string) + keyboard = [[button for button in row] for row in obj['inline_keyboard']] + return cls(keyboard) - def __init__(self, row_width=3): + def __init__(self, keyboard=[] ,row_width=3): """ This object represents an inline keyboard that appears right next to the message it belongs to. @@ -957,7 +965,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): row_width = self.max_row_keys self.row_width = row_width - self.keyboard = [] + self.keyboard = keyboard def add(self, *args, row_width=None): """ From 32a9e65ecca3781cf067c81251bd9c13a763b5d1 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Wed, 2 Sep 2020 09:12:49 +0800 Subject: [PATCH 049/350] fix: reply_markup does not change content_type --- telebot/types.py | 1 - 1 file changed, 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 9ae4ccc..45181f3 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -387,7 +387,6 @@ class Message(JsonDeserializable): content_type = 'passport_data' if 'reply_markup' in obj: opts['reply_markup'] = InlineKeyboardMarkup.de_json(obj['reply_markup']) - content_type = 'reply_markup' return cls(message_id, from_user, date, chat, content_type, opts, json_string) @classmethod From a803edd09b70e3ff3636e19f2dbd98c6769c6e47 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Wed, 2 Sep 2020 09:25:23 +0800 Subject: [PATCH 050/350] fix: button in markup should be obj, not json text --- telebot/types.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 45181f3..0c9b99e 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -940,7 +940,7 @@ class KeyboardButtonPollType(Dictionaryable): return {'type': self.type} -class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable)): +class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable): max_row_keys = 8 @classmethod @@ -948,7 +948,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) if (json_string is None): return None obj = cls.check_json(json_string) - keyboard = [[button for button in row] for row in obj['inline_keyboard']] + keyboard = [[InlineKeyboardButton.de_json(button) for button in row] for row in obj['inline_keyboard']] return cls(keyboard) def __init__(self, keyboard=[] ,row_width=3): @@ -990,7 +990,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) row_width = self.max_row_keys for row in util.chunks(args, row_width): - button_array = [button.to_dict() for button in row] + button_array = [button for button in row] self.keyboard.append(button_array) return self @@ -1020,7 +1020,8 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) return json.dumps(self.to_dict()) def to_dict(self): - json_dict = {'inline_keyboard': self.keyboard} + json_dict = dict() + json_dict['inline_keyboard'] = [[json.loads(button.to_json()) for button in row] for row in self.keyboard] return json_dict From 698b4371e6d5aca396fe011de3d9b17ceffbe801 Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Wed, 2 Sep 2020 10:33:32 +0800 Subject: [PATCH 051/350] test: Add tests for InlineKeyboardMarkup and ... Add tests for InlineKeyboardMarkup and InlineKeyboardButton --- tests/test_types.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/test_types.py b/tests/test_types.py index 2f1e698..173cda9 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -17,6 +17,28 @@ def test_json_message(): assert msg.text == 'HIHI' +def test_json_message_with_reply_markup(): + jsonstring = r'{"message_id":48,"from":{"id":153587469,"is_bot":false,"first_name":"Neko","username":"Neko"},"chat":{"id":153587469,"first_name":"Neko","username":"Neko","type":"private"},"date":1598879570,"text":"test","reply_markup":{"inline_keyboard":[[{"text":"Google","url":"http://www.google.com"},{"text":"Yahoo","url":"http://www.yahoo.com"}]]}}' + msg = types.Message.de_json(jsonstring) + assert msg.content_type == 'text' + assert msg.reply_markup.keyboard[0][0].text == 'Google' + + +def test_json_InlineKeyboardMarkup(): + jsonstring = r'{"inline_keyboard":[[{"text":"Google","url":"http://www.google.com"},{"text":"Yahoo","url":"http://www.yahoo.com"}]]}' + markup = types.InlineKeyboardMarkup.de_json(jsonstring) + assert markup.keyboard[0][0].text == 'Google' + assert markup.keyboard[0][1].url == 'http://www.yahoo.com' + + +def test_json_InlineKeyboardButton(): + jsonstring = r'{"text":"Google","url":"http://www.google.com"}' + button = types.InlineKeyboardButton.de_json(jsonstring) + assert button.text == 'Google' + assert button.url == 'http://www.google.com' + + + def test_json_message_with_dice(): jsonstring = r'{"message_id":5560,"from":{"id":879343317,"is_bot":false,"first_name":"George","last_name":"Forse","username":"dr_fxrse","language_code":"ru"},"chat":{"id":879343317,"first_name":"George","last_name":"Forse","username":"dr_fxrse","type":"private"},"date":1586926330,"dice":{"value": 4, "emoji": "\ud83c\udfaf"}}' msg = types.Message.de_json(jsonstring) From 9ab906e60ccbcba7a445d9dac5d4be215cecdd3b Mon Sep 17 00:00:00 2001 From: meoww-bot <14239840+meoww-bot@users.noreply.github.com> Date: Wed, 2 Sep 2020 18:09:14 +0800 Subject: [PATCH 052/350] fix: simplify code json.loads(button.to_json()) equals to button.to_dict() --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 0c9b99e..f1b9af0 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1021,7 +1021,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) def to_dict(self): json_dict = dict() - json_dict['inline_keyboard'] = [[json.loads(button.to_json()) for button in row] for row in self.keyboard] + json_dict['inline_keyboard'] = [[button.to_dict() for button in row] for row in self.keyboard] return json_dict From 3ae145f206eae4ae1c9f3e7838e80fdff54379ff Mon Sep 17 00:00:00 2001 From: FrankWang Date: Thu, 10 Sep 2020 16:22:50 +0800 Subject: [PATCH 053/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7953711..fc6e8b0 100644 --- a/README.md +++ b/README.md @@ -663,5 +663,6 @@ Get help. Discuss. Chat. * [RandomInfoBot](https://t.me/RandomInfoBot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Generates Random Information Of Humans Scraped From Over 13 Websites. * [TasksListsBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/TasksListsBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - A (tasks) lists manager bot for Telegram. * [MyElizaPsychologistBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/MyElizaPsychologistBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - An implementation of the famous Eliza psychologist chatbot. +* [Evdembot](https://t.me/Evdembot) by Adem Kavak. A bot that informs you about everything you want. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 75a5dd14928a33470e8892b2d72e28d9260a1151 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 22 Sep 2020 01:34:49 +0300 Subject: [PATCH 054/350] Minor bugfix --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 55689a6..2d004fa 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -945,7 +945,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable): """ This method adds buttons to the keyboard without exceeding row_width. - E.g. InlineKeyboardMarkup#add("A", "B", "C") yields the json result: + E.g. InlineKeyboardMarkup.add("A", "B", "C") yields the json result: {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the result: From 00c2e9b51c1ac971848d48c28b3455a182c688a2 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 22 Sep 2020 01:41:51 +0300 Subject: [PATCH 055/350] Piece death fix --- telebot/types.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 3519533..3845532 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -951,7 +951,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) keyboard = [[InlineKeyboardButton.de_json(button) for button in row] for row in obj['inline_keyboard']] return cls(keyboard) - def __init__(self, keyboard=[] ,row_width=3): + def __init__(self, keyboard=None ,row_width=3): """ This object represents an inline keyboard that appears right next to the message it belongs to. @@ -964,7 +964,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) row_width = self.max_row_keys self.row_width = row_width - self.keyboard = keyboard + self.keyboard = keyboard if keyboard else [] def add(self, *args, row_width=None): """ From 36a3ce62c453e8b9b56a5401bb76c7b5f3ae0acf Mon Sep 17 00:00:00 2001 From: andvch Date: Wed, 14 Oct 2020 12:06:49 +0300 Subject: [PATCH 056/350] Fix broken text_mention html formatting --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 3845532..1534da8 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -503,7 +503,7 @@ class Message(JsonDeserializable): def func(upd_text, subst_type=None, url=None, user=None): upd_text = upd_text.decode("utf-16-le") if subst_type == "text_mention": - subst_type = "url" + subst_type = "text_link" url = "tg://user?id={0}".format(user.id) elif subst_type == "mention": url = "https://t.me/{0}".format(upd_text[1:]) From 746c71665e47134f8d02e44f3f8633d3a6fab515 Mon Sep 17 00:00:00 2001 From: Pinguluk Date: Wed, 28 Oct 2020 12:31:57 +0200 Subject: [PATCH 057/350] Update README.md linked example/webhook_examples to the directory --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fc6e8b0..9d2a370 100644 --- a/README.md +++ b/README.md @@ -505,7 +505,7 @@ bot.polling() ### Using web hooks When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it. -There are some examples using webhooks in the *examples/webhook_examples* directory. +There are some examples using webhooks in the [examples/webhook_examples](examples/webhook_examples) directory. ### Logging From afa88304d7cb59e9c639db6bcab767eb8a7e023f Mon Sep 17 00:00:00 2001 From: Mrsqd Date: Thu, 29 Oct 2020 02:09:47 +0300 Subject: [PATCH 058/350] Added Frcstbot I've made a weather forecast bot using your API. Can you approve my request to add it, please? --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9d2a370..1a227eb 100644 --- a/README.md +++ b/README.md @@ -664,5 +664,6 @@ Get help. Discuss. Chat. * [TasksListsBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/TasksListsBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - A (tasks) lists manager bot for Telegram. * [MyElizaPsychologistBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/MyElizaPsychologistBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - An implementation of the famous Eliza psychologist chatbot. * [Evdembot](https://t.me/Evdembot) by Adem Kavak. A bot that informs you about everything you want. +* [Frcstbot](https://t.me/frcstbot) ([source](https://github.com/Mrsqd/frcstbot_public)) by [Mrsqd](https://github.com/Mrsqd). A Telegram bot that will always be happy to show you the weather forecast. Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From 27461c03af76226b95905046305ba51eeb81e817 Mon Sep 17 00:00:00 2001 From: diegop384 <67247633+diegop384@users.noreply.github.com> Date: Tue, 3 Nov 2020 09:28:31 -0500 Subject: [PATCH 059/350] Update README.md I added my bot --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1a227eb..78939e5 100644 --- a/README.md +++ b/README.md @@ -665,5 +665,6 @@ Get help. Discuss. Chat. * [MyElizaPsychologistBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/MyElizaPsychologistBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - An implementation of the famous Eliza psychologist chatbot. * [Evdembot](https://t.me/Evdembot) by Adem Kavak. A bot that informs you about everything you want. * [Frcstbot](https://t.me/frcstbot) ([source](https://github.com/Mrsqd/frcstbot_public)) by [Mrsqd](https://github.com/Mrsqd). A Telegram bot that will always be happy to show you the weather forecast. +* [Bot Hour](https://t.me/roadtocode_bot) a little bot that say the time in different countries by [@diegop384](https://github.com/diegop384) [repo](https://github.com/diegop384/telegrambothour) Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. From fa3ca84d2466a58fb243df0b4dc3bb69b62f865c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 3 Nov 2020 17:46:19 +0300 Subject: [PATCH 060/350] Animation content_type "When you send gif telegram gives you animation and document at same time in update and when you parse that first if is animation and second is document because of this the content_type set document not animation" --- telebot/types.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 1534da8..6dcf6c2 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -296,12 +296,13 @@ class Message(JsonDeserializable): if 'audio' in obj: opts['audio'] = Audio.de_json(obj['audio']) content_type = 'audio' - if 'animation' in obj: - opts['animation'] = Animation.de_json(obj['animation']) - content_type = 'animation' if 'document' in obj: opts['document'] = Document.de_json(obj['document']) content_type = 'document' + if 'animation' in obj: + # Document content type accompanies "animation", so "animation" should be checked below "document" to override it + opts['animation'] = Animation.de_json(obj['animation']) + content_type = 'animation' if 'game' in obj: opts['game'] = Game.de_json(obj['game']) content_type = 'game' From 7a3fd30f6ac7c06e39673665f9ec2817ad64294c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 7 Nov 2020 12:52:51 +0300 Subject: [PATCH 061/350] Long polling updates and combo content types --- telebot/apihelper.py | 17 +++++++++++------ telebot/util.py | 10 +++++++++- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index b80a627..ec4ad9b 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -52,11 +52,11 @@ def _make_request(token, method_name, method='get', params=None, files=None): :param files: Optional files. :return: The result parsed to a JSON dictionary. """ - if API_URL is None: - request_url = "https://api.telegram.org/bot{0}/{1}".format(token, method_name) - else: + if API_URL: request_url = API_URL.format(token, method_name) - + else: + request_url = "https://api.telegram.org/bot{0}/{1}".format(token, method_name) + logger.debug("Request: method={0} url={1} params={2} files={3}".format(method, request_url, params, files)) read_timeout = READ_TIMEOUT connect_timeout = CONNECT_TIMEOUT @@ -67,7 +67,12 @@ def _make_request(token, method_name, method='get', params=None, files=None): read_timeout = params.pop('timeout') + 10 if 'connect-timeout' in params: connect_timeout = params.pop('connect-timeout') + 10 - + if 'long_polling_timeout' in params: + # For getUpdates: the only function with timeout on the BOT API side + params['timeout'] = params.pop('long_polling_timeout') + + + result = None if RETRY_ON_ERROR: got_result = False current_try = 0 @@ -235,7 +240,7 @@ def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=No if limit: payload['limit'] = limit if timeout: - payload['timeout'] = timeout + payload['long_polling_timeout'] = timeout if allowed_updates: payload['allowed_updates'] = json.dumps(allowed_updates) return _make_request(token, method_url, params=payload) diff --git a/telebot/util.py b/telebot/util.py index 438e8c1..3ad4463 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -21,6 +21,15 @@ logger = logging.getLogger('TeleBot') thread_local = threading.local() +content_type_media = [ + 'text', 'audio', 'document', 'photo', 'sticker', 'video', 'video_note', 'voice', 'contact', 'dice', 'poll', + 'venue', 'location' +] + +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' +] class WorkerThread(threading.Thread): count = 0 @@ -286,7 +295,6 @@ def chunks(lst, n): def generate_random_token(): return ''.join(random.sample(string.ascii_letters, 16)) - def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted From 03e1aef70e25d8ed5f218ff25c80eb57372d2eb9 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 7 Nov 2020 14:02:11 +0300 Subject: [PATCH 062/350] long_polling_timeout update 1 --- .travis.yml | 1 + telebot/__init__.py | 36 +++++++++++++++++++----------------- telebot/apihelper.py | 6 ++++-- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2ce0711..eaed67e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ python: - "3.6" - "3.7" - "3.8" + - "3.9" - "pypy3" install: "pip install -r requirements.txt" script: diff --git a/telebot/__init__.py b/telebot/__init__.py index df59f39..3028c8c 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -252,16 +252,17 @@ class TeleBot: def remove_webhook(self): return self.set_webhook() # No params resets webhook - def get_updates(self, offset=None, limit=None, timeout=20, allowed_updates=None): + def get_updates(self, offset=None, limit=None, timeout=20, allowed_updates=None, long_polling_timeout = 20): """ Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. :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. Timeout in seconds for long polling. + :param timeout: Integer. Request connection timeout + :param long_polling_timeout. Timeout in seconds for long polling. :return: array of Updates """ - json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates) + json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout) ret = [] for ju in json_updates: ret.append(types.Update.de_json(ju)) @@ -273,16 +274,16 @@ class TeleBot: :return: total updates skipped """ total = 0 - updates = self.get_updates(offset=self.last_update_id, timeout=1) + updates = self.get_updates(offset=self.last_update_id, long_polling_timeout=1) while updates: total += len(updates) for update in updates: if update.update_id > self.last_update_id: self.last_update_id = update.update_id - updates = self.get_updates(offset=self.last_update_id + 1, timeout=1) + updates = self.get_updates(offset=self.last_update_id + 1, long_polling_timeout=1) return total - def __retrieve_updates(self, timeout=20): + def __retrieve_updates(self, timeout=20, long_polling_timeout=20): """ Retrieves any updates from the Telegram API. Registered listeners and applicable message handlers will be notified when a new message arrives. @@ -291,7 +292,7 @@ class TeleBot: if self.skip_pending: logger.debug('Skipped {0} pending messages'.format(self.__skip_updates())) self.skip_pending = False - updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout) + updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout, long_polling_timeout = long_polling_timeout) self.process_new_updates(updates) def process_new_updates(self, updates): @@ -427,16 +428,16 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, *args, **kwargs): + def infinity_polling(self, timeout=20, long_polling_timeout=20, *args, **kwargs): while not self.__stop_polling.is_set(): try: - self.polling(timeout=timeout, *args, **kwargs) + self.polling(timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) except Exception: time.sleep(timeout) pass logger.info("Break infinity polling") - def polling(self, none_stop=False, interval=0, timeout=20): + def polling(self, none_stop=False, interval=0, timeout=20, long_polling_timeout=20): """ 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. @@ -446,15 +447,16 @@ class TeleBot: Always get updates. :param interval: :param none_stop: Do not stop polling when an ApiException occurs. - :param timeout: Timeout in seconds for long polling. + :param timeout: Integer. Request connection timeout + :param long_polling_timeout. Timeout in seconds for long polling. :return: """ if self.threaded: - self.__threaded_polling(none_stop, interval, timeout) + self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout) else: - self.__non_threaded_polling(none_stop, interval, timeout) + self.__non_threaded_polling(none_stop, interval, timeout, long_polling_timeout) - def __threaded_polling(self, none_stop=False, interval=0, timeout=3): + def __threaded_polling(self, none_stop=False, interval=0, timeout = None, long_polling_timeout = None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 @@ -469,7 +471,7 @@ class TeleBot: while not self.__stop_polling.wait(interval): or_event.clear() try: - polling_thread.put(self.__retrieve_updates, timeout) + polling_thread.put(self.__retrieve_updates, timeout, long_polling_timeout) or_event.wait() # wait for polling thread finish, polling thread error or thread pool error @@ -517,14 +519,14 @@ class TeleBot: polling_thread.stop() logger.info('Stopped polling.') - def __non_threaded_polling(self, none_stop=False, interval=0, timeout=3): + def __non_threaded_polling(self, none_stop=False, interval=0, timeout = None, long_polling_timeout = None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 while not self.__stop_polling.wait(interval): try: - self.__retrieve_updates(timeout) + self.__retrieve_updates(timeout, long_polling_timeout) error_interval = 0.25 except apihelper.ApiException as e: if self.exception_handler is not None: diff --git a/telebot/apihelper.py b/telebot/apihelper.py index ec4ad9b..40f8354 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -232,7 +232,7 @@ def get_webhook_info(token): return _make_request(token, method_url, params=payload) -def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=None): +def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=None, long_polling_timeout = None): method_url = r'getUpdates' payload = {} if offset: @@ -240,7 +240,9 @@ def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=No if limit: payload['limit'] = limit if timeout: - payload['long_polling_timeout'] = timeout + payload['timeout'] = timeout + if long_polling_timeout: + payload['long_polling_timeout'] = long_polling_timeout if allowed_updates: payload['allowed_updates'] = json.dumps(allowed_updates) return _make_request(token, method_url, params=payload) From a548374a4db7d9c31a62d7a6887bbb1044cefcf5 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 7 Nov 2020 14:43:17 +0300 Subject: [PATCH 063/350] long_polling_timeout update 2 --- telebot/__init__.py | 10 +++++----- telebot/util.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3028c8c..1a9f479 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -433,7 +433,7 @@ class TeleBot: try: self.polling(timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) except Exception: - time.sleep(timeout) + time.sleep(3) pass logger.info("Break infinity polling") @@ -456,7 +456,7 @@ class TeleBot: else: self.__non_threaded_polling(none_stop, interval, timeout, long_polling_timeout) - def __threaded_polling(self, none_stop=False, interval=0, timeout = None, long_polling_timeout = None): + def __threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 @@ -487,7 +487,7 @@ class TeleBot: if not handled: logger.error(e) - if not none_stop: + if not non_stop: self.__stop_polling.set() logger.info("Exception occurred. Stopping.") else: @@ -519,7 +519,7 @@ class TeleBot: polling_thread.stop() logger.info('Stopped polling.') - def __non_threaded_polling(self, none_stop=False, interval=0, timeout = None, long_polling_timeout = None): + def __non_threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 @@ -536,7 +536,7 @@ class TeleBot: if not handled: logger.error(e) - if not none_stop: + if not non_stop: self.__stop_polling.set() logger.info("Exception occurred. Stopping.") else: diff --git a/telebot/util.py b/telebot/util.py index 3ad4463..4c5251c 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -72,7 +72,7 @@ class WorkerThread(threading.Thread): except Queue.Empty: pass except Exception as e: - logger.error(type(e).__name__ + " occurred, args=" + str(e.args) + "\n" + traceback.format_exc()) + logger.debug(type(e).__name__ + " occurred, args=" + str(e.args) + "\n" + traceback.format_exc()) self.exception_info = e self.exception_event.set() From 00d125a298a0e24362d0950fed7c5ff3d040421c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 7 Nov 2020 14:59:45 +0300 Subject: [PATCH 064/350] long_polling_timeout update 3 --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 1a9f479..ccc017a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -431,7 +431,7 @@ class TeleBot: def infinity_polling(self, timeout=20, long_polling_timeout=20, *args, **kwargs): while not self.__stop_polling.is_set(): try: - self.polling(timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) + self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) except Exception: time.sleep(3) pass From bd276459656895489d606fe5f9d4d547dd232339 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 11 Nov 2020 00:32:34 +0300 Subject: [PATCH 065/350] set_webhook bugfinx set_webhook does not reset allowed_updates for empty list (to default) --- telebot/apihelper.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 40f8354..8e817bd 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -216,7 +216,7 @@ def set_webhook(token, url=None, certificate=None, max_connections=None, allowed files = {'certificate': certificate} if max_connections: payload['max_connections'] = max_connections - if allowed_updates: + if allowed_updates is not None: # Empty lists should pass payload['allowed_updates'] = json.dumps(allowed_updates) return _make_request(token, method_url, params=payload, files=files) @@ -243,7 +243,7 @@ def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=No payload['timeout'] = timeout if long_polling_timeout: payload['long_polling_timeout'] = long_polling_timeout - if allowed_updates: + if allowed_updates is not None: # Empty lists should pass payload['allowed_updates'] = json.dumps(allowed_updates) return _make_request(token, method_url, params=payload) From 5824d47590cf77d36a0ebcaef1c184aa806e8b6c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Nov 2020 02:22:52 +0300 Subject: [PATCH 066/350] added only_if_banned to unban_chat_member --- telebot/__init__.py | 5 +++-- telebot/apihelper.py | 4 +++- telebot/types.py | 1 + 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index ccc017a..20fdf45 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1052,14 +1052,15 @@ class TeleBot: """ return apihelper.kick_chat_member(self.token, chat_id, user_id, until_date) - def unban_chat_member(self, chat_id, user_id): + def unban_chat_member(self, chat_id, user_id, only_if_banned = False): """ Removes member from the ban :param chat_id: :param user_id: + :param only_if_banned: :return: """ - return apihelper.unban_chat_member(self.token, chat_id, user_id) + return apihelper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) def restrict_chat_member( self, chat_id, user_id, until_date=None, diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 8e817bd..3bc6d35 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -700,9 +700,11 @@ def kick_chat_member(token, chat_id, user_id, until_date=None): return _make_request(token, method_url, params=payload, method='post') -def unban_chat_member(token, chat_id, user_id): +def unban_chat_member(token, chat_id, user_id, only_if_banned): method_url = 'unbanChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} + if only_if_banned: + payload['only_if_banned'] = only_if_banned return _make_request(token, method_url, params=payload, method='post') diff --git a/telebot/types.py b/telebot/types.py index 6dcf6c2..5e6b59a 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -413,6 +413,7 @@ class Message(JsonDeserializable): def __init__(self, message_id, from_user, date, chat, content_type, options, json_string): self.content_type = content_type + self.id = message_id # Lets fix the telegram usability ####up with ID in Message :) self.message_id = message_id self.from_user = from_user self.date = date From 640f3982622e9950a9ca472e39122568c1cf3834 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Fri, 20 Nov 2020 23:49:55 +0300 Subject: [PATCH 067/350] Version 3.7.4 release --- README.md | 2 +- telebot/version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 78939e5..3e3d109 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ ## Getting started. -This API is tested with Python Python 3.6-3.8 and Pypy 3. +This API is tested with Python Python 3.6-3.9 and Pypy 3. There are two ways to install the library: * Installation using pip (a Python package manager)*: diff --git a/telebot/version.py b/telebot/version.py index 92aad92..35ac633 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.3' +__version__ = '3.7.4' From 0a2216a22bf89b8f3482462109270b6e9c048e04 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 29 Nov 2020 14:47:53 +0300 Subject: [PATCH 068/350] Bot API 5.0 pinning-unpinning logic update + add unpin_all_chat_messages() (former unpin_chat_message()) * update unpin_chat_message() (add message_id arg) --- telebot/__init__.py | 22 +++++++++++++++++++--- telebot/apihelper.py | 8 +++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 20fdf45..f151195 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1239,16 +1239,28 @@ class TeleBot: """ return apihelper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - def unpin_chat_message(self, chat_id): + def unpin_chat_message(self, chat_id, message_id): """ - Use this method to unpin a message in a supergroup chat. + Use this method to unpin specific pinned message in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to unpin + :return: + """ + return apihelper.unpin_chat_message(self.token, chat_id) + + def unpin_all_chat_messages(self, chat_id): + """ + Use this method to unpin a all pinned messages in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :return: """ - return apihelper.unpin_chat_message(self.token, chat_id) + return apihelper.unpin_all_chat_messages(self.token, chat_id, message_id) def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None): @@ -2317,6 +2329,10 @@ class AsyncTeleBot(TeleBot): def unpin_chat_message(self, *args): return TeleBot.unpin_chat_message(self, *args) + @util.async_dec() + def unpin_all_chat_messages(self, *args): + return TeleBot.unpin_all_chat_messages(self, *args) + @util.async_dec() def edit_message_text(self, *args, **kwargs): return TeleBot.edit_message_text(self, *args, **kwargs) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 3bc6d35..b43d341 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -830,8 +830,14 @@ def pin_chat_message(token, chat_id, message_id, disable_notification=None): return _make_request(token, method_url, params=payload, method='post') -def unpin_chat_message(token, chat_id): +def unpin_chat_message(token, chat_id, message_id): method_url = 'unpinChatMessage' + payload = {'chat_id': chat_id, 'message_id': message_id} + return _make_request(token, method_url, params=payload, method='post') + + +def unpin_all_chat_messages(token, chat_id): + method_url = 'unpinAllChatMessages' payload = {'chat_id': chat_id} return _make_request(token, method_url, params=payload, method='post') From 00c9351f83ddff17e0b4c88d380f8cbfcb90d6f0 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 29 Nov 2020 15:12:14 +0300 Subject: [PATCH 069/350] Hotfix 0a2216a22bf89b8f3482462109270b6e9c048e04 * message_id made optional as API declares --- telebot/__init__.py | 2 +- telebot/apihelper.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f151195..4f59e04 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1239,7 +1239,7 @@ class TeleBot: """ return apihelper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - def unpin_chat_message(self, chat_id, message_id): + def unpin_chat_message(self, chat_id, message_id=None): """ Use this method to unpin specific pinned message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. diff --git a/telebot/apihelper.py b/telebot/apihelper.py index b43d341..1cc57ab 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -830,7 +830,7 @@ def pin_chat_message(token, chat_id, message_id, disable_notification=None): return _make_request(token, method_url, params=payload, method='post') -def unpin_chat_message(token, chat_id, message_id): +def unpin_chat_message(token, chat_id, message_id=None): method_url = 'unpinChatMessage' payload = {'chat_id': chat_id, 'message_id': message_id} return _make_request(token, method_url, params=payload, method='post') From b9898bbdda1ca783046acc9c976f63a56059cb82 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 29 Nov 2020 15:21:59 +0300 Subject: [PATCH 070/350] Fix 0a2216a22bf89b8f3482462109270b6e9c048e04 #2 + message_id arg of unpin_chat_message() passing to the helper - removed passing arg to unpin_all_chat_messages() --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 4f59e04..03b6c6c 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1249,7 +1249,7 @@ class TeleBot: :param message_id: Int: Identifier of a message to unpin :return: """ - return apihelper.unpin_chat_message(self.token, chat_id) + return apihelper.unpin_chat_message(self.token, chat_id, message_id) def unpin_all_chat_messages(self, chat_id): """ @@ -1260,7 +1260,7 @@ class TeleBot: (in the format @channelusername) :return: """ - return apihelper.unpin_all_chat_messages(self.token, chat_id, message_id) + return apihelper.unpin_all_chat_messages(self.token, chat_id) def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None): From 6cc80f25d78149db849aaa83134d43ef4f10b52f Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 29 Nov 2020 15:33:39 +0300 Subject: [PATCH 071/350] Bot API 5.0 pinning-unpinning logic post-fix. --- telebot/apihelper.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 1cc57ab..2fe3a7d 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -830,9 +830,11 @@ def pin_chat_message(token, chat_id, message_id, disable_notification=None): return _make_request(token, method_url, params=payload, method='post') -def unpin_chat_message(token, chat_id, message_id=None): +def unpin_chat_message(token, chat_id, message_id): method_url = 'unpinChatMessage' - payload = {'chat_id': chat_id, 'message_id': message_id} + payload = {'chat_id': chat_id} + if message_id: + payload['message_id'] = message_id return _make_request(token, method_url, params=payload, method='post') From 65c3ca58da9a787084cfaecbdaee9f97b9b709df Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 9 Dec 2020 01:41:07 +0300 Subject: [PATCH 072/350] Update __init__.py Allow parse_mode = "" to disable default parse mode. --- telebot/__init__.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 03b6c6c..dcb2cb3 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -687,8 +687,8 @@ class TeleBot: """ Use this method to send text messages. - Warning: Do not send more than about 5000 characters each message, otherwise you'll risk an HTTP 414 error. - If you must send more than 5000 characters, use the split_string function in apihelper.py. + Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error. + If you must send more than 4000 characters, use the split_string function in apihelper.py. :param chat_id: :param text: @@ -700,7 +700,7 @@ class TeleBot: :param timeout: :return: API reply. """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, @@ -763,7 +763,7 @@ class TeleBot: :param timeout: :return: API reply. """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_photo(self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, @@ -788,6 +788,8 @@ class TeleBot: :param thumb: :return: Message """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + return types.Message.de_json( apihelper.send_audio(self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout, thumb)) @@ -807,7 +809,7 @@ class TeleBot: :param timeout: :return: Message """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_voice(self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, @@ -828,7 +830,7 @@ class TeleBot: :param thumb: InputFile or String : Thumbnail of the file sent :return: API reply. """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, @@ -871,7 +873,7 @@ class TeleBot: :param height: :return: """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, @@ -895,7 +897,7 @@ class TeleBot: :param thumb: InputFile or String : Thumbnail of the file sent :return: """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, reply_markup, @@ -1275,7 +1277,7 @@ class TeleBot: :param reply_markup: :return: """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode result = apihelper.edit_message_text(self.token, text, chat_id, message_id, inline_message_id, parse_mode, disable_web_page_preview, reply_markup) @@ -1430,6 +1432,7 @@ class TeleBot: :param timeout: :return: """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode if isinstance(question, types.Poll): raise Exception("The send_poll signature was changed, please see send_poll function details.") @@ -1485,7 +1488,7 @@ class TeleBot: :param reply_markup: :return: """ - parse_mode = self.parse_mode if not parse_mode else parse_mode + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode result = apihelper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, parse_mode, reply_markup) From 75a18e586991f40b0b54f0633fc1c7b548802506 Mon Sep 17 00:00:00 2001 From: vixfwis Date: Tue, 15 Dec 2020 14:38:50 +0300 Subject: [PATCH 073/350] add webhook example for Twisted framework --- .../webhook_twisted_echo_bot.py | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100755 examples/webhook_examples/webhook_twisted_echo_bot.py diff --git a/examples/webhook_examples/webhook_twisted_echo_bot.py b/examples/webhook_examples/webhook_twisted_echo_bot.py new file mode 100755 index 0000000..6db5893 --- /dev/null +++ b/examples/webhook_examples/webhook_twisted_echo_bot.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import logging +import telebot +import json +from twisted.internet import ssl, reactor +from twisted.web.resource import Resource, ErrorPage +from twisted.web.server import Site, Request + +API_TOKEN = '' + +WEBHOOK_HOST = '' +WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open') +WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr + +WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate +WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key + +# Quick'n'dirty SSL certificate generation: +# +# openssl genrsa -out webhook_pkey.pem 2048 +# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem +# +# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply +# with the same value in you put in WEBHOOK_HOST + +WEBHOOK_URL_BASE = "https://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT) +WEBHOOK_URL_PATH = "/{}/".format(API_TOKEN) + +logger = telebot.logger +telebot.logger.setLevel(logging.INFO) +bot = telebot.TeleBot(API_TOKEN) + + +# Handle '/start' and '/help' +@bot.message_handler(commands=['help', 'start']) +def send_welcome(message): + bot.reply_to(message, + ("Hi there, I am EchoBot.\n" + "I am here to echo your kind words back to you.")) + + +# Handle all other messages +@bot.message_handler(func=lambda message: True, content_types=['text']) +def echo_message(message): + bot.reply_to(message, message.text) + + +# Remove webhook, it fails sometimes the set if there is a previous webhook +bot.remove_webhook() + +# Set webhook +bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH, + certificate=open(WEBHOOK_SSL_CERT, 'r')) + + +# Process webhook calls +class WebhookHandler(Resource): + isLeaf = True + def render_POST(self, request: Request): + request_body_dict = json.load(request.content) + update = telebot.types.Update.de_json(request_body_dict) + reactor.callInThread(lambda: bot.process_new_updates([update])) + return b'' + + +root = ErrorPage(403, 'Forbidden', '') +root.putChild(API_TOKEN.encode(), WebhookHandler()) +site = Site(root) +sslcontext = ssl.DefaultOpenSSLContextFactory(WEBHOOK_SSL_PRIV, WEBHOOK_SSL_CERT) +reactor.listenSSL(8443, site, sslcontext) +reactor.run() From 4658d2b8da94109a25cf9be714a3ebb69a2e2339 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 16 Dec 2020 01:57:30 +0300 Subject: [PATCH 074/350] Fix unban_chat_member in async --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index dcb2cb3..f5ee53a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2293,8 +2293,8 @@ class AsyncTeleBot(TeleBot): return TeleBot.kick_chat_member(self, *args, **kwargs) @util.async_dec() - def unban_chat_member(self, *args): - return TeleBot.unban_chat_member(self, *args) + def unban_chat_member(self, *args, **kwargs): + return TeleBot.unban_chat_member(self, *args, **kwargs) @util.async_dec() def restrict_chat_member(self, *args, **kwargs): From 4e61bc3a8b3b4ee8cbd3365c59f826c5dc9d5ba3 Mon Sep 17 00:00:00 2001 From: vixfwis Date: Thu, 17 Dec 2020 15:34:36 +0300 Subject: [PATCH 075/350] add short description to example and readme files --- examples/webhook_examples/README.md | 13 +++++++++++-- .../webhook_examples/webhook_twisted_echo_bot.py | 6 ++++++ 2 files changed, 17 insertions(+), 2 deletions(-) mode change 100755 => 100644 examples/webhook_examples/webhook_twisted_echo_bot.py diff --git a/examples/webhook_examples/README.md b/examples/webhook_examples/README.md index b1e4351..686a38b 100644 --- a/examples/webhook_examples/README.md +++ b/examples/webhook_examples/README.md @@ -1,6 +1,6 @@ # Webhook examples using pyTelegramBotAPI -There are 4 examples in this directory using different libraries: +There are 5 examples in this directory using different libraries: * **Python (CPython):** *webhook_cpython_echo_bot.py* * **Pros:** @@ -42,4 +42,13 @@ There are 4 examples in this directory using different libraries: * **Cons:** * Requires Python 3.4.2+, don't work with Python 2 -*Latest update of this document: 2017-01-30* +* **Twisted (20.3.0):** *webhook_twisted_echo_bot.py* + * **Pros:** + * Asynchronous event-driven networking engine + * Very high performance + * Built-in support for many internet protocols + * **Cons:** + * Twisted is low-level, which may be good or bad depending on use case + * Considerable learning curve - reading docs is a must. + +*Latest update of this document: 2020-12-17* diff --git a/examples/webhook_examples/webhook_twisted_echo_bot.py b/examples/webhook_examples/webhook_twisted_echo_bot.py old mode 100755 new mode 100644 index 6db5893..9a15190 --- a/examples/webhook_examples/webhook_twisted_echo_bot.py +++ b/examples/webhook_examples/webhook_twisted_echo_bot.py @@ -1,6 +1,12 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +# This is an example echo bot using webhook with Twisted network framework. +# Updates are received with Twisted web server and processed in reactor thread pool. +# Relevant docs: +# https://twistedmatrix.com/documents/current/core/howto/reactor-basics.html +# https://twistedmatrix.com/documents/current/web/howto/using-twistedweb.html + import logging import telebot import json From 96686e522104564e14f43ada2ae9b9e249793d89 Mon Sep 17 00:00:00 2001 From: Mikhail Krostelev Date: Tue, 22 Dec 2020 21:38:38 +0300 Subject: [PATCH 076/350] fix restrict_chat_member method --- telebot/apihelper.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 2fe3a7d..d09b22d 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -715,25 +715,27 @@ def restrict_chat_member( can_add_web_page_previews=None, can_change_info=None, can_invite_users=None, can_pin_messages=None): method_url = 'restrictChatMember' - payload = {'chat_id': chat_id, 'user_id': user_id} + permissions = {} if until_date is not None: - payload['until_date'] = until_date + permissions['until_date'] = until_date if can_send_messages is not None: - payload['can_send_messages'] = can_send_messages + permissions['can_send_messages'] = can_send_messages if can_send_media_messages is not None: - payload['can_send_media_messages'] = can_send_media_messages + permissions['can_send_media_messages'] = can_send_media_messages if can_send_polls is not None: - payload['can_send_polls'] = can_send_polls + permissions['can_send_polls'] = can_send_polls if can_send_other_messages is not None: - payload['can_send_other_messages'] = can_send_other_messages + permissions['can_send_other_messages'] = can_send_other_messages if can_add_web_page_previews is not None: - payload['can_add_web_page_previews'] = can_add_web_page_previews + permissions['can_add_web_page_previews'] = can_add_web_page_previews if can_change_info is not None: - payload['can_change_info'] = can_change_info + permissions['can_change_info'] = can_change_info if can_invite_users is not None: - payload['can_invite_users'] = can_invite_users + permissions['can_invite_users'] = can_invite_users if can_pin_messages is not None: - payload['can_pin_messages'] = can_pin_messages + permissions['can_pin_messages'] = can_pin_messages + permissions_json = json.dumps(permissions) + payload = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions_json} return _make_request(token, method_url, params=payload, method='post') From 2534dc5925b91b7f0ddfd54228e7007a8960fe73 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 24 Dec 2020 19:55:24 +0300 Subject: [PATCH 077/350] Exception if middleware is used but not enabled. --- examples/step_example.py | 2 +- telebot/__init__.py | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/step_example.py b/examples/step_example.py index 0fc17e5..0291c66 100644 --- a/examples/step_example.py +++ b/examples/step_example.py @@ -68,7 +68,7 @@ def process_sex_step(message): if (sex == u'Male') or (sex == u'Female'): user.sex = sex else: - raise Exception() + raise Exception("Unknown sex") bot.send_message(chat_id, 'Nice to meet you ' + user.name + '\n Age:' + str(user.age) + '\n Sex:' + user.sex) except Exception as e: bot.reply_to(message, 'oooops') diff --git a/telebot/__init__.py b/telebot/__init__.py index f5ee53a..9f7674f 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1432,10 +1432,9 @@ class TeleBot: :param timeout: :return: """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode if isinstance(question, types.Poll): - raise Exception("The send_poll signature was changed, please see send_poll function details.") + raise RuntimeError("The send_poll signature was changed, please see send_poll function details.") return types.Message.de_json( apihelper.send_poll( @@ -1759,7 +1758,6 @@ class TeleBot: def decorator(handler): self.add_middleware_handler(handler, update_types) - return handler return decorator @@ -1771,6 +1769,9 @@ class TeleBot: :param update_types: :return: """ + if not apihelper.ENABLE_MIDDLEWARE: + raise RuntimeError("Middleware is not enabled. Use apihelper.ENABLE_MIDDLEWARE.") + if update_types: for update_type in update_types: self.typed_middleware_handlers[update_type].append(handler) From c4e624d99911a09e1b0d464dc31e5884c67a2bcd Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 24 Dec 2020 23:55:12 +0300 Subject: [PATCH 078/350] Avoid dead threads in treaded polling --- telebot/__init__.py | 19 +++++++++++-------- telebot/util.py | 1 - 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 9f7674f..5492666 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -472,34 +472,32 @@ class TeleBot: or_event.clear() try: polling_thread.put(self.__retrieve_updates, timeout, long_polling_timeout) - or_event.wait() # wait for polling thread finish, polling thread error or thread pool error - polling_thread.raise_exceptions() self.worker_pool.raise_exceptions() - error_interval = 0.25 except apihelper.ApiException as e: if self.exception_handler is not None: handled = self.exception_handler.handle(e) else: handled = False - if not handled: logger.error(e) if not non_stop: self.__stop_polling.set() logger.info("Exception occurred. Stopping.") else: - polling_thread.clear_exceptions() - self.worker_pool.clear_exceptions() + # polling_thread.clear_exceptions() + # self.worker_pool.clear_exceptions() logger.info("Waiting for {0} seconds until retry".format(error_interval)) time.sleep(error_interval) error_interval *= 2 else: - polling_thread.clear_exceptions() - self.worker_pool.clear_exceptions() + # polling_thread.clear_exceptions() + # self.worker_pool.clear_exceptions() time.sleep(error_interval) + polling_thread.clear_exceptions() #* + self.worker_pool.clear_exceptions() #* except KeyboardInterrupt: logger.info("KeyboardInterrupt received.") self.__stop_polling.set() @@ -510,6 +508,9 @@ class TeleBot: else: handled = False if not handled: + polling_thread.stop() + polling_thread.clear_exceptions() #* + self.worker_pool.clear_exceptions() #* raise e else: polling_thread.clear_exceptions() @@ -517,6 +518,8 @@ class TeleBot: time.sleep(error_interval) polling_thread.stop() + polling_thread.clear_exceptions() #* + self.worker_pool.clear_exceptions() #* logger.info('Stopped polling.') def __non_threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None): diff --git a/telebot/util.py b/telebot/util.py index 4c5251c..713cbc3 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -75,7 +75,6 @@ class WorkerThread(threading.Thread): logger.debug(type(e).__name__ + " occurred, args=" + str(e.args) + "\n" + traceback.format_exc()) self.exception_info = e self.exception_event.set() - if self.exception_callback: self.exception_callback(self, self.exception_info) self.continue_event.wait() From 93b86307d9ef49ad9f6f73521a9c47f60b5a1fec Mon Sep 17 00:00:00 2001 From: Tim Gates Date: Fri, 25 Dec 2020 09:47:40 +1100 Subject: [PATCH 079/350] docs: fix simple typo, perfomance -> performance There is a small typo in examples/webhook_examples/README.md. Should read `performance` rather than `perfomance`. --- examples/webhook_examples/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/webhook_examples/README.md b/examples/webhook_examples/README.md index 686a38b..221d9c5 100644 --- a/examples/webhook_examples/README.md +++ b/examples/webhook_examples/README.md @@ -37,7 +37,7 @@ There are 5 examples in this directory using different libraries: * **Pros:** * It's a web application framework * Python 3 compatible - * Asynchronous, excellent perfomance + * Asynchronous, excellent performance * Utilizes new async/await syntax * **Cons:** * Requires Python 3.4.2+, don't work with Python 2 From 6559f431b7ff808b40bf9500ac00ac43d4b4f36c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 29 Dec 2020 19:24:41 +0300 Subject: [PATCH 080/350] Bot API update Bot API conformance up to 4.4 Added webhook parameters from 5.0 --- README.md | 6 ++-- telebot/__init__.py | 78 ++++++++++++++++++++++++++++++-------------- telebot/apihelper.py | 17 +++++++--- telebot/types.py | 48 +++++++++++++++------------ 4 files changed, 97 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 3e3d109..a4285e0 100644 --- a/README.md +++ b/README.md @@ -540,11 +540,13 @@ apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'} _Checking is in progress..._ -✅ [Bot API 4.3](https://core.telegram.org/bots/api-changelog#may-31-2019) _- To be checked..._ +✅ [Bot API 4.5](https://core.telegram.org/bots/api-changelog#december-31-2019) _- To be checked..._ +* ✔ [Bot API 4.4](https://core.telegram.org/bots/api-changelog#july-29-2019) +* ✔ [Bot API 4.3](https://core.telegram.org/bots/api-changelog#may-31-2019) * ✔ [Bot API 4.2](https://core.telegram.org/bots/api-changelog#april-14-2019) * ➕ [Bot API 4.1](https://core.telegram.org/bots/api-changelog#august-27-2018) - No Passport support. -* ➕ [Bot API 4.0](https://core.telegram.org/bots/api-changelog#july-26-2018) - No Passport support. +* ➕ [Bot API 4.0](https://core.telegram.org/bots/api-changelog#july-26-2018) - No Passport support. * ✔ [Bot API 3.6](https://core.telegram.org/bots/api-changelog#february-13-2018) * ✔ [Bot API 3.5](https://core.telegram.org/bots/api-changelog#november-17-2017) * ✔ [Bot API 3.4](https://core.telegram.org/bots/api-changelog#october-11-2017) diff --git a/telebot/__init__.py b/telebot/__init__.py index 5492666..180211a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -235,17 +235,37 @@ class TeleBot: """ self.reply_backend.load_handlers(filename, del_file_after_loading) - def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None): - return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates) + def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None): + """ + Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an + update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. + In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. - def delete_webhook(self): + :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 + :return: + """ + return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address) + + def delete_webhook(self, drop_pending_updates=None): """ Use this method to remove webhook integration if you decide to switch back to getUpdates. + + :param drop_pending_updates: Pass True to drop all pending updates :return: bool """ - return apihelper.delete_webhook(self.token) + return apihelper.delete_webhook(self.token, drop_pending_updates) def get_webhook_info(self): + """ + 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. + + :return: On success, returns a WebhookInfo object. + """ result = apihelper.get_webhook_info(self.token) return types.WebhookInfo.de_json(result) @@ -432,7 +452,8 @@ class TeleBot: while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) - except Exception: + except Exception as e: + logger.error("Infinity polling exception: {}".format(e)) time.sleep(3) pass logger.info("Break infinity polling") @@ -1059,11 +1080,16 @@ class TeleBot: def unban_chat_member(self, chat_id, user_id, only_if_banned = False): """ - Removes member from the ban - :param chat_id: - :param user_id: - :param only_if_banned: - :return: + 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 default, this method guarantees that after the call + the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat + they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. + + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel (in the format @username) + :param user_id: Unique identifier of the target user + :param only_if_banned: Do nothing if the user is not banned + :return: True on success """ return apihelper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) @@ -1077,7 +1103,7 @@ class TeleBot: Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. - Returns True on success. + :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 @@ -1096,7 +1122,7 @@ class TeleBot: :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, implies can_invite_users :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups - :return: types.Message + :return: True on success """ return apihelper.restrict_chat_member( self.token, chat_id, user_id, until_date, @@ -1111,7 +1137,8 @@ class TeleBot: """ Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Pass False for all boolean parameters to demote a user. Returns True on success. + Pass False for all boolean parameters to demote a user. + :param chat_id: Unique identifier for the target chat or username of the target channel ( in the format @channelusername) :param user_id: Int : Unique identifier of the target user @@ -1125,7 +1152,7 @@ class TeleBot: :param can_promote_members: Bool: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him) - :return: + :return: True on success. """ return apihelper.promote_chat_member(self.token, chat_id, user_id, can_change_info, can_post_messages, can_edit_messages, can_delete_messages, can_invite_users, @@ -1134,26 +1161,27 @@ class TeleBot: def set_chat_administrator_custom_title(self, chat_id, user_id, custom_title): """ Use this method to set a custom title for an administrator - in a supergroup promoted by the bot. - Returns True on success. + in a supergroup promoted by the bot. + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) :param user_id: Unique identifier of the target user :param custom_title: New custom title for the administrator; 0-16 characters, emoji are not allowed - :return: + :return: True on success. """ return apihelper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) def set_chat_permissions(self, chat_id, permissions): """ 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. + The bot must be an administrator in the group or a supergroup for this to work + and must have the can_restrict_members admin rights. + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) :param permissions: New default chat permissions - :return: + :return: True on success """ return apihelper.set_chat_permissions(self.token, chat_id, permissions) @@ -1161,10 +1189,10 @@ class TeleBot: """ Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns exported invite link as String on success. + :param chat_id: Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) - :return: + :return: exported invite link as String on success. """ return apihelper.export_chat_invite_link(self.token, chat_id) @@ -1218,15 +1246,15 @@ class TeleBot: """ return apihelper.set_chat_title(self.token, chat_id, title) - def set_chat_description(self, chat_id, description): + def set_chat_description(self, chat_id, description=None): """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param description: Str: New chat description, 0-255 characters - :return: + :return: True on success. """ return apihelper.set_chat_description(self.token, chat_id, description) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index d09b22d..207b3ae 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -206,7 +206,7 @@ def send_message( return _make_request(token, method_url, params=payload, method='post') -def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None): +def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None): method_url = r'setWebhook' payload = { 'url': url if url else "", @@ -218,12 +218,17 @@ def set_webhook(token, url=None, certificate=None, max_connections=None, allowed payload['max_connections'] = max_connections if allowed_updates is not None: # Empty lists should pass payload['allowed_updates'] = json.dumps(allowed_updates) + if ip_address is not None: # Empty string should pass + payload['ip_address'] = ip_address return _make_request(token, method_url, params=payload, files=files) -def delete_webhook(token): +def delete_webhook(token, drop_pending_updates=None): method_url = r'deleteWebhook' - return _make_request(token, method_url) + payload = {} + if drop_pending_updates is not None: # None / True / False + payload['drop_pending_updates'] = drop_pending_updates + return _make_request(token, method_url, params=payload) def get_webhook_info(token): @@ -703,7 +708,7 @@ def kick_chat_member(token, chat_id, user_id, until_date=None): def unban_chat_member(token, chat_id, user_id, only_if_banned): method_url = 'unbanChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} - if only_if_banned: + if only_if_banned is not None: # None / True / False payload['only_if_banned'] = only_if_banned return _make_request(token, method_url, params=payload, method='post') @@ -820,7 +825,9 @@ def set_my_commands(token, commands): def set_chat_description(token, chat_id, description): method_url = 'setChatDescription' - payload = {'chat_id': chat_id, 'description': description} + payload = {'chat_id': chat_id} + if description is not None: # Allow empty strings + payload['description'] = description return _make_request(token, method_url, params=payload, method='post') diff --git a/telebot/types.py b/telebot/types.py index 5e6b59a..73e5db5 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -132,18 +132,20 @@ class WebhookInfo(JsonDeserializable): url = obj['url'] has_custom_certificate = obj['has_custom_certificate'] pending_update_count = obj['pending_update_count'] + ip_address = obj.get('ip_address') last_error_date = obj.get('last_error_date') last_error_message = obj.get('last_error_message') max_connections = obj.get('max_connections') allowed_updates = obj.get('allowed_updates') - return cls(url, has_custom_certificate, pending_update_count, last_error_date, last_error_message, - max_connections, allowed_updates) + return cls(url, has_custom_certificate, pending_update_count, ip_address, last_error_date, + last_error_message, max_connections, allowed_updates) - def __init__(self, url, has_custom_certificate, pending_update_count, last_error_date, last_error_message, - max_connections, allowed_updates): + def __init__(self, url, has_custom_certificate, pending_update_count, ip_address, last_error_date, + last_error_message, max_connections, allowed_updates): self.url = url self.has_custom_certificate = has_custom_certificate self.pending_update_count = pending_update_count + self.ip_address = ip_address self.last_error_date = last_error_date self.last_error_message = last_error_message self.max_connections = max_connections @@ -218,8 +220,8 @@ class Chat(JsonDeserializable): username = obj.get('username') first_name = obj.get('first_name') last_name = obj.get('last_name') - all_members_are_administrators = obj.get('all_members_are_administrators') photo = ChatPhoto.de_json(obj.get('photo')) + bio = obj.get('bio') description = obj.get('description') invite_link = obj.get('invite_link') pinned_message = Message.de_json(obj.get('pinned_message')) @@ -227,25 +229,27 @@ class Chat(JsonDeserializable): slow_mode_delay = obj.get('slow_mode_delay') sticker_set_name = obj.get('sticker_set_name') can_set_sticker_set = obj.get('can_set_sticker_set') + linked_chat_id = obj.get('linked_chat_id') + location = None # Not implemented return cls( id, type, title, username, first_name, last_name, - all_members_are_administrators, photo, description, invite_link, + photo, bio, description, invite_link, pinned_message, permissions, slow_mode_delay, sticker_set_name, - can_set_sticker_set) + can_set_sticker_set, linked_chat_id, location) def __init__(self, id, type, title=None, username=None, first_name=None, - last_name=None, all_members_are_administrators=None, - photo=None, description=None, invite_link=None, + last_name=None, photo=None, bio=None, description=None, invite_link=None, pinned_message=None, permissions=None, slow_mode_delay=None, - sticker_set_name=None, can_set_sticker_set=None): + sticker_set_name=None, can_set_sticker_set=None, + linked_chat_id=None, location=None): self.id = id self.type = type self.title = title self.username = username self.first_name = first_name self.last_name = last_name - self.all_members_are_administrators = all_members_are_administrators self.photo = photo + self.bio = bio self.description = description self.invite_link = invite_link self.pinned_message = pinned_message @@ -253,6 +257,8 @@ class Chat(JsonDeserializable): self.slow_mode_delay = slow_mode_delay self.sticker_set_name = sticker_set_name self.can_set_sticker_set = can_set_sticker_set + self.linked_chat_id = linked_chat_id + self.location = location class Message(JsonDeserializable): @@ -1054,7 +1060,7 @@ class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): json_dict['forward_text'] = self.forward_text if self.bot_username: json_dict['bot_username'] = self.bot_username - if self.request_write_access: + if self.request_write_access is not None: json_dict['request_write_access'] = self.request_write_access return json_dict @@ -1160,7 +1166,6 @@ class ChatMember(JsonDeserializable): user = User.de_json(obj['user']) status = obj['status'] custom_title = obj.get('custom_title') - until_date = obj.get('until_date') can_be_edited = obj.get('can_be_edited') can_post_messages = obj.get('can_post_messages') can_edit_messages = obj.get('can_edit_messages') @@ -1176,23 +1181,23 @@ class ChatMember(JsonDeserializable): can_send_polls = obj.get('can_send_polls') can_send_other_messages = obj.get('can_send_other_messages') can_add_web_page_previews = obj.get('can_add_web_page_previews') + until_date = obj.get('until_date') return cls( - user, status, custom_title, until_date, can_be_edited, can_post_messages, + user, status, custom_title, can_be_edited, can_post_messages, can_edit_messages, can_delete_messages, can_restrict_members, can_promote_members, can_change_info, can_invite_users, can_pin_messages, is_member, can_send_messages, can_send_media_messages, can_send_polls, - can_send_other_messages, can_add_web_page_previews) + can_send_other_messages, can_add_web_page_previews, until_date) - def __init__(self, user, status, custom_title=None, until_date=None, can_be_edited=None, + def __init__(self, user, status, custom_title=None, can_be_edited=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_restrict_members=None, can_promote_members=None, can_change_info=None, can_invite_users=None, can_pin_messages=None, is_member=None, can_send_messages=None, can_send_media_messages=None, can_send_polls=None, - can_send_other_messages=None, can_add_web_page_previews=None): + can_send_other_messages=None, can_add_web_page_previews=None, until_date=None): self.user = user self.status = status self.custom_title = custom_title - self.until_date = until_date self.can_be_edited = can_be_edited self.can_post_messages = can_post_messages self.can_edit_messages = can_edit_messages @@ -1208,6 +1213,7 @@ class ChatMember(JsonDeserializable): self.can_send_polls = can_send_polls self.can_send_other_messages = can_send_other_messages self.can_add_web_page_previews = can_add_web_page_previews + self.until_date = until_date class ChatPermissions(JsonDeserializable, JsonSerializable, Dictionaryable): @@ -2297,14 +2303,16 @@ class StickerSet(JsonDeserializable): obj = cls.check_json(json_string) name = obj['name'] title = obj['title'] + is_animated = obj['is_animated'] contains_masks = obj['contains_masks'] stickers = [] for s in obj['stickers']: stickers.append(Sticker.de_json(s)) - return cls(name, title, contains_masks, stickers) + return cls(name, title, is_animated, contains_masks, stickers) - def __init__(self, name, title, contains_masks, stickers): + def __init__(self, name, title, is_animated, contains_masks, stickers): self.stickers = stickers + self.is_animated = is_animated self.contains_masks = contains_masks self.title = title self.name = name From eab36a99e981a618f5feafa485c21c9afb58daf6 Mon Sep 17 00:00:00 2001 From: FrankWang Date: Fri, 1 Jan 2021 23:14:00 +0800 Subject: [PATCH 081/350] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a4285e0..0d000c8 100644 --- a/README.md +++ b/README.md @@ -668,5 +668,6 @@ Get help. Discuss. Chat. * [Evdembot](https://t.me/Evdembot) by Adem Kavak. A bot that informs you about everything you want. * [Frcstbot](https://t.me/frcstbot) ([source](https://github.com/Mrsqd/frcstbot_public)) by [Mrsqd](https://github.com/Mrsqd). A Telegram bot that will always be happy to show you the weather forecast. * [Bot Hour](https://t.me/roadtocode_bot) a little bot that say the time in different countries by [@diegop384](https://github.com/diegop384) [repo](https://github.com/diegop384/telegrambothour) +* [moodforfood_bot](https://t.me/moodforfood_bot) This bot will provide you with a list of food place(s) near your current Telegram location, which you are prompted to share. The API for all this info is from https://foursquare.com/. by [@sophiamarani](https://github.com/sophiamarani) -Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh. +Want to have your bot listed here? Just make a pull requet. From 6b0484b9db21e05c96545253c3c484916ffa95ae Mon Sep 17 00:00:00 2001 From: Taras Date: Tue, 5 Jan 2021 13:06:14 +0200 Subject: [PATCH 082/350] Modify RedisHandlerBackend, add argument "password=None" to __init__() With argument "password=None" in method __init__(), and argument "password" in "self.redis = Redis(host, port, db, password)", will be able to use Redis with password protection, if password is set . --- telebot/handler_backends.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index a10d13c..9b54f7c 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -114,11 +114,11 @@ class FileHandlerBackend(HandlerBackend): class RedisHandlerBackend(HandlerBackend): - def __init__(self, handlers=None, host='localhost', port=6379, db=0, prefix='telebot'): + def __init__(self, handlers=None, host='localhost', port=6379, db=0, prefix='telebot', password=None): super(RedisHandlerBackend, self).__init__(handlers) from redis import Redis self.prefix = prefix - self.redis = Redis(host, port, db) + self.redis = Redis(host, port, db, password) def _key(self, handle_group_id): return ':'.join((self.prefix, str(handle_group_id))) From 0126ba82a588839b26a07b3748de880f301e72af Mon Sep 17 00:00:00 2001 From: Andrea Barbagallo <66796758+barbax7@users.noreply.github.com> Date: Tue, 5 Jan 2021 17:31:18 +0100 Subject: [PATCH 083/350] Added bot @donamazonbot to the list --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0d000c8..20e25a1 100644 --- a/README.md +++ b/README.md @@ -669,5 +669,6 @@ Get help. Discuss. Chat. * [Frcstbot](https://t.me/frcstbot) ([source](https://github.com/Mrsqd/frcstbot_public)) by [Mrsqd](https://github.com/Mrsqd). A Telegram bot that will always be happy to show you the weather forecast. * [Bot Hour](https://t.me/roadtocode_bot) a little bot that say the time in different countries by [@diegop384](https://github.com/diegop384) [repo](https://github.com/diegop384/telegrambothour) * [moodforfood_bot](https://t.me/moodforfood_bot) This bot will provide you with a list of food place(s) near your current Telegram location, which you are prompted to share. The API for all this info is from https://foursquare.com/. by [@sophiamarani](https://github.com/sophiamarani) +* [Donation with Amazon](https://t.me/donamazonbot) by [@barbax7](https://github.com/barbax7) This bot donates amazon advertising commissions to the non-profit organization chosen by the user. Want to have your bot listed here? Just make a pull requet. From 5dc008a762d5fc80a7270dbf129436a73f88af35 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 7 Jan 2021 00:13:44 +0300 Subject: [PATCH 084/350] Added timeout to xxx_webhook --- telebot/__init__.py | 18 +++++++++++------- telebot/apihelper.py | 12 +++++++++--- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 180211a..a6a20ff 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -235,7 +235,7 @@ class TeleBot: """ self.reply_backend.load_handlers(filename, del_file_after_loading) - def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None): + def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, timeout=None): """ Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. @@ -246,27 +246,30 @@ class TeleBot: :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 timeout: Integer. Request connection timeout :return: """ - return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address) + return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, timeout) - def delete_webhook(self, drop_pending_updates=None): + def delete_webhook(self, drop_pending_updates=None, timeout=None): """ Use this method to remove webhook integration if you decide to switch back to getUpdates. :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout :return: bool """ - return apihelper.delete_webhook(self.token, drop_pending_updates) + return apihelper.delete_webhook(self.token, drop_pending_updates, timeout) - def get_webhook_info(self): + def get_webhook_info(self, timeout=None): """ Use this method to get current webhook status. Requires no parameters. If the bot is using getUpdates, will return an object with the url field empty. + :param timeout: Integer. Request connection timeout :return: On success, returns a WebhookInfo object. """ - result = apihelper.get_webhook_info(self.token) + result = apihelper.get_webhook_info(self.token, timeout) return types.WebhookInfo.de_json(result) def remove_webhook(self): @@ -455,7 +458,8 @@ class TeleBot: except Exception as e: logger.error("Infinity polling exception: {}".format(e)) time.sleep(3) - pass + continue + logger.info("Infinity polling: polling exited") logger.info("Break infinity polling") def polling(self, none_stop=False, interval=0, timeout=20, long_polling_timeout=20): diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 207b3ae..f059cb4 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -206,7 +206,7 @@ def send_message( return _make_request(token, method_url, params=payload, method='post') -def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None): +def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, timeout=None): method_url = r'setWebhook' payload = { 'url': url if url else "", @@ -220,20 +220,26 @@ def set_webhook(token, url=None, certificate=None, max_connections=None, allowed payload['allowed_updates'] = json.dumps(allowed_updates) if ip_address is not None: # Empty string should pass payload['ip_address'] = ip_address + if timeout: + payload['connect-timeout'] = timeout return _make_request(token, method_url, params=payload, files=files) -def delete_webhook(token, drop_pending_updates=None): +def delete_webhook(token, drop_pending_updates=None, timeout=None): method_url = r'deleteWebhook' payload = {} if drop_pending_updates is not None: # None / True / False payload['drop_pending_updates'] = drop_pending_updates + if timeout: + payload['connect-timeout'] = timeout return _make_request(token, method_url, params=payload) -def get_webhook_info(token): +def get_webhook_info(token, timeout=None): method_url = r'getWebhookInfo' payload = {} + if timeout: + payload['connect-timeout'] = timeout return _make_request(token, method_url, params=payload) From 0900acfae9cf9270fd04c918a009e15ec0730b06 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 7 Jan 2021 20:46:50 +0300 Subject: [PATCH 085/350] Release version 3.7.5 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 35ac633..31a8e24 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.4' +__version__ = '3.7.5' From 52ebb5a1a78039dcf12a839bd7975502952c5475 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 9 Jan 2021 21:22:49 +0300 Subject: [PATCH 086/350] drop_pending_updates in set_webhook --- telebot/__init__.py | 7 +++++-- telebot/apihelper.py | 11 +++++++---- tests/test_telebot.py | 16 +++++++++++----- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index a6a20ff..f166a27 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -45,6 +45,7 @@ class ExceptionHandler: Class for handling exceptions while Polling """ + # noinspection PyMethodMayBeStatic,PyUnusedLocal def handle(self, exception): return False @@ -235,7 +236,8 @@ class TeleBot: """ self.reply_backend.load_handlers(filename, del_file_after_loading) - def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, timeout=None): + def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): """ Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. @@ -246,10 +248,11 @@ class TeleBot: :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS + :param drop_pending_updates: Pass True to drop all pending updates :param timeout: Integer. Request connection timeout :return: """ - return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, timeout) + return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, drop_pending_updates, timeout) def delete_webhook(self, drop_pending_updates=None, timeout=None): """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index f059cb4..1cedbc8 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -206,7 +206,8 @@ def send_message( return _make_request(token, method_url, params=payload, method='post') -def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, timeout=None): +def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): method_url = r'setWebhook' payload = { 'url': url if url else "", @@ -216,10 +217,12 @@ def set_webhook(token, url=None, certificate=None, max_connections=None, allowed files = {'certificate': certificate} if max_connections: payload['max_connections'] = max_connections - if allowed_updates is not None: # Empty lists should pass + if allowed_updates is not None: # Empty lists should pass payload['allowed_updates'] = json.dumps(allowed_updates) - if ip_address is not None: # Empty string should pass + if ip_address is not None: # Empty string should pass payload['ip_address'] = ip_address + if drop_pending_updates is not None: # Any bool value should pass + payload['drop_pending_updates'] = drop_pending_updates if timeout: payload['connect-timeout'] = timeout return _make_request(token, method_url, params=payload, files=files) @@ -228,7 +231,7 @@ def set_webhook(token, url=None, certificate=None, max_connections=None, allowed def delete_webhook(token, drop_pending_updates=None, timeout=None): method_url = r'deleteWebhook' payload = {} - if drop_pending_updates is not None: # None / True / False + if drop_pending_updates is not None: # Any bool value should pass payload['drop_pending_updates'] = drop_pending_updates if timeout: payload['connect-timeout'] = timeout diff --git a/tests/test_telebot.py b/tests/test_telebot.py index 6ca56fb..547d29d 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -48,6 +48,7 @@ class TestTeleBot: bot = telebot.TeleBot('') msg = self.create_text_message(r'https://web.telegram.org/') + # noinspection PyUnusedLocal @bot.message_handler(regexp=r'((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)') def command_url(message): msg.text = 'got' @@ -60,6 +61,7 @@ class TestTeleBot: bot = telebot.TeleBot('') msg = self.create_text_message(r'lambda_text') + # noinspection PyUnusedLocal @bot.message_handler(func=lambda message: r'lambda' in message.text) def command_url(message): msg.text = 'got' @@ -72,6 +74,7 @@ class TestTeleBot: bot = telebot.TeleBot('') msg = self.create_text_message(r'text') + # noinspection PyUnusedLocal @bot.message_handler(func=lambda message: r'lambda' in message.text) def command_url(message): msg.text = 'got' @@ -84,6 +87,7 @@ class TestTeleBot: bot = telebot.TeleBot('') msg = self.create_text_message(r'web.telegram.org/') + # noinspection PyUnusedLocal @bot.message_handler(regexp=r'((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)') def command_url(message): msg.text = 'got' @@ -522,6 +526,7 @@ class TestTeleBot: tb = telebot.TeleBot('') update = self.create_message_update('/help') + # noinspection PyUnusedLocal @tb.middleware_handler(update_types=['message']) def middleware(tb_instance, message): message.text = 'got' @@ -542,9 +547,10 @@ class TestTeleBot: tb = telebot.TeleBot('') update = self.create_message_update('/help') + # noinspection PyUnusedLocal @tb.middleware_handler() - def middleware(tb_instance, update): - update.message.text = 'got' + def middleware(tb_instance, mw_update): + mw_update.message.text = 'got' @tb.message_handler(func=lambda m: m.text == 'got') def command_handler(message): @@ -556,6 +562,6 @@ class TestTeleBot: def test_chat_permissions(self): return # CHAT_ID is private chat, no permissions can be set - tb = telebot.TeleBot(TOKEN) - permissions = types.ChatPermissions(can_send_messages=True, can_send_polls=False) - msg = tb.set_chat_permissions(CHAT_ID, permissions) + #tb = telebot.TeleBot(TOKEN) + #permissions = types.ChatPermissions(can_send_messages=True, can_send_polls=False) + #msg = tb.set_chat_permissions(CHAT_ID, permissions) From 58281f0a1000fe510d53ca541b4908754743e626 Mon Sep 17 00:00:00 2001 From: Alireza Date: Mon, 11 Jan 2021 02:50:17 +0330 Subject: [PATCH 087/350] Added copyMessage method --- telebot/__init__.py | 25 ++++++++++++++++++++++++- telebot/apihelper.py | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f166a27..91cd332 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -750,6 +750,24 @@ class TeleBot: return types.Message.de_json( apihelper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) + def copy_message(self, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, + reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, + disable_notification=None, timeout=None): + # FIXME: rewrite the docstring + """ + Use this method to copy messages of any kind. + :param disable_notification: + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param timeout: + :return: API reply. + """ + return types.Message.de_json( + apihelper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, + reply_to_message_id, allow_sending_without_reply, reply_markup, + disable_notification, timeout)) + def delete_message(self, chat_id, message_id, timeout=None): """ Use this method to delete message. Returns True on success. @@ -863,7 +881,7 @@ class TeleBot: """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - return types.Message.de_json( + return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout, caption, thumb)) @@ -2267,6 +2285,11 @@ class AsyncTeleBot(TeleBot): def forward_message(self, *args, **kwargs): return TeleBot.forward_message(self, *args, **kwargs) + @util.async_dec() + def copy_message(self, *args, **kwargs): + return TeleBot.copy_message(self, *args, **kwargs) + + @util.async_dec() def delete_message(self, *args): return TeleBot.delete_message(self, *args) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 1cedbc8..9ba0a1a 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -326,6 +326,30 @@ def forward_message( return _make_request(token, method_url, params=payload) +def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, + reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, + disable_notification=None, timeout=None): + method_url = r'copyMessage' + payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} + if caption is not None: + payload['caption'] = caption + if parse_mode is not None: + payload['parse_mode'] = parse_mode + if caption_entities is not None: + payload['caption_entities'] = caption_entities + if reply_to_message_id is not None: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup is not None: + payload['reply_markup'] = reply_markup + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['connect-timeout'] = timeout + return _make_request(token, method_url, params=payload) + + def send_dice( token, chat_id, emoji=None, disable_notification=None, reply_to_message_id=None, From b684c4f60de4604d2cf959efcafbd33a3d654989 Mon Sep 17 00:00:00 2001 From: Alireza Date: Tue, 12 Jan 2021 11:17:53 +0330 Subject: [PATCH 088/350] Fix Things on copyMessage --- telebot/__init__.py | 17 ++++++++++++----- telebot/apihelper.py | 10 ++++++++-- telebot/types.py | 26 +++++++++++++++++++++++++- tests/test_telebot.py | 7 +++++++ 4 files changed, 52 insertions(+), 8 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 91cd332..b8b679e 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -7,6 +7,8 @@ import sys import threading import time +from telebot.types import MessageID + logger = logging.getLogger('TeleBot') formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' @@ -751,19 +753,24 @@ class TeleBot: apihelper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) def copy_message(self, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, - reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, - disable_notification=None, timeout=None): - # FIXME: rewrite the docstring + disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, + timeout=None): """ Use this method to copy messages of any kind. - :param disable_notification: :param chat_id: which chat to forward :param from_chat_id: which chat message from :param message_id: message id + :param caption: + :param parse_mode: + :param caption_entities: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: :param timeout: :return: API reply. """ - return types.Message.de_json( + return MessageID.de_json( apihelper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, reply_to_message_id, allow_sending_without_reply, reply_markup, disable_notification, timeout)) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 9ba0a1a..407ffcf 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -336,11 +336,11 @@ def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_m if parse_mode is not None: payload['parse_mode'] = parse_mode if caption_entities is not None: - payload['caption_entities'] = caption_entities + payload['caption_entities'] = _convert_entites(caption_entities) if reply_to_message_id is not None: payload['reply_to_message_id'] = reply_to_message_id if reply_markup is not None: - payload['reply_markup'] = reply_markup + payload['reply_markup'] = _convert_markup(reply_markup) if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply if disable_notification is not None: @@ -1309,6 +1309,12 @@ def _convert_markup(markup): return markup +def _convert_entites(entites): + if isinstance(entites[0], types.JsonSerializable): + return [entity.to_json() for entity in entites] + return entites + + def convert_input_media(media): if isinstance(media, types.InputMedia): return media.convert_input_media() diff --git a/telebot/types.py b/telebot/types.py index 73e5db5..94316c0 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -261,6 +261,19 @@ class Chat(JsonDeserializable): self.location = location +class MessageID(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if(json_string is None): + return None + obj = cls.check_json(json_string) + message_id = obj['message_id'] + return cls(message_id) + + def __init__(self, message_id): + self.message_id = message_id + + class Message(JsonDeserializable): @classmethod def de_json(cls, json_string): @@ -548,7 +561,7 @@ class Message(JsonDeserializable): return self.__html_text(self.caption, self.caption_entities) -class MessageEntity(JsonDeserializable): +class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable): @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -569,6 +582,17 @@ class MessageEntity(JsonDeserializable): self.user = user self.language = language + def to_json(self): + return json.dumps(self.to_dict()) + + def to_dict(self): + return {"type": self.type, + "offset": self.offset, + "length": self.length, + "url": self.url, + "user": self.user, + "language": self.language} + class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): @classmethod diff --git a/tests/test_telebot.py b/tests/test_telebot.py index 547d29d..a70911e 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -293,6 +293,13 @@ class TestTeleBot: ret_msg = tb.forward_message(CHAT_ID, CHAT_ID, msg.message_id) assert ret_msg.forward_from + def test_copy_message(self): + text = 'CI copy_message Test Message' + tb = telebot.TeleBot(TOKEN) + msg = tb.send_message(CHAT_ID, text) + ret_msg = tb.copy_message(CHAT_ID, CHAT_ID, msg.message_id) + assert ret_msg + def test_forward_message_dis_noti(self): text = 'CI forward_message Test Message' tb = telebot.TeleBot(TOKEN) From b561e353303f6befc5d4a39e53ada27b070a41d8 Mon Sep 17 00:00:00 2001 From: Alireza Date: Tue, 12 Jan 2021 11:19:57 +0330 Subject: [PATCH 089/350] Update __init__.py --- telebot/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index b8b679e..8696ded 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -7,8 +7,6 @@ import sys import threading import time -from telebot.types import MessageID - logger = logging.getLogger('TeleBot') formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' @@ -770,7 +768,7 @@ class TeleBot: :param timeout: :return: API reply. """ - return MessageID.de_json( + return types.MessageID.de_json( apihelper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, reply_to_message_id, allow_sending_without_reply, reply_markup, disable_notification, timeout)) From 6e3e1591097774eaf130d99e18842a52411cc785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa=20Coego?= <37184503+dgarcoe@users.noreply.github.com> Date: Wed, 13 Jan 2021 17:55:08 +0100 Subject: [PATCH 090/350] Update README.md I included my bot in the README. Thanks for the library! --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 20e25a1..ef04483 100644 --- a/README.md +++ b/README.md @@ -670,5 +670,6 @@ Get help. Discuss. Chat. * [Bot Hour](https://t.me/roadtocode_bot) a little bot that say the time in different countries by [@diegop384](https://github.com/diegop384) [repo](https://github.com/diegop384/telegrambothour) * [moodforfood_bot](https://t.me/moodforfood_bot) This bot will provide you with a list of food place(s) near your current Telegram location, which you are prompted to share. The API for all this info is from https://foursquare.com/. by [@sophiamarani](https://github.com/sophiamarani) * [Donation with Amazon](https://t.me/donamazonbot) by [@barbax7](https://github.com/barbax7) This bot donates amazon advertising commissions to the non-profit organization chosen by the user. +* [COVID-19 Galicia Bot](https://t.me/covid19_galicia_bot) by [@dgarcoe](https://github.com/dgarcoe) This bot provides daily data related to the COVID19 crisis in Galicia (Spain) obtained from official government sources. Want to have your bot listed here? Just make a pull requet. From 82838e1d26bd26ff967fc5fbc4bdbf4f217fbb98 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 14 Jan 2021 03:44:37 +0300 Subject: [PATCH 091/350] Infinity polling fall down fixed --- telebot/__init__.py | 4 +++- telebot/apihelper.py | 2 +- telebot/util.py | 8 +++++--- telebot/version.py | 2 +- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f166a27..af5309d 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -6,6 +6,7 @@ import re import sys import threading import time +import traceback logger = logging.getLogger('TeleBot') formatter = logging.Formatter( @@ -459,7 +460,8 @@ class TeleBot: try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) except Exception as e: - logger.error("Infinity polling exception: {}".format(e)) + logger.error("Infinity polling exception: %s", str(e)) + logger.debug("Exception traceback:\n%s", traceback.format_exc()) time.sleep(3) continue logger.info("Infinity polling: polling exited") diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 1cedbc8..00763e0 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -254,7 +254,7 @@ def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=No if limit: payload['limit'] = limit if timeout: - payload['timeout'] = timeout + payload['connect-timeout'] = timeout if long_polling_timeout: payload['long_polling_timeout'] = long_polling_timeout if allowed_updates is not None: # Empty lists should pass diff --git a/telebot/util.py b/telebot/util.py index 713cbc3..1226ecc 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -235,8 +235,10 @@ def or_clear(self): def orify(e, changed_callback): - e._set = e.set - e._clear = e.clear + if not hasattr(e, "_set"): + e._set = e.set + if not hasattr(e, "_clear"): + e._clear = e.clear e.changed = changed_callback e.set = lambda: or_set(e) e.clear = lambda: or_clear(e) @@ -244,7 +246,7 @@ def orify(e, changed_callback): def OrEvent(*events): or_event = threading.Event() def changed(): - bools = [e.is_set() for e in events] + bools = [ev.is_set() for ev in events] if any(bools): or_event.set() else: diff --git a/telebot/version.py b/telebot/version.py index 31a8e24..2400619 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.5' +__version__ = '3.7.5.u1' From f56da17741c3cd045d98087a31bf9404081892a8 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 14 Jan 2021 15:45:47 +0300 Subject: [PATCH 092/350] Fix restrict_chat_member until_date bug --- telebot/apihelper.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 00763e0..41b647c 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import time +import datetime try: import ujson as json @@ -709,7 +710,9 @@ def get_method_by_type(data_type): def kick_chat_member(token, chat_id, user_id, until_date=None): method_url = 'kickChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} - if until_date: + if isinstance(until_date, datetime.datetime): + payload['until_date'] = until_date.timestamp() + else: payload['until_date'] = until_date return _make_request(token, method_url, params=payload, method='post') @@ -730,8 +733,6 @@ def restrict_chat_member( can_invite_users=None, can_pin_messages=None): method_url = 'restrictChatMember' permissions = {} - if until_date is not None: - permissions['until_date'] = until_date if can_send_messages is not None: permissions['can_send_messages'] = can_send_messages if can_send_media_messages is not None: @@ -750,6 +751,11 @@ def restrict_chat_member( permissions['can_pin_messages'] = can_pin_messages permissions_json = json.dumps(permissions) payload = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions_json} + if until_date is not None: + if isinstance(until_date, datetime.datetime): + payload['until_date'] = until_date.timestamp() + else: + payload['until_date'] = until_date return _make_request(token, method_url, params=payload, method='post') @@ -1246,7 +1252,10 @@ def send_poll( if open_period is not None: payload['open_period'] = open_period if close_date is not None: - payload['close_date'] = close_date + if isinstance(close_date, datetime.datetime): + payload['close_date'] = close_date.timestamp() + else: + payload['close_date'] = close_date if is_closed is not None: payload['is_closed'] = is_closed From 2e5250ec9844094a2047589b4278b1366307f10a Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 14 Jan 2021 15:48:30 +0300 Subject: [PATCH 093/350] Version update to previous commit --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 2400619..60813d8 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.5.u1' +__version__ = '3.7.5.u2' From e9ba2fd8bbf9f4683d98e8fc8256647b517e7545 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 16 Jan 2021 02:14:29 +0300 Subject: [PATCH 094/350] Polling timeout fix --- telebot/apihelper.py | 5 ++++- telebot/version.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 41b647c..98ed5eb 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -69,8 +69,11 @@ def _make_request(token, method_name, method='get', params=None, files=None): if 'connect-timeout' in params: connect_timeout = params.pop('connect-timeout') + 10 if 'long_polling_timeout' in params: - # For getUpdates: the only function with timeout on the BOT API side + # For getUpdates + # The only function with timeout on the BOT API side params['timeout'] = params.pop('long_polling_timeout') + # Long polling hangs for given time. Read timeout should be greater that long_polling_timeout + read_timeout = max(params['timeout'] + 10, read_timeout) result = None diff --git a/telebot/version.py b/telebot/version.py index 60813d8..308e7a3 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.5.u2' +__version__ = '3.7.5.u3' From bc54a5379cd10ca52d0957c29a3a6908e11fc454 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 16 Jan 2021 23:50:25 +0300 Subject: [PATCH 095/350] Added short live sessions --- telebot/apihelper.py | 23 ++++++++++++++++++----- telebot/version.py | 2 +- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 98ed5eb..849bf55 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import time -import datetime +from datetime import datetime try: import ujson as json @@ -29,6 +29,7 @@ FILE_URL = None CONNECT_TIMEOUT = 3.5 READ_TIMEOUT = 9999 +SESSION_TIME_TO_LIVE = None # In seconds. None - live forever, 0 - one-time RETRY_ON_ERROR = False RETRY_TIMEOUT = 2 @@ -40,7 +41,19 @@ ENABLE_MIDDLEWARE = False def _get_req_session(reset=False): - return util.per_thread('req_session', lambda: session if session else requests.session(), reset) + if SESSION_TIME_TO_LIVE: + # If session TTL is set - check time passed + creation_date = util.per_thread('req_session_time', lambda: datetime(2021, 1, 1), reset) + if (datetime.now() - creation_date).total_seconds() > SESSION_TIME_TO_LIVE: + # Force session reset + reset = True + + if SESSION_TIME_TO_LIVE == 0: + # Session is one-time use + return requests.sessions.Session() + else: + # Session lives some time or forever once created. Default + return util.per_thread('req_session', lambda: session if session else requests.sessions.Session(), reset) def _make_request(token, method_name, method='get', params=None, files=None): @@ -713,7 +726,7 @@ def get_method_by_type(data_type): def kick_chat_member(token, chat_id, user_id, until_date=None): method_url = 'kickChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} - if isinstance(until_date, datetime.datetime): + if isinstance(until_date, datetime): payload['until_date'] = until_date.timestamp() else: payload['until_date'] = until_date @@ -755,7 +768,7 @@ def restrict_chat_member( permissions_json = json.dumps(permissions) payload = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions_json} if until_date is not None: - if isinstance(until_date, datetime.datetime): + if isinstance(until_date, datetime): payload['until_date'] = until_date.timestamp() else: payload['until_date'] = until_date @@ -1255,7 +1268,7 @@ def send_poll( if open_period is not None: payload['open_period'] = open_period if close_date is not None: - if isinstance(close_date, datetime.datetime): + if isinstance(close_date, datetime): payload['close_date'] = close_date.timestamp() else: payload['close_date'] = close_date diff --git a/telebot/version.py b/telebot/version.py index 308e7a3..fdd20d3 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.5.u3' +__version__ = '3.7.5.u4' From ec8714ad3a267276c45f376605b78af7a7078b44 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 17 Jan 2021 00:43:52 +0300 Subject: [PATCH 096/350] Short live sessions u1 --- telebot/apihelper.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 849bf55..2a42318 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -43,10 +43,12 @@ ENABLE_MIDDLEWARE = False def _get_req_session(reset=False): if SESSION_TIME_TO_LIVE: # If session TTL is set - check time passed - creation_date = util.per_thread('req_session_time', lambda: datetime(2021, 1, 1), reset) + creation_date = util.per_thread('req_session_time', lambda: datetime.now(), reset) if (datetime.now() - creation_date).total_seconds() > SESSION_TIME_TO_LIVE: # Force session reset reset = True + # Save reset time + util.per_thread('req_session_time', lambda: datetime.now(), True) if SESSION_TIME_TO_LIVE == 0: # Session is one-time use From ea51b1e95e0430d7128bc055a02e19f543172267 Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Sun, 17 Jan 2021 01:06:47 +0100 Subject: [PATCH 097/350] hide token from debug logs prevent leaks of the bot token by hiding it from the log --- telebot/apihelper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 2a42318..27d3c95 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -73,7 +73,7 @@ def _make_request(token, method_name, method='get', params=None, files=None): else: request_url = "https://api.telegram.org/bot{0}/{1}".format(token, method_name) - logger.debug("Request: method={0} url={1} params={2} files={3}".format(method, request_url, params, files)) + logger.debug("Request: method={0} url={1} params={2} files={3}".format(method, request_url, params, files).replace(token, "{TOKEN}")) read_timeout = READ_TIMEOUT connect_timeout = CONNECT_TIMEOUT if files and format_header_param: From 3109e35bb4f0d5f921a72ecb54eb1dce9f0bfa17 Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Sun, 17 Jan 2021 01:26:38 +0100 Subject: [PATCH 098/350] show bot id --- telebot/apihelper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 27d3c95..4f9f84c 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -73,7 +73,7 @@ def _make_request(token, method_name, method='get', params=None, files=None): else: request_url = "https://api.telegram.org/bot{0}/{1}".format(token, method_name) - logger.debug("Request: method={0} url={1} params={2} files={3}".format(method, request_url, params, files).replace(token, "{TOKEN}")) + logger.debug("Request: method={0} url={1} params={2} files={3}".format(method, request_url, params, files).replace(token, token.split(':')[0] + ":{TOKEN}")) read_timeout = READ_TIMEOUT connect_timeout = CONNECT_TIMEOUT if files and format_header_param: From d57aa04bfb77a29d94d5c055a08aee3297179d12 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 18 Jan 2021 01:02:19 +0300 Subject: [PATCH 099/350] Release v.3.7.6 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index fdd20d3..e3cfe4c 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.5.u4' +__version__ = '3.7.6' From 80c9e17fd41123b17b336079707d3921342bc596 Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Sun, 17 Jan 2021 23:22:45 +0100 Subject: [PATCH 100/350] add apihelper.ENABLE_MIDDLEWARE = True to readme --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ef04483..eb1cc33 100644 --- a/README.md +++ b/README.md @@ -231,9 +231,11 @@ def test_callback(call): A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are -executed. +executed. Middleware processing is disabled by default, enable it by setting `apihelper.ENABLE_MIDDLEWARE = True`. ```python +apihelper.ENABLE_MIDDLEWARE = True + @bot.middleware_handler(update_types=['message']) def modify_message(bot_instance, message): # modifying the message before it reaches any other handler From f93916372e22a015e0d5b1f25d26f9114f6d2c3b Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Sun, 17 Jan 2021 23:34:54 +0100 Subject: [PATCH 101/350] document edit_message_text in readme --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index eb1cc33..57d49e4 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,9 @@ updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout): # sendMessage tb.send_message(chat_id, text) +# editMessageText +tb.send_message(new_text, chat_id, message_id) + # forwardMessage tb.forward_message(to_chat_id, from_chat_id, message_id) From 6d7116d521df48c86b4c40d0383d018d8efb5db2 Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Sun, 17 Jan 2021 23:45:23 +0100 Subject: [PATCH 102/350] document SESSION_TIME_TO_LIVE --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 57d49e4..975093c 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ * [F.A.Q.](#faq) * [Bot 2.0](#bot-20) * [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat) + * [How can I handle reocurring ConnectionResetErrors?](#how-can-i-handle-reocurring-connectionreseterrors) * [The Telegram Chat Group](#the-telegram-chat-group) * [More examples](#more-examples) * [Bots using this API](#bots-using-this-api) @@ -603,6 +604,10 @@ if message.chat.type == "channel": ``` +### How can I handle reocurring ConnectionResetErrors? + +Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add `apihelper.SESSION_TIME_TO_LIVE = 5 * 60` to your initialisation to force recreation after 5 minutes without any activity. + ## The Telegram Chat Group Get help. Discuss. Chat. From cd31c8db5c9171515c0f22ab89a1a35e72ef615f Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Sun, 17 Jan 2021 23:47:03 +0100 Subject: [PATCH 103/350] fix example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 975093c..711e8a3 100644 --- a/README.md +++ b/README.md @@ -279,7 +279,7 @@ updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout): tb.send_message(chat_id, text) # editMessageText -tb.send_message(new_text, chat_id, message_id) +tb.edit_message_text(new_text, chat_id, message_id) # forwardMessage tb.forward_message(to_chat_id, from_chat_id, message_id) From fdf2838669309d9fafb72c122a2705bd2f7a82aa Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 19 Jan 2021 01:27:39 +0300 Subject: [PATCH 104/350] Minor update to copyMessage --- telebot/__init__.py | 8 ++++---- telebot/apihelper.py | 21 +++++++++++++-------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 80f8c35..5396ee7 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -753,8 +753,8 @@ class TeleBot: apihelper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) def copy_message(self, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, - disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, - timeout=None): + disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None): """ Use this method to copy messages of any kind. :param chat_id: which chat to forward @@ -772,8 +772,8 @@ class TeleBot: """ return types.MessageID.de_json( apihelper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, - reply_to_message_id, allow_sending_without_reply, reply_markup, - disable_notification, timeout)) + disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, + timeout)) def delete_message(self, chat_id, message_id, timeout=None): """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 4725501..140479f 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -346,24 +346,24 @@ def forward_message( def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, - reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, - disable_notification=None, timeout=None): + disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None): method_url = r'copyMessage' payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} if caption is not None: payload['caption'] = caption - if parse_mode is not None: + if parse_mode: payload['parse_mode'] = parse_mode if caption_entities is not None: payload['caption_entities'] = _convert_entites(caption_entities) - if reply_to_message_id is not None: + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if reply_markup is not None: payload['reply_markup'] = _convert_markup(reply_markup) if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply - if disable_notification is not None: - payload['disable_notification'] = disable_notification if timeout: payload['connect-timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -1337,9 +1337,14 @@ def _convert_markup(markup): def _convert_entites(entites): - if isinstance(entites[0], types.JsonSerializable): + if entites is None: + return None + elif len(entites) == 0: + return [] + elif isinstance(entites[0], types.JsonSerializable): return [entity.to_json() for entity in entites] - return entites + else: + return entites def convert_input_media(media): From a7d1dbf0e9b7675aeabad198d84c4d68aff06b24 Mon Sep 17 00:00:00 2001 From: Robin Modisch Date: Wed, 20 Jan 2021 11:04:55 +0100 Subject: [PATCH 105/350] add MineGramBot --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 711e8a3..7f91251 100644 --- a/README.md +++ b/README.md @@ -681,5 +681,6 @@ Get help. Discuss. Chat. * [moodforfood_bot](https://t.me/moodforfood_bot) This bot will provide you with a list of food place(s) near your current Telegram location, which you are prompted to share. The API for all this info is from https://foursquare.com/. by [@sophiamarani](https://github.com/sophiamarani) * [Donation with Amazon](https://t.me/donamazonbot) by [@barbax7](https://github.com/barbax7) This bot donates amazon advertising commissions to the non-profit organization chosen by the user. * [COVID-19 Galicia Bot](https://t.me/covid19_galicia_bot) by [@dgarcoe](https://github.com/dgarcoe) This bot provides daily data related to the COVID19 crisis in Galicia (Spain) obtained from official government sources. +* [MineGramBot](https://github.com/ModischFabrications/MineGramBot) by [ModischFabrications](https://github.com/ModischFabrications). This bot can start, stop and monitor a minecraft server. Want to have your bot listed here? Just make a pull requet. From 20d0ab229f2e335509231011510c9fbb4ad4bfbc Mon Sep 17 00:00:00 2001 From: dexpiper <58036191+dexpiper@users.noreply.github.com> Date: Thu, 21 Jan 2021 17:19:54 +0300 Subject: [PATCH 106/350] README list of bots update Add another bot to the list below --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7f91251..1ce7150 100644 --- a/README.md +++ b/README.md @@ -682,5 +682,6 @@ Get help. Discuss. Chat. * [Donation with Amazon](https://t.me/donamazonbot) by [@barbax7](https://github.com/barbax7) This bot donates amazon advertising commissions to the non-profit organization chosen by the user. * [COVID-19 Galicia Bot](https://t.me/covid19_galicia_bot) by [@dgarcoe](https://github.com/dgarcoe) This bot provides daily data related to the COVID19 crisis in Galicia (Spain) obtained from official government sources. * [MineGramBot](https://github.com/ModischFabrications/MineGramBot) by [ModischFabrications](https://github.com/ModischFabrications). This bot can start, stop and monitor a minecraft server. +* [Tabletop DiceBot](https://github.com/dexpiper/tabletopdicebot) by [dexpiper](https://github.com/dexpiper). This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. Want to have your bot listed here? Just make a pull requet. From 8790f26e682ad2702e1bd65ca7833e42b7c6c34c Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 30 Jan 2021 14:41:19 +0300 Subject: [PATCH 107/350] Custom logging level for infinity_polling --- telebot/__init__.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 5396ee7..2a0c6cd 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -455,17 +455,28 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, long_polling_timeout=20, *args, **kwargs): + def infinity_polling(self, timeout=20, long_polling_timeout=20, logger_level=logging.ERROR, *args, **kwargs): + """ + Wrap polling with infinite loop and exception handling to avoid bot stops polling. + + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param logger_level: Custom logging level for infinity_polling logging. None/NOTSET = no error logging + """ while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) except Exception as e: - logger.error("Infinity polling exception: %s", str(e)) - logger.debug("Exception traceback:\n%s", traceback.format_exc()) + if logger_level and logger_level >= logging.ERROR: + logger.error("Infinity polling exception: %s", str(e)) + if logger_level and logger_level >= logging.DEBUG: + logger.error("Exception traceback:\n%s", traceback.format_exc()) time.sleep(3) continue - logger.info("Infinity polling: polling exited") - logger.info("Break infinity polling") + if logger_level and logger_level >= logging.INFO: + logger.error("Infinity polling: polling exited") + if logger_level and logger_level >= logging.INFO: + logger.error("Break infinity polling") def polling(self, none_stop=False, interval=0, timeout=20, long_polling_timeout=20): """ @@ -475,10 +486,10 @@ class TeleBot: Warning: Do not call this function more than once! Always get updates. - :param interval: + :param interval: Delay between two update retrivals :param none_stop: Do not stop polling when an ApiException occurs. - :param timeout: Integer. Request connection timeout - :param long_polling_timeout. Timeout in seconds for long polling. + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :return: """ if self.threaded: From b39244f827eed7b57992a3671b05d3c32e58c934 Mon Sep 17 00:00:00 2001 From: Mohammad Arab Anvari Date: Tue, 16 Feb 2021 13:41:56 +0330 Subject: [PATCH 108/350] Add my bot to Readme.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1ce7150..4d643aa 100644 --- a/README.md +++ b/README.md @@ -683,5 +683,5 @@ Get help. Discuss. Chat. * [COVID-19 Galicia Bot](https://t.me/covid19_galicia_bot) by [@dgarcoe](https://github.com/dgarcoe) This bot provides daily data related to the COVID19 crisis in Galicia (Spain) obtained from official government sources. * [MineGramBot](https://github.com/ModischFabrications/MineGramBot) by [ModischFabrications](https://github.com/ModischFabrications). This bot can start, stop and monitor a minecraft server. * [Tabletop DiceBot](https://github.com/dexpiper/tabletopdicebot) by [dexpiper](https://github.com/dexpiper). This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. - +* [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calnedar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) Want to have your bot listed here? Just make a pull requet. From 07e93f95a12f2cd97760152d1869576709affa02 Mon Sep 17 00:00:00 2001 From: Aleksandr Date: Tue, 9 Mar 2021 02:05:44 +0300 Subject: [PATCH 109/350] Removed my bot from list The link is now dead, and so is that bot --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 4d643aa..4fe7ece 100644 --- a/README.md +++ b/README.md @@ -627,7 +627,6 @@ Get help. Discuss. Chat. * [Send to Kindle Bot](https://telegram.me/Send2KindleBot) by *GabrielRF* - Send to Kindle files or links to files. * [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) ([source](https://github.com/GabrielRF/telegram-lmgtfy_bot)) by *GabrielRF* - Let me Google that for you. * [Telegram UrlProBot](https://github.com/GabrielRF/telegram-urlprobot) ([source](https://github.com/GabrielRF/telegram-urlprobot)) by *GabrielRF* - URL shortener and URL expander. -* [Telegram Proxy Bot](https://bitbucket.org/master_groosha/telegram-proxy-bot) by *Groosha* - A simple BITM (bot-in-the-middle) for Telegram acting as some kind of "proxy". * [Telegram Proxy Bot](https://github.com/mrgigabyte/proxybot) by *mrgigabyte* - `Credits for the original version of this bot goes to` **Groosha** `, simply added certain features which I thought were needed`. * [RadRetroRobot](https://github.com/Tronikart/RadRetroRobot) by *Tronikart* - Multifunctional Telegram Bot RadRetroRobot. * [League of Legends bot](https://telegram.me/League_of_Legends_bot) ([source](https://github.com/i32ropie/lol)) by *i32ropie* From f23059d7ec9febd9d66d2891b9484ad529a75cda Mon Sep 17 00:00:00 2001 From: Andrea Barbagallo <66796758+barbax7@users.noreply.github.com> Date: Thu, 18 Mar 2021 08:38:47 +0100 Subject: [PATCH 110/350] Added Price Tracker bot --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4fe7ece..51a7a7f 100644 --- a/README.md +++ b/README.md @@ -682,5 +682,6 @@ Get help. Discuss. Chat. * [COVID-19 Galicia Bot](https://t.me/covid19_galicia_bot) by [@dgarcoe](https://github.com/dgarcoe) This bot provides daily data related to the COVID19 crisis in Galicia (Spain) obtained from official government sources. * [MineGramBot](https://github.com/ModischFabrications/MineGramBot) by [ModischFabrications](https://github.com/ModischFabrications). This bot can start, stop and monitor a minecraft server. * [Tabletop DiceBot](https://github.com/dexpiper/tabletopdicebot) by [dexpiper](https://github.com/dexpiper). This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. -* [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calnedar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) +* [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calendar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) +* [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. Want to have your bot listed here? Just make a pull requet. From 96e0be89420608438d1ad2b5827ce8ffe673ced7 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 28 Mar 2021 11:54:46 +0300 Subject: [PATCH 111/350] Heroku example update --- examples/webhook_examples/webhook_flask_heroku_echo.py | 4 +++- telebot/__init__.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/webhook_examples/webhook_flask_heroku_echo.py b/examples/webhook_examples/webhook_flask_heroku_echo.py index 7bbf2bf..a465abc 100644 --- a/examples/webhook_examples/webhook_flask_heroku_echo.py +++ b/examples/webhook_examples/webhook_flask_heroku_echo.py @@ -21,7 +21,9 @@ def echo_message(message): @server.route('/' + TOKEN, methods=['POST']) def getMessage(): - bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))]) + json_string = request.get_data().decode('utf-8') + update = telebot.types.Update.de_json(json_string) + bot.process_new_updates([update]) return "!", 200 diff --git a/telebot/__init__.py b/telebot/__init__.py index 2a0c6cd..7fcffc9 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -461,7 +461,7 @@ class TeleBot: :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) - :param logger_level: Custom logging level for infinity_polling logging. None/NOTSET = no error logging + :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging """ while not self.__stop_polling.is_set(): try: From 209d9b27b4396ead58f3bc447efae461b358f126 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 28 Mar 2021 11:57:05 +0300 Subject: [PATCH 112/350] Minor release --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index e3cfe4c..182ec1e 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.6' +__version__ = '3.7.7' From 6c90da793ec9e8b1021a0500a3598ee30009afae Mon Sep 17 00:00:00 2001 From: David256 Date: Thu, 1 Apr 2021 14:56:08 -0500 Subject: [PATCH 113/350] New property full_name --- telebot/types.py | 7 +++++++ tests/test_types.py | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 94316c0..21c43aa 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -179,6 +179,13 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): self.can_read_all_group_messages = can_read_all_group_messages self.supports_inline_queries = supports_inline_queries + @property + def full_name(self): + full_name = self.first_name + if self.last_name: + full_name += f' {self.last_name}' + return full_name + def to_json(self): return json.dumps(self.to_dict()) diff --git a/tests/test_types.py b/tests/test_types.py index 173cda9..355f690 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -6,9 +6,10 @@ from telebot import types def test_json_user(): - jsonstring = r'{"id":101176298,"first_name":"RDSSBOT","username":"rdss_bot","is_bot":true}' + jsonstring = r'{"id":101176298,"first_name":"RDSSBOT","last_name":")))","username":"rdss_bot","is_bot":true}' u = types.User.de_json(jsonstring) assert u.id == 101176298 + assert u.full_name == 'RDSSBOT )))' def test_json_message(): From 2f69917a8221ff0feb4baf84577dc814711c5d44 Mon Sep 17 00:00:00 2001 From: David256 Date: Thu, 1 Apr 2021 16:52:12 -0500 Subject: [PATCH 114/350] Change fstrings to string formatting --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 21c43aa..9cad691 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -183,7 +183,7 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): def full_name(self): full_name = self.first_name if self.last_name: - full_name += f' {self.last_name}' + full_name += ' {0}'.format(self.last_name) return full_name def to_json(self): From a39fb1472685285af6389df9a41b44a3ef137be9 Mon Sep 17 00:00:00 2001 From: FosterToster Date: Sun, 18 Apr 2021 19:56:52 +0700 Subject: [PATCH 115/350] middleware handlers exception handling --- telebot/__init__.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 7fcffc9..597d486 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -339,13 +339,19 @@ class TeleBot: new_pre_checkout_queries = None new_polls = None new_poll_answers = None - + for update in updates: if apihelper.ENABLE_MIDDLEWARE: - self.process_middlewares(update) - + try: + self.process_middlewares(update) + except Exception as e: + logger.error(str(e)) + update.middleware_error = e # for future handling if it needed + if update.update_id > self.last_update_id: self.last_update_id = update.update_id + if hasattr(update, 'middleware_error'): + continue if update.message: if new_messages is None: new_messages = [] new_messages.append(update.message) @@ -443,11 +449,19 @@ class TeleBot: for update_type, middlewares in self.typed_middleware_handlers.items(): if getattr(update, update_type) is not None: for typed_middleware_handler in middlewares: - typed_middleware_handler(self, getattr(update, update_type)) + try: + typed_middleware_handler(self, getattr(update, update_type)) + except Exception as e: + e.args = (f'Typed middleware handler "{typed_middleware_handler.__qualname__}" raised exception: {str(e)}',) + raise if len(self.default_middleware_handlers) > 0: for default_middleware_handler in self.default_middleware_handlers: - default_middleware_handler(self, update) + try: + default_middleware_handler(self, update) + except Exception as e: + e.args = (f'Default middleware handler "{typed_middleware_handler.__qualname__}" raised exception: {str(e)}',) + raise def __notify_update(self, new_messages): if len(self.update_listener) == 0: From 042d8c17da814b2a5706f6f1d55474a1c8668178 Mon Sep 17 00:00:00 2001 From: FosterToster Date: Sun, 18 Apr 2021 22:31:24 +0700 Subject: [PATCH 116/350] suppress_middleware_excepions configuration. False by default. --- telebot/__init__.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 597d486..46c201a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -95,7 +95,8 @@ class TeleBot: def __init__( self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, - next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0 + next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0, + suppress_middleware_excepions=False ): """ :param token: bot API token @@ -107,6 +108,7 @@ class TeleBot: self.parse_mode = parse_mode self.update_listener = [] self.skip_pending = skip_pending + self.suppress_middleware_excepions = suppress_middleware_excepions self.__stop_polling = threading.Event() self.last_update_id = last_update_id @@ -346,6 +348,8 @@ class TeleBot: self.process_middlewares(update) except Exception as e: logger.error(str(e)) + if not self.suppress_middleware_excepions: + raise update.middleware_error = e # for future handling if it needed if update.update_id > self.last_update_id: From 855b838e912e87279b8fe845e70648f800dc6e81 Mon Sep 17 00:00:00 2001 From: FosterToster Date: Sun, 18 Apr 2021 22:41:28 +0700 Subject: [PATCH 117/350] more explict process_middleware exceptions suppressing --- telebot/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 46c201a..8638d94 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -350,12 +350,12 @@ class TeleBot: logger.error(str(e)) if not self.suppress_middleware_excepions: raise - update.middleware_error = e # for future handling if it needed + else: + if update.update_id > self.last_update_id: self.last_update_id = update.update_id + continue if update.update_id > self.last_update_id: self.last_update_id = update.update_id - if hasattr(update, 'middleware_error'): - continue if update.message: if new_messages is None: new_messages = [] new_messages.append(update.message) From 2565094897bada8bd2ae2f43cc322a0b8e37a250 Mon Sep 17 00:00:00 2001 From: FosterToster Date: Mon, 19 Apr 2021 22:20:42 +0700 Subject: [PATCH 118/350] fixed overwriting exception args --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 8638d94..64d283e 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -456,7 +456,7 @@ class TeleBot: try: typed_middleware_handler(self, getattr(update, update_type)) except Exception as e: - e.args = (f'Typed middleware handler "{typed_middleware_handler.__qualname__}" raised exception: {str(e)}',) + e.args = e.args + (f'Typed middleware handler "{typed_middleware_handler.__qualname__}"',) raise if len(self.default_middleware_handlers) > 0: @@ -464,7 +464,7 @@ class TeleBot: try: default_middleware_handler(self, update) except Exception as e: - e.args = (f'Default middleware handler "{typed_middleware_handler.__qualname__}" raised exception: {str(e)}',) + e.args = e.args + (f'Default middleware handler "{default_middleware_handler.__qualname__}"',) raise def __notify_update(self, new_messages): From 990bb827bed0603f42cef6f08698673c7a6c3644 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 19 Apr 2021 18:45:49 +0300 Subject: [PATCH 119/350] Python 3.5 end-of-life --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index eaed67e..2f6ddfb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ language: python python: - - "3.5" - "3.6" - "3.7" - "3.8" From b7a18bf0d95b8feda3b8799ab2ef0b904483c8ff Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 20 Apr 2021 17:03:50 +0000 Subject: [PATCH 120/350] Bump py from 1.4.29 to 1.10.0 Bumps [py](https://github.com/pytest-dev/py) from 1.4.29 to 1.10.0. - [Release notes](https://github.com/pytest-dev/py/releases) - [Changelog](https://github.com/pytest-dev/py/blob/master/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/py/compare/1.4.29...1.10.0) Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a38fc09..cf92363 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -py==1.4.29 +py==1.10.0 pytest==3.0.2 requests==2.20.0 wheel==0.24.0 From 4a256750070309ff6aca0e50a5df7ac1131bf990 Mon Sep 17 00:00:00 2001 From: Hemanta Pokharel Date: Tue, 11 May 2021 07:51:13 +0545 Subject: [PATCH 121/350] Add Torrent Hunt bot in README --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 51a7a7f..cbeb200 100644 --- a/README.md +++ b/README.md @@ -684,4 +684,6 @@ Get help. Discuss. Chat. * [Tabletop DiceBot](https://github.com/dexpiper/tabletopdicebot) by [dexpiper](https://github.com/dexpiper). This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. * [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calendar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) * [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. -Want to have your bot listed here? Just make a pull requet. +* [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. + +**Want to have your bot listed here? Just make a pull requet.** From 47cab4d63ee52cd8bd398594a7c9651107fbd731 Mon Sep 17 00:00:00 2001 From: Hemanta Pokharel Date: Tue, 11 May 2021 07:58:19 +0545 Subject: [PATCH 122/350] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cbeb200..f8fce31 100644 --- a/README.md +++ b/README.md @@ -686,4 +686,4 @@ Get help. Discuss. Chat. * [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. * [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. -**Want to have your bot listed here? Just make a pull requet.** +**Want to have your bot listed here? Just make a pull request.** From 73fb18c193691f87b784bf280e8b4bc9e5e71952 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 11 May 2021 23:26:22 +0300 Subject: [PATCH 123/350] Change message handler filtering order Now content_type is checked first. --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 7fcffc9..f0b8da9 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1880,7 +1880,7 @@ class TeleBot: :param commands: Optional list of strings (commands to handle). :param regexp: Optional regular expression. :param func: Optional lambda function. The lambda receives the message to test as the first parameter. It must return True if the command should handle the message. - :param content_types: This commands' supported content types. Must be a list. Defaults to ['text']. + :param content_types: Supported message content types. Must be a list. Defaults to ['text']. """ if content_types is None: @@ -1888,10 +1888,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + content_types=content_types, commands=commands, regexp=regexp, func=func, - content_types=content_types, **kwargs) self.add_message_handler(handler_dict) return handler From 53c98328c1790b5cede6e36d76757652c7fef9d3 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 12 May 2021 00:26:33 +0300 Subject: [PATCH 124/350] send_poll fix with PollOptions Now send_poll correctly operates with PollOptions passed as array of PollOption. --- telebot/apihelper.py | 16 +++++++++++++++- telebot/types.py | 11 ++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 140479f..4cbf670 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1277,7 +1277,7 @@ def send_poll( payload = { 'chat_id': str(chat_id), 'question': question, - 'options': json.dumps(options)} + 'options': json.dumps(_convert_poll_options(options))} if is_anonymous is not None: payload['is_anonymous'] = is_anonymous @@ -1347,6 +1347,20 @@ def _convert_entites(entites): return entites +def _convert_poll_options(poll_options): + if poll_options is None: + return None + elif len(poll_options) == 0: + return [] + elif isinstance(poll_options[0], str): + # Compatibility mode with previous bug when only list of string was accepted as poll_options + return poll_options + elif isinstance(poll_options[0], types.JsonSerializable): + return [option.text for option in poll_options] + else: + return poll_options + + def convert_input_media(media): if isinstance(media, types.InputMedia): return media.convert_input_media() diff --git a/telebot/types.py b/telebot/types.py index 9cad691..5e3b333 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -2527,7 +2527,8 @@ class InputMediaDocument(InputMedia): return ret -class PollOption(JsonSerializable, JsonDeserializable): +class PollOption(JsonDeserializable): +#class PollOption(JsonSerializable, JsonDeserializable): @classmethod def de_json(cls, json_string): if (json_string is None): return None @@ -2539,10 +2540,10 @@ class PollOption(JsonSerializable, JsonDeserializable): def __init__(self, text, voter_count = 0): self.text = text self.voter_count = voter_count - - def to_json(self): - # send_poll Option is a simple string: https://core.telegram.org/bots/api#sendpoll - return json.dumps(self.text) + # Converted in _convert_poll_options + # def to_json(self): + # # send_poll Option is a simple string: https://core.telegram.org/bots/api#sendpoll + # return json.dumps(self.text) class Poll(JsonDeserializable): From 90de2e4ad973da5ca553073c1108a395ea5f42c2 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 15 May 2021 11:35:13 +0300 Subject: [PATCH 125/350] Release 3.7.8 Regular release with minor updates --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 182ec1e..c5b41b7 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.7' +__version__ = '3.7.8' From 7540a26fb944c6485def1bc35ef6f249e94c04ee Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 15 May 2021 20:08:51 +0300 Subject: [PATCH 126/350] send_poll fix of fix Previous update was inconsistent, sorry. --- telebot/apihelper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 4cbf670..582e25b 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1355,7 +1355,7 @@ def _convert_poll_options(poll_options): elif isinstance(poll_options[0], str): # Compatibility mode with previous bug when only list of string was accepted as poll_options return poll_options - elif isinstance(poll_options[0], types.JsonSerializable): + elif isinstance(poll_options[0], types.PollOption): return [option.text for option in poll_options] else: return poll_options From 26e5f3d3a88e2e5d8e1d81958bb196a0acf194c9 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 15 May 2021 20:27:52 +0300 Subject: [PATCH 127/350] Fix release 3.7.8u1 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index c5b41b7..0266440 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.8' +__version__ = '3.7.8u1' From 59559199d5a13e7d350401f4b79bf90affa7f736 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 15 May 2021 20:29:58 +0300 Subject: [PATCH 128/350] Update version.py --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 0266440..54f9f84 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.8u1' +__version__ = '3.7.9' From ff54f194ad29301aae95cb2a163607fab48e77a9 Mon Sep 17 00:00:00 2001 From: Yaroslav Vorobev Date: Wed, 19 May 2021 02:24:07 +0300 Subject: [PATCH 129/350] Added: create_chat_invite_link, edit_chat_invite_link, revoke_chat_invite_link methods --- telebot/__init__.py | 40 ++++++++++++++++++++++++++++++++++++++++ telebot/apihelper.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/telebot/__init__.py b/telebot/__init__.py index 8844546..4b2116d 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1246,6 +1246,46 @@ class TeleBot: """ return apihelper.set_chat_permissions(self.token, chat_id, permissions) + def create_chat_invite_link(self, chat_id, expire_date=None, member_limit=None): + """ + Use this method to create an additional invite link for a chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :expire_date: Point in time (Unix timestamp) when the link will expire + :member_limit: Maximum number of users that can be members of the chat simultaneously + :return: + """ + return apihelper.create_chat_invite_link(self.token, chat_id, expire_date, member_limit) + + def edit_chat_invite_link(self, chat_id, invite_link, expire_date=None, member_limit=None): + """ + Use this method to edit a non-primary invite link created by the bot. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :invite_link: The invite link to edit + :expire_date: Point in time (Unix timestamp) when the link will expire + :member_limit: Maximum number of users that can be members of the chat simultaneously + :return: + """ + return apihelper.edit_chat_invite_link(self.token, chat_id, invite_link, expire_date, member_limit) + + def revoke_chat_invite_link(self, chat_id, invite_link): + """ + Use this method to revoke an invite link created by the bot. + Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :invite_link: The invite link to revoke + :return: + """ + return apihelper.revoke_chat_invite_link(self.token, chat_id, invite_link) + def export_chat_invite_link(self, chat_id): """ Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 582e25b..a2f04b2 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -843,6 +843,50 @@ def set_chat_permissions(token, chat_id, permissions): return _make_request(token, method_url, params=payload, method='post') +def create_chat_invite_link(token, chat_id, expire_date, member_limit): + method_url = 'createChatInviteLink' + payload = { + 'chat_id': chat_id + } + + if expire_date is not None: + payload['expire_date'] = expire_date + if isinstance(payload['expire_date'], datetime): + payload['expire_date'] = payload['expire_date'].timestamp() + + if member_limit is not None: + payload['member_limit'] = member_limit + + return _make_request(token, method_url, params=payload, method='post') + + +def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit): + method_url = 'editChatInviteLink' + payload = { + 'chat_id': chat_id, + 'invite_link': invite_link + } + + if expire_date is not None: + payload['expire_date'] = expire_date + if isinstance(payload['expire_date'], datetime): + payload['expire_date'] = payload['expire_date'].timestamp() + + if member_limit is not None: + payload['member_limit'] = member_limit + + return _make_request(token, method_url, params=payload, method='post') + + +def revoke_chat_invite_link(token, chat_id, invite_link): + method_url = 'revokeChatInviteLink' + payload = { + 'chat_id': chat_id, + 'invite_link': invite_link + } + return _make_request(token, method_url, params=payload, method='post') + + def export_chat_invite_link(token, chat_id): method_url = 'exportChatInviteLink' payload = {'chat_id': chat_id} From e22fcbe3c0d173c81c200c4e41602beb99195823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=88=ED=99=98=20Ye-Hwan=20Kim=20=28Sam=29?= <43813340+yehwankim23@users.noreply.github.com> Date: Thu, 20 May 2021 18:01:10 +0900 Subject: [PATCH 130/350] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f8fce31..e23d36b 100644 --- a/README.md +++ b/README.md @@ -455,7 +455,7 @@ Refer [Bot Api](https://core.telegram.org/bots/api#messageentity) for extra deta ## Advanced use of the API ### Asynchronous delivery of messages -There exists an implementation of TeleBot which executes all `send_xyz` and the `get_me` functions asynchronously. This can speed up you bot __significantly__, but it has unwanted side effects if used without caution. +There exists an implementation of TeleBot which executes all `send_xyz` and the `get_me` functions asynchronously. This can speed up your bot __significantly__, but it has unwanted side effects if used without caution. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot. ```python tb = telebot.AsyncTeleBot("TOKEN") From 1209281787c1073b24e48db8b526e565b3201c7b Mon Sep 17 00:00:00 2001 From: zora89 <42845567+zora89@users.noreply.github.com> Date: Wed, 26 May 2021 02:17:49 +0530 Subject: [PATCH 131/350] type corrected. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e23d36b..df11c64 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ Outlined below are some general use cases of the API. #### Message handlers A message handler is a function that is decorated with the `message_handler` decorator of a TeleBot instance. Message handlers consist of one or multiple filters. -Each filter much return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided `bot` is an instance of TeleBot): +Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided `bot` is an instance of TeleBot): ```python @bot.message_handler(filters) def function_name(message): From aea067f78946df8be3856a5af10211e02c630138 Mon Sep 17 00:00:00 2001 From: anvar Date: Tue, 1 Jun 2021 08:39:09 +0500 Subject: [PATCH 132/350] Bug fixed on set_game_score fixed wrong ordered argument error on calling apihelper.set_game_score method in set_game_score --- telebot/__init__.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 4b2116d..b1c1093 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1465,7 +1465,7 @@ class TeleBot: return types.Message.de_json(result) def set_game_score(self, user_id, score, force=None, chat_id=None, message_id=None, inline_message_id=None, - edit_message=None): + disable_edit_message=None): """ Sets the value of points in the game to a specific user :param user_id: @@ -1474,11 +1474,11 @@ class TeleBot: :param chat_id: :param message_id: :param inline_message_id: - :param edit_message: + :param disable_edit_message: :return: """ - result = apihelper.set_game_score(self.token, user_id, score, force, chat_id, message_id, inline_message_id, - edit_message) + result = apihelper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, message_id, + inline_message_id) if type(result) == bool: return result return types.Message.de_json(result) From 20030f47af3154daf99599854242f2eadeb67754 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Thu, 3 Jun 2021 18:51:32 +0200 Subject: [PATCH 133/350] Update util.py Added the function `smart_split` to split text into meaningful parts. --- telebot/util.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index 1226ecc..bb19831 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -17,6 +17,8 @@ try: except: pil_imported = False +MAX_MESSAGE_LENGTH = 4096 + logger = logging.getLogger('TeleBot') thread_local = threading.local() @@ -223,6 +225,38 @@ def split_string(text, chars_per_string): """ return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)] + +def smart_split(text, chars_per_string=MAX_MESSAGE_LENGTH): + f""" + Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. + This is very useful for splitting one giant message into multiples. + If `chars_per_string` > {MAX_MESSAGE_LENGTH}: `chars_per_string` = {MAX_MESSAGE_LENGTH}. + Splits by '\n', '. ' or ' ' in exactly this priority. + + :param text: The text to split + :param chars_per_string: The number of maximum characters per part the text is split to. + :return: The splitted text as a list of strings. + """ + def _text_before_last(substr): + return substr.join(part.split(substr)[:-1]) + substr + + if chars_per_string > MAX_MESSAGE_LENGTH: chars_per_string = MAX_MESSAGE_LENGTH + + parts = [] + while True: + if len(text) < chars_per_string: + parts.append(text) + return parts + + part = text[:chars_per_string] + + if ("\n" in part): part = _text_before_last("\n") + elif (". " in part): part = _text_before_last(". ") + elif (" " in part): part = _text_before_last(" ") + + parts.append(part) + text = text[len(part):] + # CREDITS TO http://stackoverflow.com/questions/12317940#answer-12320352 def or_set(self): self._set() From 9a6ddce8dfdb43c32207ca565ed1b4c42ef689f2 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Thu, 3 Jun 2021 19:06:53 +0200 Subject: [PATCH 134/350] Added the function `unix_time` --- telebot/util.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index bb19831..ea39b81 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -6,6 +6,7 @@ import threading import traceback import warnings import functools +import time import queue as Queue import logging @@ -214,6 +215,25 @@ def extract_command(text): return text.split()[0].split('@')[0][1:] if is_command(text) else None +def unix_time(seconds=0, minutes=0, hours=0, days=0): + """ + Returns UNIX time + given paramenters + This is useful to restrict or kick a chat member. Just use it as parameter `until_date`. + + Examples: + bot.kick_chat_member(chat_id, user_id, until_date=unix_time(days=1)): bans a chat member for 1 day + bot.kick_chat_member(chat_id, user_id, until_date=unix_time(seconds=45)): bans a chat member for 45 seconds + + :param seconds: how many seconds from now + :param minutes: how many minutes from now + :param hours: how many hours from now + :param days: how many days from now + :return: UNIX time + """ + t = seconds + (60 * minutes) + (3600 * hours) + (86400 * days) + return (int(t + time.time())) + + def split_string(text, chars_per_string): """ Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. From ed5e5e507728be25d08083773d928b59aee867ad Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Thu, 3 Jun 2021 19:51:33 +0200 Subject: [PATCH 135/350] Update util.py - Removed function `unix_time` - Added function `escape` - Added function `user_link` - Added function `quick_markup` - Added some type hints --- telebot/util.py | 121 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 85 insertions(+), 36 deletions(-) diff --git a/telebot/util.py b/telebot/util.py index ea39b81..842a48d 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -6,10 +6,11 @@ import threading import traceback import warnings import functools -import time +from typing import Any, List, Dict import queue as Queue import logging +from telebot import types try: from PIL import Image @@ -187,7 +188,7 @@ def pil_image_to_file(image, extension='JPEG', quality='web_low'): else: raise RuntimeError('PIL module is not imported') -def is_command(text): +def is_command(text: str) -> bool: """ Checks if `text` is a command. Telegram chat commands start with the '/' character. :param text: Text to check. @@ -197,7 +198,7 @@ def is_command(text): return text.startswith('/') -def extract_command(text): +def extract_command(text: str) -> str: """ 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. @@ -215,26 +216,24 @@ def extract_command(text): return text.split()[0].split('@')[0][1:] if is_command(text) else None -def unix_time(seconds=0, minutes=0, hours=0, days=0): +def extract_arguments(text: str) -> str: """ - Returns UNIX time + given paramenters - This is useful to restrict or kick a chat member. Just use it as parameter `until_date`. - - Examples: - bot.kick_chat_member(chat_id, user_id, until_date=unix_time(days=1)): bans a chat member for 1 day - bot.kick_chat_member(chat_id, user_id, until_date=unix_time(seconds=45)): bans a chat member for 45 seconds + Returns the argument after the command. - :param seconds: how many seconds from now - :param minutes: how many minutes from now - :param hours: how many hours from now - :param days: how many days from now - :return: UNIX time + 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 + :return: the arguments if `text` is a command (according to is_command), else None. """ - t = seconds + (60 * minutes) + (3600 * hours) + (86400 * days) - return (int(t + time.time())) + regexp = re.compile(r"/\w*(@\w*)*\s*([\s\S]*)",re.IGNORECASE) + result = regexp.match(text) + return result.group(2) if is_command(text) else None -def split_string(text, chars_per_string): +def split_string(text: str, chars_per_string: int) -> List[str]: """ Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. @@ -246,7 +245,7 @@ def split_string(text, chars_per_string): return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)] -def smart_split(text, chars_per_string=MAX_MESSAGE_LENGTH): +def smart_split(text: str, chars_per_string: int=MAX_MESSAGE_LENGTH) -> List[str]: f""" Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. @@ -257,7 +256,7 @@ def smart_split(text, chars_per_string=MAX_MESSAGE_LENGTH): :param chars_per_string: The number of maximum characters per part the text is split to. :return: The splitted text as a list of strings. """ - def _text_before_last(substr): + def _text_before_last(substr: str) -> str: return substr.join(part.split(substr)[:-1]) + substr if chars_per_string > MAX_MESSAGE_LENGTH: chars_per_string = MAX_MESSAGE_LENGTH @@ -277,6 +276,72 @@ def smart_split(text, chars_per_string=MAX_MESSAGE_LENGTH): parts.append(part) text = text[len(part):] + +def escape(text: str) -> str: + """ + Replaces the following chars in `text` ('&' with '&', '<' with '<' and '>' with '>'). + + :param text: the text to escape + :return: the escaped text + """ + chars = {"&": "&", "<": "<", ">": ">"} + for old, new in chars.items(): text = text.replace(old, new) + return text + + +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) + ' startet the bot!', parse_mode='HTML') + + :param user: the user (not the user_id) + :param include_id: include the user_id + :return: HTML user link + """ + name = escape(user.first_name) + return (f"{name}" + + f" (
{user.id}
)" if include_id else "") + + +def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.InlineKeyboardMarkup: + """ + Returns a reply markup from a dict in this format: {'text': kwargs} + This is useful to avoid always typing 'btn1 = InlineKeyboardButton(...)' 'btn2 = InlineKeyboardButton(...)' + + Example: + 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 + + kwargs can be: + { + 'url': None, + 'callback_data': None, + 'switch_inline_query': None, + 'switch_inline_query_current_chat': None, + 'callback_game': None, + 'pay': None, + 'login_url': None + } + + :param values: a dict containing all buttons to create in this format: {text: kwargs} {str:} + :return: InlineKeyboardMarkup + """ + markup = types.InlineKeyboardMarkup(row_width=row_width) + buttons = [] + for text, kwargs in values.items(): + buttons.append(types.InlineKeyboardButton(text=text, **kwargs)) + markup.add(*buttons) + return markup + + # CREDITS TO http://stackoverflow.com/questions/12317940#answer-12320352 def or_set(self): self._set() @@ -317,22 +382,6 @@ def OrEvent(*events): changed() return or_event -def extract_arguments(text): - """ - Returns the argument after the command. - - 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 - :return: the arguments if `text` is a command (according to is_command), else None. - """ - regexp = re.compile(r"/\w*(@\w*)*\s*([\s\S]*)",re.IGNORECASE) - result = regexp.match(text) - return result.group(2) if is_command(text) else None - def per_thread(key, construct_value, reset=False): if reset or not hasattr(thread_local, key): From afbc67795a58e35c3e1b050400c7ae0e328ade35 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Fri, 4 Jun 2021 12:11:37 +0300 Subject: [PATCH 136/350] Partial rollback for previous update --- telebot/util.py | 73 +++++++++++++++++++++++++------------------------ 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/telebot/util.py b/telebot/util.py index 842a48d..6b41801 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -10,7 +10,7 @@ from typing import Any, List, Dict import queue as Queue import logging -from telebot import types +# from telebot import types try: from PIL import Image @@ -289,7 +289,7 @@ def escape(text: str) -> str: return text -def user_link(user: types.User, include_id: bool=False) -> str: +def user_link(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'! @@ -306,40 +306,41 @@ def user_link(user: types.User, include_id: bool=False) -> str: + f" (
{user.id}
)" if include_id else "") -def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.InlineKeyboardMarkup: - """ - Returns a reply markup from a dict in this format: {'text': kwargs} - This is useful to avoid always typing 'btn1 = InlineKeyboardButton(...)' 'btn2 = InlineKeyboardButton(...)' - - Example: - 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 - - kwargs can be: - { - 'url': None, - 'callback_data': None, - 'switch_inline_query': None, - 'switch_inline_query_current_chat': None, - 'callback_game': None, - 'pay': None, - 'login_url': None - } - - :param values: a dict containing all buttons to create in this format: {text: kwargs} {str:} - :return: InlineKeyboardMarkup - """ - markup = types.InlineKeyboardMarkup(row_width=row_width) - buttons = [] - for text, kwargs in values.items(): - buttons.append(types.InlineKeyboardButton(text=text, **kwargs)) - markup.add(*buttons) - return markup +# def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2): +# """ +# Returns a reply markup from a dict in this format: {'text': kwargs} +# This is useful to avoid always typing 'btn1 = InlineKeyboardButton(...)' 'btn2 = InlineKeyboardButton(...)' +# +# Example: +# 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 +# +# kwargs can be: +# { +# 'url': None, +# 'callback_data': None, +# 'switch_inline_query': None, +# 'switch_inline_query_current_chat': None, +# 'callback_game': None, +# 'pay': None, +# 'login_url': None +# } +# +# :param values: a dict containing all buttons to create in this format: {text: kwargs} {str:} +# :param row_width: +# :return: InlineKeyboardMarkup +# """ +# markup = types.InlineKeyboardMarkup(row_width=row_width) +# buttons = [] +# for text, kwargs in values.items(): +# buttons.append(types.InlineKeyboardButton(text=text, **kwargs)) +# markup.add(*buttons) +# return markup # CREDITS TO http://stackoverflow.com/questions/12317940#answer-12320352 From 2add34c70261949cfcd18df5b602a1a2f6eb4da4 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Fri, 4 Jun 2021 12:28:33 +0300 Subject: [PATCH 137/350] Fix special case when content_type is None --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index b1c1093..f6277ae 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2254,8 +2254,8 @@ class TeleBot: """ test_cases = { 'content_types': lambda msg: msg.content_type in filter_value, - 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), - 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + 'regexp': lambda msg: msg.content_type and msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), + 'commands': lambda msg: msg.content_type and msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, 'func': lambda msg: filter_value(msg) } From 709eb8cf452b3ea49b80945710ff1e6aa9289bdd Mon Sep 17 00:00:00 2001 From: ZurMaD Date: Sun, 6 Jun 2021 14:30:55 -0500 Subject: [PATCH 138/350] Github Actions: setup for 3.6+ pypy3.6+ --- .github/workflows/setup_python.yml | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/setup_python.yml diff --git a/.github/workflows/setup_python.yml b/.github/workflows/setup_python.yml new file mode 100644 index 0000000..0631897 --- /dev/null +++ b/.github/workflows/setup_python.yml @@ -0,0 +1,35 @@ +# This is a basic workflow to help you get started with Actions + +name: ActionsSetupPython + +# Controls when the action will run. +on: + # Triggers the workflow on push or pull request events but only for the master branch + push: + branches: [ master ] + pull_request: + branches: [ master ] + + # Allows you to run this workflow manually from the Actions tab + #workflow_dispatch: + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "build" + all-setups: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [ '3.6','3.7','3.8','3.9', 'pypy-3.6', 'pypy-3.7' ] #'pypy-3.8', 'pypy-3.9' NOT SUPPORTED NOW + name: Python ${{ matrix.python-version }} setup and tests + steps: + - uses: actions/checkout@v2 + - name: Setup python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + architecture: x64 + - run: | + pip3 install -r requirements.txt + python setup.py install + cd tests && py.test From ab05cb004502b4eceea43b8a7d1e24498760e89b Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 9 Jun 2021 16:20:42 +0200 Subject: [PATCH 139/350] Fixed a bug in `user_link` `user_link` returned an empty string if `include_id` was set to False --- telebot/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/util.py b/telebot/util.py index 842a48d..10c4fe3 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -303,7 +303,7 @@ def user_link(user: types.User, include_id: bool=False) -> str: """ name = escape(user.first_name) return (f"{name}" - + f" (
{user.id}
)" if include_id else "") + + (f" (
{user.id}
)" if include_id else "")) def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.InlineKeyboardMarkup: From 25bac683097583312f39e035f4ae1b29feb3e06f Mon Sep 17 00:00:00 2001 From: AREEG94FAHAD Date: Sat, 12 Jun 2021 18:18:16 +0300 Subject: [PATCH 140/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index df11c64..9cf23f1 100644 --- a/README.md +++ b/README.md @@ -685,5 +685,6 @@ Get help. Discuss. Chat. * [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calendar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) * [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. * [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. +* Translator bot by [Areeg Fahad](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. **Want to have your bot listed here? Just make a pull request.** From 81299ff61399e0367519657f2029d2252910dd1d Mon Sep 17 00:00:00 2001 From: AREEG94FAHAD Date: Sat, 12 Jun 2021 18:18:51 +0300 Subject: [PATCH 141/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9cf23f1..2afe002 100644 --- a/README.md +++ b/README.md @@ -685,6 +685,6 @@ Get help. Discuss. Chat. * [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calendar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) * [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. * [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. -* Translator bot by [Areeg Fahad](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. +* Translator bot by [Areeg Fahad source](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. **Want to have your bot listed here? Just make a pull request.** From d5c202abbd18440ee85ec8dfbef9fa14fe1101eb Mon Sep 17 00:00:00 2001 From: AREEG94FAHAD Date: Sat, 12 Jun 2021 18:19:18 +0300 Subject: [PATCH 142/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2afe002..22e1120 100644 --- a/README.md +++ b/README.md @@ -685,6 +685,6 @@ Get help. Discuss. Chat. * [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calendar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) * [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. * [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. -* Translator bot by [Areeg Fahad source](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. +* Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. **Want to have your bot listed here? Just make a pull request.** From a01e59951a866aa84c5a15f998e91af1d247c546 Mon Sep 17 00:00:00 2001 From: AREEG94FAHAD Date: Sat, 12 Jun 2021 19:01:42 +0300 Subject: [PATCH 143/350] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 22e1120..c19529a 100644 --- a/README.md +++ b/README.md @@ -686,5 +686,7 @@ Get help. Discuss. Chat. * [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. * [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. * Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. +* Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. + **Want to have your bot listed here? Just make a pull request.** From bbafdd1c1d1c118b416ca66d09ce3cd30e7f1fed Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Thu, 17 Jun 2021 20:28:53 +0200 Subject: [PATCH 144/350] Some Updates > Added lot of type hints to types.py > Added some new fields from TelegramBotAPI to pyTelegramBotAPI > fixed `circular import error in util.py > Added functions `log_out` and `close` to __init__.py and apihelper.py > And some more small changes --- .gitignore | 1 + telebot/__init__.py | 212 ++++--- telebot/apihelper.py | 7 + telebot/types.py | 1380 ++++++++++++++++++++---------------------- telebot/util.py | 79 +-- 5 files changed, 821 insertions(+), 858 deletions(-) diff --git a/.gitignore b/.gitignore index dd11917..c9919ab 100644 --- a/.gitignore +++ b/.gitignore @@ -62,3 +62,4 @@ testMain.py #VS Code .vscode/ +.DS_Store diff --git a/telebot/__init__.py b/telebot/__init__.py index f6277ae..eaf8465 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -7,6 +7,7 @@ import sys import threading import time import traceback +from typing import List, Union logger = logging.getLogger('TeleBot') formatter = logging.Formatter( @@ -55,6 +56,8 @@ class TeleBot: """ This is TeleBot Class Methods: getMe + logOut + close sendMessage forwardMessage deleteMessage @@ -76,6 +79,9 @@ class TeleBot: unbanChatMember restrictChatMember promoteChatMember + createChatInviteLink + editChatInviteLink + revokeChatInviteLink exportChatInviteLink setChatPhoto deleteChatPhoto @@ -640,20 +646,50 @@ class TeleBot: def set_update_listener(self, listener): self.update_listener.append(listener) - def get_me(self): + def get_me(self) -> types.User: + """ + Returns basic information about the bot in form of a User object. + """ result = apihelper.get_me(self.token) return types.User.de_json(result) - def get_file(self, file_id): + def get_file(self, file_id) -> types.File: + """ + Use this method to get basic info about a file and prepare it for downloading. + For the moment, bots can download files of up to 20MB in size. + On success, a File object is returned. + It is guaranteed that the link will be valid for at least 1 hour. + When the link expires, a new one can be requested by calling get_file again. + """ return types.File.de_json(apihelper.get_file(self.token, file_id)) - def get_file_url(self, file_id): + def get_file_url(self, file_id) -> str: return apihelper.get_file_url(self.token, file_id) - def download_file(self, file_path): + def download_file(self, file_path) -> bytes: return apihelper.download_file(self.token, file_path) - def get_user_profile_photos(self, user_id, offset=None, limit=None): + def log_out(self) -> bool: + """ + Use this method to log out from the cloud Bot API server before launching the bot locally. + You MUST log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. + After a successful call, you can immediately log in on a local server, + but will not be able to log in back to the cloud Bot API server for 10 minutes. + Returns True on success. + """ + return apihelper.log_out(self.token) + + def close(self) -> bool: + """ + Use this method to close the bot instance before moving it from one local server to another. + You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. + The method will return error 429 in the first 10 minutes after the bot is launched. + Returns True on success. + """ + return apihelper.close(self.token) + + + def get_user_profile_photos(self, user_id, offset=None, limit=None) -> types.UserProfilePhotos: """ Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos @@ -665,7 +701,7 @@ class TeleBot: result = apihelper.get_user_profile_photos(self.token, user_id, offset, limit) return types.UserProfilePhotos.de_json(result) - def get_chat(self, chat_id): + def get_chat(self, chat_id) -> types.Chat: """ Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. @@ -675,7 +711,7 @@ class TeleBot: result = apihelper.get_chat(self.token, chat_id) return types.Chat.de_json(result) - def leave_chat(self, chat_id): + def leave_chat(self, chat_id) -> bool: """ Use this method for your bot to leave a group, supergroup or channel. Returns True on success. :param chat_id: @@ -684,7 +720,7 @@ class TeleBot: result = apihelper.leave_chat(self.token, chat_id) return result - def get_chat_administrators(self, chat_id): + def get_chat_administrators(self, chat_id) -> List[types.ChatMember]: """ Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains @@ -699,7 +735,7 @@ class TeleBot: ret.append(types.ChatMember.de_json(r)) return ret - def get_chat_members_count(self, chat_id): + def get_chat_members_count(self, chat_id) -> int: """ Use this method to get the number of members in a chat. Returns Int on success. :param chat_id: @@ -708,7 +744,7 @@ class TeleBot: result = apihelper.get_chat_members_count(self.token, chat_id) return result - def set_chat_sticker_set(self, chat_id, sticker_set_name): + def set_chat_sticker_set(self, chat_id, sticker_set_name) -> 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. @@ -722,7 +758,7 @@ class TeleBot: result = apihelper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) return result - def delete_chat_sticker_set(self, chat_id): + def delete_chat_sticker_set(self, chat_id) -> bool: """ Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set @@ -734,7 +770,7 @@ class TeleBot: result = apihelper.delete_chat_sticker_set(self.token, chat_id) return result - def get_chat_member(self, chat_id, user_id): + def get_chat_member(self, chat_id, user_id) -> types.ChatMember: """ Use this method to get information about a member of a chat. Returns a ChatMember object on success. :param chat_id: @@ -745,7 +781,7 @@ class TeleBot: return types.ChatMember.de_json(result) def send_message(self, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None) -> types.Message: """ Use this method to send text messages. @@ -768,7 +804,7 @@ class TeleBot: apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout)) - def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=None, timeout=None): + def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=None, timeout=None) -> types.Message: """ Use this method to forward messages of any kind. :param disable_notification: @@ -783,7 +819,7 @@ class TeleBot: def copy_message(self, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, - reply_markup=None, timeout=None): + reply_markup=None, timeout=None) -> int: """ Use this method to copy messages of any kind. :param chat_id: which chat to forward @@ -804,7 +840,7 @@ class TeleBot: disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, timeout)) - def delete_message(self, chat_id, message_id, timeout=None): + def delete_message(self, chat_id, message_id, timeout=None) -> bool: """ Use this method to delete message. Returns True on success. :param chat_id: in which chat to delete @@ -817,7 +853,7 @@ class TeleBot: def send_dice( self, chat_id, emoji=None, disable_notification=None, reply_to_message_id=None, - reply_markup=None, timeout=None): + reply_markup=None, timeout=None) -> types.Message: """ Use this method to send dices. :param chat_id: @@ -835,7 +871,7 @@ class TeleBot: ) def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None) -> types.Message: """ Use this method to send photos. :param disable_notification: @@ -856,7 +892,7 @@ class TeleBot: def send_audio(self, chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, - timeout=None, thumb=None): + timeout=None, thumb=None) -> types.Message: """ Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. :param chat_id:Unique identifier for the message recipient @@ -880,7 +916,7 @@ class TeleBot: reply_markup, parse_mode, disable_notification, timeout, thumb)) def send_voice(self, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None) -> types.Message: """ Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. :param chat_id:Unique identifier for the message recipient. @@ -901,7 +937,7 @@ class TeleBot: parse_mode, disable_notification, timeout)) def send_document(self, chat_id, data,reply_to_message_id=None, caption=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None, thumb=None): + parse_mode=None, disable_notification=None, timeout=None, thumb=None) -> types.Message: """ Use this method to send general files. :param chat_id: @@ -923,7 +959,7 @@ class TeleBot: def send_sticker( self, chat_id, data, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None): + disable_notification=None, timeout=None) -> types.Message: """ Use this method to send .webp stickers. :param chat_id: @@ -940,7 +976,8 @@ class TeleBot: disable_notification, timeout)) def send_video(self, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, thumb=None, width=None, height=None): + parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, thumb=None, + width=None, height=None) -> types.Message: """ Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -967,7 +1004,7 @@ class TeleBot: def send_animation(self, chat_id, animation, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, - disable_notification=None, timeout=None, thumb=None): + disable_notification=None, timeout=None, thumb=None) -> types.Message: """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -990,7 +1027,7 @@ class TeleBot: def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None, thumb=None): + disable_notification=None, timeout=None, thumb=None) -> types.Message: """ As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -1010,7 +1047,7 @@ class TeleBot: def send_media_group( self, chat_id, media, - disable_notification=None, reply_to_message_id=None, timeout=None): + disable_notification=None, reply_to_message_id=None, timeout=None) -> List[types.Message]: """ send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: @@ -1029,7 +1066,7 @@ class TeleBot: def send_location( self, chat_id, latitude, longitude, live_period=None, reply_to_message_id=None, - reply_markup=None, disable_notification=None, timeout=None): + reply_markup=None, disable_notification=None, timeout=None) -> types.Message: """ Use this method to send point on the map. :param chat_id: @@ -1048,7 +1085,7 @@ class TeleBot: reply_markup, disable_notification, timeout)) def edit_message_live_location(self, latitude, longitude, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None, timeout=None): + inline_message_id=None, reply_markup=None, timeout=None) -> types.Message: """ Use this method to edit live location :param latitude: @@ -1067,7 +1104,7 @@ class TeleBot: def stop_message_live_location( self, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None, timeout=None): + inline_message_id=None, reply_markup=None, timeout=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 @@ -1084,7 +1121,7 @@ class TeleBot: def send_venue( self, chat_id, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: """ Use this method to send information about a venue. :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel @@ -1108,14 +1145,14 @@ class TeleBot: def send_contact( self, chat_id, phone_number, first_name, last_name=None, vcard=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: return types.Message.de_json( apihelper.send_contact( self.token, chat_id, phone_number, first_name, last_name, vcard, disable_notification, reply_to_message_id, reply_markup, timeout) ) - def send_chat_action(self, chat_id, action, timeout=None): + def send_chat_action(self, chat_id, action, timeout=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 @@ -1128,7 +1165,7 @@ class TeleBot: """ return apihelper.send_chat_action(self.token, chat_id, action, timeout) - def kick_chat_member(self, chat_id, user_id, until_date=None): + def kick_chat_member(self, chat_id, user_id, until_date=None) -> bool: """ Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup @@ -1139,7 +1176,7 @@ class TeleBot: """ return apihelper.kick_chat_member(self.token, chat_id, user_id, until_date) - def unban_chat_member(self, chat_id, user_id, only_if_banned = False): + def unban_chat_member(self, chat_id, user_id, only_if_banned = False) -> bool: """ Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. @@ -1159,7 +1196,7 @@ class TeleBot: 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): + can_invite_users=None, can_pin_messages=None) -> bool: """ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have @@ -1194,7 +1231,7 @@ class TeleBot: def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, - can_restrict_members=None, can_pin_messages=None, can_promote_members=None): + can_restrict_members=None, can_pin_messages=None, can_promote_members=None) -> bool: """ Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1219,7 +1256,7 @@ class TeleBot: can_edit_messages, can_delete_messages, can_invite_users, can_restrict_members, can_pin_messages, can_promote_members) - def set_chat_administrator_custom_title(self, chat_id, user_id, custom_title): + def set_chat_administrator_custom_title(self, chat_id, user_id, custom_title) -> bool: """ Use this method to set a custom title for an administrator in a supergroup promoted by the bot. @@ -1233,7 +1270,7 @@ class TeleBot: """ return apihelper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) - def set_chat_permissions(self, chat_id, permissions): + def set_chat_permissions(self, chat_id, permissions) -> bool: """ 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 @@ -1246,7 +1283,7 @@ class TeleBot: """ return apihelper.set_chat_permissions(self.token, chat_id, permissions) - def create_chat_invite_link(self, chat_id, expire_date=None, member_limit=None): + def create_chat_invite_link(self, chat_id, expire_date=None, member_limit=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. @@ -1257,7 +1294,9 @@ class TeleBot: :member_limit: Maximum number of users that can be members of the chat simultaneously :return: """ - return apihelper.create_chat_invite_link(self.token, chat_id, expire_date, member_limit) + return types.ChatInviteLink.de_json( + apihelper.create_chat_invite_link(self.token, chat_id, expire_date, member_limit) + ) def edit_chat_invite_link(self, chat_id, invite_link, expire_date=None, member_limit=None): """ @@ -1271,9 +1310,11 @@ class TeleBot: :member_limit: Maximum number of users that can be members of the chat simultaneously :return: """ - return apihelper.edit_chat_invite_link(self.token, chat_id, invite_link, expire_date, member_limit) + return types.ChatInviteLink.de_json( + apihelper.edit_chat_invite_link(self.token, chat_id, invite_link, expire_date, member_limit) + ) - def revoke_chat_invite_link(self, chat_id, invite_link): + def revoke_chat_invite_link(self, chat_id, invite_link) -> types.ChatInviteLink: """ Use this method to revoke an invite link created by the bot. Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator @@ -1284,9 +1325,11 @@ class TeleBot: :invite_link: The invite link to revoke :return: """ - return apihelper.revoke_chat_invite_link(self.token, chat_id, invite_link) + return types.ChatInviteLink.de_json( + apihelper.revoke_chat_invite_link(self.token, chat_id, invite_link) + ) - def export_chat_invite_link(self, chat_id): + def export_chat_invite_link(self, chat_id) -> str: """ Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1297,7 +1340,7 @@ class TeleBot: """ return apihelper.export_chat_invite_link(self.token, chat_id) - def set_chat_photo(self, chat_id, photo): + def set_chat_photo(self, chat_id, photo) -> 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. @@ -1311,7 +1354,7 @@ class TeleBot: """ return apihelper.set_chat_photo(self.token, chat_id, photo) - def delete_chat_photo(self, chat_id): + def delete_chat_photo(self, chat_id) -> 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. @@ -1324,7 +1367,7 @@ class TeleBot: """ return apihelper.delete_chat_photo(self.token, chat_id) - def set_my_commands(self, commands): + def set_my_commands(self, commands) -> bool: """ Use this method to change the list of the bot's commands. :param commands: Array of BotCommand. A JSON-serialized list of bot commands @@ -1333,7 +1376,7 @@ class TeleBot: """ return apihelper.set_my_commands(self.token, commands) - def set_chat_title(self, chat_id, title): + def set_chat_title(self, chat_id, title) -> bool: """ Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1347,7 +1390,7 @@ class TeleBot: """ return apihelper.set_chat_title(self.token, chat_id, title) - def set_chat_description(self, chat_id, description=None): + def set_chat_description(self, chat_id, description=None) -> bool: """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1359,7 +1402,7 @@ class TeleBot: """ return apihelper.set_chat_description(self.token, chat_id, description) - def pin_chat_message(self, chat_id, message_id, disable_notification=False): + def pin_chat_message(self, chat_id, message_id, disable_notification=False) -> bool: """ Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1373,7 +1416,7 @@ class TeleBot: """ return apihelper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - def unpin_chat_message(self, chat_id, message_id=None): + def unpin_chat_message(self, chat_id, message_id=None) -> bool: """ Use this method to unpin specific pinned message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1385,7 +1428,7 @@ class TeleBot: """ return apihelper.unpin_chat_message(self.token, chat_id, message_id) - def unpin_all_chat_messages(self, chat_id): + def unpin_all_chat_messages(self, chat_id) -> bool: """ Use this method to unpin a all pinned messages in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1397,7 +1440,7 @@ class TeleBot: return apihelper.unpin_all_chat_messages(self.token, chat_id) def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, - disable_web_page_preview=None, reply_markup=None): + disable_web_page_preview=None, reply_markup=None) -> Union[types.Message, bool]: """ Use this method to edit text and game messages. :param text: @@ -1417,7 +1460,7 @@ class TeleBot: return result return types.Message.de_json(result) - def edit_message_media(self, media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + def edit_message_media(self, media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: """ Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. :param media: @@ -1432,7 +1475,7 @@ class TeleBot: return result return types.Message.de_json(result) - def edit_message_reply_markup(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + def edit_message_reply_markup(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: """ Use this method to edit only the reply markup of messages. :param chat_id: @@ -1448,7 +1491,7 @@ class TeleBot: def send_game( self, chat_id, game_short_name, disable_notification=None, - reply_to_message_id=None, reply_markup=None, timeout=None): + reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: """ Used to send the game :param chat_id: @@ -1465,7 +1508,7 @@ class TeleBot: return types.Message.de_json(result) def set_game_score(self, user_id, score, force=None, chat_id=None, message_id=None, inline_message_id=None, - disable_edit_message=None): + disable_edit_message=None) -> Union[types.Message, bool]: """ Sets the value of points in the game to a specific user :param user_id: @@ -1483,7 +1526,7 @@ class TeleBot: return result return types.Message.de_json(result) - def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None): + def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None) -> List[types.GameHighScore]: """ Gets top points and game play :param user_id: @@ -1502,7 +1545,8 @@ class TeleBot: start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider=None, send_email_to_provider=None, is_flexible=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, timeout=None): + disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, + timeout=None) -> types.Message: """ Sends invoice :param chat_id: Unique identifier for the target private chat @@ -1543,7 +1587,7 @@ class TeleBot: self, chat_id, question, options, is_anonymous=None, type=None, allows_multiple_answers=None, correct_option_id=None, explanation=None, explanation_parse_mode=None, open_period=None, close_date=None, is_closed=None, - disable_notifications=False, reply_to_message_id=None, reply_markup=None, timeout=None): + disable_notifications=False, reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: """ Send polls :param chat_id: @@ -1576,7 +1620,7 @@ class TeleBot: explanation, explanation_parse_mode, open_period, close_date, is_closed, disable_notifications, reply_to_message_id, reply_markup, timeout)) - def stop_poll(self, chat_id, message_id, reply_markup=None): + def stop_poll(self, chat_id, message_id, reply_markup=None) -> types.Poll: """ Stops poll :param chat_id: @@ -1586,7 +1630,7 @@ class TeleBot: """ return types.Poll.de_json(apihelper.stop_poll(self.token, chat_id, message_id, reply_markup)) - def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None): + def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None) -> bool: """ Asks for an answer to a shipping question :param shipping_query_id: @@ -1597,7 +1641,7 @@ class TeleBot: """ return apihelper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) - def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None): + def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None) -> bool: """ Response to a request for pre-inspection :param pre_checkout_query_id: @@ -1608,7 +1652,7 @@ class TeleBot: return apihelper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) def edit_message_caption(self, caption, chat_id=None, message_id=None, inline_message_id=None, - parse_mode=None, reply_markup=None): + parse_mode=None, reply_markup=None) -> Union[types.Message, bool]: """ Use this method to edit captions of messages :param caption: @@ -1627,7 +1671,7 @@ class TeleBot: return result return types.Message.de_json(result) - def reply_to(self, message, text, **kwargs): + def reply_to(self, message, text, **kwargs) -> types.Message: """ Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` :param message: @@ -1638,7 +1682,7 @@ class TeleBot: return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, - switch_pm_text=None, switch_pm_parameter=None): + switch_pm_text=None, switch_pm_parameter=None) -> bool: """ Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. @@ -1655,7 +1699,7 @@ class TeleBot: return apihelper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset, switch_pm_text, switch_pm_parameter) - def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): + def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None) -> bool: """ Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. @@ -1668,7 +1712,7 @@ class TeleBot: """ return apihelper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) - def get_sticker_set(self, name): + def get_sticker_set(self, name) -> types.StickerSet: """ Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: @@ -1677,7 +1721,7 @@ class TeleBot: result = apihelper.get_sticker_set(self.token, name) return types.StickerSet.de_json(result) - def upload_sticker_file(self, user_id, png_sticker): + def upload_sticker_file(self, user_id, png_sticker) -> types.File: """ Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success. @@ -1689,7 +1733,7 @@ class TeleBot: return types.File.de_json(result) def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, - mask_position=None): + mask_position=None) -> bool: """ Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success. @@ -1705,7 +1749,7 @@ class TeleBot: return apihelper.create_new_sticker_set(self.token, user_id, name, title, png_sticker, emojis, contains_masks, mask_position) - def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None): + def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None) -> bool: """ Use this method to add a new sticker to a set created by the bot. Returns True on success. :param user_id: @@ -1717,7 +1761,7 @@ class TeleBot: """ return apihelper.add_sticker_to_set(self.token, user_id, name, png_sticker, emojis, mask_position) - def set_sticker_position_in_set(self, sticker, position): + def set_sticker_position_in_set(self, sticker, position) -> bool: """ Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. :param sticker: @@ -1726,7 +1770,7 @@ class TeleBot: """ return apihelper.set_sticker_position_in_set(self.token, sticker, position) - def delete_sticker_from_set(self, sticker): + def delete_sticker_from_set(self, sticker) -> bool: """ Use this method to delete a sticker from a set created by the bot. Returns True on success. :param sticker: @@ -1734,7 +1778,7 @@ class TeleBot: """ return apihelper.delete_sticker_from_set(self.token, sticker) - def register_for_reply(self, message, callback, *args, **kwargs): + def register_for_reply(self, message, callback, *args, **kwargs) -> None: """ Registers a callback function to be notified when a reply to `message` arrives. @@ -1747,7 +1791,7 @@ class TeleBot: message_id = message.message_id self.register_for_reply_by_message_id(message_id, callback, *args, **kwargs) - def register_for_reply_by_message_id(self, message_id, callback, *args, **kwargs): + def register_for_reply_by_message_id(self, message_id, callback, *args, **kwargs) -> None: """ Registers a callback function to be notified when a reply to `message` arrives. @@ -1759,7 +1803,7 @@ class TeleBot: """ self.reply_backend.register_handler(message_id, Handler(callback, *args, **kwargs)) - def _notify_reply_handlers(self, new_messages): + def _notify_reply_handlers(self, new_messages) -> None: """ Notify handlers of the answers :param new_messages: @@ -1772,7 +1816,7 @@ class TeleBot: for handler in handlers: self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) - def register_next_step_handler(self, message, callback, *args, **kwargs): + def register_next_step_handler(self, message, callback, *args, **kwargs) -> None: """ Registers a callback function to be notified when new message arrives after `message`. @@ -1786,7 +1830,7 @@ class TeleBot: chat_id = message.chat.id self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) - def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs): + def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs) -> None: """ Registers a callback function to be notified when new message arrives after `message`. @@ -1799,7 +1843,7 @@ class TeleBot: """ self.next_step_backend.register_handler(chat_id, Handler(callback, *args, **kwargs)) - def clear_step_handler(self, message): + def clear_step_handler(self, message) -> None: """ Clears all callback functions registered by register_next_step_handler(). @@ -1808,7 +1852,7 @@ class TeleBot: chat_id = message.chat.id self.clear_step_handler_by_chat_id(chat_id) - def clear_step_handler_by_chat_id(self, chat_id): + def clear_step_handler_by_chat_id(self, chat_id) -> None: """ Clears all callback functions registered by register_next_step_handler(). @@ -1816,7 +1860,7 @@ class TeleBot: """ self.next_step_backend.clear_handlers(chat_id) - def clear_reply_handlers(self, message): + def clear_reply_handlers(self, message) -> None: """ Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). @@ -1825,7 +1869,7 @@ class TeleBot: message_id = message.message_id self.clear_reply_handlers_by_message_id(message_id) - def clear_reply_handlers_by_message_id(self, message_id): + def clear_reply_handlers_by_message_id(self, message_id) -> None: """ Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). @@ -2254,8 +2298,8 @@ class TeleBot: """ test_cases = { 'content_types': lambda msg: msg.content_type in filter_value, - 'regexp': lambda msg: msg.content_type and msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), - 'commands': lambda msg: msg.content_type and msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), + 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, 'func': lambda msg: filter_value(msg) } diff --git a/telebot/apihelper.py b/telebot/apihelper.py index a2f04b2..a6710e8 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -165,6 +165,13 @@ def get_me(token): method_url = r'getMe' return _make_request(token, method_url) +def log_out(token): + method_url = r'logOut' + return _make_request(token, method_url) + +def close(token): + method_url = r'close' + return _make_request(token, method_url) def get_file(token, file_id): method_url = r'getFile' diff --git a/telebot/types.py b/telebot/types.py index 5e3b333..5b52676 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- import logging +import types +from typing import Dict, List try: import ujson as json @@ -157,27 +159,19 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - id = obj['id'] - is_bot = obj['is_bot'] - first_name = obj['first_name'] - last_name = obj.get('last_name') - username = obj.get('username') - language_code = obj.get('language_code') - can_join_groups = obj.get('can_join_groups') - can_read_all_group_messages = obj.get('can_read_all_group_messages') - supports_inline_queries = obj.get('supports_inline_queries') - return cls(id, is_bot, first_name, last_name, username, language_code, can_join_groups, can_read_all_group_messages, supports_inline_queries) + return cls(**obj) - def __init__(self, id, is_bot, first_name, last_name=None, username=None, language_code=None, can_join_groups=None, can_read_all_group_messages=None, supports_inline_queries=None): - self.id = id - self.is_bot = is_bot - self.first_name = first_name - self.username = username - self.last_name = last_name - self.language_code = language_code - self.can_join_groups = can_join_groups - self.can_read_all_group_messages = can_read_all_group_messages - self.supports_inline_queries = supports_inline_queries + def __init__(self, id, is_bot, first_name, last_name=None, username=None, language_code=None, + can_join_groups=None, can_read_all_group_messages=None, supports_inline_queries=None, **kwargs): + self.id: int = id + self.is_bot: bool = is_bot + self.first_name: str = first_name + self.username: str = username + self.last_name: str = last_name + self.language_code: str = language_code + self.can_join_groups: bool = can_join_groups + self.can_read_all_group_messages: bool = can_read_all_group_messages + self.supports_inline_queries: bool = supports_inline_queries @property def full_name(self): @@ -206,66 +200,51 @@ class GroupChat(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - id = obj['id'] - title = obj['title'] - return cls(id, title) + return cls(**obj) - def __init__(self, id, title): - self.id = id - self.title = title + def __init__(self, id, title, **kwargs): + self.id: int = id + self.title: str = title class Chat(JsonDeserializable): @classmethod def de_json(cls, json_string): - if json_string is None: - return None + if json_string is None: return None obj = cls.check_json(json_string) - id = obj['id'] - type = obj['type'] - title = obj.get('title') - username = obj.get('username') - first_name = obj.get('first_name') - last_name = obj.get('last_name') - photo = ChatPhoto.de_json(obj.get('photo')) - bio = obj.get('bio') - description = obj.get('description') - invite_link = obj.get('invite_link') - pinned_message = Message.de_json(obj.get('pinned_message')) - permissions = ChatPermissions.de_json(obj.get('permissions')) - slow_mode_delay = obj.get('slow_mode_delay') - sticker_set_name = obj.get('sticker_set_name') - can_set_sticker_set = obj.get('can_set_sticker_set') - linked_chat_id = obj.get('linked_chat_id') - location = None # Not implemented - return cls( - id, type, title, username, first_name, last_name, - photo, bio, description, invite_link, - pinned_message, permissions, slow_mode_delay, sticker_set_name, - can_set_sticker_set, linked_chat_id, location) + if 'photo' in obj: + obj['photo'] = ChatPhoto.de_json(obj['photo']) + if 'pinned_message' in obj: + obj['pinned_message'] = Message.de_json(obj['pinned_message']) + if 'permissions' in obj: + obj['permissions'] = ChatPermissions.de_json(obj['permissions']) + if 'location' in obj: + obj['location'] = ChatLocation.de_json(obj['location']) + return cls(**obj) def __init__(self, id, type, title=None, username=None, first_name=None, last_name=None, photo=None, bio=None, description=None, invite_link=None, pinned_message=None, permissions=None, slow_mode_delay=None, - sticker_set_name=None, can_set_sticker_set=None, - linked_chat_id=None, location=None): - self.id = id - self.type = type - self.title = title - self.username = username - self.first_name = first_name - self.last_name = last_name - self.photo = photo - self.bio = bio - self.description = description - self.invite_link = invite_link - self.pinned_message = pinned_message - self.permissions = permissions - self.slow_mode_delay = slow_mode_delay - self.sticker_set_name = sticker_set_name - self.can_set_sticker_set = can_set_sticker_set - self.linked_chat_id = linked_chat_id - self.location = location + message_auto_delete_time=None, sticker_set_name=None, can_set_sticker_set=None, + linked_chat_id=None, location=None, **kwargs): + self.id: int = id + self.type: str = type + self.title: str = title + self.username: str = username + self.first_name: str = first_name + self.last_name: str = last_name + self.photo: ChatPhoto = photo + self.bio: str = bio + self.description: str = description + self.invite_link: str = invite_link + self.pinned_message: Message = pinned_message + self.permissions: ChatPermissions = permissions + self.slow_mode_delay: int = slow_mode_delay + self.message_auto_delete_time = message_auto_delete_time + self.sticker_set_name: str = sticker_set_name + self.can_set_sticker_set: bool = can_set_sticker_set + self.linked_chat_id: int = linked_chat_id + self.location: ChatLocation = location class MessageID(JsonDeserializable): @@ -306,6 +285,8 @@ class Message(JsonDeserializable): opts['forward_date'] = obj.get('forward_date') if 'reply_to_message' in obj: opts['reply_to_message'] = Message.de_json(obj['reply_to_message']) + if 'via_bot' in obj: + opts['via_bot'] = User.de_json(obj['via_bot']) if 'edit_date' in obj: opts['edit_date'] = obj.get('edit_date') if 'media_group_id' in obj: @@ -438,54 +419,55 @@ class Message(JsonDeserializable): return ret def __init__(self, message_id, from_user, date, chat, content_type, options, json_string): - self.content_type = content_type - self.id = message_id # Lets fix the telegram usability ####up with ID in Message :) - self.message_id = message_id - self.from_user = from_user - self.date = date - self.chat = chat - self.forward_from = None - self.forward_from_chat = None - self.forward_from_message_id = None - self.forward_signature = None - self.forward_sender_name = None - self.forward_date = None - self.reply_to_message = None - self.edit_date = None - self.media_group_id = None - self.author_signature = None - self.text = None - self.entities = None - self.caption_entities = None - self.audio = None - self.document = None - self.photo = None - self.sticker = None - self.video = None - self.video_note = None - self.voice = None - self.caption = None - self.contact = None - self.location = None - self.venue = None - self.animation = None - self.dice = None - self.new_chat_member = None # Deprecated since Bot API 3.0. Not processed anymore - self.new_chat_members = None - self.left_chat_member = None - self.new_chat_title = None - self.new_chat_photo = None - self.delete_chat_photo = None - self.group_chat_created = None - self.supergroup_chat_created = None - self.channel_chat_created = None - self.migrate_to_chat_id = None - self.migrate_from_chat_id = None - self.pinned_message = None - self.invoice = None - self.successful_payment = None - self.connected_website = None - self.reply_markup = None + self.content_type: str = content_type + self.id: int = message_id # Lets fix the telegram usability ####up with ID in Message :) + self.message_id: int = message_id + self.from_user: User = from_user + self.date: int = date + self.chat: Chat = chat + self.forward_from: User = None + self.forward_from_chat: Chat = None + self.forward_from_message_id: int = None + self.forward_signature: str = None + self.forward_sender_name: str = None + self.forward_date: int = None + self.reply_to_message: Message = None + self.via_bot: User = None + self.edit_date: int = None + self.media_group_id: str = None + self.author_signature: str = None + self.text: str = None + self.entities: List[MessageEntity] = None + self.caption_entities: List[MessageEntity] = None + self.audio: Audio = None + self.document: Document = None + self.photo: List[PhotoSize] = None + self.sticker: Sticker = None + self.video: Video = None + self.video_note: VideoNote = None + self.voice: Voice = None + self.caption: str = None + self.contact: Contact = None + self.location: Location = None + self.venue: Venue = None + self.animation: Animation = None + self.dice: Dice = None + self.new_chat_member: User = None # Deprecated since Bot API 3.0. Not processed anymore + self.new_chat_members: List[User] = None + self.left_chat_member: User = None + self.new_chat_title: str = None + self.new_chat_photo: List[PhotoSize] = None + self.delete_chat_photo: bool = None + self.group_chat_created: bool = None + self.supergroup_chat_created: bool = None + self.channel_chat_created: bool = None + self.migrate_to_chat_id: int = None + self.migrate_from_chat_id: int = None + self.pinned_message: Message = None + self.invoice: Invoice = None + self.successful_payment: SuccessfulPayment = None + self.connected_website: str = None + self.reply_markup: InlineKeyboardMarkup = None for key in options: setattr(self, key, options[key]) self.json = json_string @@ -569,25 +551,27 @@ class Message(JsonDeserializable): class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable): + @staticmethod + def to_list_of_dicts(entity_list) -> List[Dict]: + res = [] + for e in entity_list: + res.append(MessageEntity.to_dict(e)) + return res or None @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) - type = obj['type'] - offset = obj['offset'] - length = obj['length'] - url = obj.get('url') - user = User.de_json(obj.get('user')) - language = obj.get('language') - return cls(type, offset, length, url, user, language) + if 'user' in obj: + obj['user'] = User.de_json(obj['user']) + return cls(**obj) - def __init__(self, type, offset, length, url=None, user=None, language=None): - self.type = type - self.offset = offset - self.length = length - self.url = url - self.user = user - self.language = language + def __init__(self, type, offset, length, url=None, user=None, language=None, **kwargs): + self.type: str = type + self.offset: int = offset + self.length: int = length + self.url: str = url + self.user: User = user + self.language: str = language def to_json(self): return json.dumps(self.to_dict()) @@ -606,13 +590,11 @@ class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - value = obj['value'] - emoji = obj['emoji'] - return cls(value, emoji) + return cls(**obj) - def __init__(self, value, emoji): - self.value = value - self.emoji = emoji + def __init__(self, value, emoji, **kwargs): + self.value: int = value + self.emoji: str = emoji def to_json(self): return json.dumps(self.to_dict()) @@ -627,19 +609,14 @@ class PhotoSize(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - width = obj['width'] - height = obj['height'] - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, width, height, file_size) + return cls(**obj) - def __init__(self, file_id, file_unique_id, width, height, file_size=None): - self.file_size = file_size - self.file_unique_id = file_unique_id - self.height = height - self.width = width - self.file_id = file_id + def __init__(self, file_id, file_unique_id, width, height, file_size=None, **kwargs): + self.file_size: int = file_size + self.file_unique_id: str = file_unique_id + self.height: int = height + self.width: int = width + self.file_id: str = file_id class Audio(JsonDeserializable): @@ -647,23 +624,21 @@ class Audio(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - duration = obj['duration'] - performer = obj.get('performer') - title = obj.get('title') - mime_type = obj.get('mime_type') - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, duration, performer, title, mime_type, file_size) + if 'thumb' in obj and 'file_id' in obj['thumb']: + obj['thumb'] = PhotoSize.de_json(obj['thumb']) + return cls(**obj) - def __init__(self, file_id, file_unique_id, duration, performer=None, title=None, mime_type=None, file_size=None): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.duration = duration - self.performer = performer - self.title = title - self.mime_type = mime_type - self.file_size = file_size + def __init__(self, file_id, file_unique_id, duration, performer=None, title=None, file_name=None, mime_type=None, + file_size=None, thumb=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.duration: int = duration + self.performer: str = performer + self.title: str = title + self.file_name: str = file_name + self.mime_type: str = mime_type + self.file_size: int = file_size + self.thumb: PhotoSize = thumb class Voice(JsonDeserializable): @@ -671,189 +646,168 @@ class Voice(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - duration = obj['duration'] - mime_type = obj.get('mime_type') - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, duration, mime_type, file_size) + return cls(**obj) - def __init__(self, file_id, file_unique_id, duration, mime_type=None, file_size=None): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.duration = duration - self.mime_type = mime_type - self.file_size = file_size + def __init__(self, file_id, file_unique_id, duration, mime_type=None, file_size=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.duration: int = duration + self.mime_type: str = mime_type + self.file_size: int = file_size class Document(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - thumb = None if 'thumb' in obj and 'file_id' in obj['thumb']: - thumb = PhotoSize.de_json(obj['thumb']) - file_name = obj.get('file_name') - mime_type = obj.get('mime_type') - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, thumb, file_name, mime_type, file_size) + obj['thumb'] = PhotoSize.de_json(obj['thumb']) + return cls(**obj) - def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.thumb = thumb - self.file_name = file_name - self.mime_type = mime_type - self.file_size = file_size + def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.thumb: PhotoSize = thumb + self.file_name: str = file_name + self.mime_type: str = mime_type + self.file_size: int = file_size class Video(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - width = obj['width'] - height = obj['height'] - duration = obj['duration'] - thumb = PhotoSize.de_json(obj.get('thumb')) - mime_type = obj.get('mime_type') - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, width, height, duration, thumb, mime_type, file_size) + if ('thumb' in obj and 'file_id' in obj['thumb']): + obj['thumb'] = PhotoSize.de_json(obj['thumb']) + return cls(**obj) - def __init__(self, file_id, file_unique_id, width, height, duration, thumb=None, mime_type=None, file_size=None): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.width = width - self.height = height - self.duration = duration - self.thumb = thumb - self.mime_type = mime_type - self.file_size = file_size + def __init__(self, file_id, file_unique_id, width, height, duration, thumb=None, file_name=None, mime_type=None, file_size=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.width: int = width + self.height: int = height + self.duration: int = duration + self.thumb: PhotoSize = thumb + self.file_name: str = file_name + self.mime_type: str = mime_type + self.file_size: int = file_size class VideoNote(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - length = obj['length'] - duration = obj['duration'] - thumb = PhotoSize.de_json(obj.get('thumb')) - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, length, duration, thumb, file_size) + if ('thumb' in obj and 'file_id' in obj['thumb']): + obj['thumb'] = PhotoSize.de_json(obj['thumb']) + return cls(**obj) - def __init__(self, file_id, file_unique_id, length, duration, thumb=None, file_size=None): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.length = length - self.duration = duration - self.thumb = thumb - self.file_size = file_size + def __init__(self, file_id, file_unique_id, length, duration, thumb=None, file_size=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.length: int = length + self.duration: int = duration + self.thumb: PhotoSize = thumb + self.file_size: int = file_size class Contact(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - phone_number = obj['phone_number'] - first_name = obj['first_name'] - last_name = obj.get('last_name') - user_id = obj.get('user_id') - vcard = obj.get('vcard') - return cls(phone_number, first_name, last_name, user_id, vcard) + return cls(**obj) - def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None): - self.phone_number = phone_number - self.first_name = first_name - self.last_name = last_name - self.user_id = user_id - self.vcard = vcard + def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None, **kwargs): + self.phone_number: str = phone_number + self.first_name: str = first_name + self.last_name: str = last_name + self.user_id: int = user_id + self.vcard: str = vcard -class Location(JsonDeserializable): +class Location(JsonDeserializable, JsonSerializable, Dictionaryable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - longitude = obj['longitude'] - latitude = obj['latitude'] - return cls(longitude, latitude) + return cls(**obj) - def __init__(self, longitude, latitude): - self.longitude = longitude - self.latitude = latitude + def __init__(self, longitude: float, latitude: float, horizontal_accuracy:float=None, + live_period: int=None, heading: int=None, proximity_alert_radius: int=None, **kwargs): + self.longitude: float = longitude + self.latitude: float = latitude + self.horizontal_accuracy: float = horizontal_accuracy + self.live_period: int = live_period + self.heading: int = heading + self.proximity_alert_radius: int = proximity_alert_radius + + def to_json(self): + return json.dumps(self.to_dict()) + + def to_dict(self): + return { + "longitude": self.longitude, + "latitude": self.latitude, + "horizontal_accuracy": self.horizontal_accuracy, + "live_period": self.live_period, + "heading": self.heading, + "proximity_alert_radius": self.proximity_alert_radius, + } class Venue(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - location = Location.de_json(obj['location']) - title = obj['title'] - address = obj['address'] - foursquare_id = obj.get('foursquare_id') - foursquare_type = obj.get('foursquare_type') - return cls(location, title, address, foursquare_id, foursquare_type) + obj['location'] = Location.de_json(obj['location']) + return cls(**obj) - def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None): - self.location = location - self.title = title - self.address = address - self.foursquare_id = foursquare_id - self.foursquare_type = foursquare_type + def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None, + google_place_id=None, google_place_type=None, **kwargs): + self.location: Location = location + self.title: str = title + self.address: str = address + self.foursquare_id: str = foursquare_id + self.foursquare_type: str = foursquare_type + self.google_place_id: str = google_place_id + self.google_place_type: str = google_place_type class UserProfilePhotos(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - total_count = obj['total_count'] photos = [[PhotoSize.de_json(y) for y in x] for x in obj['photos']] - return cls(total_count, photos) + obj['photos'] = photos + return cls(**obj) - def __init__(self, total_count, photos): - self.total_count = total_count - self.photos = photos + def __init__(self, total_count, photos, **kwargs): + self.total_count: int = total_count + self.photos: List[PhotoSize] = photos class File(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - file_size = obj.get('file_size') - file_path = obj.get('file_path') - return cls(file_id, file_unique_id, file_size, file_path) + return cls(**obj) - def __init__(self, file_id, file_unique_id, file_size, file_path): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.file_size = file_size - self.file_path = file_path + def __init__(self, file_id, file_unique_id, file_size, file_path, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.file_size: int = file_size + self.file_path: str = file_path class ForceReply(JsonSerializable): def __init__(self, selective=None): - self.selective = selective + self.selective: bool = selective def to_json(self): json_dict = {'force_reply': True} @@ -864,7 +818,7 @@ class ForceReply(JsonSerializable): class ReplyKeyboardRemove(JsonSerializable): def __init__(self, selective=None): - self.selective = selective + self.selective: bool = selective def to_json(self): json_dict = {'remove_keyboard': True} @@ -883,11 +837,11 @@ class ReplyKeyboardMarkup(JsonSerializable): logger.error('Telegram does not support reply keyboard row width over %d.' % self.max_row_keys) row_width = self.max_row_keys - self.resize_keyboard = resize_keyboard - self.one_time_keyboard = one_time_keyboard - self.selective = selective - self.row_width = row_width - self.keyboard = [] + self.resize_keyboard: bool = resize_keyboard + self.one_time_keyboard: bool = one_time_keyboard + self.selective: bool = selective + self.row_width: int = row_width + self.keyboard: List[List[KeyboardButton]] = [] def add(self, *args, row_width=None): """ @@ -952,10 +906,10 @@ class ReplyKeyboardMarkup(JsonSerializable): class KeyboardButton(Dictionaryable, JsonSerializable): def __init__(self, text, request_contact=None, request_location=None, request_poll=None): - self.text = text - self.request_contact = request_contact - self.request_location = request_location - self.request_poll = request_poll + self.text: str = text + self.request_contact: bool = request_contact + self.request_location: bool = request_location + self.request_poll: KeyboardButtonPollType = request_poll def to_json(self): return json.dumps(self.to_dict()) @@ -973,7 +927,7 @@ class KeyboardButton(Dictionaryable, JsonSerializable): class KeyboardButtonPollType(Dictionaryable): def __init__(self, type=''): - self.type = type + self.type: str = type def to_dict(self): return {'type': self.type} @@ -984,8 +938,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) keyboard = [[InlineKeyboardButton.de_json(button) for button in row] for row in obj['inline_keyboard']] return cls(keyboard) @@ -1002,8 +955,8 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) logger.error('Telegram does not support inline keyboard row width over %d.' % self.max_row_keys) row_width = self.max_row_keys - self.row_width = row_width - self.keyboard = keyboard if keyboard else [] + self.row_width: int = row_width + self.keyboard: List[List[InlineKeyboardButton]] = keyboard or [] def add(self, *args, row_width=None): """ @@ -1064,64 +1017,25 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) return json_dict -class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): - def __init__(self, url, forward_text=None, bot_username=None, request_write_access=None): - self.url = url - self.forward_text = forward_text - self.bot_username = bot_username - self.request_write_access = request_write_access - - @classmethod - def de_json(cls, json_string): - if (json_string is None): - return None - obj = cls.check_json(json_string) - url = obj['url'] - forward_text = obj.get('forward_text') - bot_username = obj.get('bot_username') - request_write_access = obj.get('request_write_access') - return cls(url, forward_text, bot_username, request_write_access) - - def to_json(self): - return json.dumps(self.to_dict()) - - def to_dict(self): - json_dict = {'url': self.url} - if self.forward_text: - json_dict['forward_text'] = self.forward_text - if self.bot_username: - json_dict['bot_username'] = self.bot_username - if self.request_write_access is not None: - json_dict['request_write_access'] = self.request_write_access - return json_dict - - class InlineKeyboardButton(Dictionaryable, JsonSerializable, JsonDeserializable): - def __init__(self, text, url=None, callback_data=None, switch_inline_query=None, - switch_inline_query_current_chat=None, callback_game=None, pay=None, login_url=None): - self.text = text - self.url = url - self.callback_data = callback_data - self.switch_inline_query = switch_inline_query - self.switch_inline_query_current_chat = switch_inline_query_current_chat - self.callback_game = callback_game - self.pay = pay - self.login_url = login_url - @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - text = obj['text'] - url = obj.get('url') - callback_data = obj.get('callback_data') - switch_inline_query = obj.get('switch_inline_query') - switch_inline_query_current_chat = obj.get('switch_inline_query_current_chat') - callback_game = obj.get('callback_game') - pay = obj.get('pay') - login_url = LoginUrl.de_json(obj.get('login_url')) - return cls(text, url, callback_data, switch_inline_query, switch_inline_query_current_chat, callback_game, pay, login_url) + if 'login_url' in obj: + obj['login_url'] = LoginUrl.de_json(obj.get('login_url')) + return cls(**obj) + + def __init__(self, text, url=None, callback_data=None, switch_inline_query=None, + switch_inline_query_current_chat=None, callback_game=None, pay=None, login_url=None, **kwargs): + self.text: str = text + self.url: str = url + self.callback_data: str = callback_data + self.switch_inline_query: str = switch_inline_query + self.switch_inline_query_current_chat: str = switch_inline_query_current_chat + self.callback_game = callback_game # Not Implemented + self.pay: bool = pay + self.login_url: LoginUrl = login_url def to_json(self): return json.dumps(self.to_dict()) @@ -1145,139 +1059,122 @@ class InlineKeyboardButton(Dictionaryable, JsonSerializable, JsonDeserializable) return json_dict +class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + return cls(**obj) + + def __init__(self, url, forward_text=None, bot_username=None, request_write_access=None, **kwargs): + self.url: str = url + self.forward_text: str = forward_text + self.bot_username: str = bot_username + self.request_write_access: bool = request_write_access + + def to_json(self): + return json.dumps(self.to_dict()) + + def to_dict(self): + json_dict = {'url': self.url} + if self.forward_text: + json_dict['forward_text'] = self.forward_text + if self.bot_username: + json_dict['bot_username'] = self.bot_username + if self.request_write_access is not None: + json_dict['request_write_access'] = self.request_write_access + return json_dict + + class CallbackQuery(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) - id = obj['id'] - from_user = User.de_json(obj['from']) - message = Message.de_json(obj.get('message')) - inline_message_id = obj.get('inline_message_id') - chat_instance = obj['chat_instance'] - data = obj.get('data') - game_short_name = obj.get('game_short_name') - return cls(id, from_user, data, chat_instance, message, inline_message_id, game_short_name) - - def __init__(self, id, from_user, data, chat_instance, message=None, inline_message_id=None, game_short_name=None): - self.game_short_name = game_short_name - self.chat_instance = chat_instance - self.id = id - self.from_user = from_user - self.message = message - self.data = data - self.inline_message_id = inline_message_id - + obj['from_user'] = User.de_json(obj.pop('from')) + if 'message' in obj: + obj['message'] = Message.de_json(obj.get('message')) + return cls(**obj) + def __init__(self, id, from_user, data, chat_instance, message=None, inline_message_id=None, game_short_name=None, **kwargs): + self.id: int = id + self.from_user: User = from_user + self.message: Message = message + self.inline_message_id: str = inline_message_id + self.chat_instance: str = chat_instance + self.data: str = data + self.game_short_name: str = game_short_name + + class ChatPhoto(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - small_file_id = obj['small_file_id'] - small_file_unique_id = obj['small_file_unique_id'] - big_file_id = obj['big_file_id'] - big_file_unique_id = obj['big_file_unique_id'] - return cls(small_file_id, small_file_unique_id, big_file_id, big_file_unique_id) + return cls(**obj) - def __init__(self, small_file_id, small_file_unique_id, big_file_id, big_file_unique_id): - self.small_file_id = small_file_id - self.small_file_unique_id = small_file_unique_id - self.big_file_id = big_file_id - self.big_file_unique_id = big_file_unique_id + def __init__(self, small_file_id, small_file_unique_id, big_file_id, big_file_unique_id, **kwargs): + self.small_file_id: str = small_file_id + self.small_file_unique_id: str = small_file_unique_id + self.big_file_id: str = big_file_id + self.big_file_unique_id: str = big_file_unique_id class ChatMember(JsonDeserializable): @classmethod def de_json(cls, json_string): - if json_string is None: - return None + if json_string is None: return None obj = cls.check_json(json_string) - user = User.de_json(obj['user']) - status = obj['status'] - custom_title = obj.get('custom_title') - can_be_edited = obj.get('can_be_edited') - can_post_messages = obj.get('can_post_messages') - can_edit_messages = obj.get('can_edit_messages') - can_delete_messages = obj.get('can_delete_messages') - can_restrict_members = obj.get('can_restrict_members') - can_promote_members = obj.get('can_promote_members') - can_change_info = obj.get('can_change_info') - can_invite_users = obj.get('can_invite_users') - can_pin_messages = obj.get('can_pin_messages') - is_member = obj.get('is_member') - can_send_messages = obj.get('can_send_messages') - can_send_media_messages = obj.get('can_send_media_messages') - can_send_polls = obj.get('can_send_polls') - can_send_other_messages = obj.get('can_send_other_messages') - can_add_web_page_previews = obj.get('can_add_web_page_previews') - until_date = obj.get('until_date') - return cls( - user, status, custom_title, can_be_edited, can_post_messages, - can_edit_messages, can_delete_messages, can_restrict_members, - can_promote_members, can_change_info, can_invite_users, can_pin_messages, - is_member, can_send_messages, can_send_media_messages, can_send_polls, - can_send_other_messages, can_add_web_page_previews, until_date) + obj['user'] = User.de_json(obj['user']) + return cls(**obj) - def __init__(self, user, status, custom_title=None, can_be_edited=None, + def __init__(self, user, status, custom_title=None, is_anonymous=None, can_be_edited=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_restrict_members=None, can_promote_members=None, can_change_info=None, can_invite_users=None, can_pin_messages=None, is_member=None, can_send_messages=None, can_send_media_messages=None, can_send_polls=None, - can_send_other_messages=None, can_add_web_page_previews=None, until_date=None): - self.user = user - self.status = status - self.custom_title = custom_title - self.can_be_edited = can_be_edited - self.can_post_messages = can_post_messages - self.can_edit_messages = can_edit_messages - self.can_delete_messages = can_delete_messages - self.can_restrict_members = can_restrict_members - self.can_promote_members = can_promote_members - self.can_change_info = can_change_info - self.can_invite_users = can_invite_users - self.can_pin_messages = can_pin_messages - self.is_member = is_member - self.can_send_messages = can_send_messages - self.can_send_media_messages = can_send_media_messages - self.can_send_polls = can_send_polls - self.can_send_other_messages = can_send_other_messages - self.can_add_web_page_previews = can_add_web_page_previews - self.until_date = until_date + can_send_other_messages=None, can_add_web_page_previews=None, until_date=None, **kwargs): + self.user: User = user + self.status: str = status + self.custom_title: str = custom_title + self.is_anonymous: bool = is_anonymous + self.can_be_edited: bool = can_be_edited + self.can_post_messages: bool = can_post_messages + self.can_edit_messages: bool = can_edit_messages + self.can_delete_messages: bool = can_delete_messages + self.can_restrict_members: bool = can_restrict_members + self.can_promote_members: bool = can_promote_members + self.can_change_info: bool = can_change_info + self.can_invite_users: bool = can_invite_users + self.can_pin_messages: bool = can_pin_messages + self.is_member: bool = is_member + 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 + self.can_add_web_page_previews: bool = can_add_web_page_previews + self.until_date: int = until_date 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) + 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): - self.can_send_messages = can_send_messages - self.can_send_media_messages = can_send_media_messages - self.can_send_polls = can_send_polls - self.can_send_other_messages = can_send_other_messages - self.can_add_web_page_previews = can_add_web_page_previews - self.can_change_info = can_change_info - self.can_invite_users = can_invite_users - self.can_pin_messages = can_pin_messages - - @classmethod - def de_json(cls, json_string): - if json_string is None: - return json_string - obj = cls.check_json(json_string) - can_send_messages = obj.get('can_send_messages') - can_send_media_messages = obj.get('can_send_media_messages') - can_send_polls = obj.get('can_send_polls') - can_send_other_messages = obj.get('can_send_other_messages') - can_add_web_page_previews = obj.get('can_add_web_page_previews') - can_change_info = obj.get('can_change_info') - can_invite_users = obj.get('can_invite_users') - can_pin_messages = obj.get('can_pin_messages') - return cls( - can_send_messages, can_send_media_messages, can_send_polls, - can_send_other_messages, can_add_web_page_previews, - can_change_info, can_invite_users, can_pin_messages) + 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 + self.can_add_web_page_previews: bool = can_add_web_page_previews + self.can_change_info: bool = can_change_info + self.can_invite_users: bool = can_invite_users + self.can_pin_messages: bool = can_pin_messages def to_json(self): return json.dumps(self.to_dict()) @@ -1312,8 +1209,8 @@ class BotCommand(JsonSerializable): :param description: Description of the command, 3-256 characters. :return: """ - self.command = command - self.description = description + self.command: str = command + self.description: str = description def to_json(self): return json.dumps(self.to_dict()) @@ -1327,71 +1224,89 @@ class BotCommand(JsonSerializable): class InlineQuery(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - id = obj['id'] - from_user = User.de_json(obj['from']) - location = Location.de_json(obj.get('location')) - query = obj['query'] - offset = obj['offset'] - return cls(id, from_user, location, query, offset) + obj['from_user'] = User.de_json(obj.pop('from')) + if 'location' in obj: + obj['location'] = Location.de_json(obj['location']) + return cls(**obj) - def __init__(self, id, from_user, location, query, offset): + 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 location: Sender location, only for bots that request user location :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 = id - self.from_user = from_user - self.location = location - self.query = query - self.offset = offset + self.id: int = id + self.from_user: User = from_user + self.query: str = query + self.offset: str = offset + self.chat_type: str = chat_type + self.location: Location = location + + class InputTextMessageContent(Dictionaryable): - def __init__(self, message_text, parse_mode=None, disable_web_page_preview=None): - self.message_text = message_text - self.parse_mode = parse_mode - self.disable_web_page_preview = disable_web_page_preview + 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 + self.entities: List[MessageEntity] = entities + self.disable_web_page_preview: bool = disable_web_page_preview def to_dict(self): - json_dic = {'message_text': self.message_text} + json_dict = {'message_text': self.message_text} if self.parse_mode: - json_dic['parse_mode'] = self.parse_mode + json_dict['parse_mode'] = self.parse_mode + if self.entities: + json_dict['entities'] = MessageEntity.to_list_of_dicts(self.entities) if self.disable_web_page_preview: - json_dic['disable_web_page_preview'] = self.disable_web_page_preview - return json_dic + json_dict['disable_web_page_preview'] = self.disable_web_page_preview + return json_dict class InputLocationMessageContent(Dictionaryable): - def __init__(self, latitude, longitude, live_period=None): - self.latitude = latitude - self.longitude = longitude - self.live_period = live_period + 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 + self.horizontal_accuracy: float = horizontal_accuracy + self.live_period: int = live_period + self.heading: int = heading + self.proximity_alert_radius: int = proximity_alert_radius def to_dict(self): - json_dic = {'latitude': self.latitude, 'longitude': self.longitude} + json_dict = {'latitude': self.latitude, 'longitude': self.longitude} + if self.horizontal_accuracy: + json_dict['horizontal_accuracy'] = self.horizontal_accuracy if self.live_period: - json_dic['live_period'] = self.live_period - return json_dic + json_dict['live_period'] = self.live_period + if self.heading: + json_dict['heading'] = self.heading + if self.proximity_alert_radius: + json_dict['proximity_alert_radius'] = self.proximity_alert_radius + return json_dict class InputVenueMessageContent(Dictionaryable): - def __init__(self, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None): - self.latitude = latitude - self.longitude = longitude - self.title = title - self.address = address - self.foursquare_id = foursquare_id - self.foursquare_type = foursquare_type + 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 + self.longitude: float = longitude + self.title: str = title + self.address: str = address + self.foursquare_id: str = foursquare_id + self.foursquare_type: str = foursquare_type + self.google_place_id: str = google_place_id + self.google_place_type: str = google_place_type def to_dict(self): json_dict = { @@ -1404,15 +1319,19 @@ class InputVenueMessageContent(Dictionaryable): json_dict['foursquare_id'] = self.foursquare_id if self.foursquare_type: json_dict['foursquare_type'] = self.foursquare_type + if self.google_place_id: + json_dict['google_place_id'] = self.google_place_id + if self.google_place_type: + json_dict['google_place_type'] = self.google_place_type return json_dict class InputContactMessageContent(Dictionaryable): def __init__(self, phone_number, first_name, last_name=None, vcard=None): - self.phone_number = phone_number - self.first_name = first_name - self.last_name = last_name - self.vcard = vcard + self.phone_number: str = phone_number + self.first_name: str = first_name + self.last_name: str = last_name + self.vcard: str = vcard def to_dict(self): json_dict = {'phone_numbe': self.phone_number, 'first_name': self.first_name} @@ -1426,17 +1345,14 @@ class InputContactMessageContent(Dictionaryable): class ChosenInlineResult(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) - result_id = obj['result_id'] - from_user = User.de_json(obj['from']) - query = obj['query'] - location = Location.de_json(obj.get('location')) - inline_message_id = obj.get('inline_message_id') - return cls(result_id, from_user, query, location, inline_message_id) + obj['from_user'] = User.de_json(obj.pop('from')) + if 'location' in obj: + obj['location'] = Location.de_json(obj['location']) + return cls(**obj) - def __init__(self, result_id, from_user, query, location=None, inline_message_id=None): + 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. @@ -1445,11 +1361,11 @@ class ChosenInlineResult(JsonDeserializable): :param query: String The query that was used to obtain the result. :return: ChosenInlineResult Object. """ - self.result_id = result_id - self.from_user = from_user - self.query = query - self.location = location - self.inline_message_id = inline_message_id + self.result_id: str = result_id + self.from_user: User = from_user + self.location: Location = location + self.inline_message_id: str = inline_message_id + self.query: str = query class InlineQueryResultArticle(JsonSerializable): @@ -2089,16 +2005,12 @@ class Game(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - title = obj['title'] - description = obj['description'] - photo = Game.parse_photo(obj['photo']) - text = obj.get('text') + obj['photo'] = Game.parse_photo(obj['photo']) if 'text_entities' in obj: - text_entities = Game.parse_entities(obj['text_entities']) - else: - text_entities = None - animation = Animation.de_json(obj.get('animation')) - return cls(title, description, photo, text, text_entities, animation) + obj['text_entities'] = Game.parse_entities(obj['text_entities']) + if 'animation' in obj: + obj['animation'] = Animation.de_json(obj['animation']) + return cls(**obj) @classmethod def parse_photo(cls, photo_size_array): @@ -2114,13 +2026,13 @@ class Game(JsonDeserializable): ret.append(MessageEntity.de_json(me)) return ret - def __init__(self, title, description, photo, text=None, text_entities=None, animation=None): - self.title = title - self.description = description - self.photo = photo - self.text = text - self.text_entities = text_entities - self.animation = animation + def __init__(self, title, description, photo, text=None, text_entities=None, animation=None, **kwargs): + self.title: str = title + self.description: str = description + self.photo: List[PhotoSize] = photo + self.text: str = text + self.text_entities: List[MessageEntity] = text_entities + self.animation: Animation = animation class Animation(JsonDeserializable): @@ -2128,21 +2040,20 @@ class Animation(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - thumb = PhotoSize.de_json(obj.get('thumb')) - file_name = obj.get('file_name') - mime_type = obj.get('mime_type') - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, thumb, file_name, mime_type, file_size) + obj["thumb"] = PhotoSize.de_json(obj['thumb']) + return cls(**obj) - def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.thumb = thumb - self.file_name = file_name - self.mime_type = mime_type - self.file_size = file_size + def __init__(self, file_id, file_unique_id, width=None, height=None, duration=None, + thumb=None, file_name=None, mime_type=None, file_size=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.width: int = width + self.height: int = height + self.duration: int = duration + self.thumb: PhotoSize = thumb + self.file_name: str = file_name + self.mime_type: str = mime_type + self.file_size: int = file_size class GameHighScore(JsonDeserializable): @@ -2150,23 +2061,21 @@ class GameHighScore(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - position = obj['position'] - user = User.de_json(obj['user']) - score = obj['score'] - return cls(position, user, score) + obj['user'] = User.de_json(obj['user']) + return cls(**obj) - def __init__(self, position, user, score): - self.position = position - self.user = user - self.score = score + def __init__(self, position, user, score, **kwargs): + self.position: int = position + self.user: User = user + self.score: int = score # Payments class LabeledPrice(JsonSerializable): def __init__(self, label, amount): - self.label = label - self.amount = amount + self.label: str = label + self.amount: int = amount def to_json(self): return json.dumps({ @@ -2179,19 +2088,14 @@ class Invoice(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - title = obj['title'] - description = obj['description'] - start_parameter = obj['start_parameter'] - currency = obj['currency'] - total_amount = obj['total_amount'] - return cls(title, description, start_parameter, currency, total_amount) + return cls(**obj) - def __init__(self, title, description, start_parameter, currency, total_amount): - self.title = title - self.description = description - self.start_parameter = start_parameter - self.currency = currency - self.total_amount = total_amount + def __init__(self, title, description, start_parameter, currency, total_amount, **kwargs): + self.title: str = title + self.description: str = description + self.start_parameter: str = start_parameter + self.currency: str = currency + self.total_amount: int = total_amount class ShippingAddress(JsonDeserializable): @@ -2199,21 +2103,15 @@ class ShippingAddress(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - country_code = obj['country_code'] - state = obj['state'] - city = obj['city'] - street_line1 = obj['street_line1'] - street_line2 = obj['street_line2'] - post_code = obj['post_code'] - return cls(country_code, state, city, street_line1, street_line2, post_code) + return cls(**obj) - def __init__(self, country_code, state, city, street_line1, street_line2, post_code): - self.country_code = country_code - self.state = state - self.city = city - self.street_line1 = street_line1 - self.street_line2 = street_line2 - self.post_code = post_code + def __init__(self, country_code, state, city, street_line1, street_line2, post_code, **kwargs): + self.country_code: str = country_code + self.state: str = state + self.city: str = city + self.street_line1: str = street_line1 + self.street_line2: str = street_line2 + self.post_code: str = post_code class OrderInfo(JsonDeserializable): @@ -2221,24 +2119,21 @@ class OrderInfo(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - name = obj.get('name') - phone_number = obj.get('phone_number') - email = obj.get('email') - shipping_address = ShippingAddress.de_json(obj.get('shipping_address')) - return cls(name, phone_number, email, shipping_address) + obj['shipping_address'] = ShippingAddress.de_json(obj['shipping_address']) + return cls(**obj) - def __init__(self, name, phone_number, email, shipping_address): - self.name = name - self.phone_number = phone_number - self.email = email - self.shipping_address = shipping_address + def __init__(self, name, phone_number, email, shipping_address, **kwargs): + self.name: str = name + self.phone_number: str = phone_number + self.email: str = email + self.shipping_address: ShippingAddress = shipping_address class ShippingOption(JsonSerializable): def __init__(self, id, title): - self.id = id - self.title = title - self.prices = [] + self.id: str = id + self.title: str = title + self.prices: List[LabeledPrice] = [] def add_price(self, *args): """ @@ -2262,25 +2157,19 @@ class SuccessfulPayment(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - currency = obj['currency'] - total_amount = obj['total_amount'] - invoice_payload = obj['invoice_payload'] - shipping_option_id = obj.get('shipping_option_id') - order_info = OrderInfo.de_json(obj.get('order_info')) - telegram_payment_charge_id = obj['telegram_payment_charge_id'] - provider_payment_charge_id = obj['provider_payment_charge_id'] - return cls(currency, total_amount, invoice_payload, shipping_option_id, order_info, - telegram_payment_charge_id, provider_payment_charge_id) + if 'order_info' in obj: + obj['order_info'] = OrderInfo.de_json(obj['order_info']) + return cls(**obj) - def __init__(self, currency, total_amount, invoice_payload, shipping_option_id, order_info, - telegram_payment_charge_id, provider_payment_charge_id): - self.currency = currency - self.total_amount = total_amount - self.invoice_payload = invoice_payload - self.shipping_option_id = shipping_option_id - self.order_info = order_info - self.telegram_payment_charge_id = telegram_payment_charge_id - self.provider_payment_charge_id = provider_payment_charge_id + def __init__(self, currency, total_amount, invoice_payload, shipping_option_id=None, order_info=None, + telegram_payment_charge_id=None, provider_payment_charge_id=None, **kwargs): + self.currency: str = currency + self.total_amount: int = total_amount + self.invoice_payload: str = invoice_payload + self.shipping_option_id: str = shipping_option_id + self.order_info: OrderInfo = order_info + self.telegram_payment_charge_id: str = telegram_payment_charge_id + self.provider_payment_charge_id: str = provider_payment_charge_id class ShippingQuery(JsonDeserializable): @@ -2288,17 +2177,15 @@ class ShippingQuery(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - id = obj['id'] - from_user = User.de_json(obj['from']) - invoice_payload = obj['invoice_payload'] - shipping_address = ShippingAddress.de_json(obj['shipping_address']) - return cls(id, from_user, invoice_payload, shipping_address) + obj['from_user'] = User.de_json(obj.pop('from')) + obj['shipping_address'] = ShippingAddress.de_json(obj['shipping_address']) + return cls(**obj) - def __init__(self, id, from_user, invoice_payload, shipping_address): - self.id = id - self.from_user = from_user - self.invoice_payload = invoice_payload - self.shipping_address = shipping_address + def __init__(self, id, from_user, invoice_payload, shipping_address, **kwargs): + self.id: str = id + self.from_user: User = from_user + self.invoice_payload: str = invoice_payload + self.shipping_address: ShippingAddress = shipping_address class PreCheckoutQuery(JsonDeserializable): @@ -2306,23 +2193,19 @@ class PreCheckoutQuery(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - id = obj['id'] - from_user = User.de_json(obj['from']) - currency = obj['currency'] - total_amount = obj['total_amount'] - invoice_payload = obj['invoice_payload'] - shipping_option_id = obj.get('shipping_option_id') - order_info = OrderInfo.de_json(obj.get('order_info')) - return cls(id, from_user, currency, total_amount, invoice_payload, shipping_option_id, order_info) + obj['from_user'] = User.de_json(obj.pop('from')) + if 'order_info' in obj: + obj['order_info'] = OrderInfo.de_json(obj['order_info']) + return cls(**obj) - def __init__(self, id, from_user, currency, total_amount, invoice_payload, shipping_option_id, order_info): - self.id = id - self.from_user = from_user - self.currency = currency - self.total_amount = total_amount - self.invoice_payload = invoice_payload - self.shipping_option_id = shipping_option_id - self.order_info = order_info + def __init__(self, id, from_user, currency, total_amount, invoice_payload, shipping_option_id=None, order_info=None, **kwargs): + self.id: str = id + self.from_user: User = from_user + self.currency: str = currency + self.total_amount: int = total_amount + self.invoice_payload: str = invoice_payload + self.shipping_option_id: str = shipping_option_id + self.order_info: OrderInfo = order_info # Stickers @@ -2332,21 +2215,21 @@ class StickerSet(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - name = obj['name'] - title = obj['title'] - is_animated = obj['is_animated'] - contains_masks = obj['contains_masks'] stickers = [] for s in obj['stickers']: stickers.append(Sticker.de_json(s)) - return cls(name, title, is_animated, contains_masks, stickers) + obj['stickers'] = stickers + if 'thumb' in obj and 'file_id' in obj['thumb']: + obj['thumb'] = PhotoSize.de_json(obj['thumb']) + return cls(**obj) - def __init__(self, name, title, is_animated, contains_masks, stickers): - self.stickers = stickers - self.is_animated = is_animated - self.contains_masks = contains_masks - self.title = title - self.name = name + def __init__(self, name, title, is_animated, contains_masks, stickers, thumb=None, **kwargs): + self.name: str = name + self.title: str = title + self.is_animated: bool = is_animated + self.contains_masks: bool = contains_masks + self.stickers: List[Sticker] = stickers + self.thumb: PhotoSize = thumb class Sticker(JsonDeserializable): @@ -2354,29 +2237,25 @@ class Sticker(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - file_id = obj['file_id'] - file_unique_id = obj['file_unique_id'] - width = obj['width'] - height = obj['height'] - is_animated = obj['is_animated'] - thumb = PhotoSize.de_json(obj.get('thumb')) - emoji = obj.get('emoji') - set_name = obj.get('set_name') - mask_position = MaskPosition.de_json(obj.get('mask_position')) - file_size = obj.get('file_size') - return cls(file_id, file_unique_id, width, height, thumb, emoji, set_name, mask_position, file_size, is_animated) + if 'thumb' in obj and 'file_id' in obj['thumb']: + obj['thumb'] = PhotoSize.de_json(obj['thumb']) + if 'mask_position' in obj: + obj['mask_position'] = MaskPosition.de_json(obj['mask_position']) + return cls(**obj) - def __init__(self, file_id, file_unique_id, width, height, thumb, emoji, set_name, mask_position, file_size, is_animated): - self.file_id = file_id - self.file_unique_id = file_unique_id - self.width = width - self.height = height - self.thumb = thumb - self.emoji = emoji - self.set_name = set_name - self.mask_position = mask_position - self.file_size = file_size - self.is_animated = is_animated + def __init__(self, file_id, file_unique_id, width, height, is_animated, + thumb=None, emoji=None, set_name=None, mask_position=None, file_size=None, **kwargs): + self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.width: int = width + self.height: int = height + self.is_animated: bool = is_animated + self.thumb: PhotoSize = thumb + self.emoji: str = emoji + self.set_name: str = set_name + self.mask_position: MaskPosition = mask_position + self.file_size: int = file_size + class MaskPosition(Dictionaryable, JsonDeserializable, JsonSerializable): @@ -2384,17 +2263,13 @@ class MaskPosition(Dictionaryable, JsonDeserializable, JsonSerializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - point = obj['point'] - x_shift = obj['x_shift'] - y_shift = obj['y_shift'] - scale = obj['scale'] - return cls(point, x_shift, y_shift, scale) + return cls(**obj) - def __init__(self, point, x_shift, y_shift, scale): - self.point = point - self.x_shift = x_shift - self.y_shift = y_shift - self.scale = scale + def __init__(self, point, x_shift, y_shift, scale, **kwargs): + self.point: str = point + self.x_shift: float = x_shift + self.y_shift: float = y_shift + self.scale: float = scale def to_json(self): return json.dumps(self.to_dict()) @@ -2407,10 +2282,10 @@ class MaskPosition(Dictionaryable, JsonDeserializable, JsonSerializable): class InputMedia(Dictionaryable, JsonSerializable): def __init__(self, type, media, caption=None, parse_mode=None): - self.type = type - self.media = media - self.caption = caption - self.parse_mode = parse_mode + self.type: str = type + self.media: str = media + self.caption: str = caption + self.parse_mode: str = parse_mode if util.is_string(self.media): self._media_name = '' @@ -2533,13 +2408,11 @@ class PollOption(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - text = obj['text'] - voter_count = int(obj['voter_count']) - return cls(text, voter_count) + return cls(**obj) - def __init__(self, text, voter_count = 0): - self.text = text - self.voter_count = voter_count + def __init__(self, text, voter_count = 0, **kwargs): + self.text: str = text + self.voter_count: int = voter_count # Converted in _convert_poll_options # def to_json(self): # # send_poll Option is a simple string: https://core.telegram.org/bots/api#sendpoll @@ -2551,49 +2424,33 @@ class Poll(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - poll_id = obj['id'] - question = obj['question'] options = [] for opt in obj['options']: options.append(PollOption.de_json(opt)) - total_voter_count = obj['total_voter_count'] - is_closed = obj['is_closed'] - is_anonymous = obj['is_anonymous'] - poll_type = obj['type'] - allows_multiple_answers = obj['allows_multiple_answers'] - correct_option_id = obj.get('correct_option_id') - explanation = obj.get('explanation') + obj['options'] = options or None if 'explanation_entities' in obj: - explanation_entities = Message.parse_entities(obj['explanation_entities']) - else: - explanation_entities = None - open_period = obj.get('open_period') - close_date = obj.get('close_date') - return cls( - question, options, - poll_id, total_voter_count, is_closed, is_anonymous, poll_type, - allows_multiple_answers, correct_option_id, explanation, explanation_entities, - open_period, close_date) + obj['explanation_entities'] = Message.parse_entities(obj['explanation_entities']) + return cls(**obj) def __init__( self, question, options, poll_id=None, total_voter_count=None, is_closed=None, is_anonymous=None, poll_type=None, allows_multiple_answers=None, correct_option_id=None, explanation=None, explanation_entities=None, - open_period=None, close_date=None): - self.id = poll_id - self.question = question - self.options = options - self.total_voter_count = total_voter_count - self.is_closed = is_closed - self.is_anonymous = is_anonymous - self.type = poll_type - self.allows_multiple_answers = allows_multiple_answers - self.correct_option_id = correct_option_id - self.explanation = explanation - self.explanation_entities = explanation_entities # Default state of entities is None. if (explanation_entities is not None) else [] - self.open_period = open_period - self.close_date = close_date + open_period=None, close_date=None, **kwargs): + self.id: str = poll_id + self.question: str = question + self.options: List[PollOption] = options + self.total_voter_count: int = total_voter_count + self.is_closed: bool = is_closed + self.is_anonymous: bool = is_anonymous + self.type: str = poll_type + self.allows_multiple_answers: bool = allows_multiple_answers + self.correct_option_id: int = correct_option_id + self.explanation: str = explanation + self.explanation_entities: List[MessageEntity] = explanation_entities # Default state of entities is None. if (explanation_entities is not None) else [] + self.open_period: int = open_period + self.close_date: int = close_date def add(self, option): if type(option) is PollOption: @@ -2607,15 +2464,13 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - poll_id = obj['poll_id'] - user = User.de_json(obj['user']) - options_ids = obj['option_ids'] - return cls(poll_id, user, options_ids) + obj['user'] = User.de_json(obj['user']) + return cls(**obj) - def __init__(self, poll_id, user, options_ids): - self.poll_id = poll_id - self.user = user - self.options_ids = options_ids + def __init__(self, poll_id, user, options_ids, **kwargs): + self.poll_id: str = poll_id + self.user: User = user + self.options_ids: List[int] = options_ids def to_json(self): return json.dumps(self.to_dict()) @@ -2624,3 +2479,56 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): return {'poll_id': self.poll_id, 'user': self.user.to_dict(), 'options_ids': self.options_ids} + + +class ChatLocation(JsonSerializable, JsonDeserializable, Dictionaryable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return json_string + obj = cls.check_json(json_string) + obj['location'] = Location.de_json(obj['location']) + return cls(**obj) + + def __init__(self, location: Location, address: str, **kwargs): + self.location: Location = location + self.address: str = address + + def to_json(self): + return json.dumps(self.to_dict()) + + def to_dict(self): + return { + "location": self.location.to_dict(), + "address": self.address + } + + +class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + obj['creator'] = User.de_json(obj['creator']) + return cls(**obj) + + def __init__(self, invite_link: str, creator: User, is_primary: bool, is_revoked: bool, + expire_date: int=None, member_limit: int=None, **kwargs): + self.invite_link: str = invite_link + self.creator: User = creator + self.is_primary: bool = is_primary + self.is_revoked: bool = is_revoked + self.expire_date: int = expire_date + self.member_limit: int = member_limit + + def to_json(self): + return json.dumps(self.to_dict()) + + def to_dict(self): + return { + "invite_link": self.invite_link, + "creator": self.creator.to_dict(), + "is_primary": self.is_primary, + "is_revoked": self.is_revoked, + "expire_date": self.expire_date, + "member_limit": self.member_limit + } \ No newline at end of file diff --git a/telebot/util.py b/telebot/util.py index de9c1ce..72a4b89 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +# credits: https://adamj.eu/tech/2021/05/13/python-type-hints-how-to-fix-circular-imports/ +from __future__ import annotations import random import re import string @@ -6,11 +8,13 @@ import threading import traceback import warnings import functools -from typing import Any, List, Dict +from typing import Any, List, Dict, TYPE_CHECKING import queue as Queue import logging -# from telebot import types +# credits: https://adamj.eu/tech/2021/05/13/python-type-hints-how-to-fix-circular-imports/ +if TYPE_CHECKING: + from telebot import types try: from PIL import Image @@ -289,7 +293,7 @@ def escape(text: str) -> str: return text -def user_link(user, include_id: bool=False) -> str: +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'! @@ -306,41 +310,40 @@ def user_link(user, include_id: bool=False) -> str: + (f" (
{user.id}
)" if include_id else "")) -# def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2): -# """ -# Returns a reply markup from a dict in this format: {'text': kwargs} -# This is useful to avoid always typing 'btn1 = InlineKeyboardButton(...)' 'btn2 = InlineKeyboardButton(...)' -# -# Example: -# 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 -# -# kwargs can be: -# { -# 'url': None, -# 'callback_data': None, -# 'switch_inline_query': None, -# 'switch_inline_query_current_chat': None, -# 'callback_game': None, -# 'pay': None, -# 'login_url': None -# } -# -# :param values: a dict containing all buttons to create in this format: {text: kwargs} {str:} -# :param row_width: -# :return: InlineKeyboardMarkup -# """ -# markup = types.InlineKeyboardMarkup(row_width=row_width) -# buttons = [] -# for text, kwargs in values.items(): -# buttons.append(types.InlineKeyboardButton(text=text, **kwargs)) -# markup.add(*buttons) -# return markup +def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.InlineKeyboardMarkup: + """ + Returns a reply markup from a dict in this format: {'text': kwargs} + This is useful to avoid always typing 'btn1 = InlineKeyboardButton(...)' 'btn2 = InlineKeyboardButton(...)' + + Example: + 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 + + kwargs can be: + { + 'url': None, + 'callback_data': None, + 'switch_inline_query': None, + 'switch_inline_query_current_chat': None, + 'callback_game': None, + 'pay': None, + 'login_url': None + } + + :param values: a dict containing all buttons to create in this format: {text: kwargs} {str:} + :return: InlineKeyboardMarkup + """ + markup = types.InlineKeyboardMarkup(row_width=row_width) + buttons = [] + for text, kwargs in values.items(): + buttons.append(types.InlineKeyboardButton(text=text, **kwargs)) + markup.add(*buttons) + return markup # CREDITS TO http://stackoverflow.com/questions/12317940#answer-12320352 From 63fe6e01d18360e6e9b8cf12b398dfc523bc3575 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Fri, 18 Jun 2021 22:35:49 +0200 Subject: [PATCH 145/350] Fixed the errors from my last PRs I testet all using pytest and python versions 3.6-3.9 on macOS --- telebot/__init__.py | 3 +++ telebot/types.py | 12 +++++++++++- telebot/util.py | 11 ++++------- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index eaf8465..cb582dc 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -9,6 +9,9 @@ import time import traceback from typing import List, Union +import telebot.util +import telebot.types + logger = logging.getLogger('TeleBot') formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' diff --git a/telebot/types.py b/telebot/types.py index 5b52676..79ffcf2 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- import logging -import types from typing import Dict, List try: @@ -159,6 +158,7 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) + print (obj) return cls(**obj) def __init__(self, id, is_bot, first_name, last_name=None, username=None, language_code=None, @@ -626,6 +626,8 @@ class Audio(JsonDeserializable): obj = cls.check_json(json_string) if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) + else: + obj['thumb'] = None return cls(**obj) def __init__(self, file_id, file_unique_id, duration, performer=None, title=None, file_name=None, mime_type=None, @@ -663,6 +665,8 @@ class Document(JsonDeserializable): obj = cls.check_json(json_string) if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) + else: + obj['thumb'] = None return cls(**obj) def __init__(self, file_id, file_unique_id, thumb=None, file_name=None, mime_type=None, file_size=None, **kwargs): @@ -2221,6 +2225,8 @@ class StickerSet(JsonDeserializable): obj['stickers'] = stickers if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) + else: + obj['thumb'] = None return cls(**obj) def __init__(self, name, title, is_animated, contains_masks, stickers, thumb=None, **kwargs): @@ -2239,6 +2245,8 @@ class Sticker(JsonDeserializable): obj = cls.check_json(json_string) if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) + else: + obj['thumb'] = None if 'mask_position' in obj: obj['mask_position'] = MaskPosition.de_json(obj['mask_position']) return cls(**obj) @@ -2424,6 +2432,7 @@ class Poll(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) + obj['poll_id'] = obj.pop('id') options = [] for opt in obj['options']: options.append(PollOption.de_json(opt)) @@ -2465,6 +2474,7 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): if (json_string is None): return None obj = cls.check_json(json_string) obj['user'] = User.de_json(obj['user']) + obj['options_ids'] = obj.pop('option_ids') return cls(**obj) def __init__(self, poll_id, user, options_ids, **kwargs): diff --git a/telebot/util.py b/telebot/util.py index 72a4b89..beb9e90 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -# credits: https://adamj.eu/tech/2021/05/13/python-type-hints-how-to-fix-circular-imports/ -from __future__ import annotations import random import re import string @@ -8,13 +6,12 @@ import threading import traceback import warnings import functools -from typing import Any, List, Dict, TYPE_CHECKING +from typing import Any, List, Dict import queue as Queue import logging -# credits: https://adamj.eu/tech/2021/05/13/python-type-hints-how-to-fix-circular-imports/ -if TYPE_CHECKING: - from telebot import types + +from telebot import types try: from PIL import Image @@ -198,7 +195,7 @@ def is_command(text: str) -> bool: :param text: Text to check. :return: True if `text` is a command, else False. """ - if (text is None): return None + if (text is None): return False return text.startswith('/') From a9ae070256bf65c64bc78547d6f57c2aa339177a Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Fri, 18 Jun 2021 22:37:31 +0200 Subject: [PATCH 146/350] Update types.py --- telebot/types.py | 1 - 1 file changed, 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 79ffcf2..6ecb75d 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -158,7 +158,6 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - print (obj) return cls(**obj) def __init__(self, id, is_bot, first_name, last_name=None, username=None, language_code=None, From d26923e167e4ce324134bbdb117039890c874007 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 19 Jun 2021 15:09:52 +0300 Subject: [PATCH 147/350] Raise exception if no token passed --- telebot/apihelper.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index a2f04b2..7a238e3 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -68,6 +68,8 @@ def _make_request(token, method_name, method='get', params=None, files=None): :param files: Optional files. :return: The result parsed to a JSON dictionary. """ + if not token: + raise Exception('Bot token is not defined') if API_URL: request_url = API_URL.format(token, method_name) else: From 795f7fff7fb41e6cc74b88f1229fee56032d8872 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Sat, 19 Jun 2021 17:59:55 +0200 Subject: [PATCH 148/350] Some small changes * Fixed type warnings in some editors by changing `var: Type = None` to `var: Union[Type, None] = None` * changed some args from `obj['arg']` to `obj.get('arg')` if arg is optional * better PEP-8 compliance for less weak warnings * added tests for the new type `ChatInviteLink` --- telebot/__init__.py | 157 +++++++++++++++++++++++------------- telebot/types.py | 180 +++++++++++++++++++++--------------------- telebot/util.py | 35 +++++--- tests/test_telebot.py | 18 +++++ tests/test_types.py | 11 +++ 5 files changed, 245 insertions(+), 156 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index cb582dc..d5d2e1a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -9,6 +9,7 @@ import time import traceback from typing import List, Union +# this imports are used to avoid circular import error import telebot.util import telebot.types @@ -23,7 +24,7 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) -from telebot import apihelper, types, util +from telebot import apihelper, util, types from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend """ @@ -252,19 +253,30 @@ class TeleBot: drop_pending_updates = None, timeout=None): """ Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an - update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. - In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. + update for the bot, we will send an HTTPS POST request to the specified url, + containing a JSON-serialized Update. + In case of an unsuccessful request, we will give up after a reasonable amount of attempts. + Returns True on success. :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration - :param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. - :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. - :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. - :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS + :param certificate: Upload your public key certificate so that the root certificate in use can be checked. + See our self-signed guide for details. + :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook + for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, + and higher values to increase your bot's throughput. + :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates + of these types. See Update for a complete list of available update types. + Specify an empty list to receive all updates regardless of type (default). + If not specified, the previous setting will be used. + :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address + resolved through DNS :param drop_pending_updates: Pass True to drop all pending updates :param timeout: Integer. Request connection timeout :return: """ - return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, drop_pending_updates, timeout) + return apihelper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, + drop_pending_updates, timeout) def delete_webhook(self, drop_pending_updates=None, timeout=None): """ @@ -330,14 +342,14 @@ class TeleBot: if self.skip_pending: logger.debug('Skipped {0} pending messages'.format(self.__skip_updates())) self.skip_pending = False - updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout, long_polling_timeout = long_polling_timeout) + updates = self.get_updates(offset=(self.last_update_id + 1), + timeout=timeout, long_polling_timeout=long_polling_timeout) self.process_new_updates(updates) def process_new_updates(self, updates): upd_count = len(updates) logger.debug('Received {0} new updates'.format(upd_count)) - if (upd_count == 0): - return + if upd_count == 0: return new_messages = None new_edited_messages = None @@ -488,11 +500,13 @@ class TeleBot: :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) - :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging + :param logger_level: Custom logging level for infinity_polling logging. + Use logger levels from logging as a value. None/NOTSET = no error logging """ while not self.__stop_polling.is_set(): try: - self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, *args, **kwargs) + self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, + *args, **kwargs) except Exception as e: if logger_level and logger_level >= logging.ERROR: logger.error("Infinity polling exception: %s", str(e)) @@ -590,7 +604,7 @@ class TeleBot: self.worker_pool.clear_exceptions() #* logger.info('Stopped polling.') - def __non_threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None): + def __non_threaded_polling(self, non_stop=False, interval=0, timeout=None, long_polling_timeout=None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 @@ -675,7 +689,8 @@ class TeleBot: def log_out(self) -> bool: """ Use this method to log out from the cloud Bot API server before launching the bot locally. - You MUST log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. + You MUST log out the bot before running it locally, otherwise there is no guarantee + that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. @@ -685,13 +700,13 @@ class TeleBot: def close(self) -> bool: """ Use this method to close the bot instance before moving it from one local server to another. - You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. + You need to delete the webhook before calling this method to ensure that the bot isn't launched again + after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. """ return apihelper.close(self.token) - def get_user_profile_photos(self, user_id, offset=None, limit=None) -> types.UserProfilePhotos: """ Retrieves the user profile photos of the person with 'user_id' @@ -807,7 +822,8 @@ class TeleBot: apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout)) - def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=None, timeout=None) -> types.Message: + def forward_message(self, chat_id, from_chat_id, message_id, + disable_notification=None, timeout=None) -> types.Message: """ Use this method to forward messages of any kind. :param disable_notification: @@ -897,7 +913,8 @@ class TeleBot: reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, thumb=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. + Use this method to send audio files, if you want Telegram clients to display them in the music player. + Your audio must be in the .mp3 format. :param chat_id:Unique identifier for the message recipient :param audio:Audio file to send. :param caption: @@ -909,7 +926,7 @@ class TeleBot: :param parse_mode :param disable_notification: :param timeout: - :param thumb: + :param thumb: :return: Message """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -921,7 +938,8 @@ class TeleBot: def send_voice(self, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=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. :param chat_id:Unique identifier for the message recipient. :param voice: :param caption: @@ -984,7 +1002,8 @@ class TeleBot: """ Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id - :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram server + :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server :param duration: Integer : Duration of sent video in seconds :param caption: String : Video caption (may also be used when resending videos by file_id). :param parse_mode: @@ -993,7 +1012,7 @@ class TeleBot: :param reply_markup: :param disable_notification: :param timeout: - :param thumb: InputFile or String : Thumbnail of the file sent + :param thumb: InputFile or String : Thumbnail of the file sent :param width: :param height: :return: @@ -1011,7 +1030,8 @@ class TeleBot: """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id - :param animation: InputFile or String : Animation to send. You can either pass a file_id as String to resend an animation that is already on the Telegram server + :param animation: InputFile or String : Animation to send. You can either pass a file_id as String to resend an + animation that is already on the Telegram server :param duration: Integer : Duration of sent video in seconds :param caption: String : Animation caption (may also be used when resending animation by file_id). :param parse_mode: @@ -1025,16 +1045,18 @@ class TeleBot: parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, thumb)) + apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb)) def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=None, timeout=None, thumb=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 mp4 videos of up to 1 minute long. Use this method to send + video messages. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id - :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend a video that is already on the Telegram server + :param 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: @@ -1133,7 +1155,8 @@ class TeleBot: :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/default”, “arts_entertainment/aquarium” or “food/icecream”.) + :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: @@ -1162,7 +1185,8 @@ class TeleBot: its typing status). :param chat_id: :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', - 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', 'upload_video_note'. + 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', + 'upload_video_note'. :param timeout: :return: API reply. :type: boolean """ @@ -1187,7 +1211,8 @@ class TeleBot: the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. - :param chat_id: Unique identifier for the target group or username of the target supergroup or channel (in the format @username) + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel + (in the format @username) :param user_id: Unique identifier of the target user :param only_if_banned: Do nothing if the user is not banned :return: True on success @@ -1219,9 +1244,10 @@ class TeleBot: use inline bots, implies can_send_media_messages :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages - :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups - :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, - implies can_invite_users + :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. + Ignored in public supergroups + :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, + implies can_invite_users :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups :return: True on success """ @@ -1463,9 +1489,13 @@ class TeleBot: return result return types.Message.de_json(result) - def edit_message_media(self, media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: + def edit_message_media(self, media, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: """ - Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. + Use this method to edit animation, audio, document, photo, or video messages. + If a message is a part of a message album, then it can be edited only to a photo or a video. + Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. + Use previously uploaded file via its file_id or specify a URL. :param media: :param chat_id: :param message_id: @@ -1478,7 +1508,8 @@ class TeleBot: return result return types.Message.de_json(result) - def edit_message_reply_markup(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: + def edit_message_reply_markup(self, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: """ Use this method to edit only the reply markup of messages. :param chat_id: @@ -1523,13 +1554,14 @@ class TeleBot: :param disable_edit_message: :return: """ - result = apihelper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, message_id, - inline_message_id) + result = apihelper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, + message_id, inline_message_id) if type(result) == bool: return result return types.Message.de_json(result) - def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None) -> List[types.GameHighScore]: + def get_game_high_scores(self, user_id, chat_id=None, + message_id=None, inline_message_id=None) -> List[types.GameHighScore]: """ Gets top points and game play :param user_id: @@ -1555,12 +1587,17 @@ class TeleBot: :param chat_id: Unique identifier for the target private chat :param title: Product name :param description: Product description - :param invoice_payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param invoice_payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, + use for your internal processes. :param provider_token: Payments provider token, obtained via @Botfather - :param currency: Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies - :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) - :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter - :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param currency: Three-letter ISO 4217 currency code, + see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components + (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice + when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods + or a marketing image for a service. People like it better when they see what they are paying for. :param photo_size: Photo size :param photo_width: Photo width :param photo_height: Photo height @@ -1573,8 +1610,10 @@ class TeleBot: :param send_email_to_provider: Pass True, if user's email address should be sent to provider :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :param reply_to_message_id: If the message is a reply, ID of the original message - :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button - :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, + one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. + A detailed description of required fields should be provided by the payment provider. :param timeout: :return: """ @@ -1651,7 +1690,7 @@ class TeleBot: :param ok: :param error_message: :return: - """ + """ return apihelper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) def edit_message_caption(self, caption, chat_id=None, message_id=None, inline_message_id=None, @@ -1677,7 +1716,7 @@ class TeleBot: def reply_to(self, message, text, **kwargs) -> types.Message: """ Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` - :param message: + :param message: :param text: :param kwargs: :return: @@ -1691,11 +1730,14 @@ class TeleBot: No more than 50 results per query are allowed. :param inline_query_id: Unique identifier for the answered query :param results: Array of results for the inline query - :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. - :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. - :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. + :param cache_time: The maximum amount of time in seconds that the result of the inline query + may be cached on the server. + :param is_personal: Pass True, if results may be cached on the server side only for + the user that sent the query. + :param next_offset: Pass the offset that a client should send in the next query with the same text + to receive more results. :param switch_pm_parameter: If passed, clients will display a button with specified text that switches the user - to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter + 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. """ @@ -1973,18 +2015,21 @@ class TeleBot: bot.send_message(message.chat.id, 'Did someone call for help?') # Handle all sent documents of type 'text/plain'. - @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', content_types=['document']) + @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', + content_types=['document']) def command_handle_document(message): bot.send_message(message.chat.id, 'Document received, sir!') # Handle all other messages. - @bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document', 'text', 'location', 'contact', 'sticker']) + @bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document', + 'text', 'location', 'contact', 'sticker']) def default_command(message): bot.send_message(message.chat.id, "This is the default command handler.") :param commands: Optional list of strings (commands to handle). :param regexp: Optional regular expression. - :param func: Optional lambda function. The lambda receives the message to test as the first parameter. It must return True if the command should handle the message. + :param 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. Defaults to ['text']. """ diff --git a/telebot/types.py b/telebot/types.py index 6ecb75d..9139374 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import logging -from typing import Dict, List +from typing import Dict, List, Union try: import ujson as json @@ -92,7 +92,7 @@ class JsonDeserializable(object): class Update(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) update_id = obj['update_id'] message = Message.de_json(obj.get('message')) @@ -128,7 +128,7 @@ class Update(JsonDeserializable): class WebhookInfo(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) url = obj['url'] has_custom_certificate = obj['has_custom_certificate'] @@ -156,7 +156,7 @@ class WebhookInfo(JsonDeserializable): class User(JsonDeserializable, Dictionaryable, JsonSerializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) return cls(**obj) @@ -197,7 +197,7 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): class GroupChat(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) return cls(**obj) @@ -249,8 +249,7 @@ class Chat(JsonDeserializable): class MessageID(JsonDeserializable): @classmethod def de_json(cls, json_string): - if(json_string is None): - return None + if json_string is None: return None obj = cls.check_json(json_string) message_id = obj['message_id'] return cls(message_id) @@ -262,7 +261,7 @@ class MessageID(JsonDeserializable): class Message(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) message_id = obj['message_id'] from_user = User.de_json(obj.get('from')) @@ -306,7 +305,8 @@ class Message(JsonDeserializable): opts['document'] = Document.de_json(obj['document']) content_type = 'document' if 'animation' in obj: - # Document content type accompanies "animation", so "animation" should be checked below "document" to override it + # Document content type accompanies "animation", + # so "animation" should be checked below "document" to override it opts['animation'] = Animation.de_json(obj['animation']) content_type = 'animation' if 'game' in obj: @@ -424,49 +424,49 @@ class Message(JsonDeserializable): self.from_user: User = from_user self.date: int = date self.chat: Chat = chat - self.forward_from: User = None - self.forward_from_chat: Chat = None - self.forward_from_message_id: int = None - self.forward_signature: str = None - self.forward_sender_name: str = None - self.forward_date: int = None - self.reply_to_message: Message = None - self.via_bot: User = None - self.edit_date: int = None - self.media_group_id: str = None - self.author_signature: str = None - self.text: str = None - self.entities: List[MessageEntity] = None - self.caption_entities: List[MessageEntity] = None - self.audio: Audio = None - self.document: Document = None - self.photo: List[PhotoSize] = None - self.sticker: Sticker = None - self.video: Video = None - self.video_note: VideoNote = None - self.voice: Voice = None - self.caption: str = None - self.contact: Contact = None - self.location: Location = None - self.venue: Venue = None - self.animation: Animation = None - self.dice: Dice = None - self.new_chat_member: User = None # Deprecated since Bot API 3.0. Not processed anymore - self.new_chat_members: List[User] = None - self.left_chat_member: User = None - self.new_chat_title: str = None - self.new_chat_photo: List[PhotoSize] = None - self.delete_chat_photo: bool = None - self.group_chat_created: bool = None - self.supergroup_chat_created: bool = None - self.channel_chat_created: bool = None - self.migrate_to_chat_id: int = None - self.migrate_from_chat_id: int = None - self.pinned_message: Message = None - self.invoice: Invoice = None - self.successful_payment: SuccessfulPayment = None - self.connected_website: str = None - self.reply_markup: InlineKeyboardMarkup = None + self.forward_from: Union[User, None] = None + self.forward_from_chat: Union[Chat, None] = None + self.forward_from_message_id: Union[int, None] = None + self.forward_signature: Union[str, None] = None + self.forward_sender_name: Union[str, None] = None + self.forward_date: Union[int, None] = None + self.reply_to_message: Union[Message, None] = None + self.via_bot: Union[User, None] = None + self.edit_date: Union[int, None] = None + self.media_group_id: Union[str, None] = None + self.author_signature: Union[str, None] = None + self.text: Union[str, None] = None + self.entities: Union[List[MessageEntity], None] = None + self.caption_entities: Union[List[MessageEntity], None] = None + self.audio: Union[Audio, None] = None + self.document: Union[Document, None] = None + self.photo: Union[List[PhotoSize], None] = None + self.sticker: Union[Sticker, None] = None + self.video: Union[Video, None] = None + self.video_note: Union[VideoNote, None] = None + self.voice: Union[Voice, None] = None + self.caption: Union[str, None] = None + self.contact: Union[Contact, None] = None + self.location: Union[Location, None] = None + self.venue: Union[Venue, None] = None + self.animation: Union[Animation, None] = None + self.dice: Union[Dice, None] = None + self.new_chat_member: Union[User, None] = None # Deprecated since Bot API 3.0. Not processed anymore + self.new_chat_members: Union[List[User], None] = None + self.left_chat_member: Union[User, None] = None + self.new_chat_title: Union[str, None] = None + self.new_chat_photo: Union[List[PhotoSize], None] = None + self.delete_chat_photo: Union[bool, None] = None + self.group_chat_created: Union[bool, None] = None + self.supergroup_chat_created: Union[bool, None] = None + self.channel_chat_created: Union[bool, None] = None + self.migrate_to_chat_id: Union[int, None] = None + self.migrate_from_chat_id: Union[int, None] = None + self.pinned_message: Union[Message, None] = None + self.invoice: Union[Invoice, None] = None + self.successful_payment: Union[SuccessfulPayment, None] = None + self.connected_website: Union[str, None] = None + self.reply_markup: Union[InlineKeyboardMarkup, None] = None for key in options: setattr(self, key, options[key]) self.json = json_string @@ -481,7 +481,7 @@ class Message(JsonDeserializable): message.html_text >> "Test parse formatting, url, text_mention and mention @username" - Cusom subs: + 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: message.custom_subs = {"bold": "{text}", "italic": "{text}", "mention": "{text}"} @@ -493,15 +493,15 @@ class Message(JsonDeserializable): return text _subs = { - "bold" : "{text}", - "italic" : "{text}", - "pre" : "
{text}
", - "code" : "{text}", - #"url" : "{text}", # @badiboy plain URLs have no text and do not need tags + "bold": "{text}", + "italic": "{text}", + "pre": "
{text}
", + "code": "{text}", + # "url": "{text}", # @badiboy plain URLs have no text and do not need tags "text_link": "{text}", "strikethrough": "{text}", "underline": "{text}" - } + } if hasattr(self, "custom_subs"): for key, value in self.custom_subs.items(): @@ -551,11 +551,12 @@ class Message(JsonDeserializable): class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable): @staticmethod - def to_list_of_dicts(entity_list) -> List[Dict]: + def to_list_of_dicts(entity_list) -> Union[List[Dict], None]: res = [] for e in entity_list: res.append(MessageEntity.to_dict(e)) return res or None + @classmethod def de_json(cls, json_string): if json_string is None: return None @@ -587,7 +588,7 @@ class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable): class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) return cls(**obj) @@ -606,7 +607,7 @@ class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): class PhotoSize(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) return cls(**obj) @@ -621,7 +622,7 @@ class PhotoSize(JsonDeserializable): class Audio(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + 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']) @@ -645,7 +646,7 @@ class Audio(JsonDeserializable): class Voice(JsonDeserializable): @classmethod def de_json(cls, json_string): - if (json_string is None): return None + if json_string is None: return None obj = cls.check_json(json_string) return cls(**obj) @@ -682,7 +683,7 @@ class Video(JsonDeserializable): 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']): + if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) return cls(**obj) @@ -703,7 +704,7 @@ class VideoNote(JsonDeserializable): 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']): + if 'thumb' in obj and 'file_id' in obj['thumb']: obj['thumb'] = PhotoSize.de_json(obj['thumb']) return cls(**obj) @@ -738,8 +739,8 @@ class Location(JsonDeserializable, JsonSerializable, Dictionaryable): obj = cls.check_json(json_string) return cls(**obj) - def __init__(self, longitude: float, latitude: float, horizontal_accuracy:float=None, - live_period: int=None, heading: int=None, proximity_alert_radius: int=None, **kwargs): + def __init__(self, longitude, latitude, horizontal_accuracy=None, + live_period=None, heading=None, proximity_alert_radius=None, **kwargs): self.longitude: float = longitude self.latitude: float = latitude self.horizontal_accuracy: float = horizontal_accuracy @@ -766,7 +767,7 @@ class Venue(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) - obj['location'] = Location.de_json(obj['location']) + obj['location'] = Location.de_json(obj.get('location')) return cls(**obj) def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None, @@ -785,11 +786,12 @@ class UserProfilePhotos(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) - photos = [[PhotoSize.de_json(y) for y in x] for x in obj['photos']] - obj['photos'] = photos + if 'photos' in obj: + photos = [[PhotoSize.de_json(y) for y in x] for x in obj['photos']] + obj['photos'] = photos return cls(**obj) - def __init__(self, total_count, photos, **kwargs): + def __init__(self, total_count, photos=None, **kwargs): self.total_count: int = total_count self.photos: List[PhotoSize] = photos @@ -859,8 +861,7 @@ class ReplyKeyboardMarkup(JsonSerializable): """ if row_width is None: row_width = self.row_width - - + if row_width > self.max_row_keys: # Todo: Will be replaced with Exception in future releases if not DISABLE_KEYLEN_ERROR: @@ -946,7 +947,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) keyboard = [[InlineKeyboardButton.de_json(button) for button in row] for row in obj['inline_keyboard']] return cls(keyboard) - def __init__(self, keyboard=None ,row_width=3): + def __init__(self, keyboard=None, row_width=3): """ This object represents an inline keyboard that appears right next to the message it belongs to. @@ -993,7 +994,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) def row(self, *args): """ Adds a list of InlineKeyboardButton to the keyboard. - This metod does not consider row_width. + This method does not consider row_width. InlineKeyboardMarkup.row("A").row("B", "C").to_json() outputs: '{keyboard: [["A"], ["B", "C"]]}' @@ -1255,8 +1256,6 @@ class InlineQuery(JsonDeserializable): self.offset: str = offset self.chat_type: str = chat_type self.location: Location = location - - class InputTextMessageContent(Dictionaryable): @@ -1337,7 +1336,7 @@ class InputContactMessageContent(Dictionaryable): self.vcard: str = vcard def to_dict(self): - json_dict = {'phone_numbe': self.phone_number, 'first_name': self.first_name} + json_dict = {'phone_number': self.phone_number, 'first_name': self.first_name} if self.last_name: json_dict['last_name'] = self.last_name if self.vcard: @@ -2043,7 +2042,10 @@ class Animation(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - obj["thumb"] = PhotoSize.de_json(obj['thumb']) + if 'thumb' in obj and 'file_id' in obj['thumb']: + obj["thumb"] = PhotoSize.de_json(obj['thumb']) + else: + obj['thumb'] = None return cls(**obj) def __init__(self, file_id, file_unique_id, width=None, height=None, duration=None, @@ -2122,10 +2124,10 @@ class OrderInfo(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - obj['shipping_address'] = ShippingAddress.de_json(obj['shipping_address']) + obj['shipping_address'] = ShippingAddress.de_json(obj.get('shipping_address')) return cls(**obj) - def __init__(self, name, phone_number, email, shipping_address, **kwargs): + def __init__(self, name=None, phone_number=None, email=None, shipping_address=None, **kwargs): self.name: str = name self.phone_number: str = phone_number self.email: str = email @@ -2160,8 +2162,7 @@ class SuccessfulPayment(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) - if 'order_info' in obj: - obj['order_info'] = OrderInfo.de_json(obj['order_info']) + obj['order_info'] = OrderInfo.de_json(obj.get('order_info')) return cls(**obj) def __init__(self, currency, total_amount, invoice_payload, shipping_option_id=None, order_info=None, @@ -2197,8 +2198,7 @@ class PreCheckoutQuery(JsonDeserializable): if (json_string is None): return None obj = cls.check_json(json_string) obj['from_user'] = User.de_json(obj.pop('from')) - if 'order_info' in obj: - obj['order_info'] = OrderInfo.de_json(obj['order_info']) + obj['order_info'] = OrderInfo.de_json(obj.get('order_info')) return cls(**obj) def __init__(self, id, from_user, currency, total_amount, invoice_payload, shipping_option_id=None, order_info=None, **kwargs): @@ -2473,6 +2473,7 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): if (json_string is None): return None obj = cls.check_json(json_string) obj['user'] = User.de_json(obj['user']) + # Strange name, i think it should be `option_ids` not `options_ids` maybe replace that obj['options_ids'] = obj.pop('option_ids') return cls(**obj) @@ -2487,6 +2488,7 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): def to_dict(self): return {'poll_id': self.poll_id, 'user': self.user.to_dict(), + #should be `option_ids` not `options_ids` could cause problems here 'options_ids': self.options_ids} @@ -2498,7 +2500,7 @@ class ChatLocation(JsonSerializable, JsonDeserializable, Dictionaryable): obj['location'] = Location.de_json(obj['location']) return cls(**obj) - def __init__(self, location: Location, address: str, **kwargs): + def __init__(self, location, address, **kwargs): self.location: Location = location self.address: str = address @@ -2520,8 +2522,8 @@ class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): obj['creator'] = User.de_json(obj['creator']) return cls(**obj) - def __init__(self, invite_link: str, creator: User, is_primary: bool, is_revoked: bool, - expire_date: int=None, member_limit: int=None, **kwargs): + def __init__(self, invite_link, creator, is_primary, is_revoked, + expire_date=None, member_limit=None, **kwargs): self.invite_link: str = invite_link self.creator: User = creator self.is_primary: bool = is_primary diff --git a/telebot/util.py b/telebot/util.py index beb9e90..7b87959 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -6,7 +6,7 @@ import threading import traceback import warnings import functools -from typing import Any, List, Dict +from typing import Any, List, Dict, Union import queue as Queue import logging @@ -36,6 +36,7 @@ content_type_service = [ 'supergroup_chat_created', 'channel_chat_created', 'migrate_to_chat_id', 'migrate_from_chat_id', 'pinned_message' ] + class WorkerThread(threading.Thread): count = 0 @@ -170,15 +171,19 @@ def async_dec(): def is_string(var): return isinstance(var, str) + def is_dict(var): return isinstance(var, dict) + def is_bytes(var): return isinstance(var, bytes) + def is_pil_image(var): return pil_imported and isinstance(var, Image.Image) + def pil_image_to_file(image, extension='JPEG', quality='web_low'): if pil_imported: photoBuffer = BytesIO() @@ -189,17 +194,18 @@ def pil_image_to_file(image, extension='JPEG', quality='web_low'): else: raise RuntimeError('PIL module is not imported') + def is_command(text: str) -> bool: """ Checks if `text` is a command. Telegram chat commands start with the '/' character. :param text: Text to check. :return: True if `text` is a command, else False. """ - if (text is None): return False + if text is None: return False return text.startswith('/') -def extract_command(text: str) -> str: +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. @@ -213,7 +219,7 @@ def extract_command(text: str) -> str: :param text: String to extract the command from :return: the command if `text` is a command (according to is_command), else None. """ - if (text is None): return None + if text is None: return None return text.split()[0].split('@')[0][1:] if is_command(text) else None @@ -229,7 +235,7 @@ def extract_arguments(text: str) -> str: :param text: String to extract the arguments from a command :return: the arguments if `text` is a command (according to is_command), else None. """ - regexp = re.compile(r"/\w*(@\w*)*\s*([\s\S]*)",re.IGNORECASE) + regexp = re.compile(r"/\w*(@\w*)*\s*([\s\S]*)", re.IGNORECASE) result = regexp.match(text) return result.group(2) if is_command(text) else None @@ -247,16 +253,17 @@ def split_string(text: str, chars_per_string: int) -> List[str]: def smart_split(text: str, chars_per_string: int=MAX_MESSAGE_LENGTH) -> List[str]: - f""" + """ Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. - If `chars_per_string` > {MAX_MESSAGE_LENGTH}: `chars_per_string` = {MAX_MESSAGE_LENGTH}. + If `chars_per_string` > 4096: `chars_per_string` = 4096. Splits by '\n', '. ' or ' ' in exactly this priority. :param text: The text to split :param chars_per_string: The number of maximum characters per part the text is split to. :return: The splitted text as a list of strings. """ + def _text_before_last(substr: str) -> str: return substr.join(part.split(substr)[:-1]) + substr @@ -270,9 +277,9 @@ def smart_split(text: str, chars_per_string: int=MAX_MESSAGE_LENGTH) -> List[str part = text[:chars_per_string] - if ("\n" in part): part = _text_before_last("\n") - elif (". " in part): part = _text_before_last(". ") - elif (" " in part): part = _text_before_last(" ") + if "\n" in part: part = _text_before_last("\n") + elif ". " in part: part = _text_before_last(". ") + elif " " in part: part = _text_before_last(" ") parts.append(part) text = text[len(part):] @@ -296,7 +303,7 @@ def user_link(user: types.User, include_id: bool=False) -> str: Attention: Don't forget to set parse_mode to 'HTML'! Example: - bot.send_message(your_user_id, user_link(message.from_user) + ' startet the bot!', parse_mode='HTML') + bot.send_message(your_user_id, user_link(message.from_user) + ' started the bot!', parse_mode='HTML') :param user: the user (not the user_id) :param include_id: include the user_id @@ -333,6 +340,7 @@ 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:} + :param row_width: int row width :return: InlineKeyboardMarkup """ markup = types.InlineKeyboardMarkup(row_width=row_width) @@ -363,8 +371,10 @@ def orify(e, changed_callback): e.set = lambda: or_set(e) e.clear = lambda: or_clear(e) + def OrEvent(*events): or_event = threading.Event() + def changed(): bools = [ev.is_set() for ev in events] if any(bools): @@ -391,15 +401,18 @@ def per_thread(key, construct_value, reset=False): return getattr(thread_local, key) + def chunks(lst, n): """Yield successive n-sized chunks from lst.""" # https://stackoverflow.com/a/312464/9935473 for i in range(0, len(lst), n): yield lst[i:i + n] + def generate_random_token(): return ''.join(random.sample(string.ascii_letters, 16)) + def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted diff --git a/tests/test_telebot.py b/tests/test_telebot.py index a70911e..e8f57a9 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -6,6 +6,7 @@ sys.path.append('../') import time import pytest import os +from datetime import datetime, timedelta import telebot from telebot import types @@ -407,6 +408,23 @@ class TestTeleBot: cn = tb.get_chat_members_count(GROUP_ID) assert cn > 1 + def test_export_chat_invite_link(self): + tb = telebot.TeleBot(TOKEN) + il = tb.export_chat_invite_link(GROUP_ID) + assert isinstance(il, str) + + def test_create_revoke_detailed_chat_invite_link(self): + tb = telebot.TeleBot(TOKEN) + cil = tb.create_chat_invite_link(GROUP_ID, + (datetime.now() + timedelta(minutes=1)).timestamp(), member_limit=5) + assert isinstance(cil.invite_link, str) + assert cil.creator.id == tb.get_me().id + assert isinstance(cil.expire_date, (float, int)) + assert cil.member_limit == 5 + assert not cil.is_revoked + rcil = tb.revoke_chat_invite_link(GROUP_ID, cil.invite_link) + assert rcil.is_revoked + def test_edit_markup(self): text = 'CI Test Message' tb = telebot.TeleBot(TOKEN) diff --git a/tests/test_types.py b/tests/test_types.py index 355f690..9ca73c9 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -219,3 +219,14 @@ def test_KeyboardButtonPollType(): json_str = markup.to_json() assert 'request_poll' in json_str assert 'quiz' in json_str + + +def test_json_chat_invite_link(): + json_string = r'{"invite_link": "https://t.me/joinchat/z-abCdEFghijKlMn", "creator": {"id": 329343347, "is_bot": false, "first_name": "Test", "username": "test_user", "last_name": "User", "language_code": "en"}, "is_primary": false, "is_revoked": false, "expire_date": 1624119999, "member_limit": 10}' + invite_link = types.ChatInviteLink.de_json(json_string) + assert invite_link.invite_link == 'https://t.me/joinchat/z-abCdEFghijKlMn' + assert isinstance(invite_link.creator, types.User) + assert not invite_link.is_primary + assert not invite_link.is_revoked + assert invite_link.expire_date == 1624119999 + assert invite_link.member_limit == 10 \ No newline at end of file From 0370a9f277552f2416e23b9894e08f78e02ba298 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Sat, 19 Jun 2021 20:13:53 +0200 Subject: [PATCH 149/350] Added class ChatMemberUpdated MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added class `ChatMemberUpdated` to types * Simplified `de_json` functions in `WebhookInfo` and `Update` classes (for overall more consistent code) * changed `options_ids` to ´option_id` in class `PollAnswer` * Added test for `ChatMemberUpdated` class in `test_types.py` and added the fields `my_chat_member` and `chat_member` to the `Update` class and its tests --- telebot/types.py | 81 ++++++++++++++++++++-------------- tests/test_handler_backends.py | 11 +++-- tests/test_telebot.py | 5 ++- tests/test_types.py | 14 +++++- 4 files changed, 71 insertions(+), 40 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 9139374..2898493 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -94,23 +94,24 @@ class Update(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) - update_id = obj['update_id'] - message = Message.de_json(obj.get('message')) - edited_message = Message.de_json(obj.get('edited_message')) - channel_post = Message.de_json(obj.get('channel_post')) - edited_channel_post = Message.de_json(obj.get('edited_channel_post')) - inline_query = InlineQuery.de_json(obj.get('inline_query')) - chosen_inline_result = ChosenInlineResult.de_json(obj.get('chosen_inline_result')) - callback_query = CallbackQuery.de_json(obj.get('callback_query')) - shipping_query = ShippingQuery.de_json(obj.get('shipping_query')) - pre_checkout_query = PreCheckoutQuery.de_json(obj.get('pre_checkout_query')) - poll = Poll.de_json(obj.get('poll')) - poll_answer = PollAnswer.de_json(obj.get('poll_answer')) - return cls(update_id, message, edited_message, channel_post, edited_channel_post, inline_query, - chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer) + obj['message'] = Message.de_json(obj.get('message')) + obj['edited_message'] = Message.de_json(obj.get('edited_message')) + obj['channel_post'] = Message.de_json(obj.get('channel_post')) + obj['edited_channel_post'] = Message.de_json(obj.get('edited_channel_post')) + obj['inline_query'] = InlineQuery.de_json(obj.get('inline_query')) + obj['chosen_inline_result'] = ChosenInlineResult.de_json(obj.get('chosen_inline_result')) + obj['callback_query'] = CallbackQuery.de_json(obj.get('callback_query')) + obj['shipping_query'] = ShippingQuery.de_json(obj.get('shipping_query')) + obj['pre_checkout_query'] = PreCheckoutQuery.de_json(obj.get('pre_checkout_query')) + obj['poll'] = Poll.de_json(obj.get('poll')) + obj['poll_answer'] = PollAnswer.de_json(obj.get('poll_answer')) + obj['my_chat_member'] = ChatMemberUpdated.de_json(obj.get('my_chat_member')) + obj['chat_member'] = ChatMemberUpdated.de_json(obj.get('chat_member')) + return cls(**obj) def __init__(self, update_id, message, edited_message, channel_post, edited_channel_post, inline_query, - chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer): + chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, + my_chat_member, chat_member, **kwargs): self.update_id = update_id self.message = message self.edited_message = edited_message @@ -123,6 +124,29 @@ class Update(JsonDeserializable): self.pre_checkout_query = pre_checkout_query self.poll = poll self.poll_answer = poll_answer + self.my_chat_member = my_chat_member + self.chat_member = chat_member + + +class ChatMemberUpdated(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + obj['chat'] = Chat.de_json(obj['chat']) + obj['from_user'] = User.de_json(obj.pop('from')) + obj['old_chat_member'] = ChatMember.de_json(obj['old_chat_member']) + obj['new_chat_member'] = ChatMember.de_json(obj['new_chat_member']) + obj['invite_link'] = ChatInviteLink.de_json(obj.get('invite_link')) + return cls(**obj) + + def __init__(self, chat, from_user, date, old_chat_member, new_chat_member, invite_link=None, **kwargs): + self.chat: Chat = chat + self.from_user: User = from_user + self.date: int = date + self.old_chat_member: ChatMember = old_chat_member + self.new_chat_member: ChatMember = new_chat_member + self.invite_link: Union[ChatInviteLink, None] = invite_link class WebhookInfo(JsonDeserializable): @@ -130,19 +154,11 @@ class WebhookInfo(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) - url = obj['url'] - has_custom_certificate = obj['has_custom_certificate'] - pending_update_count = obj['pending_update_count'] - ip_address = obj.get('ip_address') - last_error_date = obj.get('last_error_date') - last_error_message = obj.get('last_error_message') - max_connections = obj.get('max_connections') - allowed_updates = obj.get('allowed_updates') - return cls(url, has_custom_certificate, pending_update_count, ip_address, last_error_date, - last_error_message, max_connections, allowed_updates) + return cls(**obj) - def __init__(self, url, has_custom_certificate, pending_update_count, ip_address, last_error_date, - last_error_message, max_connections, allowed_updates): + def __init__(self, url, has_custom_certificate, pending_update_count, ip_address=None, + last_error_date=None, last_error_message=None, max_connections=None, + allowed_updates=None, **kwargs): self.url = url self.has_custom_certificate = has_custom_certificate self.pending_update_count = pending_update_count @@ -767,7 +783,7 @@ class Venue(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) - obj['location'] = Location.de_json(obj.get('location')) + obj['location'] = Location.de_json(obj['location']) return cls(**obj) def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None, @@ -2473,14 +2489,12 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): if (json_string is None): return None obj = cls.check_json(json_string) obj['user'] = User.de_json(obj['user']) - # Strange name, i think it should be `option_ids` not `options_ids` maybe replace that - obj['options_ids'] = obj.pop('option_ids') return cls(**obj) - def __init__(self, poll_id, user, options_ids, **kwargs): + def __init__(self, poll_id, user, option_ids, **kwargs): self.poll_id: str = poll_id self.user: User = user - self.options_ids: List[int] = options_ids + self.option_ids: List[int] = option_ids def to_json(self): return json.dumps(self.to_dict()) @@ -2488,8 +2502,7 @@ class PollAnswer(JsonSerializable, JsonDeserializable, Dictionaryable): def to_dict(self): return {'poll_id': self.poll_id, 'user': self.user.to_dict(), - #should be `option_ids` not `options_ids` could cause problems here - 'options_ids': self.options_ids} + 'option_ids': self.option_ids} class ChatLocation(JsonSerializable, JsonDeserializable, Dictionaryable): diff --git a/tests/test_handler_backends.py b/tests/test_handler_backends.py index 9605900..638cb27 100644 --- a/tests/test_handler_backends.py +++ b/tests/test_handler_backends.py @@ -62,8 +62,11 @@ def update_type(message): pre_checkout_query = None poll = None poll_answer = None + my_chat_member = None + chat_member = None return types.Update(1001234038283, message, edited_message, channel_post, edited_channel_post, inline_query, - chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer) + chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, + my_chat_member, chat_member) @pytest.fixture() @@ -78,9 +81,11 @@ def reply_to_message_update_type(reply_to_message): pre_checkout_query = None poll = None poll_answer = None + my_chat_member = None + chat_member = None return types.Update(1001234038284, reply_to_message, edited_message, channel_post, edited_channel_post, - inline_query, - chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer) + inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, + poll, poll_answer, my_chat_member, chat_member) def next_handler(message): diff --git a/tests/test_telebot.py b/tests/test_telebot.py index e8f57a9..a22adcd 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -458,8 +458,11 @@ class TestTeleBot: pre_checkout_query = None poll = None poll_answer = None + my_chat_member = None + chat_member = None return types.Update(-1001234038283, message, edited_message, channel_post, edited_channel_post, inline_query, - chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer) + chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, + my_chat_member, chat_member) def test_is_string_unicode(self): s1 = u'string' diff --git a/tests/test_types.py b/tests/test_types.py index 9ca73c9..417a678 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -210,7 +210,7 @@ def test_json_poll_answer(): poll_answer = types.PollAnswer.de_json(jsonstring) assert poll_answer.poll_id == '5895675970559410186' assert isinstance(poll_answer.user, types.User) - assert poll_answer.options_ids == [1] + assert poll_answer.option_ids == [1] def test_KeyboardButtonPollType(): @@ -229,4 +229,14 @@ def test_json_chat_invite_link(): assert not invite_link.is_primary assert not invite_link.is_revoked assert invite_link.expire_date == 1624119999 - assert invite_link.member_limit == 10 \ No newline at end of file + assert invite_link.member_limit == 10 + +def test_chat_member_updated(): + json_string = r'{"chat": {"id": -1234567890123, "type": "supergroup", "title": "No Real Group", "username": "NoRealGroup"}, "from": {"id": 133869498, "is_bot": false, "first_name": "Vincent"}, "date": 1624119999, "old_chat_member": {"user": {"id": 77777777, "is_bot": false, "first_name": "Pepe"}, "status": "member"}, "new_chat_member": {"user": {"id": 77777777, "is_bot": false, "first_name": "Pepe"}, "status": "administrator"}}' + cm_updated = types.ChatMemberUpdated.de_json(json_string) + assert cm_updated.chat.id == -1234567890123 + assert cm_updated.from_user.id == 133869498 + assert cm_updated.date == 1624119999 + assert cm_updated.old_chat_member.status == "member" + assert cm_updated.new_chat_member.status == "administrator" + From 18f1fd42b034f76125036e07fc84c7b92525a2de Mon Sep 17 00:00:00 2001 From: Leon Heess Date: Sun, 20 Jun 2021 13:14:55 +0200 Subject: [PATCH 150/350] Add Anti-Tracking Bot --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c19529a..cfbe149 100644 --- a/README.md +++ b/README.md @@ -687,6 +687,6 @@ Get help. Discuss. Chat. * [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. * Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. * Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. - +* [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by [Leon Heess (source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. **Want to have your bot listed here? Just make a pull request.** From 4146b5038464c9f878fcb07b9a48cc386c96c95d Mon Sep 17 00:00:00 2001 From: Vishal Singh <38159691+vishal2376@users.noreply.github.com> Date: Mon, 21 Jun 2021 13:16:22 +0530 Subject: [PATCH 151/350] Add developer bot --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index cfbe149..466d69d 100644 --- a/README.md +++ b/README.md @@ -688,5 +688,10 @@ Get help. Discuss. Chat. * Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. * Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. * [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by [Leon Heess (source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. +* [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot is specially created for 💻 coders and it can do following tasks + - Provide c++ learning resources 📚 + - GitHub(search,clone) + - Stackoverflow search 🔍 + - Codeforces(profile visualizer,random problems) **Want to have your bot listed here? Just make a pull request.** From 66598e39fe9ae79cd2e82b68fe94ba095d3f51c4 Mon Sep 17 00:00:00 2001 From: Vishal Singh <38159691+vishal2376@users.noreply.github.com> Date: Mon, 21 Jun 2021 16:27:32 +0530 Subject: [PATCH 152/350] Change description of developer bot --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 466d69d..305537b 100644 --- a/README.md +++ b/README.md @@ -688,10 +688,6 @@ Get help. Discuss. Chat. * Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. * Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. * [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by [Leon Heess (source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. -* [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot is specially created for 💻 coders and it can do following tasks - - Provide c++ learning resources 📚 - - GitHub(search,clone) - - Stackoverflow search 🔍 - - Codeforces(profile visualizer,random problems) +* [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot can do tasks like GitHub(search,clone),provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) **Want to have your bot listed here? Just make a pull request.** From f11bf08ba1660e87572e37ca9cbb54a95ff1288b Mon Sep 17 00:00:00 2001 From: Vishal Singh <38159691+vishal2376@users.noreply.github.com> Date: Mon, 21 Jun 2021 16:30:17 +0530 Subject: [PATCH 153/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 305537b..7048b6c 100644 --- a/README.md +++ b/README.md @@ -688,6 +688,6 @@ Get help. Discuss. Chat. * Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. * Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. * [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by [Leon Heess (source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. -* [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot can do tasks like GitHub(search,clone),provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) +* [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) **Want to have your bot listed here? Just make a pull request.** From 7118613ef7ffeb6e196f046a61fd907092e8623d Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 21 Jun 2021 17:39:13 +0200 Subject: [PATCH 154/350] Added missing features * added some missing features of TelegramBotAPI 4.6-5.2 to pyTelegramBotAPI * added type hints to (almost) all public TeleBot functions --- telebot/__init__.py | 681 ++++++++++++++++++++++++++++++++----------- telebot/apihelper.py | 159 ++++++++-- telebot/types.py | 116 +++++++- telebot/util.py | 4 +- 4 files changed, 761 insertions(+), 199 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index d5d2e1a..484b208 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import print_function +from datetime import datetime import logging import re @@ -7,12 +8,14 @@ import sys import threading import time import traceback -from typing import List, Union +from typing import Any, Callable, List, Optional, Union # this imports are used to avoid circular import error import telebot.util import telebot.types + + logger = logging.getLogger('TeleBot') formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' @@ -27,6 +30,12 @@ logger.setLevel(logging.ERROR) from telebot import apihelper, util, types from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend + +REPLY_MARKUP_TYPES = Union[ + types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, + types.ReplyKeyboardRemove, types.ForceReply] + + """ Module : telebot """ @@ -99,6 +108,7 @@ class TeleBot: getChatMembersCount getChatMember answerCallbackQuery + getMyCommands setMyCommands answerInlineQuery """ @@ -106,7 +116,7 @@ class TeleBot: def __init__( self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0, - suppress_middleware_excepions=False + suppress_middleware_excepions=False # <- Typo in exceptions ): """ :param token: bot API token @@ -302,7 +312,9 @@ class TeleBot: def remove_webhook(self): return self.set_webhook() # No params resets webhook - def get_updates(self, offset=None, limit=None, timeout=20, allowed_updates=None, long_polling_timeout = 20): + def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, + timeout: Optional[int]=20, allowed_updates: Optional[List[str]]=None, + long_polling_timeout: int=20) -> List[types.Update]: """ Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. :param allowed_updates: Array of string. List the types of updates you want your bot to receive. @@ -670,7 +682,7 @@ class TeleBot: result = apihelper.get_me(self.token) return types.User.de_json(result) - def get_file(self, file_id) -> types.File: + def get_file(self, file_id: str) -> types.File: """ Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. @@ -680,10 +692,10 @@ class TeleBot: """ return types.File.de_json(apihelper.get_file(self.token, file_id)) - def get_file_url(self, file_id) -> str: + def get_file_url(self, file_id: str) -> str: return apihelper.get_file_url(self.token, file_id) - def download_file(self, file_path) -> bytes: + def download_file(self, file_path: str) -> bytes: return apihelper.download_file(self.token, file_path) def log_out(self) -> bool: @@ -707,7 +719,8 @@ class TeleBot: """ return apihelper.close(self.token) - def get_user_profile_photos(self, user_id, offset=None, limit=None) -> types.UserProfilePhotos: + def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None, + limit: Optional[int]=None) -> types.UserProfilePhotos: """ Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos @@ -719,7 +732,7 @@ class TeleBot: result = apihelper.get_user_profile_photos(self.token, user_id, offset, limit) return types.UserProfilePhotos.de_json(result) - def get_chat(self, chat_id) -> types.Chat: + def get_chat(self, chat_id: Union[int, str]) -> types.Chat: """ Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. @@ -729,7 +742,7 @@ class TeleBot: result = apihelper.get_chat(self.token, chat_id) return types.Chat.de_json(result) - def leave_chat(self, chat_id) -> bool: + def leave_chat(self, chat_id: Union[int, str]) -> bool: """ Use this method for your bot to leave a group, supergroup or channel. Returns True on success. :param chat_id: @@ -738,7 +751,7 @@ class TeleBot: result = apihelper.leave_chat(self.token, chat_id) return result - def get_chat_administrators(self, chat_id) -> List[types.ChatMember]: + def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: """ Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains @@ -753,7 +766,7 @@ class TeleBot: ret.append(types.ChatMember.de_json(r)) return ret - def get_chat_members_count(self, chat_id) -> int: + def get_chat_members_count(self, chat_id: Union[int, str]) -> int: """ Use this method to get the number of members in a chat. Returns Int on success. :param chat_id: @@ -762,7 +775,7 @@ class TeleBot: result = apihelper.get_chat_members_count(self.token, chat_id) return result - def set_chat_sticker_set(self, chat_id, sticker_set_name) -> types.StickerSet: + 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. @@ -776,7 +789,7 @@ class TeleBot: result = apihelper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) return result - def delete_chat_sticker_set(self, chat_id) -> bool: + def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool: """ Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set @@ -788,7 +801,7 @@ class TeleBot: result = apihelper.delete_chat_sticker_set(self.token, chat_id) return result - def get_chat_member(self, chat_id, user_id) -> types.ChatMember: + def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: """ Use this method to get information about a member of a chat. Returns a ChatMember object on success. :param chat_id: @@ -798,13 +811,22 @@ class TeleBot: result = apihelper.get_chat_member(self.token, chat_id, user_id) return types.ChatMember.de_json(result) - def send_message(self, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None) -> types.Message: + def send_message( + self, chat_id: Union[int, str], text: str, + disable_web_page_preview: Optional[bool]=None, + reply_to_message_id: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send text messages. Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error. - If you must send more than 4000 characters, use the split_string function in apihelper.py. + If you must send more than 4000 characters, + use the `split_string` or `smart_split` function in util.py. :param chat_id: :param text: @@ -814,16 +836,22 @@ class TeleBot: :param parse_mode: :param disable_notification: Boolean, Optional. Sends the message silently. :param timeout: + :param entities: + :param allow_sending_without_reply: :return: API reply. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, - reply_markup, parse_mode, disable_notification, timeout)) + apihelper.send_message( + self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, + entities, allow_sending_without_reply)) - def forward_message(self, chat_id, from_chat_id, message_id, - disable_notification=None, timeout=None) -> types.Message: + def forward_message( + self, chat_id: Union[int, str], from_chat_id: Union[int, str], + message_id: int, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None) -> types.Message: """ Use this method to forward messages of any kind. :param disable_notification: @@ -836,9 +864,18 @@ class TeleBot: return types.Message.de_json( apihelper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) - def copy_message(self, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, - disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, - reply_markup=None, timeout=None) -> int: + def copy_message( + self, chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + caption: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> int: """ Use this method to copy messages of any kind. :param chat_id: which chat to forward @@ -859,7 +896,8 @@ class TeleBot: disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, timeout)) - def delete_message(self, chat_id, message_id, timeout=None) -> bool: + def delete_message(self, chat_id: Union[int, str], message_id: int, + timeout: Optional[int]=None) -> bool: """ Use this method to delete message. Returns True on success. :param chat_id: in which chat to delete @@ -870,9 +908,12 @@ class TeleBot: return apihelper.delete_message(self.token, chat_id, message_id, timeout) def send_dice( - self, chat_id, - emoji=None, disable_notification=None, reply_to_message_id=None, - reply_markup=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], + emoji: Optional[str]=None, disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send dices. :param chat_id: @@ -881,37 +922,57 @@ class TeleBot: :param reply_to_message_id: :param reply_markup: :param timeout: + :param allow_sending_without_reply: :return: Message """ return types.Message.de_json( apihelper.send_dice( self.token, chat_id, emoji, disable_notification, reply_to_message_id, - reply_markup, timeout) + reply_markup, timeout, allow_sending_without_reply) ) - def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None) -> types.Message: + def send_photo( + self, chat_id: Union[int, str], photo: Union[Any, str], + caption: Optional[str]=None, reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send photos. - :param disable_notification: :param chat_id: :param photo: :param caption: - :param parse_mode + :param parse_mode: + :param disable_notification: :param reply_to_message_id: :param reply_markup: :param timeout: + :param caption_entities: + :param allow_sending_without_reply: :return: API reply. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_photo(self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout)) + apihelper.send_photo( + self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) - def send_audio(self, chat_id, audio, caption=None, duration=None, performer=None, title=None, - reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, - timeout=None, thumb=None) -> types.Message: + def send_audio( + self, chat_id: Union[int, str], audio: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + performer: Optional[str]=None, title: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. @@ -927,16 +988,28 @@ class TeleBot: :param disable_notification: :param timeout: :param thumb: + :param caption_entities: + :param allow_sending_without_reply: :return: Message """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_audio(self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, - reply_markup, parse_mode, disable_notification, timeout, thumb)) + apihelper.send_audio( + self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) - def send_voice(self, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None) -> types.Message: + def send_voice( + self, chat_id: Union[int, str], voice: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. @@ -949,16 +1022,29 @@ class TeleBot: :param parse_mode :param disable_notification: :param timeout: + :param caption_entities: + :param allow_sending_without_reply: :return: Message """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_voice(self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout)) + apihelper.send_voice( + self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) - def send_document(self, chat_id, data,reply_to_message_id=None, caption=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None, thumb=None) -> types.Message: + def send_document( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + caption: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send general files. :param chat_id: @@ -970,17 +1056,25 @@ class TeleBot: :param disable_notification: :param timeout: :param thumb: InputFile or String : Thumbnail of the file sent + :param caption_entities: + :param allow_sending_without_reply: :return: API reply. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, caption, thumb)) + apihelper.send_data( + self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption, thumb, caption_entities, + allow_sending_without_reply)) def send_sticker( - self, chat_id, data, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send .webp stickers. :param chat_id: @@ -989,16 +1083,31 @@ class TeleBot: :param reply_markup: :param disable_notification: to disable the notification :param timeout: timeout + :param allow_sending_without_reply: :return: API reply. """ return types.Message.de_json( apihelper.send_data( - self.token, chat_id, data, 'sticker', reply_to_message_id, reply_markup, - disable_notification, timeout)) + self.token, chat_id=chat_id, data=data, data_type='sticker', + reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, + disable_notification=disable_notification, timeout=timeout, + allow_sending_without_reply=allow_sending_without_reply)) - def send_video(self, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, thumb=None, - width=None, height=None) -> types.Message: + def send_video( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + supports_streaming: Optional[bool]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + width: Optional[int]=None, + height: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -1015,18 +1124,30 @@ class TeleBot: :param thumb: InputFile or String : Thumbnail of the file sent :param width: :param height: + :param caption_entities: + :param allow_sending_without_reply: :return: """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, - parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height)) + apihelper.send_video( + self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, + parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height, + caption_entities, allow_sending_without_reply)) - def send_animation(self, chat_id, animation, duration=None, - caption=None, reply_to_message_id=None, - reply_markup=None, parse_mode=None, - disable_notification=None, timeout=None, thumb=None) -> types.Message: + def send_animation( + self, chat_id: Union[int, str], animation: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id @@ -1040,17 +1161,28 @@ class TeleBot: :param disable_notification: :param timeout: :param thumb: InputFile or String : Thumbnail of the file sent + :param caption_entities: + :param allow_sending_without_reply: :return: """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( - apihelper.send_animation(self.token, chat_id, animation, duration, caption, reply_to_message_id, - reply_markup, parse_mode, disable_notification, timeout, thumb)) + apihelper.send_animation( + self.token, chat_id, animation, duration, caption, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) - def send_video_note(self, chat_id, data, duration=None, length=None, - reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None, thumb=None) -> types.Message: + def send_video_note( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + length: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. @@ -1064,15 +1196,23 @@ class TeleBot: :param disable_notification: :param timeout: :param thumb: InputFile or String : Thumbnail of the file sent + :param allow_sending_without_reply: :return: """ return types.Message.de_json( - apihelper.send_video_note(self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, - disable_notification, timeout, thumb)) + apihelper.send_video_note( + self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, + disable_notification, timeout, thumb, allow_sending_without_reply)) def send_media_group( - self, chat_id, media, - disable_notification=None, reply_to_message_id=None, timeout=None) -> List[types.Message]: + self, chat_id: Union[int, str], + media: List[Union[ + types.InputMediaAudio, types.InputMediaDocument, + types.InputMediaPhoto, types.InputMediaVideo]], + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> List[types.Message]: """ send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: @@ -1080,56 +1220,90 @@ class TeleBot: :param disable_notification: :param reply_to_message_id: :param timeout: + :param allow_sending_without_reply: :return: """ result = apihelper.send_media_group( - self.token, chat_id, media, disable_notification, reply_to_message_id, timeout) + self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, + allow_sending_without_reply) ret = [] for msg in result: ret.append(types.Message.de_json(msg)) return ret def send_location( - self, chat_id, latitude, longitude, live_period=None, reply_to_message_id=None, - reply_markup=None, disable_notification=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], + latitude: float, longitude: float, + live_period: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + + """ Use this method to send point on the map. :param chat_id: :param latitude: :param longitude: - :param live_period + :param live_period: :param reply_to_message_id: :param reply_markup: :param disable_notification: :param timeout: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :param allow_sending_without_reply: :return: API reply. """ return types.Message.de_json( apihelper.send_location( - self.token, chat_id, latitude, longitude, live_period, reply_to_message_id, - reply_markup, disable_notification, timeout)) + self.token, chat_id, latitude, longitude, live_period, + reply_to_message_id, reply_markup, disable_notification, timeout, + horizontal_accuracy, heading, proximity_alert_radius, + allow_sending_without_reply)) - def edit_message_live_location(self, latitude, longitude, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None, timeout=None) -> types.Message: + def edit_message_live_location( + self, latitude: float, longitude: float, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None) -> types.Message: """ Use this method to edit live location :param latitude: :param longitude: :param chat_id: :param message_id: - :param inline_message_id: :param reply_markup: :param timeout: + :param inline_message_id: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: :return: """ return types.Message.de_json( apihelper.edit_message_live_location( self.token, latitude, longitude, chat_id, message_id, - inline_message_id, reply_markup, timeout)) + inline_message_id, reply_markup, timeout, + horizontal_accuracy, heading, proximity_alert_radius)) def stop_message_live_location( - self, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None, timeout=None) -> types.Message: + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> types.Message: """ Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires @@ -1145,8 +1319,18 @@ class TeleBot: self.token, chat_id, message_id, inline_message_id, reply_markup, timeout)) def send_venue( - self, chat_id, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], + latitude: float, longitude: float, + title: str, address: str, + foursquare_id: Optional[str]=None, + foursquare_type: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + google_place_id: Optional[str]=None, + google_place_type: Optional[str]=None) -> types.Message: """ Use this method to send information about a venue. :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel @@ -1161,24 +1345,36 @@ class TeleBot: :param reply_to_message_id: :param reply_markup: :param timeout: + :param allow_sending_without_reply: + :param google_place_id: + :param google_place_type: :return: """ return types.Message.de_json( apihelper.send_venue( self.token, chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, - disable_notification, reply_to_message_id, reply_markup, timeout) + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply, google_place_id, google_place_type) ) def send_contact( - self, chat_id, phone_number, first_name, last_name=None, vcard=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], phone_number: str, + first_name: str, last_name: Optional[str]=None, + vcard: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: return types.Message.de_json( apihelper.send_contact( self.token, chat_id, phone_number, first_name, last_name, vcard, - disable_notification, reply_to_message_id, reply_markup, timeout) + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) ) - def send_chat_action(self, chat_id, action, timeout=None) -> bool: + 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 @@ -1192,18 +1388,26 @@ class TeleBot: """ return apihelper.send_chat_action(self.token, chat_id, action, timeout) - def kick_chat_member(self, chat_id, user_id, until_date=None) -> bool: + def kick_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: """ Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup :param user_id: Int : Unique identifier of the target user :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever + :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. + If False, the user will be able to see messages in the group that were sent before the user was removed. + Always True for supergroups and channels. :return: boolean """ - return apihelper.kick_chat_member(self.token, chat_id, user_id, until_date) + return apihelper.kick_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) - def unban_chat_member(self, chat_id, user_id, only_if_banned = False) -> bool: + def unban_chat_member( + self, chat_id: Union[int, str], user_id: int, + only_if_banned: Optional[bool]=False) -> bool: """ Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. @@ -1220,11 +1424,16 @@ class TeleBot: return apihelper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) def restrict_chat_member( - self, chat_id, user_id, until_date=None, - can_send_messages=None, can_send_media_messages=None, - can_send_polls=None, can_send_other_messages=None, - can_add_web_page_previews=None, can_change_info=None, - can_invite_users=None, can_pin_messages=None) -> bool: + self, chat_id: Union[int, str], user_id: int, + until_date: Optional[Union[int, datetime]]=None, + can_send_messages: Optional[bool]=None, + can_send_media_messages: Optional[bool]=None, + can_send_polls: Optional[bool]=None, + can_send_other_messages: Optional[bool]=None, + can_add_web_page_previews: Optional[bool]=None, + can_change_info: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_pin_messages: Optional[bool]=None) -> bool: """ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have @@ -1258,9 +1467,19 @@ class TeleBot: can_add_web_page_previews, can_change_info, can_invite_users, can_pin_messages) - def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, - can_edit_messages=None, can_delete_messages=None, can_invite_users=None, - can_restrict_members=None, can_pin_messages=None, can_promote_members=None) -> bool: + def promote_chat_member( + self, chat_id: Union[int, str], user_id: int, + can_change_info: Optional[bool]=None, + can_post_messages: Optional[bool]=None, + can_edit_messages: Optional[bool]=None, + can_delete_messages: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_restrict_members: Optional[bool]=None, + can_pin_messages: Optional[bool]=None, + can_promote_members: Optional[bool]=None, + is_anonymous: Optional[bool]=None, + can_manage_chat: Optional[bool]=None, + can_manage_voice_chats: Optional[bool]=None) -> bool: """ Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1279,13 +1498,23 @@ class TeleBot: :param can_promote_members: Bool: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him) + :param is_anonymous: Bool: Pass True, if the administrator's presence in the chat is hidden + :param can_manage_chat: Bool: Pass True, if the administrator can access the chat event log, chat statistics, + message statistics in channels, see channel members, + see anonymous administrators in supergroups and ignore slow mode. + Implied by any other administrator privilege + :param can_manage_voice_chats: Bool: Pass True, if the administrator can manage voice chats + For now, bots can use this privilege only for passing to other administrators. :return: True on success. """ - return apihelper.promote_chat_member(self.token, chat_id, user_id, can_change_info, can_post_messages, - can_edit_messages, can_delete_messages, can_invite_users, - can_restrict_members, can_pin_messages, can_promote_members) + return apihelper.promote_chat_member( + self.token, chat_id, user_id, can_change_info, can_post_messages, + can_edit_messages, can_delete_messages, can_invite_users, + can_restrict_members, can_pin_messages, can_promote_members, + is_anonymous, can_manage_chat, can_manage_voice_chats) - def set_chat_administrator_custom_title(self, chat_id, user_id, custom_title) -> bool: + 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. @@ -1299,7 +1528,8 @@ class TeleBot: """ return apihelper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) - def set_chat_permissions(self, chat_id, permissions) -> bool: + def set_chat_permissions( + self, chat_id: Union[int, str], permissions: types.ChatPermissions) -> bool: """ 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 @@ -1312,7 +1542,10 @@ class TeleBot: """ return apihelper.set_chat_permissions(self.token, chat_id, permissions) - def create_chat_invite_link(self, chat_id, expire_date=None, member_limit=None) -> types.ChatInviteLink: + def create_chat_invite_link( + self, chat_id: Union[int, str], + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=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. @@ -1327,7 +1560,10 @@ class TeleBot: apihelper.create_chat_invite_link(self.token, chat_id, expire_date, member_limit) ) - def edit_chat_invite_link(self, chat_id, invite_link, expire_date=None, member_limit=None): + def edit_chat_invite_link( + self, chat_id: Union[int, str], invite_link: str, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None) -> types.ChatInviteLink: """ Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1343,7 +1579,8 @@ class TeleBot: apihelper.edit_chat_invite_link(self.token, chat_id, invite_link, expire_date, member_limit) ) - def revoke_chat_invite_link(self, chat_id, invite_link) -> types.ChatInviteLink: + def revoke_chat_invite_link( + self, chat_id: Union[int, str], invite_link: str) -> types.ChatInviteLink: """ Use this method to revoke an invite link created by the bot. Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator @@ -1358,7 +1595,7 @@ class TeleBot: apihelper.revoke_chat_invite_link(self.token, chat_id, invite_link) ) - def export_chat_invite_link(self, chat_id) -> str: + def export_chat_invite_link(self, chat_id: Union[int, str]) -> str: """ Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1369,7 +1606,7 @@ class TeleBot: """ return apihelper.export_chat_invite_link(self.token, chat_id) - def set_chat_photo(self, chat_id, photo) -> bool: + 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. @@ -1383,7 +1620,7 @@ class TeleBot: """ return apihelper.set_chat_photo(self.token, chat_id, photo) - def delete_chat_photo(self, chat_id) -> bool: + 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. @@ -1395,17 +1632,24 @@ class TeleBot: :return: """ return apihelper.delete_chat_photo(self.token, chat_id) + + def get_my_commands(self) -> List[types.BotCommand]: + """ + Use this method to get the current list of the bot's commands. + Returns List of BotCommand on success. + """ + result = apihelper.get_my_commands(self.token) + return [types.BotCommand.de_json(cmd) for cmd in result] - def set_my_commands(self, commands) -> bool: + def set_my_commands(self, commands: List[types.BotCommand]) -> bool: """ Use this method to change the list of the bot's commands. - :param commands: Array of BotCommand. A JSON-serialized list of bot commands - to be set as the list of the bot's commands. At most 100 commands can be specified. + :param commands: List of BotCommand. At most 100 commands can be specified. :return: """ return apihelper.set_my_commands(self.token, commands) - def set_chat_title(self, chat_id, title) -> bool: + def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: """ Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1419,7 +1663,7 @@ class TeleBot: """ return apihelper.set_chat_title(self.token, chat_id, title) - def set_chat_description(self, chat_id, description=None) -> bool: + def set_chat_description(self, chat_id: Union[int, str], description: Optional[str]=None) -> bool: """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1431,7 +1675,9 @@ class TeleBot: """ return apihelper.set_chat_description(self.token, chat_id, description) - def pin_chat_message(self, chat_id, message_id, disable_notification=False) -> bool: + def pin_chat_message( + self, chat_id: Union[int, str], message_id: int, + disable_notification: Optional[bool]=False) -> bool: """ Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1445,7 +1691,7 @@ class TeleBot: """ return apihelper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - def unpin_chat_message(self, chat_id, message_id=None) -> bool: + def unpin_chat_message(self, chat_id: Union[int, str], message_id: Optional[int]=None) -> bool: """ Use this method to unpin specific pinned message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1457,7 +1703,7 @@ class TeleBot: """ return apihelper.unpin_chat_message(self.token, chat_id, message_id) - def unpin_all_chat_messages(self, chat_id) -> bool: + def unpin_all_chat_messages(self, chat_id: Union[int, str]) -> bool: """ Use this method to unpin a all pinned messages in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1468,8 +1714,14 @@ class TeleBot: """ return apihelper.unpin_all_chat_messages(self.token, chat_id) - def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, - disable_web_page_preview=None, reply_markup=None) -> Union[types.Message, bool]: + def edit_message_text( + self, text: str, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + disable_web_page_preview: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit text and game messages. :param text: @@ -1489,8 +1741,11 @@ class TeleBot: return result return types.Message.de_json(result) - def edit_message_media(self, media, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: + def edit_message_media( + self, media: Any, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. @@ -1508,8 +1763,11 @@ class TeleBot: return result return types.Message.de_json(result) - def edit_message_reply_markup(self, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None) -> Union[types.Message, bool]: + def edit_message_reply_markup( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit only the reply markup of messages. :param chat_id: @@ -1524,8 +1782,12 @@ class TeleBot: return types.Message.de_json(result) def send_game( - self, chat_id, game_short_name, disable_notification=None, - reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], game_short_name: str, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Used to send the game :param chat_id: @@ -1534,15 +1796,22 @@ class TeleBot: :param reply_to_message_id: :param reply_markup: :param timeout: + :param allow_sending_without_reply: :return: """ result = apihelper.send_game( self.token, chat_id, game_short_name, disable_notification, - reply_to_message_id, reply_markup, timeout) + reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) return types.Message.de_json(result) - def set_game_score(self, user_id, score, force=None, chat_id=None, message_id=None, inline_message_id=None, - disable_edit_message=None) -> Union[types.Message, bool]: + def set_game_score( + self, user_id: Union[int, str], score: int, + force: Optional[bool]=None, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + disable_edit_message: Optional[bool]=None) -> Union[types.Message, bool]: """ Sets the value of points in the game to a specific user :param user_id: @@ -1560,8 +1829,10 @@ class TeleBot: return result return types.Message.de_json(result) - def get_game_high_scores(self, user_id, chat_id=None, - message_id=None, inline_message_id=None) -> List[types.GameHighScore]: + def get_game_high_scores( + self, user_id: int, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: """ Gets top points and game play :param user_id: @@ -1576,12 +1847,23 @@ class TeleBot: ret.append(types.GameHighScore.de_json(r)) return ret - def send_invoice(self, chat_id, title, description, invoice_payload, provider_token, currency, prices, - start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, - need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, - send_phone_number_to_provider=None, send_email_to_provider=None, is_flexible=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, - timeout=None) -> types.Message: + def send_invoice( + self, chat_id: Union[int, str], title: str, description: str, + invoice_payload: str, provider_token: str, currency: str, + prices: List[types.LabeledPrice], start_parameter: Optional[str]=None, + photo_url: Optional[str]=None, photo_size: Optional[int]=None, + photo_width: Optional[int]=None, photo_height: Optional[int]=None, + need_name: Optional[bool]=None, need_phone_number: Optional[bool]=None, + need_email: Optional[bool]=None, need_shipping_address: Optional[bool]=None, + send_phone_number_to_provider: Optional[bool]=None, + send_email_to_provider: Optional[bool]=None, + is_flexible: Optional[bool]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + provider_data: Optional[str]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: """ Sends invoice :param chat_id: Unique identifier for the target private chat @@ -1615,6 +1897,7 @@ class TeleBot: :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: :return: """ result = apihelper.send_invoice( @@ -1622,14 +1905,25 @@ class TeleBot: currency, prices, start_parameter, photo_url, photo_size, photo_width, photo_height, need_name, need_phone_number, need_email, need_shipping_address, send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, - reply_to_message_id, reply_markup, provider_data, timeout) + reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply) return types.Message.de_json(result) def send_poll( - self, chat_id, question, options, - is_anonymous=None, type=None, allows_multiple_answers=None, correct_option_id=None, - explanation=None, explanation_parse_mode=None, open_period=None, close_date=None, is_closed=None, - disable_notifications=False, reply_to_message_id=None, reply_markup=None, timeout=None) -> types.Message: + self, chat_id: Union[int, str], question: str, options: List[str], + is_anonymous: Optional[bool]=None, type: Optional[str]=None, + allows_multiple_answers: Optional[bool]=None, + correct_option_id: Optional[int]=None, + explanation: Optional[str]=None, + explanation_parse_mode: Optional[str]=None, + open_period: Optional[int]=None, + close_date: Optional[Union[int, datetime]]=None, + is_closed: Optional[bool]=None, + disable_notifications: Optional[bool]=False, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + allow_sending_without_reply: Optional[bool]=None, + timeout: Optional[int]=None, + explanation_entities: Optional[List[types.MessageEntity]]=None) -> types.Message: """ Send polls :param chat_id: @@ -1646,8 +1940,10 @@ class TeleBot: :param is_closed: :param disable_notifications: :param reply_to_message_id: + :param allow_sending_without_reply: :param reply_markup: :param timeout: + :param explanation_entities: :return: """ @@ -1660,9 +1956,12 @@ class TeleBot: question, options, is_anonymous, type, allows_multiple_answers, correct_option_id, explanation, explanation_parse_mode, open_period, close_date, is_closed, - disable_notifications, reply_to_message_id, reply_markup, timeout)) + disable_notifications, reply_to_message_id, allow_sending_without_reply, + reply_markup, timeout, explanation_entities)) - def stop_poll(self, chat_id, message_id, reply_markup=None) -> types.Poll: + def stop_poll( + self, chat_id: Union[int, str], message_id: int, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Poll: """ Stops poll :param chat_id: @@ -1672,7 +1971,10 @@ class TeleBot: """ return types.Poll.de_json(apihelper.stop_poll(self.token, chat_id, message_id, reply_markup)) - def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None) -> bool: + def answer_shipping_query( + self, shipping_query_id: str, ok: bool, + shipping_options: Optional[List[types.ShippingOption]]=None, + error_message: Optional[str]=None) -> bool: """ Asks for an answer to a shipping question :param shipping_query_id: @@ -1683,7 +1985,9 @@ class TeleBot: """ return apihelper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) - def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None) -> bool: + def answer_pre_checkout_query( + self, pre_checkout_query_id: int, ok: bool, + error_message: Optional[str]=None) -> bool: """ Response to a request for pre-inspection :param pre_checkout_query_id: @@ -1693,8 +1997,12 @@ class TeleBot: """ return apihelper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) - def edit_message_caption(self, caption, chat_id=None, message_id=None, inline_message_id=None, - parse_mode=None, reply_markup=None) -> Union[types.Message, bool]: + def edit_message_caption( + self, caption: str, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit captions of messages :param caption: @@ -1713,7 +2021,7 @@ class TeleBot: return result return types.Message.de_json(result) - def reply_to(self, message, text, **kwargs) -> types.Message: + def reply_to(self, message: types.Message, text: str, **kwargs) -> types.Message: """ Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` :param message: @@ -1723,8 +2031,14 @@ class TeleBot: """ return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) - def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, - switch_pm_text=None, switch_pm_parameter=None) -> bool: + def answer_inline_query( + self, inline_query_id: str, + results: List[Any], + cache_time: Optional[int]=None, + is_personal: Optional[bool]=None, + next_offset: Optional[str]=None, + switch_pm_text: Optional[str]=None, + switch_pm_parameter: Optional[str]=None) -> bool: """ Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. @@ -1744,7 +2058,10 @@ class TeleBot: return apihelper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset, switch_pm_text, switch_pm_parameter) - def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None) -> bool: + def answer_callback_query( + self, callback_query_id: str, + text: Optional[str]=None, show_alert: Optional[bool]=None, + url: Optional[str]=None, cache_time: Optional[int]=None) -> bool: """ Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. @@ -1757,7 +2074,15 @@ class TeleBot: """ return apihelper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) - def get_sticker_set(self, name) -> types.StickerSet: + def set_sticker_set_thumb( + self, name: str, user_id: int, thumb: Union[Any, str]=None): + """ + Use this method to set the thumbnail of a sticker set. + Animated thumbnails can be set for animated sticker sets only. Returns True on success. + """ + return apihelper.set_sticker_set_thumb(self.token, name, user_id, thumb) + + def get_sticker_set(self, name: str) -> types.StickerSet: """ Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: @@ -1766,7 +2091,7 @@ class TeleBot: result = apihelper.get_sticker_set(self.token, name) return types.StickerSet.de_json(result) - def upload_sticker_file(self, user_id, png_sticker) -> types.File: + def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: """ Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success. @@ -1777,24 +2102,32 @@ class TeleBot: result = apihelper.upload_sticker_file(self.token, user_id, png_sticker) return types.File.de_json(result) - def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, - mask_position=None) -> bool: + def create_new_sticker_set( + self, user_id: int, name: str, title: str, + png_sticker: Union[Any, str], + emojis: str, + contains_masks: Optional[bool]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: """ - Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. + Use this method to create new sticker set owned by a user. + The bot will be able to edit the created sticker set. Returns True on success. :param user_id: :param name: :param title: - :param png_sticker: + :param png_sticker: :param emojis: :param contains_masks: :param mask_position: :return: """ - return apihelper.create_new_sticker_set(self.token, user_id, name, title, png_sticker, emojis, contains_masks, - mask_position) + return apihelper.create_new_sticker_set(self.token, user_id, name, title, png_sticker, emojis, + contains_masks, mask_position) + - def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None) -> bool: + def add_sticker_to_set( + self, user_id: int, name: str, png_sticker: Union[Any, str], + emojis: str, mask_position: Optional[types.MaskPosition]=None) -> bool: """ Use this method to add a new sticker to a set created by the bot. Returns True on success. :param user_id: @@ -1806,7 +2139,7 @@ class TeleBot: """ return apihelper.add_sticker_to_set(self.token, user_id, name, png_sticker, emojis, mask_position) - def set_sticker_position_in_set(self, sticker, position) -> bool: + def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: """ Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. :param sticker: @@ -1815,7 +2148,7 @@ class TeleBot: """ return apihelper.set_sticker_position_in_set(self.token, sticker, position) - def delete_sticker_from_set(self, sticker) -> bool: + def delete_sticker_from_set(self, sticker: str) -> bool: """ Use this method to delete a sticker from a set created by the bot. Returns True on success. :param sticker: @@ -1823,7 +2156,8 @@ class TeleBot: """ return apihelper.delete_sticker_from_set(self.token, sticker) - def register_for_reply(self, message, callback, *args, **kwargs) -> None: + def register_for_reply( + self, message: types.Message, callback: Callable, *args, **kwargs) -> None: """ Registers a callback function to be notified when a reply to `message` arrives. @@ -1836,7 +2170,8 @@ class TeleBot: message_id = message.message_id self.register_for_reply_by_message_id(message_id, callback, *args, **kwargs) - def register_for_reply_by_message_id(self, message_id, callback, *args, **kwargs) -> None: + def register_for_reply_by_message_id( + self, message_id: int, callback: Callable, *args, **kwargs) -> None: """ Registers a callback function to be notified when a reply to `message` arrives. @@ -1861,7 +2196,8 @@ class TeleBot: for handler in handlers: self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) - def register_next_step_handler(self, message, callback, *args, **kwargs) -> None: + def register_next_step_handler( + self, message: types.Message, callback: Callable, *args, **kwargs) -> None: """ Registers a callback function to be notified when new message arrives after `message`. @@ -1875,7 +2211,8 @@ class TeleBot: chat_id = message.chat.id self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) - def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs) -> None: + def register_next_step_handler_by_chat_id( + self, chat_id: Union[int, str], callback: Callable, *args, **kwargs) -> None: """ Registers a callback function to be notified when new message arrives after `message`. @@ -1888,7 +2225,7 @@ class TeleBot: """ self.next_step_backend.register_handler(chat_id, Handler(callback, *args, **kwargs)) - def clear_step_handler(self, message) -> None: + def clear_step_handler(self, message: types.Message) -> None: """ Clears all callback functions registered by register_next_step_handler(). @@ -1897,7 +2234,7 @@ class TeleBot: chat_id = message.chat.id self.clear_step_handler_by_chat_id(chat_id) - def clear_step_handler_by_chat_id(self, chat_id) -> None: + def clear_step_handler_by_chat_id(self, chat_id: Union[int, str]) -> None: """ Clears all callback functions registered by register_next_step_handler(). @@ -1905,7 +2242,7 @@ class TeleBot: """ self.next_step_backend.clear_handlers(chat_id) - def clear_reply_handlers(self, message) -> None: + def clear_reply_handlers(self, message: types.Message) -> None: """ Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). @@ -1914,7 +2251,7 @@ class TeleBot: message_id = message.message_id self.clear_reply_handlers_by_message_id(message_id) - def clear_reply_handlers_by_message_id(self, message_id) -> None: + def clear_reply_handlers_by_message_id(self, message_id: int) -> None: """ Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). diff --git a/telebot/apihelper.py b/telebot/apihelper.py index e9e15cf..49a125a 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import time from datetime import datetime +from typing import Dict try: import ujson as json @@ -167,14 +168,22 @@ def get_me(token): method_url = r'getMe' return _make_request(token, method_url) + +def get_my_commands(token): + method_url = r'getMyCommands' + return _make_request(token, method_url) + + def log_out(token): method_url = r'logOut' return _make_request(token, method_url) + def close(token): method_url = r'close' return _make_request(token, method_url) + def get_file(token, file_id): method_url = r'getFile' return _make_request(token, method_url, params={'file_id': file_id}) @@ -203,7 +212,8 @@ def download_file(token, file_path): def send_message( token, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None, + entities=None, allow_sending_without_reply=None): """ Use this method to send text messages. On success, the sent Message is returned. :param token: @@ -215,6 +225,8 @@ def send_message( :param parse_mode: :param disable_notification: :param timeout: + :param entities: + :param allow_sending_without_reply: :return: """ method_url = r'sendMessage' @@ -231,6 +243,10 @@ def send_message( payload['disable_notification'] = disable_notification if timeout: payload['connect-timeout'] = timeout + if entities: + payload['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, method='post') @@ -324,6 +340,18 @@ def get_chat_members_count(token, chat_id): return _make_request(token, method_url, params=payload) +def set_sticker_set_thumb(token, name, user_id, thumb): + method_url = r'setStickerSetThumb' + payload = {'name': name, 'user_id': user_id} + files = {} + if thumb: + if not isinstance(thumb, str): + files['thumb'] = thumb + else: + payload['thumb'] = thumb + return _make_request(token, method_url, params=payload, files=files or None) + + def set_chat_sticker_set(token, chat_id, sticker_set_name): method_url = r'setChatStickerSet' payload = {'chat_id': chat_id, 'sticker_set_name': sticker_set_name} @@ -381,7 +409,7 @@ def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_m def send_dice( token, chat_id, emoji=None, disable_notification=None, reply_to_message_id=None, - reply_markup=None, timeout=None): + reply_markup=None, timeout=None, allow_sending_without_reply=None): method_url = r'sendDice' payload = {'chat_id': chat_id} if emoji: @@ -394,13 +422,16 @@ def send_dice( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout + if 'allow_sending_without_reply': + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) def send_photo( token, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None, + caption_entities=None, allow_sending_without_reply=None): method_url = r'sendPhoto' payload = {'chat_id': chat_id} files = None @@ -422,13 +453,17 @@ def send_photo( payload['disable_notification'] = disable_notification if timeout: payload['connect-timeout'] = timeout + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') def send_media_group( token, chat_id, media, disable_notification=None, reply_to_message_id=None, - timeout=None): + timeout=None, allow_sending_without_reply=None): method_url = r'sendMediaGroup' media_json, files = convert_input_media_array(media) payload = {'chat_id': chat_id, 'media': media_json} @@ -438,6 +473,8 @@ def send_media_group( payload['reply_to_message_id'] = reply_to_message_id if timeout: payload['connect-timeout'] = timeout + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request( token, method_url, params=payload, method='post' if files else 'get', @@ -446,14 +483,24 @@ def send_media_group( def send_location( token, chat_id, latitude, longitude, - live_period=None, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None): + live_period=None, reply_to_message_id=None, + reply_markup=None, disable_notification=None, + timeout=None, horizontal_accuracy=None, heading=None, + proximity_alert_radius=None, allow_sending_without_reply=None): method_url = r'sendLocation' payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude} if live_period: payload['live_period'] = live_period + if horizontal_accuracy: + payload['horizontal_accuracy'] = horizontal_accuracy + if heading: + payload['heading'] = heading + if proximity_alert_radius: + payload['proximity_alert_radius'] = proximity_alert_radius if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if disable_notification is not None: @@ -463,14 +510,22 @@ def send_location( return _make_request(token, method_url, params=payload) -def edit_message_live_location(token, latitude, longitude, chat_id=None, message_id=None, - inline_message_id=None, reply_markup=None, timeout=None): +def edit_message_live_location( + token, latitude, longitude, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None, timeout=None, + horizontal_accuracy=None, heading=None, proximity_alert_radius=None): method_url = r'editMessageLiveLocation' payload = {'latitude': latitude, 'longitude': longitude} if chat_id: payload['chat_id'] = chat_id if message_id: payload['message_id'] = message_id + if horizontal_accuracy: + payload['horizontal_accuracy'] = horizontal_accuracy + if heading: + payload['heading'] = heading + if proximity_alert_radius: + payload['proximity_alert_radius'] = proximity_alert_radius if inline_message_id: payload['inline_message_id'] = inline_message_id if reply_markup: @@ -501,7 +556,9 @@ def stop_message_live_location( def send_venue( token, chat_id, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, disable_notification=None, - reply_to_message_id=None, reply_markup=None, timeout=None): + reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None, google_place_id=None, + google_place_type=None): method_url = r'sendVenue' payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address} if foursquare_id: @@ -516,12 +573,19 @@ def send_venue( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if google_place_id: + payload['google_place_id'] = google_place_id + if google_place_type: + payload['google_place_type'] = google_place_type return _make_request(token, method_url, params=payload) def send_contact( token, chat_id, phone_number, first_name, last_name=None, vcard=None, - disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None): method_url = r'sendContact' payload = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name} if last_name: @@ -536,6 +600,8 @@ def send_contact( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -548,7 +614,8 @@ def send_chat_action(token, chat_id, action, timeout=None): def send_video(token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, thumb=None, width=None, height=None): + parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, + thumb=None, width=None, height=None, caption_entities=None, allow_sending_without_reply=None): method_url = r'sendVideo' payload = {'chat_id': chat_id} files = None @@ -584,11 +651,17 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_to_messa payload['width'] = width if height: payload['height'] = height + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') -def send_animation(token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None, thumb=None): +def send_animation( + token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, thumb=None, caption_entities=None, + allow_sending_without_reply=None): method_url = r'sendAnimation' payload = {'chat_id': chat_id} files = None @@ -618,11 +691,16 @@ def send_animation(token, chat_id, data, duration=None, caption=None, reply_to_m files = {'thumb': thumb} else: payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, - parse_mode=None, disable_notification=None, timeout=None): + parse_mode=None, disable_notification=None, timeout=None, caption_entities=None, + allow_sending_without_reply=None): method_url = r'sendVoice' payload = {'chat_id': chat_id} files = None @@ -644,11 +722,15 @@ def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_mess payload['disable_notification'] = disable_notification if timeout: payload['connect-timeout'] = timeout + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, - disable_notification=None, timeout=None, thumb=None): + disable_notification=None, timeout=None, thumb=None, allow_sending_without_reply=None): method_url = r'sendVideoNote' payload = {'chat_id': chat_id} files = None @@ -678,11 +760,14 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m files = {'thumb': thumb} else: payload['thumb'] = thumb + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') def send_audio(token, chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, - reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, thumb=None): + reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, thumb=None, + caption_entities=None, allow_sending_without_reply=None): method_url = r'sendAudio' payload = {'chat_id': chat_id} files = None @@ -716,11 +801,16 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non files = {'thumb': thumb} else: payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, - disable_notification=None, timeout=None, caption=None, thumb=None): + disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, + allow_sending_without_reply=None): method_url = get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None @@ -748,6 +838,10 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m files = {'thumb': thumb} else: payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -758,13 +852,15 @@ def get_method_by_type(data_type): return r'sendSticker' -def kick_chat_member(token, chat_id, user_id, until_date=None): +def kick_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=None): method_url = 'kickChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} if isinstance(until_date, datetime): payload['until_date'] = until_date.timestamp() else: payload['until_date'] = until_date + if revoke_messages is not None: + payload['revoke_messages'] = revoke_messages return _make_request(token, method_url, params=payload, method='post') @@ -813,7 +909,8 @@ def restrict_chat_member( def promote_chat_member( token, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, - can_restrict_members=None, can_pin_messages=None, can_promote_members=None): + can_restrict_members=None, can_pin_messages=None, can_promote_members=None, + is_anonymous=None, can_manage_chat=None, can_manage_voice_chats=None): method_url = 'promoteChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} if can_change_info is not None: @@ -832,6 +929,12 @@ def promote_chat_member( payload['can_pin_messages'] = can_pin_messages if can_promote_members is not None: payload['can_promote_members'] = can_promote_members + if is_anonymous is not None: + payload['is_anonymous'] = is_anonymous + if can_manage_chat is not None: + payload['can_manage_chat'] = can_manage_chat + if can_manage_voice_chats is not None: + payload['can_manage_voice_chats'] = can_manage_voice_chats return _make_request(token, method_url, params=payload, method='post') @@ -1042,7 +1145,8 @@ def delete_message(token, chat_id, message_id, timeout=None): def send_game( token, chat_id, game_short_name, - disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None): + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None): method_url = r'sendGame' payload = {'chat_id': chat_id, 'game_short_name': game_short_name} if disable_notification is not None: @@ -1053,6 +1157,8 @@ def send_game( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -1117,7 +1223,7 @@ def send_invoice( need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, - timeout=None): + timeout=None, allow_sending_without_reply=None): """ Use this method to send invoices. On success, the sent Message is returned. :param token: Bot's token (you don't need to fill this) @@ -1145,6 +1251,7 @@ def send_invoice( :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. :param timeout: + :param allow_sending_without_reply: :return: """ method_url = r'sendInvoice' @@ -1183,6 +1290,8 @@ def send_invoice( payload['provider_data'] = provider_data if timeout: payload['connect-timeout'] = timeout + if allow_sending_without_reply: + payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -1325,7 +1434,8 @@ def send_poll( question, options, is_anonymous = None, type = None, allows_multiple_answers = None, correct_option_id = None, explanation = None, explanation_parse_mode=None, open_period = None, close_date = None, is_closed = None, - disable_notifications=False, reply_to_message_id=None, reply_markup=None, timeout=None): + disable_notifications=False, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None, explanation_entities=None): method_url = r'sendPoll' payload = { 'chat_id': str(chat_id), @@ -1358,10 +1468,15 @@ def send_poll( payload['disable_notification'] = disable_notifications if reply_to_message_id is not None: payload['reply_to_message_id'] = reply_to_message_id + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply if reply_markup is not None: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout + if explanation_entities: + payload['explanation_entities'] = json.dumps( + types.MessageEntity.to_list_of_dicts(explanation_entities)) return _make_request(token, method_url, params=payload) diff --git a/telebot/types.py b/telebot/types.py index 2898493..a134c5a 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -408,6 +408,27 @@ class Message(JsonDeserializable): if 'passport_data' in obj: opts['passport_data'] = obj['passport_data'] content_type = 'passport_data' + if 'proximity_alert_triggered' in obj: + opts['proximity_alert_triggered'] = ProximityAlertTriggered.de_json(obj[ + 'proximity_alert_triggered']) + content_type = 'proximity_alert_triggered' + if 'voice_chat_scheduled' in obj: + opts['voice_chat_scheduled'] = VoiceChatScheduled.de_json(obj['voice_chat_scheduled']) + content_type = 'voice_chat_scheduled' + if 'voice_chat_started' in obj: + opts['voice_chat_started'] = VoiceChatStarted.de_json(obj['voice_chat_started']) + content_type = 'voice_chat_started' + if 'voice_chat_ended' in obj: + opts['voice_chat_ended'] = VoiceChatEnded.de_json(obj['voice_chat_ended']) + content_type = 'voice_chat_ended' + if 'voice_chat_participants_invited' in obj: + opts['voice_chat_participants_invited'] = VoiceChatParticipantsInvited.de_json( + obj['voice_chat_participants_invited']) + content_type = 'voice_chat_participants_invited' + if 'message_auto_delete_timer_changed' in obj: + opts['message_auto_delete_timer_changed'] = MessageAutoDeleteTimerChanged.de_json( + obj['message_auto_delete_timer_changed']) + content_type = 'message_auto_delete_timer_changed' if 'reply_markup' in obj: opts['reply_markup'] = InlineKeyboardMarkup.de_json(obj['reply_markup']) return cls(message_id, from_user, date, chat, content_type, opts, json_string) @@ -1220,7 +1241,13 @@ class ChatPermissions(JsonDeserializable, JsonSerializable, Dictionaryable): return json_dict -class BotCommand(JsonSerializable): +class BotCommand(JsonSerializable, JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + return cls(**obj) + def __init__(self, command, description): """ This object represents a bot command. @@ -1748,13 +1775,14 @@ class InlineQueryResultDocument(JsonSerializable): class InlineQueryResultLocation(JsonSerializable): - def __init__(self, id, title, latitude, longitude, live_period=None, reply_markup=None, + 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): self.type = 'location' self.id = id self.title = title self.latitude = latitude self.longitude = longitude + self.horizontal_accuracy = horizontal_accuracy self.live_period = live_period self.reply_markup = reply_markup self.input_message_content = input_message_content @@ -1765,6 +1793,8 @@ class InlineQueryResultLocation(JsonSerializable): def to_json(self): json_dict = {'type': self.type, 'id': self.id, 'latitude': self.latitude, 'longitude': self.longitude, 'title': self.title} + if self.horizontal_accuracy: + json_dict['horizontal_accuracy'] = self.horizontal_accuracy if self.live_period: json_dict['live_period'] = self.live_period if self.thumb_url: @@ -1782,7 +1812,8 @@ class InlineQueryResultLocation(JsonSerializable): class InlineQueryResultVenue(JsonSerializable): 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): + reply_markup=None, input_message_content=None, thumb_url=None, + thumb_width=None, thumb_height=None, google_place_id=None, google_place_type=None): self.type = 'venue' self.id = id self.title = title @@ -1796,6 +1827,8 @@ class InlineQueryResultVenue(JsonSerializable): self.thumb_url = thumb_url self.thumb_width = thumb_width self.thumb_height = thumb_height + self.google_place_id = google_place_id + self.google_place_type = google_place_type def to_json(self): json_dict = {'type': self.type, 'id': self.id, 'title': self.title, 'latitude': self.latitude, @@ -1814,6 +1847,10 @@ class InlineQueryResultVenue(JsonSerializable): json_dict['reply_markup'] = self.reply_markup.to_dict() if self.input_message_content: json_dict['input_message_content'] = self.input_message_content.to_dict() + if self.google_place_id: + json_dict['google_place_id'] = self.google_place_id + if self.google_place_type: + json_dict['google_place_type'] = self.google_place_type return json.dumps(json_dict) @@ -2555,4 +2592,75 @@ class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): "is_revoked": self.is_revoked, "expire_date": self.expire_date, "member_limit": self.member_limit - } \ No newline at end of file + } + +class ProximityAlertTriggered(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + return cls(**obj) + + def __init__(self, traveler, watcher, distance, **kwargs): + self.traveler: User = traveler + self.watcher: User = watcher + self.distance: int = distance + + +class VoiceChatStarted(JsonDeserializable): + @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 VoiceChatScheduled(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + return cls(obj['start_date']) + + def __init__(self, start_date): + self.start_date: int = start_date + + +class VoiceChatEnded(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + return cls(obj['duration']) + + def __init__(self, duration): + self.duration: int = duration + + +class VoiceChatParticipantsInvited(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + users = None + if 'users' in obj: + users = [User.de_json(u) for u in obj['users']] + return cls(users) + + def __init__(self, users=None): + self.users: List[User] = users + + +class MessageAutoDeleteTimerChanged(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + return cls(obj['message_auto_delete_time']) + + def __init__(self, message_auto_delete_time): + self.message_auto_delete_time = message_auto_delete_time diff --git a/telebot/util.py b/telebot/util.py index 7b87959..cb12577 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -33,7 +33,9 @@ content_type_media = [ 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' + 'supergroup_chat_created', 'channel_chat_created', 'migrate_to_chat_id', 'migrate_from_chat_id', 'pinned_message', + 'proximity_alert_triggered', 'voice_chat_scheduled', 'voice_chat_started', 'voice_chat_ended', + 'voice_chat_participants_invited', 'message_auto_delete_timer_changed' ] From d3369245c4b6a64e3a3f4a72fec2a158c8d016b6 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 21 Jun 2021 17:49:03 +0200 Subject: [PATCH 155/350] fixed wrong type hint --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 484b208..c8c4f84 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -814,7 +814,7 @@ class TeleBot: def send_message( self, chat_id: Union[int, str], text: str, disable_web_page_preview: Optional[bool]=None, - reply_to_message_id: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None, parse_mode: Optional[str]=None, disable_notification: Optional[bool]=None, From 3f46ce3b7b3043276f8b8cd6e5bc0545d95060bd Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:59:39 +0200 Subject: [PATCH 156/350] added InputInvoiceMessageContent and tgs_sticker support and some small changes --- telebot/__init__.py | 49 ++++++++++++- telebot/apihelper.py | 50 ++++++------- telebot/types.py | 168 ++++++++++++++++++++++++++++++------------- 3 files changed, 191 insertions(+), 76 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index c8c4f84..a751be3 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2121,8 +2121,33 @@ class TeleBot: :param mask_position: :return: """ - return apihelper.create_new_sticker_set(self.token, user_id, name, title, png_sticker, emojis, - contains_masks, mask_position) + return apihelper.create_new_sticker_set( + self.token, user_id, name, title, png_sticker, emojis, + contains_masks, mask_position, animated=False) + + + def create_new_animated_sticker_set( + self, user_id: int, name: str, title: str, + tgs_sticker: Union[Any, str], + emojis: str, + contains_masks: Optional[bool]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to create new sticker set owned by a user. + The bot will be able to edit the created sticker set. + Returns True on success. + :param user_id: + :param name: + :param title: + :param tgs_sticker: + :param emojis: + :param contains_masks: + :param mask_position: + :return: + """ + return apihelper.create_new_sticker_set( + self.token, user_id, name, title, tgs_sticker, emojis, + contains_masks, mask_position, animated=True) def add_sticker_to_set( @@ -2137,7 +2162,25 @@ class TeleBot: :param mask_position: :return: """ - return apihelper.add_sticker_to_set(self.token, user_id, name, png_sticker, emojis, mask_position) + return apihelper.add_sticker_to_set( + self.token, user_id, name, png_sticker, emojis, mask_position, animated=False) + + + def add_sticker_to_animated_set( + self, user_id: int, name: str, tgs_sticker: Union[Any, str], + emojis: str, mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to add a new sticker to a set created by the bot. Returns True on success. + :param user_id: + :param name: + :param tgs_sticker: + :param emojis: + :param mask_position: + :return: + """ + return apihelper.add_sticker_to_set( + self.token, user_id, name, tgs_sticker, emojis, mask_position, animated=True) + def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 49a125a..106702e 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -245,7 +245,7 @@ def send_message( payload['connect-timeout'] = timeout if entities: payload['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, method='post') @@ -422,7 +422,7 @@ def send_dice( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout - if 'allow_sending_without_reply': + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -455,7 +455,7 @@ def send_photo( payload['connect-timeout'] = timeout if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -473,7 +473,7 @@ def send_media_group( payload['reply_to_message_id'] = reply_to_message_id if timeout: payload['connect-timeout'] = timeout - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request( token, method_url, params=payload, @@ -499,7 +499,7 @@ def send_location( payload['proximity_alert_radius'] = proximity_alert_radius if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) @@ -573,7 +573,7 @@ def send_venue( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply if google_place_id: payload['google_place_id'] = google_place_id @@ -600,7 +600,7 @@ def send_contact( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -653,7 +653,7 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_to_messa payload['height'] = height if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -693,7 +693,7 @@ def send_animation( payload['thumb'] = thumb if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -724,7 +724,7 @@ def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_mess payload['connect-timeout'] = timeout if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -760,7 +760,7 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m files = {'thumb': thumb} else: payload['thumb'] = thumb - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -803,7 +803,7 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non payload['thumb'] = thumb if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -840,7 +840,7 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m payload['thumb'] = thumb if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload, files=files, method='post') @@ -1157,7 +1157,7 @@ def send_game( payload['reply_markup'] = _convert_markup(reply_markup) if timeout: payload['connect-timeout'] = timeout - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -1290,7 +1290,7 @@ def send_invoice( payload['provider_data'] = provider_data if timeout: payload['connect-timeout'] = timeout - if allow_sending_without_reply: + if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -1388,15 +1388,16 @@ def upload_sticker_file(token, user_id, png_sticker): def create_new_sticker_set( - token, user_id, name, title, png_sticker, emojis, - contains_masks=None, mask_position=None): + token, user_id, name, title, sticker, emojis, + contains_masks=None, mask_position=None, animated=False): method_url = 'createNewStickerSet' payload = {'user_id': user_id, 'name': name, 'title': title, 'emojis': emojis} files = None - if not util.is_string(png_sticker): - files = {'png_sticker': png_sticker} + stype = 'tgs_sticker' if animated else 'png_sticker' + if not util.is_string(sticker): + files = {stype: sticker} else: - payload['png_sticker'] = png_sticker + payload[stype] = sticker if contains_masks is not None: payload['contains_masks'] = contains_masks if mask_position: @@ -1404,14 +1405,15 @@ def create_new_sticker_set( return _make_request(token, method_url, params=payload, files=files, method='post') -def add_sticker_to_set(token, user_id, name, png_sticker, emojis, mask_position): +def add_sticker_to_set(token, user_id, name, sticker, emojis, mask_position, animated=False): method_url = 'addStickerToSet' payload = {'user_id': user_id, 'name': name, 'emojis': emojis} files = None - if not util.is_string(png_sticker): - files = {'png_sticker': png_sticker} + stype = 'tgs_sticker' if animated else 'png_sticker' + if not util.is_string(sticker): + files = {stype: sticker} else: - payload['png_sticker'] = png_sticker + payload[stype] = sticker if mask_position: payload['mask_position'] = mask_position.to_json() return _make_request(token, method_url, params=payload, files=files, method='post') diff --git a/telebot/types.py b/telebot/types.py index a134c5a..29e2b9d 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import logging -from typing import Dict, List, Union +from typing import Dict, List, Optional, Union try: import ujson as json @@ -146,7 +146,7 @@ class ChatMemberUpdated(JsonDeserializable): self.date: int = date self.old_chat_member: ChatMember = old_chat_member self.new_chat_member: ChatMember = new_chat_member - self.invite_link: Union[ChatInviteLink, None] = invite_link + self.invite_link: Optional[ChatInviteLink] = invite_link class WebhookInfo(JsonDeserializable): @@ -461,49 +461,49 @@ class Message(JsonDeserializable): self.from_user: User = from_user self.date: int = date self.chat: Chat = chat - self.forward_from: Union[User, None] = None - self.forward_from_chat: Union[Chat, None] = None - self.forward_from_message_id: Union[int, None] = None - self.forward_signature: Union[str, None] = None - self.forward_sender_name: Union[str, None] = None - self.forward_date: Union[int, None] = None - self.reply_to_message: Union[Message, None] = None - self.via_bot: Union[User, None] = None - self.edit_date: Union[int, None] = None - self.media_group_id: Union[str, None] = None - self.author_signature: Union[str, None] = None - self.text: Union[str, None] = None - self.entities: Union[List[MessageEntity], None] = None - self.caption_entities: Union[List[MessageEntity], None] = None - self.audio: Union[Audio, None] = None - self.document: Union[Document, None] = None - self.photo: Union[List[PhotoSize], None] = None - self.sticker: Union[Sticker, None] = None - self.video: Union[Video, None] = None - self.video_note: Union[VideoNote, None] = None - self.voice: Union[Voice, None] = None - self.caption: Union[str, None] = None - self.contact: Union[Contact, None] = None - self.location: Union[Location, None] = None - self.venue: Union[Venue, None] = None - self.animation: Union[Animation, None] = None - self.dice: Union[Dice, None] = None - self.new_chat_member: Union[User, None] = None # Deprecated since Bot API 3.0. Not processed anymore - self.new_chat_members: Union[List[User], None] = None - self.left_chat_member: Union[User, None] = None - self.new_chat_title: Union[str, None] = None - self.new_chat_photo: Union[List[PhotoSize], None] = None - self.delete_chat_photo: Union[bool, None] = None - self.group_chat_created: Union[bool, None] = None - self.supergroup_chat_created: Union[bool, None] = None - self.channel_chat_created: Union[bool, None] = None - self.migrate_to_chat_id: Union[int, None] = None - self.migrate_from_chat_id: Union[int, None] = None - self.pinned_message: Union[Message, None] = None - self.invoice: Union[Invoice, None] = None - self.successful_payment: Union[SuccessfulPayment, None] = None - self.connected_website: Union[str, None] = None - self.reply_markup: Union[InlineKeyboardMarkup, None] = None + self.forward_from: Optional[User] = None + self.forward_from_chat: Optional[Chat] = None + self.forward_from_message_id: Optional[int] = None + self.forward_signature: Optional[str] = None + self.forward_sender_name: Optional[str] = None + self.forward_date: Optional[int] = None + self.reply_to_message: Optional[Message] = None + self.via_bot: Optional[User] = None + self.edit_date: Optional[int] = None + self.media_group_id: Optional[str] = None + self.author_signature: Optional[str] = None + self.text: Optional[str] = None + self.entities: Optional[List[MessageEntity]] = None + self.caption_entities: Optional[List[MessageEntity]] = None + self.audio: Optional[Audio] = None + self.document: Optional[Document] = None + self.photo: Optional[List[PhotoSize]] = None + self.sticker: Optional[Sticker] = None + self.video: Optional[Video] = None + self.video_note: Optional[VideoNote] = None + self.voice: Optional[Voice] = None + self.caption: Optional[str] = None + self.contact: Optional[Contact] = None + self.location: Optional[Location] = None + self.venue: Optional[Venue] = None + self.animation: Optional[Animation] = None + self.dice: Optional[Dice] = None + self.new_chat_member: Optional[User] = None # Deprecated since Bot API 3.0. Not processed anymore + self.new_chat_members: Optional[List[User]] = None + self.left_chat_member: Optional[User] = None + self.new_chat_title: Optional[str] = None + self.new_chat_photo: Optional[List[PhotoSize]] = None + self.delete_chat_photo: Optional[bool] = None + self.group_chat_created: Optional[bool] = None + self.supergroup_chat_created: Optional[bool] = None + self.channel_chat_created: Optional[bool] = None + self.migrate_to_chat_id: Optional[int] = None + self.migrate_from_chat_id: Optional[int] = None + self.pinned_message: Optional[Message] = None + self.invoice: Optional[Invoice] = None + self.successful_payment: Optional[SuccessfulPayment] = None + self.connected_website: Optional[str] = None + self.reply_markup: Optional[InlineKeyboardMarkup] = None for key in options: setattr(self, key, options[key]) self.json = json_string @@ -1314,7 +1314,7 @@ class InputTextMessageContent(Dictionaryable): json_dict['parse_mode'] = self.parse_mode if self.entities: json_dict['entities'] = MessageEntity.to_list_of_dicts(self.entities) - if self.disable_web_page_preview: + if self.disable_web_page_preview is not None: json_dict['disable_web_page_preview'] = self.disable_web_page_preview return json_dict @@ -1387,6 +1387,73 @@ class InputContactMessageContent(Dictionaryable): return json_dict +class InputInvoiceMessageContent(Dictionaryable): + 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, + need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, + send_phone_number_to_provider=None, send_email_to_provider=None, + is_flexible=None): + self.title: str = title + self.description: str = description + self.payload: str = payload + self.provider_token: str = provider_token + self.currency: str = currency + self.prices: List[LabeledPrice] = prices + self.max_tip_amount: Optional[int] = max_tip_amount + self.suggested_tip_amounts: Optional[List[int]] = suggested_tip_amounts + self.provider_data: Optional[str] = provider_data + self.photo_url: Optional[str] = photo_url + self.photo_size: Optional[int] = photo_size + self.photo_width: Optional[int] = photo_width + self.photo_height: Optional[int] = photo_height + self.need_name: Optional[bool] = need_name + self.need_phone_number: Optional[bool] = need_phone_number + self.need_email: Optional[bool] = need_email + self.need_shipping_address: Optional[bool] = need_shipping_address + self.send_phone_number_to_provider: Optional[bool] = send_phone_number_to_provider + self.send_email_to_provider: Optional[bool] = send_email_to_provider + self.is_flexible: Optional[bool] = is_flexible + + def to_dict(self): + json_dict = { + 'title': self.title, + 'description': self.description, + 'payload': self.payload, + 'provider_token': self.provider_token, + 'currency': self.currency, + 'prices': [LabeledPrice.to_dict(lp) for lp in self.prices] + } + if self.max_tip_amount: + json_dict['max_tip_amount'] = self.max_tip_amount + if self.suggested_tip_amounts: + json_dict['suggested_tip_amounts'] = self.suggested_tip_amounts + if self.provider_data: + json_dict['provider_data'] = self.provider_data + if self.photo_url: + json_dict['photo_url'] = self.photo_url + if self.photo_size: + json_dict['photo_size'] = self.photo_size + if self.photo_width: + json_dict['photo_width'] = self.photo_width + if self.photo_height: + json_dict['photo_height'] = self.photo_height + if self.need_name is not None: + json_dict['need_name'] = self.need_name + if self.need_phone_number is not None: + json_dict['need_phone_number'] = self.need_phone_number + if self.need_email is not None: + json_dict['need_email'] = self.need_email + if self.need_shipping_address is not None: + json_dict['need_shipping_address'] = self.need_shipping_address + if self.send_phone_number_to_provider is not None: + json_dict['send_phone_number_to_provider'] = self.send_phone_number_to_provider + if self.send_email_to_provider is not None: + json_dict['send_email_to_provider'] = self.send_email_to_provider + if self.is_flexible is not None: + json_dict['is_flexible'] = self.is_flexible + + class ChosenInlineResult(JsonDeserializable): @classmethod def de_json(cls, json_string): @@ -2135,10 +2202,13 @@ class LabeledPrice(JsonSerializable): self.label: str = label self.amount: int = amount - def to_json(self): - return json.dumps({ + def to_dict(self): + return { 'label': self.label, 'amount': self.amount - }) + } + + def to_json(self): + return json.dumps(self.to_dict()) class Invoice(JsonDeserializable): From 558eef78b412901cf8ab195d46bf2bac57f891df Mon Sep 17 00:00:00 2001 From: Pablo Date: Mon, 21 Jun 2021 17:27:35 -0500 Subject: [PATCH 157/350] Fix long string blocking version of python on github actions setup --- .github/workflows/setup_python.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/setup_python.yml b/.github/workflows/setup_python.yml index 0631897..d2bcdf7 100644 --- a/.github/workflows/setup_python.yml +++ b/.github/workflows/setup_python.yml @@ -1,6 +1,6 @@ # This is a basic workflow to help you get started with Actions -name: ActionsSetupPython +name: Setup # Controls when the action will run. on: @@ -21,7 +21,7 @@ jobs: strategy: matrix: python-version: [ '3.6','3.7','3.8','3.9', 'pypy-3.6', 'pypy-3.7' ] #'pypy-3.8', 'pypy-3.9' NOT SUPPORTED NOW - name: Python ${{ matrix.python-version }} setup and tests + name: ${{ matrix.python-version }} and tests steps: - uses: actions/checkout@v2 - name: Setup python From c00595e212d2b510a8708d7e96bcc1bdd6a550bd Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Tue, 22 Jun 2021 15:55:14 +0200 Subject: [PATCH 158/350] Update types.py * Added Parameter `caption_entities` to `InputMedia` class * Added Parameter `disable_content_type_detection` to `InputMediaDocument` class --- telebot/types.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 29e2b9d..d3384c0 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -649,11 +649,11 @@ class PhotoSize(JsonDeserializable): return cls(**obj) def __init__(self, file_id, file_unique_id, width, height, file_size=None, **kwargs): - self.file_size: int = file_size - self.file_unique_id: str = file_unique_id - self.height: int = height - self.width: int = width self.file_id: str = file_id + self.file_unique_id: str = file_unique_id + self.width: int = width + self.height: int = height + self.file_size: int = file_size class Audio(JsonDeserializable): @@ -2411,11 +2411,12 @@ class MaskPosition(Dictionaryable, JsonDeserializable, JsonSerializable): # InputMedia class InputMedia(Dictionaryable, JsonSerializable): - def __init__(self, type, media, caption=None, parse_mode=None): + def __init__(self, type, media, caption=None, parse_mode=None, caption_entities=None): self.type: str = type self.media: str = media - self.caption: str = caption - self.parse_mode: str = parse_mode + self.caption: Optional[str] = caption + self.parse_mode: Optional[str] = parse_mode + self.caption_entities: Optional[List[MessageEntity]] = caption_entities if util.is_string(self.media): self._media_name = '' @@ -2433,6 +2434,8 @@ class InputMedia(Dictionaryable, JsonSerializable): json_dict['caption'] = self.caption if self.parse_mode: json_dict['parse_mode'] = self.parse_mode + if self.caption_entities: + json_dict['caption_entities'] = [MessageEntity.to_dict(entity) for entity in self.caption_entities] return json_dict def convert_input_media(self): @@ -2521,14 +2524,17 @@ class InputMediaAudio(InputMedia): class InputMediaDocument(InputMedia): - def __init__(self, media, thumb=None, caption=None, parse_mode=None): + 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 + self.disable_content_type_detection = disable_content_type_detection def to_dict(self): ret = super(InputMediaDocument, self).to_dict() if self.thumb: ret['thumb'] = self.thumb + if self.disable_content_type_detection is not None: + ret['disable_content_type_detection'] = self.disable_content_type_detection return ret From bffbe764e5805e8de8fe43ab8188a74978e379a2 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Tue, 22 Jun 2021 15:57:34 +0200 Subject: [PATCH 159/350] Update tgs_sticker support * Updated `create_new_sticker_set` and `add_sticker_to_set` functions * Removed `create_new_animated_sticker_set` and `add_sticker_to_animated_sticker_set` functions --- telebot/__init__.py | 65 +++++++++++--------------------------------- telebot/apihelper.py | 16 +++++++---- 2 files changed, 26 insertions(+), 55 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index a751be3..8bb417e 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2104,32 +2104,9 @@ class TeleBot: def create_new_sticker_set( self, user_id: int, name: str, title: str, + emojis: str, png_sticker: Union[Any, str], - emojis: str, - contains_masks: Optional[bool]=None, - mask_position: Optional[types.MaskPosition]=None) -> bool: - """ - Use this method to create new sticker set owned by a user. - The bot will be able to edit the created sticker set. - Returns True on success. - :param user_id: - :param name: - :param title: - :param png_sticker: - :param emojis: - :param contains_masks: - :param mask_position: - :return: - """ - return apihelper.create_new_sticker_set( - self.token, user_id, name, title, png_sticker, emojis, - contains_masks, mask_position, animated=False) - - - def create_new_animated_sticker_set( - self, user_id: int, name: str, title: str, tgs_sticker: Union[Any, str], - emojis: str, contains_masks: Optional[bool]=None, mask_position: Optional[types.MaskPosition]=None) -> bool: """ @@ -2139,47 +2116,37 @@ class TeleBot: :param user_id: :param name: :param title: - :param tgs_sticker: :param emojis: + :param png_sticker: + :param tgs_sticker: :param contains_masks: :param mask_position: :return: """ return apihelper.create_new_sticker_set( - self.token, user_id, name, title, tgs_sticker, emojis, - contains_masks, mask_position, animated=True) - + self.token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks, mask_position) + def add_sticker_to_set( - self, user_id: int, name: str, png_sticker: Union[Any, str], - emojis: str, mask_position: Optional[types.MaskPosition]=None) -> bool: + self, user_id: int, name: str, emojis: str, + png_sticker: Optional[Union[Any, str]]=None, + tgs_sticker: Optional[Union[Any, str]]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: """ - Use this method to add a new sticker to a set created by the bot. Returns True on success. + Use this method to add a new sticker to a set created by the bot. + It's required to pass `png_sticker` or `tgs_sticker`. + Returns True on success. :param user_id: :param name: - :param png_sticker: :param emojis: + :param png_sticker: Required if `tgs_sticker` is None + :param tgs_sticker: Required if `png_sticker` is None :param mask_position: :return: """ return apihelper.add_sticker_to_set( - self.token, user_id, name, png_sticker, emojis, mask_position, animated=False) - - - def add_sticker_to_animated_set( - self, user_id: int, name: str, tgs_sticker: Union[Any, str], - emojis: str, mask_position: Optional[types.MaskPosition]=None) -> bool: - """ - Use this method to add a new sticker to a set created by the bot. Returns True on success. - :param user_id: - :param name: - :param tgs_sticker: - :param emojis: - :param mask_position: - :return: - """ - return apihelper.add_sticker_to_set( - self.token, user_id, name, tgs_sticker, emojis, mask_position, animated=True) + self.token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position) def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 106702e..867eef8 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -810,7 +810,7 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, - allow_sending_without_reply=None): + allow_sending_without_reply=None, disable_content_type_detection=None): method_url = get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None @@ -842,6 +842,8 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply + if method_url == 'sendDocument' and disable_content_type_detection is not None: + payload['disable_content_type_detection'] = disable_content_type_detection return _make_request(token, method_url, params=payload, files=files, method='post') @@ -1388,12 +1390,13 @@ def upload_sticker_file(token, user_id, png_sticker): def create_new_sticker_set( - token, user_id, name, title, sticker, emojis, - contains_masks=None, mask_position=None, animated=False): + token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks=None, mask_position=None): method_url = 'createNewStickerSet' payload = {'user_id': user_id, 'name': name, 'title': title, 'emojis': emojis} + stype = 'png_sticker' if png_sticker else 'tgs_sticker' + sticker = png_sticker or tgs_sticker files = None - stype = 'tgs_sticker' if animated else 'png_sticker' if not util.is_string(sticker): files = {stype: sticker} else: @@ -1405,11 +1408,12 @@ def create_new_sticker_set( return _make_request(token, method_url, params=payload, files=files, method='post') -def add_sticker_to_set(token, user_id, name, sticker, emojis, mask_position, animated=False): +def add_sticker_to_set(token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position): method_url = 'addStickerToSet' payload = {'user_id': user_id, 'name': name, 'emojis': emojis} + stype = 'png_sticker' if png_sticker else 'tgs_sticker' + sticker = png_sticker or tgs_sticker files = None - stype = 'tgs_sticker' if animated else 'png_sticker' if not util.is_string(sticker): files = {stype: sticker} else: From 65cf8410155cd3b9cb6d4d1ca8499bea9f492cc4 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 23 Jun 2021 16:09:40 +0200 Subject: [PATCH 160/350] Update util.py added `allowed_updates` list (used by `_init_._retrieve_all_updates` because `chat_member` is not requested by default) --- telebot/util.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index cb12577..8af740c 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -38,6 +38,10 @@ content_type_service = [ 'voice_chat_participants_invited', 'message_auto_delete_timer_changed' ] +allowed_updates = ["update_id", "message", "edited_message", "channel_post", "edited_channel_post", + "inline_query", "chosen_inline_result", "callback_query", "shipping_query", "pre_checkout_query", + "poll", "poll_answer", "my_chat_member", "chat_member" +] class WorkerThread(threading.Thread): count = 0 From 4554cb969f4e7c49ce87006485880f4caa7091b3 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 23 Jun 2021 16:10:48 +0200 Subject: [PATCH 161/350] Update __init__.py added handlers for `my_chat_member` and `chat_member` --- telebot/__init__.py | 73 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 8bb417e..d959582 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -155,6 +155,8 @@ class TeleBot: self.pre_checkout_query_handlers = [] self.poll_handlers = [] self.poll_answer_handlers = [] + self.my_chat_member_handlers = [] + self.chat_member_handlers = [] if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { @@ -168,6 +170,9 @@ class TeleBot: 'shipping_query': [], 'pre_checkout_query': [], 'poll': [], + 'poll_answer': [], + 'my_chat_member': [], + 'chat_member': [] } self.default_middleware_handlers = [] @@ -354,7 +359,8 @@ class TeleBot: if self.skip_pending: logger.debug('Skipped {0} pending messages'.format(self.__skip_updates())) self.skip_pending = False - updates = self.get_updates(offset=(self.last_update_id + 1), + updates = self.get_updates(offset=(self.last_update_id + 1), + allowed_updates=util.allowed_updates, timeout=timeout, long_polling_timeout=long_polling_timeout) self.process_new_updates(updates) @@ -374,6 +380,8 @@ class TeleBot: new_pre_checkout_queries = None new_polls = None new_poll_answers = None + new_my_chat_members = None + new_chat_members = None for update in updates: if apihelper.ENABLE_MIDDLEWARE: @@ -422,6 +430,12 @@ class TeleBot: if update.poll_answer: if new_poll_answers is None: new_poll_answers = [] new_poll_answers.append(update.poll_answer) + if update.my_chat_member: + if new_my_chat_members is None: new_my_chat_members = [] + new_my_chat_members.append(update.my_chat_member) + if update.chat_member: + if new_chat_members is None: new_chat_members = [] + new_chat_members.append(update.chat_member) if new_messages: self.process_new_messages(new_messages) @@ -445,6 +459,10 @@ class TeleBot: self.process_new_poll(new_polls) if new_poll_answers: self.process_new_poll_answer(new_poll_answers) + if new_my_chat_members: + self.process_new_my_chat_member(new_my_chat_members) + if new_chat_members: + self.process_new_chat_member(new_chat_members) def process_new_messages(self, new_messages): self._notify_next_handlers(new_messages) @@ -481,6 +499,12 @@ class TeleBot: def process_new_poll_answer(self, poll_answers): self._notify_command_handlers(self.poll_answer_handlers, poll_answers) + + def process_new_my_chat_member(self, my_chat_members): + self._notify_command_handlers(self.my_chat_member_handlers, my_chat_members) + + def process_new_chat_member(self, chat_members): + self._notify_command_handlers(self.chat_member_handlers, chat_members) def process_middlewares(self, update): for update_type, middlewares in self.typed_middleware_handlers.items(): @@ -2665,6 +2689,53 @@ class TeleBot: :return: """ self.poll_answer_handlers.append(handler_dict) + + def my_chat_member_handler(self, func=None, **kwargs): + """ + my_chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_my_chat_member_handler(self, handler_dict): + """ + Adds a my_chat_member handler + :param handler_dict: + :return: + """ + self.my_chat_member_handlers.append(handler_dict) + + def chat_member_handler(self, func=None, **kwargs): + """ + chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_chat_member_handler(self, handler_dict): + """ + Adds a chat_member handler + :param handler_dict: + :return: + """ + self.chat_member_handlers.append(handler_dict) + def _test_message_handler(self, message_handler, message): """ From 506464e6370183e4047d09bcd87c18c573832168 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 23 Jun 2021 19:29:36 +0200 Subject: [PATCH 162/350] Update __init__.py Added the parameter `allowed_updates` to polling and infinity_polling functions --- telebot/__init__.py | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index d959582..967f986 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -350,7 +350,7 @@ class TeleBot: updates = self.get_updates(offset=self.last_update_id + 1, long_polling_timeout=1) return total - def __retrieve_updates(self, timeout=20, long_polling_timeout=20): + def __retrieve_updates(self, timeout=20, long_polling_timeout=20, allowed_updates=None): """ Retrieves any updates from the Telegram API. Registered listeners and applicable message handlers will be notified when a new message arrives. @@ -360,7 +360,7 @@ class TeleBot: logger.debug('Skipped {0} pending messages'.format(self.__skip_updates())) self.skip_pending = False updates = self.get_updates(offset=(self.last_update_id + 1), - allowed_updates=util.allowed_updates, + allowed_updates=allowed_updates, timeout=timeout, long_polling_timeout=long_polling_timeout) self.process_new_updates(updates) @@ -530,7 +530,8 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, long_polling_timeout=20, logger_level=logging.ERROR, *args, **kwargs): + def infinity_polling(self, timeout=20, long_polling_timeout=20, logger_level=logging.ERROR, + allowed_updates=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. @@ -538,11 +539,19 @@ class TeleBot: :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.allowed_updates for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. """ while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, - *args, **kwargs) + allowed_updates=allowed_updates *args, **kwargs) except Exception as e: if logger_level and logger_level >= logging.ERROR: logger.error("Infinity polling exception: %s", str(e)) @@ -555,7 +564,8 @@ class TeleBot: if logger_level and logger_level >= logging.INFO: logger.error("Break infinity polling") - def polling(self, none_stop=False, interval=0, timeout=20, long_polling_timeout=20): + def polling(self, none_stop: bool=False, interval: int=0, timeout: int=20, + long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=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. @@ -567,14 +577,22 @@ class TeleBot: :param none_stop: Do not stop polling when an ApiException occurs. :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.allowed_updates for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. :return: """ if self.threaded: - self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout) + self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) else: - self.__non_threaded_polling(none_stop, interval, timeout, long_polling_timeout) + self.__non_threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) - def __threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None): + def __threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None, allowed_updates=None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 @@ -589,7 +607,7 @@ class TeleBot: while not self.__stop_polling.wait(interval): or_event.clear() try: - polling_thread.put(self.__retrieve_updates, timeout, long_polling_timeout) + polling_thread.put(self.__retrieve_updates, timeout, long_polling_timeout, allowed_updates=allowed_updates) or_event.wait() # wait for polling thread finish, polling thread error or thread pool error polling_thread.raise_exceptions() self.worker_pool.raise_exceptions() @@ -640,14 +658,14 @@ class TeleBot: self.worker_pool.clear_exceptions() #* logger.info('Stopped polling.') - def __non_threaded_polling(self, non_stop=False, interval=0, timeout=None, long_polling_timeout=None): + def __non_threaded_polling(self, non_stop=False, interval=0, timeout=None, long_polling_timeout=None, allowed_updates=None): logger.info('Started polling.') self.__stop_polling.clear() error_interval = 0.25 while not self.__stop_polling.wait(interval): try: - self.__retrieve_updates(timeout, long_polling_timeout) + self.__retrieve_updates(timeout, long_polling_timeout, allowed_updates=allowed_updates) error_interval = 0.25 except apihelper.ApiException as e: if self.exception_handler is not None: From 0bfefdf15deb305bb46ac76d4ad4c05b64ace3ea Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 23 Jun 2021 19:57:44 +0200 Subject: [PATCH 163/350] changed allowed_updates in util to update_types i think its more clear name --- telebot/__init__.py | 4 ++-- telebot/util.py | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 967f986..86f65c6 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -541,7 +541,7 @@ class TeleBot: Use logger levels from logging as a value. None/NOTSET = no error logging :param allowed_updates: A list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. - See util.allowed_updates for a complete list of available update types. + See util.update_types for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used. @@ -579,7 +579,7 @@ class TeleBot: :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param allowed_updates: A list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. - See util.allowed_updates for a complete list of available update types. + See util.update_types for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used. diff --git a/telebot/util.py b/telebot/util.py index 8af740c..3dd71db 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -38,9 +38,10 @@ content_type_service = [ 'voice_chat_participants_invited', 'message_auto_delete_timer_changed' ] -allowed_updates = ["update_id", "message", "edited_message", "channel_post", "edited_channel_post", - "inline_query", "chosen_inline_result", "callback_query", "shipping_query", "pre_checkout_query", - "poll", "poll_answer", "my_chat_member", "chat_member" +update_types = [ + "update_id", "message", "edited_message", "channel_post", "edited_channel_post", "inline_query", + "chosen_inline_result", "callback_query", "shipping_query", "pre_checkout_query", "poll", "poll_answer", + "my_chat_member", "chat_member" ] class WorkerThread(threading.Thread): From 3d5415433e1749a99925e781fd4f1bd6c4218f7d Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 23 Jun 2021 22:51:17 +0200 Subject: [PATCH 164/350] Update __init__.py Updated TeleBot doc string and added the missing functions to AsyncTeleBot --- telebot/__init__.py | 75 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 86f65c6..f06ee73 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -73,29 +73,55 @@ class TeleBot: close sendMessage forwardMessage + copyMessage deleteMessage sendPhoto sendAudio sendDocument sendSticker sendVideo + sendVenue sendAnimation sendVideoNote sendLocation sendChatAction sendDice + sendContact + sendInvoice + sendMediaGroup getUserProfilePhotos getUpdates getFile sendPoll + stopPoll + sendGame + setGameScore + getGameHighScores + editMessageText + editMessageCaption + editMessageMedia + editMessageReplyMarkup + editMessageLiveLocation + stopMessageLiveLocation kickChatMember unbanChatMember restrictChatMember promoteChatMember + setChatAdministratorCustomTitle + setChatPermissions createChatInviteLink editChatInviteLink revokeChatInviteLink exportChatInviteLink + setChatStickerSet + deleteChatStickerSet + createNewStickerSet + addStickerToSet + deleteStickerFromSet + setStickerPositionInSet + uploadStickerFile + setStickerSetThumb + getStickerSet setChatPhoto deleteChatPhoto setChatTitle @@ -111,6 +137,8 @@ class TeleBot: getMyCommands setMyCommands answerInlineQuery + answerShippingQuery + answerPreCheckoutQuery """ def __init__( @@ -2808,6 +2836,8 @@ class TeleBot: class AsyncTeleBot(TeleBot): def __init__(self, *args, **kwargs): TeleBot.__init__(self, *args, **kwargs) + + # I'm not sure if `get_updates` should be added here too @util.async_dec() def enable_save_next_step_handlers(self, delay=120, filename="./.handler-saves/step.save"): @@ -2837,6 +2867,22 @@ class AsyncTeleBot(TeleBot): def get_me(self): return TeleBot.get_me(self) + @util.async_dec() + def log_out(self): + return TeleBot.log_out(self) + + @util.async_dec() + def close(self): + return TeleBot.close(self) + + @util.async_dec() + def get_my_commands(self): + return TeleBot.get_my_commands(self) + + @util.async_dec() + def set_my_commands(self, *args, **kwargs): + return TeleBot.set_my_commands(self, *args, **kwargs) + @util.async_dec() def get_file(self, *args): return TeleBot.get_file(self, *args) @@ -2885,6 +2931,10 @@ class AsyncTeleBot(TeleBot): def send_dice(self, *args, **kwargs): return TeleBot.send_dice(self, *args, **kwargs) + @util.async_dec() + def send_animation(self, *args, **kwargs): + return TeleBot.send_animation(self, *args, **kwargs) + @util.async_dec() def forward_message(self, *args, **kwargs): return TeleBot.forward_message(self, *args, **kwargs) @@ -2893,7 +2943,6 @@ class AsyncTeleBot(TeleBot): def copy_message(self, *args, **kwargs): return TeleBot.copy_message(self, *args, **kwargs) - @util.async_dec() def delete_message(self, *args): return TeleBot.delete_message(self, *args) @@ -2969,7 +3018,27 @@ class AsyncTeleBot(TeleBot): @util.async_dec() def promote_chat_member(self, *args, **kwargs): return TeleBot.promote_chat_member(self, *args, **kwargs) + + @util.async_dec() + def set_chat_administrator_custom_title(self, *args, **kwargs): + return TeleBot.set_chat_administrator_custom_title(self, *args, **kwargs) + @util.async_dec() + def set_chat_permissions(self, *args, **kwargs): + return TeleBot.set_chat_permissions(self, *args, **kwargs) + + @util.async_dec() + def create_chat_invite_link(self, *args, **kwargs): + return TeleBot.create_chat_invite_link(self, *args, **kwargs) + + @util.async_dec() + def edit_chat_invite_link(self, *args, **kwargs): + return TeleBot.edit_chat_invite_link(self, *args, **kwargs) + + @util.async_dec() + def revoke_chat_invite_link(self, *args, **kwargs): + return TeleBot.revoke_chat_invite_link(self, *args, **kwargs) + @util.async_dec() def export_chat_invite_link(self, *args): return TeleBot.export_chat_invite_link(self, *args) @@ -3073,6 +3142,10 @@ class AsyncTeleBot(TeleBot): @util.async_dec() def delete_sticker_from_set(self, *args, **kwargs): return TeleBot.delete_sticker_from_set(self, *args, **kwargs) + + @util.async_dec() + def set_sticker_set_thumb(self, *args, **kwargs): + return TeleBot.set_sticker_set_thumb(self, *args, **kwargs) @util.async_dec() def send_poll(self, *args, **kwargs): From ce991e9ac3799b9bff72bd99feb76951ded8c446 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 23 Jun 2021 22:52:24 +0200 Subject: [PATCH 165/350] Update types.py added the missing attributes `can_manage_chat` and `can_manage_voice_chats` to ChatMember class --- telebot/types.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index d3384c0..ad7e4d3 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1174,7 +1174,9 @@ class ChatMember(JsonDeserializable): can_restrict_members=None, can_promote_members=None, can_change_info=None, can_invite_users=None, can_pin_messages=None, is_member=None, can_send_messages=None, can_send_media_messages=None, can_send_polls=None, - can_send_other_messages=None, can_add_web_page_previews=None, until_date=None, **kwargs): + can_send_other_messages=None, can_add_web_page_previews=None, + can_manage_chat=None, can_manage_voice_chats=None, + until_date=None, **kwargs): self.user: User = user self.status: str = status self.custom_title: str = custom_title @@ -1194,6 +1196,8 @@ class ChatMember(JsonDeserializable): self.can_send_polls: bool = can_send_polls self.can_send_other_messages: bool = can_send_other_messages self.can_add_web_page_previews: bool = can_add_web_page_previews + self.can_manage_chat: bool = can_manage_chat + self.can_manage_voice_chats: bool = can_manage_voice_chats self.until_date: int = until_date From 3e33b7f1cb7990e28104ac2a0454a72f7adb439d Mon Sep 17 00:00:00 2001 From: MAIKS1900 Date: Sat, 26 Jun 2021 14:36:14 +0300 Subject: [PATCH 166/350] Bot API 5.3 changes - Personalized Commands for different chats - Custom Placeholders of input field for ReplyKeyboardMarkup and ForceReply. --- telebot/__init__.py | 41 +++++++++++++++++++++++---- telebot/apihelper.py | 31 +++++++++++++++++---- telebot/types.py | 65 +++++++++++++++++++++++++++++++++++++++++-- tests/test_telebot.py | 18 ++++++++++++ 4 files changed, 141 insertions(+), 14 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f06ee73..753e7d3 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1703,21 +1703,52 @@ class TeleBot: """ return apihelper.delete_chat_photo(self.token, chat_id) - def get_my_commands(self) -> List[types.BotCommand]: + def get_my_commands(self, + scope: Optional[Union[ + types.BotCommandScopeDefault, types.BotCommandScopeAllPrivateChats, + types.BotCommandScopeAllGroupChats, types.BotCommandScopeAllChatAdministrators, + types.BotCommandScopeChat, + types.BotCommandScopeChatAdministrators, types.BotCommandScopeChatMember]]=None, + language_code: Optional[str]=None) -> List[types.BotCommand]: """ - Use this method to get the current list of the bot's commands. + Use this method to get the current list of the bot's commands for the given scope and user language + :param scope: scope of users for which the commands are relevant + :param language_code: A two-letter ISO 639-1 language code Returns List of BotCommand on success. """ - result = apihelper.get_my_commands(self.token) + result = apihelper.get_my_commands(self.token, scope, language_code) return [types.BotCommand.de_json(cmd) for cmd in result] - def set_my_commands(self, commands: List[types.BotCommand]) -> bool: + def set_my_commands(self, commands: List[types.BotCommand], + scope: Optional[Union[ + types.BotCommandScopeDefault, types.BotCommandScopeAllPrivateChats, + types.BotCommandScopeAllGroupChats, types.BotCommandScopeAllChatAdministrators, + types.BotCommandScopeChat, + types.BotCommandScopeChatAdministrators, types.BotCommandScopeChatMember]] = None, + language_code: Optional[str]=None) -> bool: """ Use this method to change the list of the bot's commands. :param commands: List of BotCommand. At most 100 commands can be specified. + :param scope: scope of users for which the commands are relevant + :param language_code: A two-letter ISO 639-1 language code :return: """ - return apihelper.set_my_commands(self.token, commands) + return apihelper.set_my_commands(self.token, commands, scope, language_code) + + def delete_my_commands(self, + scope: Optional[Union[ + types.BotCommandScopeDefault, types.BotCommandScopeAllPrivateChats, + types.BotCommandScopeAllGroupChats, types.BotCommandScopeAllChatAdministrators, + types.BotCommandScopeChat, + types.BotCommandScopeChatAdministrators, types.BotCommandScopeChatMember]]=None, + language_code: Optional[str]=None) -> bool: + """ + Use this method to delete the list of the bot's commands for the given scope and user language. + :param scope: scope of users for which the commands are relevant + :param language_code: A two-letter ISO 639-1 language code + :return: + """ + return apihelper.delete_my_commands(self.token, scope, language_code) def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 867eef8..384c0bc 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -169,11 +169,6 @@ def get_me(token): return _make_request(token, method_url) -def get_my_commands(token): - method_url = r'getMyCommands' - return _make_request(token, method_url) - - def log_out(token): method_url = r'logOut' return _make_request(token, method_url) @@ -1032,9 +1027,33 @@ def set_chat_title(token, chat_id, title): return _make_request(token, method_url, params=payload, method='post') -def set_my_commands(token, commands): +def get_my_commands(token, scope, language_code): + method_url = r'getMyCommands' + payload = {} + if scope is not None: + payload['scope'] = scope.to_json() + if language_code is not None: + payload['language_code'] = language_code + return _make_request(token, method_url, params=payload, method='post') + + +def set_my_commands(token, commands, scope, language_code): method_url = r'setMyCommands' payload = {'commands': _convert_list_json_serializable(commands)} + if scope is not None: + payload['scope'] = scope.to_json() + if language_code is not None: + payload['language_code'] = language_code + return _make_request(token, method_url, params=payload, method='post') + + +def delete_my_commands(token, scope, language_code): + method_url = r'deleteMyCommands' + payload = {} + if scope is not None: + payload['scope'] = scope.to_json() + if language_code is not None: + payload['language_code'] = language_code return _make_request(token, method_url, params=payload, method='post') diff --git a/telebot/types.py b/telebot/types.py index ad7e4d3..19a6e0f 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -848,13 +848,16 @@ class File(JsonDeserializable): class ForceReply(JsonSerializable): - def __init__(self, selective=None): + def __init__(self, selective=None, input_field_placeholder=None): self.selective: bool = selective + self.input_field_placeholder = input_field_placeholder def to_json(self): json_dict = {'force_reply': True} if self.selective: json_dict['selective'] = True + if self.input_field_placeholder: + json_dict['input_field_placeholder'] = self.input_field_placeholder return json.dumps(json_dict) @@ -872,7 +875,8 @@ class ReplyKeyboardRemove(JsonSerializable): class ReplyKeyboardMarkup(JsonSerializable): max_row_keys = 12 - def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3): + def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3, + input_field_placeholder=None): if row_width > self.max_row_keys: # Todo: Will be replaced with Exception in future releases if not DISABLE_KEYLEN_ERROR: @@ -883,6 +887,7 @@ class ReplyKeyboardMarkup(JsonSerializable): self.one_time_keyboard: bool = one_time_keyboard self.selective: bool = selective self.row_width: int = row_width + self.input_field_placeholder = input_field_placeholder self.keyboard: List[List[KeyboardButton]] = [] def add(self, *args, row_width=None): @@ -926,7 +931,7 @@ class ReplyKeyboardMarkup(JsonSerializable): :param args: strings :return: self, to allow function chaining. """ - + return self.add(*args, row_width=self.max_row_keys) def to_json(self): @@ -942,6 +947,8 @@ class ReplyKeyboardMarkup(JsonSerializable): json_dict['resize_keyboard'] = True if self.selective: json_dict['selective'] = True + if self.input_field_placeholder: + json_dict['input_field_placeholder'] = self.input_field_placeholder return json.dumps(json_dict) @@ -1270,6 +1277,58 @@ class BotCommand(JsonSerializable, JsonDeserializable): return {'command': self.command, 'description': self.description} +# BotCommandScopes + +class BotCommandScope(JsonSerializable): + def __init__(self, type='default', chat_id=None, user_id=None): + self.type: str = type + self.chat_id: Optional[Union[int, str]] = chat_id + self.user_id: Optional[Union[int, str]] = user_id + + def to_json(self): + json_dict = {'type': self.type} + if self.chat_id: + json_dict['chat_id'] = self.chat_id + if self.user_id: + json_dict['user_id'] = self.user_id + return json.dumps(json_dict) + + +class BotCommandScopeDefault(BotCommandScope): + def __init__(self): + super(BotCommandScopeDefault, self).__init__(type='default') + + +class BotCommandScopeAllPrivateChats(BotCommandScope): + def __init__(self): + super(BotCommandScopeAllPrivateChats, self).__init__(type='all_private_chats') + + +class BotCommandScopeAllGroupChats(BotCommandScope): + def __init__(self): + super(BotCommandScopeAllGroupChats, self).__init__(type='all_group_chats') + + +class BotCommandScopeAllChatAdministrators(BotCommandScope): + def __init__(self): + super(BotCommandScopeAllChatAdministrators, self).__init__(type='all_chat_administrators') + + +class BotCommandScopeChat(BotCommandScope): + def __init__(self, chat_id=None): + super(BotCommandScopeChat, self).__init__(type='chat', chat_id=chat_id) + + +class BotCommandScopeChatAdministrators(BotCommandScope): + def __init__(self, chat_id=None): + super(BotCommandScopeChatAdministrators, self).__init__(type='chat_administrators', chat_id=chat_id) + + +class BotCommandScopeChatMember(BotCommandScope): + def __init__(self, chat_id=None, user_id=None): + super(BotCommandScopeChatMember, self).__init__(type='chat_administrators', chat_id=chat_id, user_id=user_id) + + # InlineQuery class InlineQuery(JsonDeserializable): diff --git a/tests/test_telebot.py b/tests/test_telebot.py index a22adcd..a2f3d36 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -546,6 +546,24 @@ class TestTeleBot: ret_msg = tb.send_document(CHAT_ID, file_data, caption='_italic_', parse_mode='Markdown') assert ret_msg.caption_entities[0].type == 'italic' + def test_chat_commands(self): + tb = telebot.TeleBot(TOKEN) + command, description, lang = 'command_1', 'description of command 1', 'en' + scope = telebot.types.BotCommandScopeChat(CHAT_ID) + ret_msg = tb.set_my_commands([telebot.types.BotCommand(command, description)], scope, lang) + assert ret_msg is True + + ret_msg = tb.get_my_commands(scope, lang) + assert ret_msg[0].command == command + assert ret_msg[0].description == description + + ret_msg = tb.delete_my_commands(scope, lang) + assert ret_msg is True + + ret_msg = tb.get_my_commands(scope, lang) + assert ret_msg == [] + + def test_typed_middleware_handler(self): from telebot import apihelper From 38c4c21030f31d3e901adcb2c44e76e3a8dca79c Mon Sep 17 00:00:00 2001 From: Vlad Galatskiy Date: Sun, 27 Jun 2021 11:37:27 +0300 Subject: [PATCH 167/350] Add file_name argument to send_data method --- telebot/apihelper.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 867eef8..9566444 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -810,12 +810,15 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, - allow_sending_without_reply=None, disable_content_type_detection=None): + allow_sending_without_reply=None, disable_content_type_detection=None, file_name=None): method_url = get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None if not util.is_string(data): - files = {data_type: data} + file_data = data + if file_name is not None: + file_data = (file_name, data) + files = {data_type: file_data} else: payload[data_type] = data if reply_to_message_id: From e56f134a7c27ce01dd61905909af06ecd2115a13 Mon Sep 17 00:00:00 2001 From: Vlad Galatskiy Date: Sun, 27 Jun 2021 11:38:45 +0300 Subject: [PATCH 168/350] Add file_name support to send_document method --- telebot/__init__.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f06ee73..dbe2765 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1114,7 +1114,8 @@ class TeleBot: timeout: Optional[int]=None, thumb: Optional[Union[Any, str]]=None, caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: + allow_sending_without_reply: Optional[bool]=None, + file_name: Optional[str]=None) -> types.Message: """ Use this method to send general files. :param chat_id: @@ -1128,6 +1129,7 @@ class TeleBot: :param thumb: InputFile or String : Thumbnail of the file sent :param caption_entities: :param allow_sending_without_reply: + :param file_name: :return: API reply. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1136,7 +1138,7 @@ class TeleBot: apihelper.send_data( self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout, caption, thumb, caption_entities, - allow_sending_without_reply)) + allow_sending_without_reply, file_name)) def send_sticker( self, chat_id: Union[int, str], data: Union[Any, str], From a791ff4e46c2496920863fc5f678f1e4df8352ad Mon Sep 17 00:00:00 2001 From: Vlad Galatskiy Date: Sun, 27 Jun 2021 11:58:33 +0300 Subject: [PATCH 169/350] Add tests for file sending with name --- tests/test_telebot.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/test_telebot.py b/tests/test_telebot.py index a22adcd..377bd72 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -126,6 +126,16 @@ class TestTeleBot: ret_msg = tb.send_document(CHAT_ID, ret_msg.document.file_id) assert ret_msg.message_id + def test_send_file_with_filename(self): + file_data = open('../examples/detailed_example/kitten.jpg', 'rb') + tb = telebot.TeleBot(TOKEN) + + ret_msg = tb.send_document(CHAT_ID, file_data) + assert ret_msg.message_id + + ret_msg = tb.send_document(CHAT_ID, file_data, file_name="test.jpg") + assert ret_msg.message_id + def test_send_file_dis_noti(self): file_data = open('../examples/detailed_example/kitten.jpg', 'rb') tb = telebot.TeleBot(TOKEN) From c088fabe6c6d8527386649996d0749fd9d32e0d1 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 27 Jun 2021 13:09:08 +0300 Subject: [PATCH 170/350] Release version 3.8.0 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 54f9f84..54c4c5d 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.7.9' +__version__ = '3.8.0' From 491cc05a95c3b590e9a0ec6a9fdee42ffca74a97 Mon Sep 17 00:00:00 2001 From: MAIKS1900 Date: Sun, 27 Jun 2021 17:28:11 +0300 Subject: [PATCH 171/350] - Set BotCommandScope as abstract class. - Docstrings from telegram API Scope types --- telebot/types.py | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 19a6e0f..8688132 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -2,6 +2,7 @@ import logging from typing import Dict, List, Optional, Union +from abc import ABC try: import ujson as json @@ -1279,8 +1280,19 @@ class BotCommand(JsonSerializable, JsonDeserializable): # BotCommandScopes -class BotCommandScope(JsonSerializable): +class BotCommandScope(ABC, JsonSerializable): 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 @@ -1296,21 +1308,34 @@ class BotCommandScope(JsonSerializable): class BotCommandScopeDefault(BotCommandScope): def __init__(self): + """ + Represents the default scope of bot commands. + Default commands are used if no commands with a narrower scope are specified for the user. + """ super(BotCommandScopeDefault, self).__init__(type='default') class BotCommandScopeAllPrivateChats(BotCommandScope): def __init__(self): + """ + Represents the scope of bot commands, covering all private chats. + """ super(BotCommandScopeAllPrivateChats, self).__init__(type='all_private_chats') class BotCommandScopeAllGroupChats(BotCommandScope): def __init__(self): + """ + Represents the scope of bot commands, covering all group and supergroup chats. + """ super(BotCommandScopeAllGroupChats, self).__init__(type='all_group_chats') class BotCommandScopeAllChatAdministrators(BotCommandScope): def __init__(self): + """ + Represents the scope of bot commands, covering all group and supergroup chat administrators. + """ super(BotCommandScopeAllChatAdministrators, self).__init__(type='all_chat_administrators') @@ -1321,11 +1346,20 @@ class BotCommandScopeChat(BotCommandScope): class BotCommandScopeChatAdministrators(BotCommandScope): 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): 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_administrators', chat_id=chat_id, user_id=user_id) From a29c4af2ee14dfcfa008e1e99972d54a9df465f2 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 27 Jun 2021 20:40:16 +0300 Subject: [PATCH 172/350] Post-release fix for infinity_polling --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f06ee73..cce73fe 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -579,7 +579,7 @@ class TeleBot: while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, - allowed_updates=allowed_updates *args, **kwargs) + allowed_updates=allowed_updates, *args, **kwargs) except Exception as e: if logger_level and logger_level >= logging.ERROR: logger.error("Infinity polling exception: %s", str(e)) From 0aa7a8a8f694459bee66dfb7652430bdfab26ec1 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 28 Jun 2021 09:31:06 +0200 Subject: [PATCH 173/350] new 5.3 function names added the new function names (the previous names are still working) from 5.3 and some other small changes --- telebot/__init__.py | 107 +++++++++++++++++++++++++++++-------------- telebot/apihelper.py | 39 ++++++++++++---- telebot/types.py | 27 +++++------ 3 files changed, 116 insertions(+), 57 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 9864b59..7adeeb1 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -104,6 +104,7 @@ class TeleBot: editMessageLiveLocation stopMessageLiveLocation kickChatMember + banChatMember unbanChatMember restrictChatMember promoteChatMember @@ -132,10 +133,12 @@ class TeleBot: getChat getChatAdministrators getChatMembersCount + getChatMemberCount getChatMember answerCallbackQuery getMyCommands setMyCommands + deleteMyCommands answerInlineQuery answerShippingQuery answerPreCheckoutQuery @@ -844,6 +847,15 @@ class TeleBot: """ result = apihelper.get_chat_members_count(self.token, chat_id) return result + + def get_chat_member_count(self, chat_id: Union[int, str]) -> int: + """ + Use this method to get the number of members in a chat. Returns Int on success. + :param chat_id: + :return: + """ + result = apihelper.get_chat_member_count(self.token, chat_id) + return result def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str) -> types.StickerSet: """ @@ -1475,6 +1487,26 @@ class TeleBot: """ return apihelper.kick_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + def ban_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + Use this method to ban a user in a group, a supergroup or a channel. + In the case of supergroups and channels, the user will not be able to return to the chat on their + own using invite links, etc., unless unbanned first. + Returns True on success. + :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or + less than 30 seconds from the current time they are considered to be banned forever + :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. + If False, the user will be able to see messages in the group that were sent before the user was removed. + Always True for supergroups and channels. + :return: boolean + """ + return apihelper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + def unban_chat_member( self, chat_id: Union[int, str], user_id: int, only_if_banned: Optional[bool]=False) -> bool: @@ -1699,54 +1731,49 @@ class TeleBot: setting is off in the target group. :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername) - :return: """ return apihelper.delete_chat_photo(self.token, chat_id) - def get_my_commands(self, - scope: Optional[Union[ - types.BotCommandScopeDefault, types.BotCommandScopeAllPrivateChats, - types.BotCommandScopeAllGroupChats, types.BotCommandScopeAllChatAdministrators, - types.BotCommandScopeChat, - types.BotCommandScopeChatAdministrators, types.BotCommandScopeChatMember]]=None, - language_code: Optional[str]=None) -> List[types.BotCommand]: + def get_my_commands(self, scope: Optional[types.BotCommandScope], + language_code: Optional[str]) -> List[types.BotCommand]: """ - Use this method to get the current list of the bot's commands for the given scope and user language - :param scope: scope of users for which the commands are relevant - :param language_code: A two-letter ISO 639-1 language code + Use this method to get the current list of the bot's commands. Returns List of BotCommand on success. + :param scope: The scope of users for which the commands are relevant. + Defaults to BotCommandScopeDefault. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands """ result = apihelper.get_my_commands(self.token, scope, language_code) return [types.BotCommand.de_json(cmd) for cmd in result] - def set_my_commands(self, commands: List[types.BotCommand], - scope: Optional[Union[ - types.BotCommandScopeDefault, types.BotCommandScopeAllPrivateChats, - types.BotCommandScopeAllGroupChats, types.BotCommandScopeAllChatAdministrators, - types.BotCommandScopeChat, - types.BotCommandScopeChatAdministrators, types.BotCommandScopeChatMember]] = None, - language_code: Optional[str]=None) -> bool: + def set_my_commands(self, commands: List[types.BotCommand], + scope: Optional[types.BotCommandScope]=None, + language_code: Optional[str]=None) -> bool: """ Use this method to change the list of the bot's commands. :param commands: List of BotCommand. At most 100 commands can be specified. - :param scope: scope of users for which the commands are relevant - :param language_code: A two-letter ISO 639-1 language code + :param scope: The scope of users for which the commands are relevant. + Defaults to BotCommandScopeDefault. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands :return: """ return apihelper.set_my_commands(self.token, commands, scope, language_code) - - def delete_my_commands(self, - scope: Optional[Union[ - types.BotCommandScopeDefault, types.BotCommandScopeAllPrivateChats, - types.BotCommandScopeAllGroupChats, types.BotCommandScopeAllChatAdministrators, - types.BotCommandScopeChat, - types.BotCommandScopeChatAdministrators, types.BotCommandScopeChatMember]]=None, - language_code: Optional[str]=None) -> bool: + + def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None, + language_code: Optional[int]=None) -> bool: """ - Use this method to delete the list of the bot's commands for the given scope and user language. - :param scope: scope of users for which the commands are relevant - :param language_code: A two-letter ISO 639-1 language code - :return: + Use this method to delete the list of the bot's commands for the given scope and user language. + After deletion, higher level commands will be shown to affected users. + Returns True on success. + :param scope: The scope of users for which the commands are relevant. + Defaults to BotCommandScopeDefault. + :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 apihelper.delete_my_commands(self.token, scope, language_code) @@ -2907,12 +2934,16 @@ class AsyncTeleBot(TeleBot): return TeleBot.close(self) @util.async_dec() - def get_my_commands(self): - return TeleBot.get_my_commands(self) + def get_my_commands(self, *args, **kwargs): # needed args because new scope and language_code + return TeleBot.get_my_commands(self, *args, **kwargs) @util.async_dec() def set_my_commands(self, *args, **kwargs): return TeleBot.set_my_commands(self, *args, **kwargs) + + @util.async_dec() + def delete_my_commands(self, *args, **kwargs): + return TeleBot.delete_my_commands(self, *args, **kwargs) @util.async_dec() def get_file(self, *args): @@ -2941,6 +2972,10 @@ class AsyncTeleBot(TeleBot): @util.async_dec() def get_chat_members_count(self, *args): return TeleBot.get_chat_members_count(self, *args) + + @util.async_dec() + def get_chat_member_count(self, *args): + return TeleBot.get_chat_member_count(self, *args) @util.async_dec() def set_chat_sticker_set(self, *args): @@ -3037,6 +3072,10 @@ class AsyncTeleBot(TeleBot): @util.async_dec() def kick_chat_member(self, *args, **kwargs): return TeleBot.kick_chat_member(self, *args, **kwargs) + + @util.async_dec() + def ban_chat_member(self, *args, **kwargs): + return TeleBot.ban_chat_member(self, *args, **kwargs) @util.async_dec() def unban_chat_member(self, *args, **kwargs): diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 384c0bc..7b1779a 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -93,6 +93,7 @@ def _make_request(token, method_name, method='get', params=None, files=None): # Long polling hangs for given time. Read timeout should be greater that long_polling_timeout read_timeout = max(params['timeout'] + 10, read_timeout) + params = params or None #set params to None if empty result = None if RETRY_ON_ERROR: @@ -335,6 +336,12 @@ def get_chat_members_count(token, chat_id): return _make_request(token, method_url, params=payload) +def get_chat_member_count(token, chat_id): + method_url = r'getChatMemberCount' + payload = {'chat_id': chat_id} + return _make_request(token, method_url, params=payload) + + def set_sticker_set_thumb(token, name, user_id, thumb): method_url = r'setStickerSetThumb' payload = {'name': name, 'user_id': user_id} @@ -861,6 +868,18 @@ def kick_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=N return _make_request(token, method_url, params=payload, method='post') +def ban_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=None): + method_url = 'banChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if isinstance(until_date, datetime): + payload['until_date'] = until_date.timestamp() + else: + payload['until_date'] = until_date + if revoke_messages is not None: + payload['revoke_messages'] = revoke_messages + return _make_request(token, method_url, params=payload, method='post') + + def unban_chat_member(token, chat_id, user_id, only_if_banned): method_url = 'unbanChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} @@ -1027,32 +1046,32 @@ def set_chat_title(token, chat_id, title): return _make_request(token, method_url, params=payload, method='post') -def get_my_commands(token, scope, language_code): +def get_my_commands(token, scope=None, language_code=None): method_url = r'getMyCommands' payload = {} - if scope is not None: + if scope: payload['scope'] = scope.to_json() - if language_code is not None: + if language_code: payload['language_code'] = language_code - return _make_request(token, method_url, params=payload, method='post') + return _make_request(token, method_url, params=payload) -def set_my_commands(token, commands, scope, language_code): +def set_my_commands(token, commands, scope=None, language_code=None): method_url = r'setMyCommands' payload = {'commands': _convert_list_json_serializable(commands)} - if scope is not None: + if scope: payload['scope'] = scope.to_json() - if language_code is not None: + if language_code: payload['language_code'] = language_code return _make_request(token, method_url, params=payload, method='post') -def delete_my_commands(token, scope, language_code): +def delete_my_commands(token, scope=None, language_code=None): method_url = r'deleteMyCommands' payload = {} - if scope is not None: + if scope: payload['scope'] = scope.to_json() - if language_code is not None: + if language_code: payload['language_code'] = language_code return _make_request(token, method_url, params=payload, method='post') diff --git a/telebot/types.py b/telebot/types.py index 8688132..aed2e92 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -849,13 +849,13 @@ class File(JsonDeserializable): class ForceReply(JsonSerializable): - def __init__(self, selective=None, input_field_placeholder=None): + def __init__(self, selective: Optional[bool]=None, input_field_placeholder: Optional[str]=None): self.selective: bool = selective - self.input_field_placeholder = input_field_placeholder + self.input_field_placeholder: str = input_field_placeholder def to_json(self): json_dict = {'force_reply': True} - if self.selective: + if self.selective is not None: json_dict['selective'] = True if self.input_field_placeholder: json_dict['input_field_placeholder'] = self.input_field_placeholder @@ -876,8 +876,8 @@ class ReplyKeyboardRemove(JsonSerializable): class ReplyKeyboardMarkup(JsonSerializable): max_row_keys = 12 - def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3, - input_field_placeholder=None): + def __init__(self, resize_keyboard: Optional[bool]=None, one_time_keyboard: Optional[bool]=None, + selective: Optional[bool]=None, row_width: int=3, input_field_placeholder: Optional[str]=None): if row_width > self.max_row_keys: # Todo: Will be replaced with Exception in future releases if not DISABLE_KEYLEN_ERROR: @@ -888,7 +888,7 @@ class ReplyKeyboardMarkup(JsonSerializable): self.one_time_keyboard: bool = one_time_keyboard self.selective: bool = selective self.row_width: int = row_width - self.input_field_placeholder = input_field_placeholder + self.input_field_placeholder: str = input_field_placeholder self.keyboard: List[List[KeyboardButton]] = [] def add(self, *args, row_width=None): @@ -942,11 +942,11 @@ class ReplyKeyboardMarkup(JsonSerializable): :return: """ json_dict = {'keyboard': self.keyboard} - if self.one_time_keyboard: + if self.one_time_keyboard is not None: json_dict['one_time_keyboard'] = True - if self.resize_keyboard: + if self.resize_keyboard is not None: json_dict['resize_keyboard'] = True - if self.selective: + if self.selective is not None: json_dict['selective'] = True if self.input_field_placeholder: json_dict['input_field_placeholder'] = self.input_field_placeholder @@ -954,7 +954,8 @@ class ReplyKeyboardMarkup(JsonSerializable): class KeyboardButton(Dictionaryable, JsonSerializable): - def __init__(self, text, request_contact=None, request_location=None, request_poll=None): + def __init__(self, text: str, request_contact: Optional[bool]=None, + request_location: Optional[bool]=None, request_poll: Optional[bool]=None): self.text: str = text self.request_contact: bool = request_contact self.request_location: bool = request_location @@ -965,11 +966,11 @@ class KeyboardButton(Dictionaryable, JsonSerializable): def to_dict(self): json_dict = {'text': self.text} - if self.request_contact: + if self.request_contact is not None: json_dict['request_contact'] = self.request_contact - if self.request_location: + if self.request_location is not None: json_dict['request_location'] = self.request_location - if self.request_poll: + if self.request_poll is not None: json_dict['request_poll'] = self.request_poll.to_dict() return json_dict From 60bb63ab2b48ae084349eedab854bf62c61d02c4 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 28 Jun 2021 12:41:15 +0300 Subject: [PATCH 174/350] Release 3.8.1 - bugfix --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 54c4c5d..b74c7d3 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.8.0' +__version__ = '3.8.1' From 0b383498eb8181709c79cd214da38ec6457455f2 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 28 Jun 2021 11:59:21 +0200 Subject: [PATCH 175/350] addded logger info for deprecated funcs --- telebot/__init__.py | 14 ++++++++------ telebot/apihelper.py | 18 ------------------ 2 files changed, 8 insertions(+), 24 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 7adeeb1..3c14456 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -103,7 +103,6 @@ class TeleBot: editMessageReplyMarkup editMessageLiveLocation stopMessageLiveLocation - kickChatMember banChatMember unbanChatMember restrictChatMember @@ -132,7 +131,6 @@ class TeleBot: leaveChat getChat getChatAdministrators - getChatMembersCount getChatMemberCount getChatMember answerCallbackQuery @@ -845,7 +843,8 @@ class TeleBot: :param chat_id: :return: """ - result = apihelper.get_chat_members_count(self.token, chat_id) + logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.') + result = apihelper.get_chat_member_count(self.token, chat_id) return result def get_chat_member_count(self, chat_id: Union[int, str]) -> int: @@ -1485,7 +1484,8 @@ class TeleBot: Always True for supergroups and channels. :return: boolean """ - return apihelper.kick_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') + return apihelper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) def ban_chat_member( self, chat_id: Union[int, str], user_id: int, @@ -2971,7 +2971,8 @@ class AsyncTeleBot(TeleBot): @util.async_dec() def get_chat_members_count(self, *args): - return TeleBot.get_chat_members_count(self, *args) + logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead') + return TeleBot.get_chat_member_count(self, *args) @util.async_dec() def get_chat_member_count(self, *args): @@ -3071,7 +3072,8 @@ class AsyncTeleBot(TeleBot): @util.async_dec() def kick_chat_member(self, *args, **kwargs): - return TeleBot.kick_chat_member(self, *args, **kwargs) + logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') + return TeleBot.ban_chat_member(self, *args, **kwargs) @util.async_dec() def ban_chat_member(self, *args, **kwargs): diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 7b1779a..ca8ec8c 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -330,12 +330,6 @@ def get_chat_administrators(token, chat_id): return _make_request(token, method_url, params=payload) -def get_chat_members_count(token, chat_id): - method_url = r'getChatMembersCount' - payload = {'chat_id': chat_id} - return _make_request(token, method_url, params=payload) - - def get_chat_member_count(token, chat_id): method_url = r'getChatMemberCount' payload = {'chat_id': chat_id} @@ -856,18 +850,6 @@ def get_method_by_type(data_type): return r'sendSticker' -def kick_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=None): - method_url = 'kickChatMember' - payload = {'chat_id': chat_id, 'user_id': user_id} - if isinstance(until_date, datetime): - payload['until_date'] = until_date.timestamp() - else: - payload['until_date'] = until_date - if revoke_messages is not None: - payload['revoke_messages'] = revoke_messages - return _make_request(token, method_url, params=payload, method='post') - - def ban_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=None): method_url = 'banChatMember' payload = {'chat_id': chat_id, 'user_id': user_id} From b48a445e9f64e1d5602e928f09ace4c397c5d5f5 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 28 Jun 2021 12:02:40 +0200 Subject: [PATCH 176/350] Update __init__.py updated docstrings --- telebot/__init__.py | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3c14456..e05cc8a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -839,9 +839,7 @@ class TeleBot: def get_chat_members_count(self, chat_id: Union[int, str]) -> int: """ - Use this method to get the number of members in a chat. Returns Int on success. - :param chat_id: - :return: + This function is deprecated. Use `get_chat_member_count` instead """ logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.') result = apihelper.get_chat_member_count(self.token, chat_id) @@ -1474,15 +1472,7 @@ class TeleBot: until_date:Optional[Union[int, datetime]]=None, revoke_messages: Optional[bool]=None) -> bool: """ - Use this method to kick a user from a group or a supergroup. - :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup - :param user_id: Int : Unique identifier of the target user - :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or - less than 30 seconds from the current time they are considered to be banned forever - :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. - If False, the user will be able to see messages in the group that were sent before the user was removed. - Always True for supergroups and channels. - :return: boolean + This function is deprecated. Use `ban_chat_member` instead """ logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') return apihelper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) From f8110cd04669540d7dc8c2e82b68fd47516756c1 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 28 Jun 2021 15:17:53 +0200 Subject: [PATCH 177/350] Update README.md * Added the new message_handlers * Added some information about local Bot API Server * Replaced the split_string with the smart_split function --- README.md | 73 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 60 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 7048b6c..26aeee8 100644 --- a/README.md +++ b/README.md @@ -208,26 +208,59 @@ def send_something(message): **Important: all handlers are tested in the order in which they were declared** #### Edited Message handlers - -@bot.edited_message_handler(filters) +Handle edited messages +`@bot.edited_message_handler(filters) # <- passes a Message type object to your function` #### channel_post_handler - -@bot.channel_post_handler(filters) +Handle channel post messages +`@bot.channel_post_handler(filters) # <- passes a Message type object to your function` #### edited_channel_post_handler - -@bot.edited_channel_post_handler(filters) +Handle edited channel post messages +`@bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function` #### Callback Query Handler - -In bot2.0 update. You can get `callback_query` in update object. In telebot use `callback_query_handler` to process callback queries. - +Handle callback queries ```python @bot.callback_query_handler(func=lambda call: True) -def test_callback(call): +def test_callback(call): # <- passes a CallbackQuery type object to your function logger.info(call) ``` + +#### Inline Handler +Handle inline queries +`@bot.inline_handler() # <- passes a InlineQuery type object to your function` + +#### Chosen Inline Handler +Handle chosen inline results +`@bot.chosen_inline_handler() # <- passes a ChosenInlineResult type object to your function` + +#### Shipping Query Handler +Handle shipping queries +`@bot.shipping_query_handeler() # <- passes a ShippingQuery type object to your function` + +#### Pre Checkout Query Handler +Handle pre checkoupt queries +`@bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function` + +#### Poll Handler +Handle poll updates +`@bot.poll_handler() # <- passes a Poll type object to your function` + +#### Poll Answer Handler +Handle poll answers +`@bot.poll_answer_handler() # <- passes a PollAnswer type object to your function` + +#### My Chat Member Handler +Handle updates of a the bot's member status in a chat +`@bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function` + +#### Chat Member Handler +Handle updates of a chat member's status in a chat +`@bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function` +*Note: "chat_member" updates are not requested by default. If you want to allow all update types, set `allowed_updates` in `bot.polling()` / `bot.infinity_polling()` to `util.update_types`* + + #### Middleware Handler A middleware handler is a function that allows you to modify requests or the bot context as they pass through the @@ -261,6 +294,7 @@ tb = telebot.TeleBot(TOKEN) #create a new Telegram Bot object # - interval: True/False (default False) - The interval between polling requests # Note: Editing this parameter harms the bot's response time # - timeout: integer (default 20) - Timeout in seconds for long polling. +# - allowed_updates: List of Strings (default None) - List of update types to request tb.polling(none_stop=False, interval=0, timeout=20) # getMe @@ -454,6 +488,18 @@ Refer [Bot Api](https://core.telegram.org/bots/api#messageentity) for extra deta ## Advanced use of the API +### Using local Bot API Sever +Since version 5.0 of the Bot API, you have the possibility to run your own [Local Bot API Server](https://core.telegram.org/bots/api#using-a-local-bot-api-server). +pyTelegramBotAPI also supports this feature. +```python +from telebot import apihelper + +apihelper.API_URL = "http://localhost:4200/bot{0}/{1}" +``` +**Important: Like described [here](https://core.telegram.org/bots/api#logout), you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use `bot.log_out()`** + +*Note: 4200 is an example port* + ### Asynchronous delivery of messages There exists an implementation of TeleBot which executes all `send_xyz` and the `get_me` functions asynchronously. This can speed up your bot __significantly__, but it has unwanted side effects if used without caution. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot. @@ -481,9 +527,10 @@ Sometimes you must send messages that exceed 5000 characters. The Telegram API c from telebot import util large_text = open("large_text.txt", "rb").read() -# Split the text each 3000 characters. -# split_string returns a list with the splitted text. -splitted_text = util.split_string(large_text, 3000) +# Splits one string into multiple strings, with a maximum amount of `chars_per_string` (max. 4096) +# Splits by last '\n', '. ' or ' ' in exactly this priority. +# smart_split returns a list with the splitted text. +splitted_text = util.smart_split(large_text, chars_per_string=3000) for text in splitted_text: tb.send_message(chat_id, text) ``` From b222416fd8fcdf19faf7010afd8ab3169a1811a8 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 28 Jun 2021 15:44:49 +0200 Subject: [PATCH 178/350] Update README.md --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 26aeee8..27ac29d 100644 --- a/README.md +++ b/README.md @@ -527,6 +527,18 @@ Sometimes you must send messages that exceed 5000 characters. The Telegram API c from telebot import util large_text = open("large_text.txt", "rb").read() +# Split the text each 3000 characters. +# split_string returns a list with the splitted text. +splitted_text = util.split_string(large_text, 3000) + +for text in splitted_text: + tb.send_message(chat_id, text) +``` + +Or you can use the new `smart_split` function to get more meaningful substrings: +```python +from telebot import util +large_text = open("large_text.txt", "rb").read() # Splits one string into multiple strings, with a maximum amount of `chars_per_string` (max. 4096) # Splits by last '\n', '. ' or ' ' in exactly this priority. # smart_split returns a list with the splitted text. From a4e73a05c6ea2696483b756c8e135f690f369235 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 29 Jun 2021 13:30:01 +0300 Subject: [PATCH 179/350] Update file_name to visible_file_name in send_document --- telebot/__init__.py | 6 +++--- telebot/apihelper.py | 6 +++--- tests/test_telebot.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f1a1e6d..fbd9545 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1124,7 +1124,7 @@ class TeleBot: thumb: Optional[Union[Any, str]]=None, caption_entities: Optional[List[types.MessageEntity]]=None, allow_sending_without_reply: Optional[bool]=None, - file_name: Optional[str]=None) -> types.Message: + visible_file_name: Optional[str]=None) -> types.Message: """ Use this method to send general files. :param chat_id: @@ -1138,7 +1138,7 @@ class TeleBot: :param thumb: InputFile or String : Thumbnail of the file sent :param caption_entities: :param allow_sending_without_reply: - :param file_name: + :param visible_file_name: allows to define file name that will be visible in the Telegram instead of original file name :return: API reply. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode @@ -1147,7 +1147,7 @@ class TeleBot: apihelper.send_data( self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout, caption, thumb, caption_entities, - allow_sending_without_reply, file_name)) + allow_sending_without_reply, visible_file_name)) def send_sticker( self, chat_id: Union[int, str], data: Union[Any, str], diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 82f43e4..177279f 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -806,14 +806,14 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, - allow_sending_without_reply=None, disable_content_type_detection=None, file_name=None): + allow_sending_without_reply=None, disable_content_type_detection=None, visible_file_name=None): method_url = get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None if not util.is_string(data): file_data = data - if file_name is not None: - file_data = (file_name, data) + if visible_file_name: + file_data = (visible_file_name, data) files = {data_type: file_data} else: payload[data_type] = data diff --git a/tests/test_telebot.py b/tests/test_telebot.py index c50c25a..1a37af8 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -133,7 +133,7 @@ class TestTeleBot: ret_msg = tb.send_document(CHAT_ID, file_data) assert ret_msg.message_id - ret_msg = tb.send_document(CHAT_ID, file_data, file_name="test.jpg") + ret_msg = tb.send_document(CHAT_ID, file_data, visible_file_name="test.jpg") assert ret_msg.message_id def test_send_file_dis_noti(self): From a6668397e10ec6203293f2582af567a8903b0a6a Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 30 Jun 2021 13:08:05 +0200 Subject: [PATCH 180/350] new deprecated decorator added a new deprecated decorator to util --- telebot/util.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/telebot/util.py b/telebot/util.py index 3dd71db..50ca450 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -6,7 +6,7 @@ import threading import traceback import warnings import functools -from typing import Any, List, Dict, Union +from typing import Any, Callable, List, Dict, Optional, Union import queue as Queue import logging @@ -420,6 +420,26 @@ def generate_random_token(): return ''.join(random.sample(string.ascii_letters, 16)) +def deprecated_dec(warn: Optional[bool]=False, alternative: Optional[Callable]=None): + """ + Use this decorator to mark functions as deprecated. + When the function is used, an info (or warning if `warn` is True) is logged. + :param warn: If True a warning is logged else an info + :param alternative: The new function to use instead + """ + def decorator(function): + def wrapper(*args, **kwargs): + if not warn: + logger.info(f"`{function.__name__}` is deprecated." + + (f" Use `{alternative.__name__}` instead" if alternative else "")) + else: + logger.warn(f"`{function.__name__}` is deprecated." + + (f" Use `{alternative.__name__}` instead" if alternative else "")) + return function(*args, **kwargs) + return wrapper + return decorator + + def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted From 073d7fb6a733ee26c1d6985fed422fd28fcbe34c Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 30 Jun 2021 13:11:48 +0200 Subject: [PATCH 181/350] Update util.py whoops warn is not optional --- telebot/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/util.py b/telebot/util.py index 50ca450..49ea25d 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -420,7 +420,7 @@ def generate_random_token(): return ''.join(random.sample(string.ascii_letters, 16)) -def deprecated_dec(warn: Optional[bool]=False, alternative: Optional[Callable]=None): +def deprecated_dec(warn: bool=False, alternative: Optional[Callable]=None): """ Use this decorator to mark functions as deprecated. When the function is used, an info (or warning if `warn` is True) is logged. From 791d65e95a9ba60ac8b798c7d865f9d887d9880c Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 30 Jun 2021 13:47:39 +0200 Subject: [PATCH 182/350] replaced old deprecated decorator --- telebot/util.py | 17 +---------------- tests/test_telebot.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/telebot/util.py b/telebot/util.py index 49ea25d..711f003 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -420,7 +420,7 @@ def generate_random_token(): return ''.join(random.sample(string.ascii_letters, 16)) -def deprecated_dec(warn: bool=False, alternative: Optional[Callable]=None): +def deprecated(warn: bool=False, alternative: Optional[Callable]=None): """ Use this decorator to mark functions as deprecated. When the function is used, an info (or warning if `warn` is True) is logged. @@ -439,18 +439,3 @@ def deprecated_dec(warn: bool=False, alternative: Optional[Callable]=None): return wrapper return decorator - -def deprecated(func): - """This is a decorator which can be used to mark functions - as deprecated. It will result in a warning being emitted - when the function is used.""" - # https://stackoverflow.com/a/30253848/441814 - @functools.wraps(func) - def new_func(*args, **kwargs): - warnings.simplefilter('always', DeprecationWarning) # turn off filter - warnings.warn("Call to deprecated function {}.".format(func.__name__), - category=DeprecationWarning, - stacklevel=2) - warnings.simplefilter('default', DeprecationWarning) # reset filter - return func(*args, **kwargs) - return new_func diff --git a/tests/test_telebot.py b/tests/test_telebot.py index a2f3d36..0421033 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -19,6 +19,14 @@ if not should_skip: CHAT_ID = os.environ['CHAT_ID'] GROUP_ID = os.environ['GROUP_ID'] +def _new_test(): + pass + +@util.deprecated(alternative=_new_test) +def _test(): + pass + + @pytest.mark.skipif(should_skip, reason="No environment variables configured") class TestTeleBot: @@ -605,6 +613,9 @@ class TestTeleBot: tb.process_new_updates([update]) time.sleep(1) assert update.message.text == 'got' * 2 + + def test_deprecated_dec(self): + _test() def test_chat_permissions(self): return # CHAT_ID is private chat, no permissions can be set From 56e4f68a839f6d647f4a9d21109abd65f4e69017 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Wed, 30 Jun 2021 14:16:38 +0200 Subject: [PATCH 183/350] added the property `difference` to ChatMemberUpdated --- telebot/types.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/telebot/types.py b/telebot/types.py index aed2e92..61ac414 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -148,6 +148,23 @@ class ChatMemberUpdated(JsonDeserializable): self.old_chat_member: ChatMember = old_chat_member self.new_chat_member: ChatMember = new_chat_member self.invite_link: Optional[ChatInviteLink] = invite_link + + @property + 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]} + """ + old: Dict = self.old_chat_member.__dict__ + new: Dict = self.new_chat_member.__dict__ + old.pop('user') # User should always be the same + new.pop('user') # No need to include + dif = {} + for key in new: + if new[key] != old[key]: + dif[key] = [old[key], new[key]] + return dif class WebhookInfo(JsonDeserializable): From c7b360e98203b79366301c519127c7377d5f57ae Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Thu, 1 Jul 2021 18:54:39 +0200 Subject: [PATCH 184/350] fixed bug --- telebot/types.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 61ac414..cae4909 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -158,10 +158,9 @@ class ChatMemberUpdated(JsonDeserializable): """ old: Dict = self.old_chat_member.__dict__ new: Dict = self.new_chat_member.__dict__ - old.pop('user') # User should always be the same - new.pop('user') # No need to include dif = {} for key in new: + if key == 'user': continue if new[key] != old[key]: dif[key] = [old[key], new[key]] return dif From a15016d7d9b7dc2cc451138d58b8bc18701e6650 Mon Sep 17 00:00:00 2001 From: Andy Kluger Date: Wed, 7 Jul 2021 13:00:32 -0400 Subject: [PATCH 185/350] mention colorcodebot as a project using this library --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 27ac29d..c392958 100644 --- a/README.md +++ b/README.md @@ -691,6 +691,7 @@ Get help. Discuss. Chat. * [League of Legends bot](https://telegram.me/League_of_Legends_bot) ([source](https://github.com/i32ropie/lol)) by *i32ropie* * [NeoBot](https://github.com/neoranger/NeoBot) by [@NeoRanger](https://github.com/neoranger) * [TagAlertBot](https://github.com/pitasi/TagAlertBot) by *pitasi* +* [ColorCodeBot](https://t.me/colorcodebot) ([source](https://github.com/andydecleyre/colorcodebot)) - Share code snippets as beautifully syntax-highlighted HTML and/or images. * [ComedoresUGRbot](http://telegram.me/ComedoresUGRbot) ([source](https://github.com/alejandrocq/ComedoresUGRbot)) by [*alejandrocq*](https://github.com/alejandrocq) - Telegram bot to check the menu of Universidad de Granada dining hall. * [picpingbot](https://web.telegram.org/#/im?p=%40picpingbot) - Fun anonymous photo exchange by Boogie Muffin. * [TheZigZagProject](https://github.com/WebShark025/TheZigZagProject) - The 'All In One' bot for Telegram! by WebShark025 From beb5a456eb282c01e3af98d41ea08a3fd583e838 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 8 Jul 2021 09:35:48 +0300 Subject: [PATCH 186/350] Preserve dict change in Update --- telebot/types.py | 98 ++++++++++++++++++++++++------------------------ 1 file changed, 50 insertions(+), 48 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index cae4909..a0efe89 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -65,15 +65,16 @@ class JsonDeserializable(object): raise NotImplementedError @staticmethod - def check_json(json_type): + 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) - :param json_type: - :return: + :param json_type: input json or parsed dict + :param dict_copy: if dict is passed and it is changed outside - should be True! + :return: Dictionary parsed from json or original dict """ if util.is_dict(json_type): - return json_type + return json_type.copy() elif util.is_string(json_type): return json.loads(json_type) else: @@ -94,25 +95,28 @@ class Update(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) - obj['message'] = Message.de_json(obj.get('message')) - obj['edited_message'] = Message.de_json(obj.get('edited_message')) - obj['channel_post'] = Message.de_json(obj.get('channel_post')) - obj['edited_channel_post'] = Message.de_json(obj.get('edited_channel_post')) - obj['inline_query'] = InlineQuery.de_json(obj.get('inline_query')) - obj['chosen_inline_result'] = ChosenInlineResult.de_json(obj.get('chosen_inline_result')) - obj['callback_query'] = CallbackQuery.de_json(obj.get('callback_query')) - obj['shipping_query'] = ShippingQuery.de_json(obj.get('shipping_query')) - obj['pre_checkout_query'] = PreCheckoutQuery.de_json(obj.get('pre_checkout_query')) - obj['poll'] = Poll.de_json(obj.get('poll')) - obj['poll_answer'] = PollAnswer.de_json(obj.get('poll_answer')) - obj['my_chat_member'] = ChatMemberUpdated.de_json(obj.get('my_chat_member')) - obj['chat_member'] = ChatMemberUpdated.de_json(obj.get('chat_member')) - return cls(**obj) + obj = cls.check_json(json_string, dict_copy=False) + update_id = obj['update_id'] + message = Message.de_json(obj.get('message')) + edited_message = Message.de_json(obj.get('edited_message')) + channel_post = Message.de_json(obj.get('channel_post')) + edited_channel_post = Message.de_json(obj.get('edited_channel_post')) + inline_query = InlineQuery.de_json(obj.get('inline_query')) + chosen_inline_result = ChosenInlineResult.de_json(obj.get('chosen_inline_result')) + callback_query = CallbackQuery.de_json(obj.get('callback_query')) + shipping_query = ShippingQuery.de_json(obj.get('shipping_query')) + pre_checkout_query = PreCheckoutQuery.de_json(obj.get('pre_checkout_query')) + poll = Poll.de_json(obj.get('poll')) + poll_answer = PollAnswer.de_json(obj.get('poll_answer')) + my_chat_member = ChatMemberUpdated.de_json(obj.get('my_chat_member')) + chat_member = ChatMemberUpdated.de_json(obj.get('chat_member')) + return cls(update_id, message, edited_message, channel_post, edited_channel_post, inline_query, + chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, + my_chat_member, chat_member) def __init__(self, update_id, message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, - my_chat_member, chat_member, **kwargs): + my_chat_member, chat_member): self.update_id = update_id self.message = message self.edited_message = edited_message @@ -170,7 +174,7 @@ class WebhookInfo(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, url, has_custom_certificate, pending_update_count, ip_address=None, @@ -190,7 +194,7 @@ class User(JsonDeserializable, Dictionaryable, JsonSerializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, id, is_bot, first_name, last_name=None, username=None, language_code=None, @@ -231,7 +235,7 @@ class GroupChat(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, id, title, **kwargs): @@ -283,11 +287,10 @@ class MessageID(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) - message_id = obj['message_id'] - return cls(message_id) + obj = cls.check_json(json_string, dict_copy=False) + return cls(**obj) - def __init__(self, message_id): + def __init__(self, message_id, **kwargs): self.message_id = message_id @@ -295,7 +298,7 @@ class Message(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) message_id = obj['message_id'] from_user = User.de_json(obj.get('from')) date = obj['date'] @@ -643,7 +646,7 @@ class Dice(JsonSerializable, Dictionaryable, JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, value, emoji, **kwargs): @@ -662,7 +665,7 @@ class PhotoSize(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, file_id, file_unique_id, width, height, file_size=None, **kwargs): @@ -701,7 +704,7 @@ class Voice(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, file_id, file_unique_id, duration, mime_type=None, file_size=None, **kwargs): @@ -775,7 +778,7 @@ class Contact(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None, **kwargs): @@ -790,7 +793,7 @@ class Location(JsonDeserializable, JsonSerializable, Dictionaryable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, longitude, latitude, horizontal_accuracy=None, @@ -854,7 +857,7 @@ class File(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, file_id, file_unique_id, file_size, file_path, **kwargs): @@ -1005,7 +1008,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) keyboard = [[InlineKeyboardButton.de_json(button) for button in row] for row in obj['inline_keyboard']] return cls(keyboard) @@ -1129,7 +1132,7 @@ class LoginUrl(Dictionaryable, JsonSerializable, JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, url, forward_text=None, bot_username=None, request_write_access=None, **kwargs): @@ -1176,7 +1179,7 @@ class ChatPhoto(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, small_file_id, small_file_unique_id, big_file_id, big_file_unique_id, **kwargs): @@ -1230,7 +1233,7 @@ 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) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, can_send_messages=None, can_send_media_messages=None, @@ -1274,7 +1277,7 @@ class BotCommand(JsonSerializable, JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, command, description): @@ -2329,7 +2332,7 @@ class Invoice(JsonDeserializable): @classmethod def de_json(cls, json_string): if (json_string is None): return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, title, description, start_parameter, currency, total_amount, **kwargs): @@ -2344,7 +2347,7 @@ class ShippingAddress(JsonDeserializable): @classmethod def de_json(cls, json_string): if (json_string is None): return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, country_code, state, city, street_line1, street_line2, post_code, **kwargs): @@ -2506,7 +2509,7 @@ class MaskPosition(Dictionaryable, JsonDeserializable, JsonSerializable): @classmethod def de_json(cls, json_string): if (json_string is None): return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, point, x_shift, y_shift, scale, **kwargs): @@ -2653,11 +2656,10 @@ class InputMediaDocument(InputMedia): class PollOption(JsonDeserializable): -#class PollOption(JsonSerializable, JsonDeserializable): @classmethod def de_json(cls, json_string): if (json_string is None): return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, text, voter_count = 0, **kwargs): @@ -2788,7 +2790,7 @@ class ProximityAlertTriggered(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, traveler, watcher, distance, **kwargs): @@ -2813,7 +2815,7 @@ class VoiceChatScheduled(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(obj['start_date']) def __init__(self, start_date): @@ -2824,7 +2826,7 @@ class VoiceChatEnded(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(obj['duration']) def __init__(self, duration): @@ -2849,7 +2851,7 @@ class MessageAutoDeleteTimerChanged(JsonDeserializable): @classmethod def de_json(cls, json_string): if json_string is None: return None - obj = cls.check_json(json_string) + obj = cls.check_json(json_string, dict_copy=False) return cls(obj['message_auto_delete_time']) def __init__(self, message_auto_delete_time): From 2578e481349dddce0e095cf27567d8784fc5b1b3 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Fri, 9 Jul 2021 10:42:56 +0300 Subject: [PATCH 187/350] Timeouts in making requests are rethought --- telebot/apihelper.py | 93 +++++++++++++++++++++++++------------------- 1 file changed, 52 insertions(+), 41 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 177279f..5ee003e 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- import time from datetime import datetime -from typing import Dict try: import ujson as json @@ -12,6 +11,7 @@ import requests from requests.exceptions import HTTPError, ConnectionError, Timeout try: + # noinspection PyUnresolvedReferences from requests.packages.urllib3 import fields format_header_param = fields.format_header_param except ImportError: @@ -28,8 +28,11 @@ session = None API_URL = None FILE_URL = None -CONNECT_TIMEOUT = 3.5 -READ_TIMEOUT = 9999 +CONNECT_TIMEOUT = 15 +READ_TIMEOUT = 30 + +LONG_POLLING_TIMEOUT = 10 # Should be positive, short polling should be used for testing purposes only (https://core.telegram.org/bots/api#getupdates) + SESSION_TIME_TO_LIVE = None # In seconds. None - live forever, 0 - one-time RETRY_ON_ERROR = False @@ -45,6 +48,7 @@ def _get_req_session(reset=False): if SESSION_TIME_TO_LIVE: # If session TTL is set - check time passed creation_date = util.per_thread('req_session_time', lambda: datetime.now(), reset) + # noinspection PyTypeChecker if (datetime.now() - creation_date).total_seconds() > SESSION_TIME_TO_LIVE: # Force session reset reset = True @@ -72,6 +76,7 @@ def _make_request(token, method_name, method='get', params=None, files=None): if not token: raise Exception('Bot token is not defined') if API_URL: + # noinspection PyUnresolvedReferences request_url = API_URL.format(token, method_name) else: request_url = "https://api.telegram.org/bot{0}/{1}".format(token, method_name) @@ -83,17 +88,21 @@ def _make_request(token, method_name, method='get', params=None, files=None): fields.format_header_param = _no_encode(format_header_param) if params: if 'timeout' in params: - read_timeout = params.pop('timeout') + 10 - if 'connect-timeout' in params: - connect_timeout = params.pop('connect-timeout') + 10 + read_timeout = params.pop('timeout') + connect_timeout = read_timeout +# if 'connect-timeout' in params: +# connect_timeout = params.pop('connect-timeout') + 10 if 'long_polling_timeout' in params: - # For getUpdates - # The only function with timeout on the BOT API side - params['timeout'] = params.pop('long_polling_timeout') - # Long polling hangs for given time. Read timeout should be greater that long_polling_timeout - read_timeout = max(params['timeout'] + 10, read_timeout) + # For getUpdates: it's the only function with timeout parameter on the BOT API side + long_polling_timeout = params.pop('long_polling_timeout') + params['timeout'] = long_polling_timeout + # Long polling hangs for a given time. Read timeout should be greater that long_polling_timeout + read_timeout = max(long_polling_timeout + 5, read_timeout) + # Lets stop suppose that user is stupid and assume that he knows what he do... + # read_timeout = read_timeout + 10 + # connect_timeout = connect_timeout + 10 - params = params or None #set params to None if empty + params = params or None # Set params to None if empty result = None if RETRY_ON_ERROR: @@ -189,13 +198,15 @@ def get_file_url(token, file_id): if FILE_URL is None: return "https://api.telegram.org/file/bot{0}/{1}".format(token, get_file(token, file_id)['file_path']) else: + # noinspection PyUnresolvedReferences return FILE_URL.format(token, get_file(token, file_id)['file_path']) - + def download_file(token, file_path): if FILE_URL is None: url = "https://api.telegram.org/file/bot{0}/{1}".format(token, file_path) else: + # noinspection PyUnresolvedReferences url = FILE_URL.format(token, file_path) result = _get_req_session().get(url, proxies=proxy) @@ -238,7 +249,7 @@ def send_message( if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if entities: payload['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) if allow_sending_without_reply is not None: @@ -264,7 +275,7 @@ def set_webhook(token, url=None, certificate=None, max_connections=None, allowed if drop_pending_updates is not None: # Any bool value should pass payload['drop_pending_updates'] = drop_pending_updates if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload, files=files) @@ -274,7 +285,7 @@ def delete_webhook(token, drop_pending_updates=None, timeout=None): if drop_pending_updates is not None: # Any bool value should pass payload['drop_pending_updates'] = drop_pending_updates if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -282,7 +293,7 @@ def get_webhook_info(token, timeout=None): method_url = r'getWebhookInfo' payload = {} if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -294,9 +305,8 @@ def get_updates(token, offset=None, limit=None, timeout=None, allowed_updates=No if limit: payload['limit'] = limit if timeout: - payload['connect-timeout'] = timeout - if long_polling_timeout: - payload['long_polling_timeout'] = long_polling_timeout + payload['timeout'] = timeout + payload['long_polling_timeout'] = long_polling_timeout if long_polling_timeout else LONG_POLLING_TIMEOUT if allowed_updates is not None: # Empty lists should pass payload['allowed_updates'] = json.dumps(allowed_updates) return _make_request(token, method_url, params=payload) @@ -374,7 +384,7 @@ def forward_message( if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -398,7 +408,7 @@ def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_m if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -417,7 +427,7 @@ def send_dice( if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -448,7 +458,7 @@ def send_photo( if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) if allow_sending_without_reply is not None: @@ -468,7 +478,7 @@ def send_media_group( if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request( @@ -502,7 +512,7 @@ def send_location( if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -527,7 +537,7 @@ def edit_message_live_location( if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -545,7 +555,7 @@ def stop_message_live_location( if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -568,7 +578,7 @@ def send_venue( if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply if google_place_id: @@ -595,7 +605,7 @@ def send_contact( if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -605,7 +615,7 @@ def send_chat_action(token, chat_id, action, timeout=None): method_url = r'sendChatAction' payload = {'chat_id': chat_id, 'action': action} if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload) @@ -634,7 +644,7 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_to_messa if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if thumb: if not util.is_string(thumb): if files: @@ -678,7 +688,7 @@ def send_animation( if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if thumb: if not util.is_string(thumb): if files: @@ -717,7 +727,7 @@ def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_mess if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if caption_entities: payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) if allow_sending_without_reply is not None: @@ -747,7 +757,7 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_m if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if thumb: if not util.is_string(thumb): if files: @@ -788,7 +798,7 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if thumb: if not util.is_string(thumb): if files: @@ -826,7 +836,7 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m if disable_notification is not None: payload['disable_notification'] = disable_notification if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if caption: payload['caption'] = caption if thumb: @@ -1162,7 +1172,7 @@ def delete_message(token, chat_id, message_id, timeout=None): method_url = r'deleteMessage' payload = {'chat_id': chat_id, 'message_id': message_id} if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout return _make_request(token, method_url, params=payload, method='post') @@ -1181,7 +1191,7 @@ def send_game( if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -1314,7 +1324,7 @@ def send_invoice( if provider_data: payload['provider_data'] = provider_data if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply return _make_request(token, method_url, params=payload) @@ -1458,6 +1468,7 @@ def delete_sticker_from_set(token, sticker): return _make_request(token, method_url, params=payload, method='post') +# noinspection PyShadowingBuiltins def send_poll( token, chat_id, question, options, @@ -1502,7 +1513,7 @@ def send_poll( if reply_markup is not None: payload['reply_markup'] = _convert_markup(reply_markup) if timeout: - payload['connect-timeout'] = timeout + payload['timeout'] = timeout if explanation_entities: payload['explanation_entities'] = json.dumps( types.MessageEntity.to_list_of_dicts(explanation_entities)) From 2d0b092ea4b2e0c367f28b583919cdb0c3b33741 Mon Sep 17 00:00:00 2001 From: dannkunt <32395839+dannkunt@users.noreply.github.com> Date: Sat, 10 Jul 2021 22:03:31 +0300 Subject: [PATCH 188/350] Fix wrong type hint call.id gives int --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index fbd9545..ecaf438 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2179,7 +2179,7 @@ class TeleBot: switch_pm_text, switch_pm_parameter) def answer_callback_query( - self, callback_query_id: str, + self, callback_query_id: int, text: Optional[str]=None, show_alert: Optional[bool]=None, url: Optional[str]=None, cache_time: Optional[int]=None) -> bool: """ From 6fb10e92e4fea41e78d86301c96c20b0e267a7e8 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 13 Jul 2021 20:11:47 +0300 Subject: [PATCH 189/350] Fix CallbackQuery issue for games --- telebot/types.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/telebot/types.py b/telebot/types.py index a0efe89..b0ccae9 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1160,6 +1160,9 @@ class CallbackQuery(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) + if not "data" in obj: + # "data" field is Optional in the API, but historically is mandatory in the class constructor + obj['data'] = None obj['from_user'] = User.de_json(obj.pop('from')) if 'message' in obj: obj['message'] = Message.de_json(obj.get('message')) From f52ea635e5fd9d8c74699b267cf4f3b7dabd36c0 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 13 Jul 2021 22:09:56 +0300 Subject: [PATCH 190/350] Fix worker_pool issue --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index ecaf438..faf1baa 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -740,7 +740,7 @@ class TeleBot: def stop_bot(self): self.stop_polling() - if self.worker_pool: + if self.threaded and self.worker_pool: self.worker_pool.close() def set_update_listener(self, listener): From fa80b1dba07a563a445614212c78e3a850900a21 Mon Sep 17 00:00:00 2001 From: Vladislav Nahorniy Date: Thu, 15 Jul 2021 08:56:04 +0300 Subject: [PATCH 191/350] Added tip for invoice --- telebot/__init__.py | 10 ++++++++-- telebot/apihelper.py | 9 ++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index faf1baa..36b5e2e 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1983,7 +1983,8 @@ class TeleBot: reply_markup: Optional[REPLY_MARKUP_TYPES]=None, provider_data: Optional[str]=None, timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: + allow_sending_without_reply: Optional[bool]=None, + max_tip_amount: Optional[int] = None, suggested_tip_amounts: Optional[list]=None) -> types.Message: """ Sends invoice :param chat_id: Unique identifier for the target private chat @@ -2018,6 +2019,10 @@ class TeleBot: A detailed description of required fields should be provided by the payment provider. :param timeout: :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest + units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip + amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. :return: """ result = apihelper.send_invoice( @@ -2025,7 +2030,8 @@ class TeleBot: currency, prices, start_parameter, photo_url, photo_size, photo_width, photo_height, need_name, need_phone_number, need_email, need_shipping_address, send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, - reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply) + reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply, + max_tip_amount, suggested_tip_amounts) return types.Message.de_json(result) def send_poll( diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 5ee003e..76684fc 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1258,7 +1258,7 @@ def send_invoice( need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, - timeout=None, allow_sending_without_reply=None): + timeout=None, allow_sending_without_reply=None,max_tip_amount=None, suggested_tip_amounts=None): """ Use this method to send invoices. On success, the sent Message is returned. :param token: Bot's token (you don't need to fill this) @@ -1287,6 +1287,9 @@ def send_invoice( :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. :param timeout: :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest units of the currency. + At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. :return: """ method_url = r'sendInvoice' @@ -1327,6 +1330,10 @@ def send_invoice( payload['timeout'] = timeout if allow_sending_without_reply is not None: payload['allow_sending_without_reply'] = allow_sending_without_reply + if max_tip_amount is not None: + payload['max_tip_amount'] = max_tip_amount + if suggested_tip_amounts is not None: + payload['suggested_tip_amounts'] = json.dumps(suggested_tip_amounts) return _make_request(token, method_url, params=payload) From 29c98b02302dc84add7f01cfbdaf111aa34dbab1 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 15 Jul 2021 09:27:07 +0300 Subject: [PATCH 192/350] Invoice tips typo fix --- telebot/__init__.py | 3 ++- telebot/apihelper.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 36b5e2e..bb48123 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1984,7 +1984,8 @@ class TeleBot: provider_data: Optional[str]=None, timeout: Optional[int]=None, allow_sending_without_reply: Optional[bool]=None, - max_tip_amount: Optional[int] = None, suggested_tip_amounts: Optional[list]=None) -> types.Message: + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[list]=None) -> types.Message: """ Sends invoice :param chat_id: Unique identifier for the target private chat diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 76684fc..2e7ee2a 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1258,7 +1258,7 @@ def send_invoice( need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, - timeout=None, allow_sending_without_reply=None,max_tip_amount=None, suggested_tip_amounts=None): + timeout=None, allow_sending_without_reply=None, max_tip_amount=None, suggested_tip_amounts=None): """ Use this method to send invoices. On success, the sent Message is returned. :param token: Bot's token (you don't need to fill this) From 097ba9fec2ff3692c03061288f3454c2058b9112 Mon Sep 17 00:00:00 2001 From: monosans Date: Mon, 19 Jul 2021 20:01:37 +0300 Subject: [PATCH 193/350] Replace for loops with comprehensions --- telebot/__init__.py | 20 ++++---------------- telebot/types.py | 11 ++++------- telebot/util.py | 7 ++++--- 3 files changed, 12 insertions(+), 26 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index bb48123..b13c396 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -359,10 +359,7 @@ class TeleBot: :return: array of Updates """ json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout) - ret = [] - for ju in json_updates: - ret.append(types.Update.de_json(ju)) - return ret + return [types.Update.de_json(ju) for ju in json_updates] def __skip_updates(self): """ @@ -832,10 +829,7 @@ class TeleBot: :return: """ result = apihelper.get_chat_administrators(self.token, chat_id) - ret = [] - for r in result: - ret.append(types.ChatMember.de_json(r)) - return ret + return [types.ChatMember.de_json(r) for r in result] def get_chat_members_count(self, chat_id: Union[int, str]) -> int: """ @@ -1307,10 +1301,7 @@ class TeleBot: result = apihelper.send_media_group( self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, allow_sending_without_reply) - ret = [] - for msg in result: - ret.append(types.Message.de_json(msg)) - return ret + return [types.Message.de_json(msg) for msg in result] def send_location( self, chat_id: Union[int, str], @@ -1962,10 +1953,7 @@ class TeleBot: :return: """ result = apihelper.get_game_high_scores(self.token, user_id, chat_id, message_id, inline_message_id) - ret = [] - for r in result: - ret.append(types.GameHighScore.de_json(r)) - return ret + return [types.GameHighScore.de_json(r) for r in result] def send_invoice( self, chat_id: Union[int, str], title: str, description: str, diff --git a/telebot/types.py b/telebot/types.py index b0ccae9..8dba5cc 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -81,13 +81,10 @@ class JsonDeserializable(object): raise ValueError("json_type should be a json dict or string.") def __str__(self): - d = {} - for x, y in self.__dict__.items(): - if hasattr(y, '__dict__'): - d[x] = y.__dict__ - else: - d[x] = y - + d = { + x: y.__dict__ if hasattr(y, '__dict__') else y + for x, y in self.__dict__.items() + } return str(d) diff --git a/telebot/util.py b/telebot/util.py index 711f003..34d08ed 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -351,9 +351,10 @@ def quick_markup(values: Dict[str, Dict[str, Any]], row_width: int=2) -> types.I :return: InlineKeyboardMarkup """ markup = types.InlineKeyboardMarkup(row_width=row_width) - buttons = [] - for text, kwargs in values.items(): - buttons.append(types.InlineKeyboardButton(text=text, **kwargs)) + buttons = [ + types.InlineKeyboardButton(text=text, **kwargs) + for text, kwargs in values.items() + ] markup.add(*buttons) return markup From ae8c3252df52770aa77142e6e5e8419ca5e4e6f2 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 21 Jul 2021 21:53:56 +0300 Subject: [PATCH 194/350] Release version 3.8.2 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index b74c7d3..80f0f16 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.8.1' +__version__ = '3.8.2' From 02b886465e3b6d7bfa05067beceaf8e38a0d4c8f Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 25 Jul 2021 15:46:53 +0500 Subject: [PATCH 195/350] new filters --- telebot/__init__.py | 56 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index b13c396..b5ce7cf 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2461,7 +2461,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, supergroup=None, user_id=None, chat_id=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. @@ -2487,12 +2487,32 @@ class TeleBot: 'text', 'location', 'contact', 'sticker']) def default_command(message): bot.send_message(message.chat.id, "This is the default command handler.") + # Handle all messages in private chat. + @bot.message_handler(is_private=True) + def default_command(message): + bot.send_message(message.chat.id, "You wrote message in private chat") + # Handle all messages in group/supergroup. + @bot.message_handler(supergroup=True) + def default_command(message): + bot.send_message(message.chat.id, "You wrote message in supergroup") + # Handle all messages from user 11111 + @bot.message_handler(user_id=[11111]) + def default_command(message): + bot.send_message(message.chat.id, "You wrote me message in special chat")# This doesn't work for other users than '11111' + # Handle all messages in specific group/supergroup. + @bot.message_handler(chat_id=[1111]]) + def default_command(message): + bot.send_message(message.chat.id, "You wrote message in special supergroup") :param commands: Optional list of strings (commands to handle). :param regexp: Optional regular expression. :param func: Optional lambda function. The lambda receives the message to test as the first parameter. It must return True if the command should handle the message. :param content_types: Supported message content types. Must be a list. Defaults to ['text']. + :param is_private: True/False, only private chats. + :param supergroup: True/False, only supergroups/groups. + :param user_id: List of user ids, which can use handler. + :param chat_id: List of chat_ids where handler is executed. """ if content_types is None: @@ -2503,6 +2523,10 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, + is_private=is_private, + supergroup=supergroup, + user_id=user_id, + chat_id = chat_id, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2518,13 +2542,17 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, supergroup=None, user_id=None, chat_id=None, **kwargs): """ Edit message handler decorator :param commands: :param regexp: :param func: :param content_types: + :param is_private: + :param supergroup: + :param user_id: + :param chat_id: :param kwargs: :return: """ @@ -2534,10 +2562,14 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + content_types=content_types, commands=commands, regexp=regexp, + is_private=is_private, + supergroup=supergroup, + user_id=user_id, + chat_id = chat_id, func=func, - content_types=content_types, **kwargs) self.add_edited_message_handler(handler_dict) return handler @@ -2552,13 +2584,14 @@ class TeleBot: """ self.edited_message_handlers.append(handler_dict) - def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_id=None, **kwargs): """ Channel post handler decorator :param commands: :param regexp: :param func: :param content_types: + :param chat_id: :param kwargs: :return: """ @@ -2568,10 +2601,11 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + content_types=content_types, commands=commands, regexp=regexp, + chat_id = chat_id, func=func, - content_types=content_types, **kwargs) self.add_channel_post_handler(handler_dict) return handler @@ -2586,7 +2620,7 @@ class TeleBot: """ self.channel_post_handlers.append(handler_dict) - def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, supergroup=None, user_id=None, chat_id=None, **kwargs): """ Edit channel post handler decorator :param commands: @@ -2602,10 +2636,14 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + content_types=content_types, commands=commands, regexp=regexp, + is_private=is_private, + supergroup=supergroup, + user_id=user_id, + chat_id = chat_id, func=func, - content_types=content_types, **kwargs) self.add_edited_channel_post_handler(handler_dict) return handler @@ -2857,6 +2895,10 @@ class TeleBot: 'content_types': lambda msg: msg.content_type in filter_value, 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + 'is_private': lambda msg: msg.chat.type == 'private', + 'supergroup': lambda msg: msg.chat.type == "supergroup", + 'user_id': lambda msg: msg.from_user.id in filter_value, + 'chat_id': lambda msg: msg.chat.id in filter_value, 'func': lambda msg: filter_value(msg) } From 9c1b19a9e49e601bbf83bf9b059caf2157cfa0dc Mon Sep 17 00:00:00 2001 From: coder2020official Date: Wed, 28 Jul 2021 23:06:31 +0500 Subject: [PATCH 196/350] upd --- telebot/__init__.py | 3 ++- telebot/apihelper.py | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index b5ce7cf..f9418d8 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2116,7 +2116,8 @@ class TeleBot: self, caption: str, chat_id: Optional[Union[int, str]]=None, message_id: Optional[int]=None, inline_message_id: Optional[str]=None, - parse_mode: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit captions of messages diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 2e7ee2a..1f0c187 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1123,7 +1123,7 @@ def edit_message_text(token, text, chat_id=None, message_id=None, inline_message def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_message_id=None, - parse_mode=None, reply_markup=None): + parse_mode=None, caption_entities=None,reply_markup=None): method_url = r'editMessageCaption' payload = {'caption': caption} if chat_id: @@ -1134,6 +1134,8 @@ def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_m payload['inline_message_id'] = inline_message_id if parse_mode: payload['parse_mode'] = parse_mode + if caption_entities: + payload['caption_entities'] = caption_entities if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload, method='post') From 7ebe589b46ba0d1218f9954730573b5ab86d011d Mon Sep 17 00:00:00 2001 From: coder2020official Date: Wed, 28 Jul 2021 23:10:15 +0500 Subject: [PATCH 197/350] Update __init__.py --- telebot/__init__.py | 58 +++++++-------------------------------------- 1 file changed, 8 insertions(+), 50 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f9418d8..59637dc 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2116,7 +2116,7 @@ class TeleBot: self, caption: str, chat_id: Optional[Union[int, str]]=None, message_id: Optional[int]=None, inline_message_id: Optional[str]=None, - parse_mode: Optional[str]=None, + parse_mode: Optional[str]=None, caption_entities: Optional[List[types.MessageEntity]]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ @@ -2462,7 +2462,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, supergroup=None, user_id=None, chat_id=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. @@ -2488,32 +2488,12 @@ class TeleBot: 'text', 'location', 'contact', 'sticker']) def default_command(message): bot.send_message(message.chat.id, "This is the default command handler.") - # Handle all messages in private chat. - @bot.message_handler(is_private=True) - def default_command(message): - bot.send_message(message.chat.id, "You wrote message in private chat") - # Handle all messages in group/supergroup. - @bot.message_handler(supergroup=True) - def default_command(message): - bot.send_message(message.chat.id, "You wrote message in supergroup") - # Handle all messages from user 11111 - @bot.message_handler(user_id=[11111]) - def default_command(message): - bot.send_message(message.chat.id, "You wrote me message in special chat")# This doesn't work for other users than '11111' - # Handle all messages in specific group/supergroup. - @bot.message_handler(chat_id=[1111]]) - def default_command(message): - bot.send_message(message.chat.id, "You wrote message in special supergroup") :param commands: Optional list of strings (commands to handle). :param regexp: Optional regular expression. :param func: Optional lambda function. The lambda receives the message to test as the first parameter. It must return True if the command should handle the message. :param content_types: Supported message content types. Must be a list. Defaults to ['text']. - :param is_private: True/False, only private chats. - :param supergroup: True/False, only supergroups/groups. - :param user_id: List of user ids, which can use handler. - :param chat_id: List of chat_ids where handler is executed. """ if content_types is None: @@ -2524,10 +2504,6 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, - is_private=is_private, - supergroup=supergroup, - user_id=user_id, - chat_id = chat_id, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2543,17 +2519,13 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, supergroup=None, user_id=None, chat_id=None, **kwargs): + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Edit message handler decorator :param commands: :param regexp: :param func: :param content_types: - :param is_private: - :param supergroup: - :param user_id: - :param chat_id: :param kwargs: :return: """ @@ -2563,14 +2535,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, - content_types=content_types, commands=commands, regexp=regexp, - is_private=is_private, - supergroup=supergroup, - user_id=user_id, - chat_id = chat_id, func=func, + content_types=content_types, **kwargs) self.add_edited_message_handler(handler_dict) return handler @@ -2585,14 +2553,13 @@ class TeleBot: """ self.edited_message_handlers.append(handler_dict) - def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_id=None, **kwargs): + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Channel post handler decorator :param commands: :param regexp: :param func: :param content_types: - :param chat_id: :param kwargs: :return: """ @@ -2602,11 +2569,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, - content_types=content_types, commands=commands, regexp=regexp, - chat_id = chat_id, func=func, + content_types=content_types, **kwargs) self.add_channel_post_handler(handler_dict) return handler @@ -2621,7 +2587,7 @@ class TeleBot: """ self.channel_post_handlers.append(handler_dict) - def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, supergroup=None, user_id=None, chat_id=None, **kwargs): + def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Edit channel post handler decorator :param commands: @@ -2637,14 +2603,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, - content_types=content_types, commands=commands, regexp=regexp, - is_private=is_private, - supergroup=supergroup, - user_id=user_id, - chat_id = chat_id, func=func, + content_types=content_types, **kwargs) self.add_edited_channel_post_handler(handler_dict) return handler @@ -2896,10 +2858,6 @@ class TeleBot: 'content_types': lambda msg: msg.content_type in filter_value, 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, - 'is_private': lambda msg: msg.chat.type == 'private', - 'supergroup': lambda msg: msg.chat.type == "supergroup", - 'user_id': lambda msg: msg.from_user.id in filter_value, - 'chat_id': lambda msg: msg.chat.id in filter_value, 'func': lambda msg: filter_value(msg) } From 81adfd335e85637011632aac89ed8602681fdb33 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Fri, 30 Jul 2021 19:15:37 +0500 Subject: [PATCH 198/350] UPD --- telebot/__init__.py | 2 +- telebot/apihelper.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 59637dc..9fd86a2 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2132,7 +2132,7 @@ class TeleBot: parse_mode = self.parse_mode if (parse_mode is None) else parse_mode result = apihelper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, - parse_mode, reply_markup) + parse_mode, caption_entities, reply_markup) if type(result) == bool: return result return types.Message.de_json(result) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 1f0c187..7647e12 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1135,7 +1135,7 @@ def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_m if parse_mode: payload['parse_mode'] = parse_mode if caption_entities: - payload['caption_entities'] = caption_entities + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload, method='post') From c117ff2d50e052b0d39a7d105769cb8d0711c66f Mon Sep 17 00:00:00 2001 From: snikidev Date: Tue, 3 Aug 2021 17:34:29 +0100 Subject: [PATCH 199/350] Add return statement to to_dict() method inside InputInvoiceMessageContent --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 8dba5cc..ceddfdb 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1569,7 +1569,7 @@ class InputInvoiceMessageContent(Dictionaryable): json_dict['send_email_to_provider'] = self.send_email_to_provider if self.is_flexible is not None: json_dict['is_flexible'] = self.is_flexible - + return json_dict class ChosenInlineResult(JsonDeserializable): @classmethod From 4ba4bc18cff1d5324e58d5f8a0e1989ac2cdcb41 Mon Sep 17 00:00:00 2001 From: snikidev Date: Tue, 3 Aug 2021 17:35:59 +0100 Subject: [PATCH 200/350] add extra space --- telebot/types.py | 1 + 1 file changed, 1 insertion(+) diff --git a/telebot/types.py b/telebot/types.py index ceddfdb..60e5c02 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1571,6 +1571,7 @@ class InputInvoiceMessageContent(Dictionaryable): json_dict['is_flexible'] = self.is_flexible return json_dict + class ChosenInlineResult(JsonDeserializable): @classmethod def de_json(cls, json_string): From ea16f3543253304b020a54566cf04f5e3c69459d Mon Sep 17 00:00:00 2001 From: Amol Soans Date: Fri, 6 Aug 2021 12:29:00 +0530 Subject: [PATCH 201/350] Add IPO bot Listed oneIPO bot created using pyTelegramBotAPI in section : Bpts using this API --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c392958..dbd5178 100644 --- a/README.md +++ b/README.md @@ -749,5 +749,6 @@ Get help. Discuss. Chat. * Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. * [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by [Leon Heess (source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. * [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) - +* [oneIPO bot](https://github.com/aaditya2200/IPO-proj) by [Aadithya](https://github.com/aaditya2200) & [Amol Soans](https://github.com/AmolDerickSoans) This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) + **Want to have your bot listed here? Just make a pull request.** From 911e35693007a1e7c45c884fc2c3dc8afa697caa Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 12 Aug 2021 15:16:04 +0300 Subject: [PATCH 202/350] BotCommandScopeChatMember fix --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index 60e5c02..6d17c9f 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1380,7 +1380,7 @@ class BotCommandScopeChatMember(BotCommandScope): @param chat_id: Unique identifier for the target chat @param user_id: Unique identifier of the target user """ - super(BotCommandScopeChatMember, self).__init__(type='chat_administrators', chat_id=chat_id, user_id=user_id) + super(BotCommandScopeChatMember, self).__init__(type='chat_member', chat_id=chat_id, user_id=user_id) # InlineQuery From 3e4a6cd702acd8f21c4ade98881da927275f4c15 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 14 Aug 2021 18:46:45 +0400 Subject: [PATCH 203/350] Create chat_member_example.py --- examples/chat_member_example.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 examples/chat_member_example.py diff --git a/examples/chat_member_example.py b/examples/chat_member_example.py new file mode 100644 index 0000000..b6fca73 --- /dev/null +++ b/examples/chat_member_example.py @@ -0,0 +1,33 @@ +import telebot +from telebot import types,util + +bot = telebot.TeleBot("token") + +#chat_member_handler. When status changes, telegram gives update. check status from old_chat_member and new_chat_member. +@bot.chat_member_handler() +def chat_m(message: types.ChatMemberUpdated): + old = message.old_chat_member + new = message.new_chat_member + if new.status == "member": + bot.send_message(message.chat.id,"Hello {name}!".format(name=new.user.first_name)) # Welcome message + +#if bot is added to group, this handler will work +@bot.my_chat_member_handler() +def my_chat_m(message: types.ChatMemberUpdated): + old = message.old_chat_member + new = message.new_chat_member + if new.status == "member": + bot.send_message(message.chat.id,"Somebody added me to group") # Welcome message, if bot was added to group + bot.leave_chat(message.chat.id) + +#content_Type_service is: +#'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', +#'proximity_alert_triggered', 'voice_chat_scheduled', 'voice_chat_started', 'voice_chat_ended', +#'voice_chat_participants_invited', 'message_auto_delete_timer_changed' +# this handler deletes service messages + +@bot.message_handler(content_types=util.content_type_service) +def delall(message: types.Message): + bot.delete_message(message.chat.id,message.message_id) +bot.polling(allowed_updates=util.update_types) \ No newline at end of file From beeb60aab8171b9a426f9d239f9b3a3da41ca3fa Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 15 Aug 2021 11:40:13 +0400 Subject: [PATCH 204/350] skip_updates --- examples/skip_updates_example.py | 15 +++++++++++++++ telebot/__init__.py | 10 ++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 examples/skip_updates_example.py diff --git a/examples/skip_updates_example.py b/examples/skip_updates_example.py new file mode 100644 index 0000000..8474e16 --- /dev/null +++ b/examples/skip_updates_example.py @@ -0,0 +1,15 @@ +import telebot + +bot = telebot.TeleBot("TOKEN") + +@bot.message_handler(commands=['start', 'help']) +def send_welcome(message): + bot.reply_to(message, "Howdy, how are you doing?") + +@bot.message_handler(func=lambda message: True) +def echo_all(message): + bot.reply_to(message, message.text) + +bot.polling(skip_updates=True) # Will skip old messages when skip_updates is set + +# Also, you can use skip_updates in infinity_polling() \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index 9fd86a2..26354b0 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -556,7 +556,7 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, long_polling_timeout=20, logger_level=logging.ERROR, + def infinity_polling(self, timeout=20, skip_updates=False, long_polling_timeout=20, logger_level=logging.ERROR, allowed_updates=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. @@ -565,6 +565,7 @@ class TeleBot: :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging + :param skip_updates: Skip previous updates :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. @@ -574,6 +575,8 @@ class TeleBot: Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. """ + if skip_updates: + apihelper.get_updates(self.token, -1) while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, @@ -590,7 +593,7 @@ class TeleBot: if logger_level and logger_level >= logging.INFO: logger.error("Break infinity polling") - def polling(self, none_stop: bool=False, interval: int=0, timeout: int=20, + def polling(self, none_stop: bool=False, skip_updates=False, interval: int=0, timeout: int=20, long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): """ This function creates a new Thread that calls an internal __retrieve_updates function. @@ -601,6 +604,7 @@ class TeleBot: Always get updates. :param interval: Delay between two update retrivals :param none_stop: Do not stop polling when an ApiException occurs. + :param skip_updates: Skip previous updates :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param allowed_updates: A list of the update types you want your bot to receive. @@ -613,6 +617,8 @@ class TeleBot: so unwanted updates may be received for a short period of time. :return: """ + if skip_updates: + apihelper.get_updates(self.token, -1) if self.threaded: self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) else: From 1e4a6e2125e1a2fd2f6fc60a26d09dc509ee0a64 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 15 Aug 2021 13:32:11 +0400 Subject: [PATCH 205/350] Update __init__.py --- telebot/__init__.py | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 26354b0..8c6e5ef 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -143,7 +143,7 @@ class TeleBot: """ def __init__( - self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, + self, token, parse_mode=None, threaded=True, num_threads=2, next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0, suppress_middleware_excepions=False # <- Typo in exceptions ): @@ -156,7 +156,6 @@ class TeleBot: self.token = token self.parse_mode = parse_mode self.update_listener = [] - self.skip_pending = skip_pending self.suppress_middleware_excepions = suppress_middleware_excepions self.__stop_polling = threading.Event() @@ -364,17 +363,10 @@ class TeleBot: def __skip_updates(self): """ Get and discard all pending updates before first poll of the bot - :return: total updates skipped + :return: """ - total = 0 - updates = self.get_updates(offset=self.last_update_id, long_polling_timeout=1) - while updates: - total += len(updates) - for update in updates: - if update.update_id > self.last_update_id: - self.last_update_id = update.update_id - updates = self.get_updates(offset=self.last_update_id + 1, long_polling_timeout=1) - return total + logger.debug('Skipped all pending messages') + self.get_updates(offset=-1, long_polling_timeout=1) def __retrieve_updates(self, timeout=20, long_polling_timeout=20, allowed_updates=None): """ @@ -382,9 +374,6 @@ class TeleBot: Registered listeners and applicable message handlers will be notified when a new message arrives. :raises ApiException when a call has failed. """ - if self.skip_pending: - logger.debug('Skipped {0} pending messages'.format(self.__skip_updates())) - self.skip_pending = False updates = self.get_updates(offset=(self.last_update_id + 1), allowed_updates=allowed_updates, timeout=timeout, long_polling_timeout=long_polling_timeout) @@ -576,7 +565,7 @@ class TeleBot: so unwanted updates may be received for a short period of time. """ if skip_updates: - apihelper.get_updates(self.token, -1) + self.__skip_updates() while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, @@ -618,7 +607,7 @@ class TeleBot: :return: """ if skip_updates: - apihelper.get_updates(self.token, -1) + self.__skip_updates() if self.threaded: self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) else: From 2c0f42b363b0149ed28c19ac304f8ae7e6ace497 Mon Sep 17 00:00:00 2001 From: _run Date: Mon, 16 Aug 2021 14:48:21 +0400 Subject: [PATCH 206/350] Update __init__.py --- telebot/__init__.py | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 8c6e5ef..249fcab 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -143,7 +143,7 @@ class TeleBot: """ def __init__( - self, token, parse_mode=None, threaded=True, num_threads=2, + self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0, suppress_middleware_excepions=False # <- Typo in exceptions ): @@ -156,6 +156,7 @@ class TeleBot: self.token = token self.parse_mode = parse_mode self.update_listener = [] + self.skip_pending = skip_pending self.suppress_middleware_excepions = suppress_middleware_excepions self.__stop_polling = threading.Event() @@ -365,8 +366,7 @@ class TeleBot: Get and discard all pending updates before first poll of the bot :return: """ - logger.debug('Skipped all pending messages') - self.get_updates(offset=-1, long_polling_timeout=1) + self.get_updates(offset=-1) def __retrieve_updates(self, timeout=20, long_polling_timeout=20, allowed_updates=None): """ @@ -374,6 +374,10 @@ class TeleBot: Registered listeners and applicable message handlers will be notified when a new message arrives. :raises ApiException when a call has failed. """ + if self.skip_pending: + self.__skip_updates() + logger.debug('Skipped all pending messages') + self.skip_pending = False updates = self.get_updates(offset=(self.last_update_id + 1), allowed_updates=allowed_updates, timeout=timeout, long_polling_timeout=long_polling_timeout) @@ -545,7 +549,7 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, skip_updates=False, long_polling_timeout=20, logger_level=logging.ERROR, + def infinity_polling(self, timeout=20, long_polling_timeout=20, logger_level=logging.ERROR, allowed_updates=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. @@ -554,7 +558,6 @@ class TeleBot: :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging - :param skip_updates: Skip previous updates :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. @@ -564,8 +567,6 @@ class TeleBot: Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. """ - if skip_updates: - self.__skip_updates() while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, @@ -582,7 +583,7 @@ class TeleBot: if logger_level and logger_level >= logging.INFO: logger.error("Break infinity polling") - def polling(self, none_stop: bool=False, skip_updates=False, interval: int=0, timeout: int=20, + def polling(self, none_stop: bool=False, interval: int=0, timeout: int=20, long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): """ This function creates a new Thread that calls an internal __retrieve_updates function. @@ -593,7 +594,6 @@ class TeleBot: Always get updates. :param interval: Delay between two update retrivals :param none_stop: Do not stop polling when an ApiException occurs. - :param skip_updates: Skip previous updates :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param allowed_updates: A list of the update types you want your bot to receive. @@ -606,8 +606,6 @@ class TeleBot: so unwanted updates may be received for a short period of time. :return: """ - if skip_updates: - self.__skip_updates() if self.threaded: self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) else: @@ -2112,7 +2110,6 @@ class TeleBot: message_id: Optional[int]=None, inline_message_id: Optional[str]=None, parse_mode: Optional[str]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit captions of messages @@ -2127,7 +2124,7 @@ class TeleBot: parse_mode = self.parse_mode if (parse_mode is None) else parse_mode result = apihelper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, - parse_mode, caption_entities, reply_markup) + parse_mode, reply_markup) if type(result) == bool: return result return types.Message.de_json(result) From 3e7da0fd1825fdac5783f1dfeb8b080d81b778b5 Mon Sep 17 00:00:00 2001 From: _run Date: Mon, 16 Aug 2021 14:49:45 +0400 Subject: [PATCH 207/350] Update skip_updates_example.py --- examples/skip_updates_example.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/examples/skip_updates_example.py b/examples/skip_updates_example.py index 8474e16..805c9e4 100644 --- a/examples/skip_updates_example.py +++ b/examples/skip_updates_example.py @@ -1,6 +1,6 @@ import telebot -bot = telebot.TeleBot("TOKEN") +bot = telebot.TeleBot("TOKEN",skip_pending=True)# Skip pending skips old updates @bot.message_handler(commands=['start', 'help']) def send_welcome(message): @@ -10,6 +10,4 @@ def send_welcome(message): def echo_all(message): bot.reply_to(message, message.text) -bot.polling(skip_updates=True) # Will skip old messages when skip_updates is set - -# Also, you can use skip_updates in infinity_polling() \ No newline at end of file +bot.polling() \ No newline at end of file From 24ef64456b941b84177d3fad43b5c87095b1300c Mon Sep 17 00:00:00 2001 From: _run Date: Mon, 16 Aug 2021 14:53:00 +0400 Subject: [PATCH 208/350] Update __init__.py --- telebot/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 249fcab..30b36b9 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2110,6 +2110,7 @@ class TeleBot: message_id: Optional[int]=None, inline_message_id: Optional[str]=None, parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit captions of messages @@ -2124,7 +2125,7 @@ class TeleBot: parse_mode = self.parse_mode if (parse_mode is None) else parse_mode result = apihelper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, - parse_mode, reply_markup) + parse_mode, caption_entities, reply_markup) if type(result) == bool: return result return types.Message.de_json(result) From f553960096e1b6c8bab79d6c9eb4313936c1181f Mon Sep 17 00:00:00 2001 From: _run Date: Mon, 16 Aug 2021 22:00:08 +0400 Subject: [PATCH 209/350] Update __init__.py --- telebot/__init__.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 30b36b9..5048863 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -549,13 +549,14 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, long_polling_timeout=20, logger_level=logging.ERROR, + def infinity_polling(self, timeout=20, skip_pending=False, long_polling_timeout=20, logger_level=logging.ERROR, allowed_updates=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param skip_pending: skip old updates :param logger_level: Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging :param allowed_updates: A list of the update types you want your bot to receive. @@ -567,6 +568,9 @@ class TeleBot: Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. """ + if skip_pending: + self.__skip_updates() + while not self.__stop_polling.is_set(): try: self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, @@ -583,7 +587,7 @@ class TeleBot: if logger_level and logger_level >= logging.INFO: logger.error("Break infinity polling") - def polling(self, none_stop: bool=False, interval: int=0, timeout: int=20, + def polling(self, none_stop: bool=False, skip_pending=False, interval: int=0, timeout: int=20, long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): """ This function creates a new Thread that calls an internal __retrieve_updates function. @@ -595,6 +599,7 @@ class TeleBot: :param interval: Delay between two update retrivals :param none_stop: Do not stop polling when an ApiException occurs. :param timeout: Request connection timeout + :param skip_pending: skip old updates :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param allowed_updates: A list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. @@ -606,6 +611,9 @@ class TeleBot: so unwanted updates may be received for a short period of time. :return: """ + if skip_pending: + self.__skip_updates() + if self.threaded: self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) else: From f4ef2366b6d73ed60cd00f616bd727546266265f Mon Sep 17 00:00:00 2001 From: _run Date: Mon, 16 Aug 2021 22:03:17 +0400 Subject: [PATCH 210/350] Update skip_updates_example.py --- examples/skip_updates_example.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/skip_updates_example.py b/examples/skip_updates_example.py index 805c9e4..0bd631b 100644 --- a/examples/skip_updates_example.py +++ b/examples/skip_updates_example.py @@ -1,6 +1,6 @@ import telebot -bot = telebot.TeleBot("TOKEN",skip_pending=True)# Skip pending skips old updates +bot = telebot.TeleBot("TOKEN") @bot.message_handler(commands=['start', 'help']) def send_welcome(message): @@ -10,4 +10,4 @@ def send_welcome(message): def echo_all(message): bot.reply_to(message, message.text) -bot.polling() \ No newline at end of file +bot.polling(skip_pending=True)# Skip pending skips old updates From 56cd3971dc406b0952aaa6cc7bb5ce8312b56cc1 Mon Sep 17 00:00:00 2001 From: _run Date: Mon, 16 Aug 2021 22:41:27 +0400 Subject: [PATCH 211/350] Update __init__.py --- telebot/__init__.py | 183 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 180 insertions(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 5048863..a3e6c0c 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -594,7 +594,7 @@ class TeleBot: 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. :param interval: Delay between two update retrivals :param none_stop: Do not stop polling when an ApiException occurs. @@ -2520,6 +2520,23 @@ class TeleBot: """ self.message_handlers.append(handler_dict) + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Edit message handler decorator @@ -2554,6 +2571,23 @@ class TeleBot: """ self.edited_message_handlers.append(handler_dict) + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers edited message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Channel post handler decorator @@ -2587,7 +2621,24 @@ class TeleBot: :return: """ self.channel_post_handlers.append(handler_dict) - + + def register_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Edit channel post handler decorator @@ -2622,6 +2673,24 @@ class TeleBot: """ self.edited_channel_post_handlers.append(handler_dict) + def register_edited_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers edited channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + def inline_handler(self, func, **kwargs): """ Inline call handler decorator @@ -2645,6 +2714,18 @@ class TeleBot: """ self.inline_handlers.append(handler_dict) + def register_inline_handler(self, callback, func, **kwargs): + """ + Registers inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_inline_handler(handler_dict) + def chosen_inline_handler(self, func, **kwargs): """ Description: TBD @@ -2668,6 +2749,19 @@ class TeleBot: """ self.chosen_inline_handlers.append(handler_dict) + def register_chosen_inline_handler(self, callback, func, **kwargs): + """ + Registers chosen inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_chosen_inline_handler(handler_dict) + + def callback_query_handler(self, func, **kwargs): """ Callback request handler decorator @@ -2691,6 +2785,18 @@ class TeleBot: """ self.callback_query_handlers.append(handler_dict) + def register_callback_query_handler(self, callback, func, **kwargs): + """ + Registers callback query handler.. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_callback_query_handler(handler_dict) + def shipping_query_handler(self, func, **kwargs): """ Shipping request handler @@ -2714,6 +2820,18 @@ class TeleBot: """ self.shipping_query_handlers.append(handler_dict) + def register_shipping_query_handler(self, callback, func, **kwargs): + """ + Registers shipping query handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_shipping_query_handler(handler_dict) + def pre_checkout_query_handler(self, func, **kwargs): """ Pre-checkout request handler @@ -2736,6 +2854,18 @@ class TeleBot: :return: """ self.pre_checkout_query_handlers.append(handler_dict) + + def register_pre_checkout_query_handler(self, callback, func, **kwargs): + """ + Registers pre-checkout request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_pre_checkout_query_handler(handler_dict) def poll_handler(self, func, **kwargs): """ @@ -2760,6 +2890,18 @@ class TeleBot: """ self.poll_handlers.append(handler_dict) + def register_poll_handler(self, callback, func, **kwargs): + """ + Registers poll handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_poll_handler(handler_dict) + def poll_answer_handler(self, func=None, **kwargs): """ Poll_answer request handler @@ -2782,7 +2924,19 @@ class TeleBot: :return: """ self.poll_answer_handlers.append(handler_dict) - + + def register_poll_answer_handler(self, callback, func, **kwargs): + """ + Registers poll answer handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_poll_answer_handler(handler_dict) + def my_chat_member_handler(self, func=None, **kwargs): """ my_chat_member handler @@ -2806,6 +2960,18 @@ class TeleBot: """ self.my_chat_member_handlers.append(handler_dict) + def register_my_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers my chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_my_chat_member_handler(handler_dict) + def chat_member_handler(self, func=None, **kwargs): """ chat_member handler @@ -2829,6 +2995,17 @@ class TeleBot: """ self.chat_member_handlers.append(handler_dict) + def register_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, + func=func, + **kwargs) + self.add_chat_member_handler(handler_dict) def _test_message_handler(self, message_handler, message): """ From d6501ddc0e90c32b5f1ec89725399ea98cd85056 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 18:47:38 +0300 Subject: [PATCH 212/350] Check and update for full compatibility to Bot API up to 5.0 --- README.md | 10 +- telebot/__init__.py | 52 ++-- telebot/apihelper.py | 4 +- telebot/types.py | 567 ++++++++++++++++++++----------------------- 4 files changed, 305 insertions(+), 328 deletions(-) diff --git a/README.md b/README.md index dbd5178..76fe327 100644 --- a/README.md +++ b/README.md @@ -591,7 +591,7 @@ You can use proxy for request. `apihelper.proxy` object will use by call `reques ```python from telebot import apihelper -apihelper.proxy = {'http':'http://10.10.1.10:3128'} +apihelper.proxy = {'http':'http://127.0.0.1:3128'} ``` If you want to use socket5 proxy you need install dependency `pip install requests[socks]` and make sure, that you have the latest version of `gunicorn`, `PySocks`, `pyTelegramBotAPI`, `requests` and `urllib3`. @@ -605,8 +605,14 @@ apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'} _Checking is in progress..._ -✅ [Bot API 4.5](https://core.telegram.org/bots/api-changelog#december-31-2019) _- To be checked..._ +✅ [Bot API 5.1](https://core.telegram.org/bots/api#march-9-2021) _- To be checked..._ +* ✔ [Bot API 5.0](https://core.telegram.org/bots/api-changelog#november-4-2020) +* ✔ [Bot API 4.9](https://core.telegram.org/bots/api-changelog#june-4-2020) +* ✔ [Bot API 4.8](https://core.telegram.org/bots/api-changelog#april-24-2020) +* ✔ [Bot API 4.7](https://core.telegram.org/bots/api-changelog#march-30-2020) +* ✔ [Bot API 4.6](https://core.telegram.org/bots/api-changelog#january-23-2020) +* ➕ [Bot API 4.5](https://core.telegram.org/bots/api-changelog#december-31-2019) - No nested MessageEntities and Markdown2 support. * ✔ [Bot API 4.4](https://core.telegram.org/bots/api-changelog#july-29-2019) * ✔ [Bot API 4.3](https://core.telegram.org/bots/api-changelog#may-31-2019) * ✔ [Bot API 4.2](https://core.telegram.org/bots/api-changelog#april-14-2019) diff --git a/telebot/__init__.py b/telebot/__init__.py index 9fd86a2..f50b932 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -145,7 +145,7 @@ class TeleBot: def __init__( self, token, parse_mode=None, threaded=True, skip_pending=False, num_threads=2, next_step_backend=None, reply_backend=None, exception_handler=None, last_update_id=0, - suppress_middleware_excepions=False # <- Typo in exceptions + suppress_middleware_excepions=False ): """ :param token: bot API token @@ -590,8 +590,9 @@ class TeleBot: if logger_level and logger_level >= logging.INFO: logger.error("Break infinity polling") - def polling(self, none_stop: bool=False, interval: int=0, timeout: int=20, - long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): + def polling(self, non_stop: bool=False, interval: int=0, timeout: int=20, + long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None, + 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. @@ -600,7 +601,7 @@ class TeleBot: Always get updates. :param interval: Delay between two update retrivals - :param none_stop: Do not stop polling when an ApiException occurs. + :param non_stop: Do not stop polling when an ApiException occurs. :param timeout: Request connection timeout :param long_polling_timeout: Timeout in seconds for long polling (see API docs) :param allowed_updates: A list of the update types you want your bot to receive. @@ -611,12 +612,16 @@ class TeleBot: Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. + :param none_stop: Deprecated, use non_stop. Old typo f***up compatibility :return: """ + if none_stop is not None: + non_stop = none_stop + if self.threaded: - self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) + self.__threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates) else: - self.__non_threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates) + self.__non_threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates) def __threaded_polling(self, non_stop=False, interval=0, timeout = None, long_polling_timeout = None, allowed_updates=None): logger.info('Started polling.') @@ -1118,30 +1123,34 @@ class TeleBot: thumb: Optional[Union[Any, str]]=None, caption_entities: Optional[List[types.MessageEntity]]=None, allow_sending_without_reply: Optional[bool]=None, - visible_file_name: Optional[str]=None) -> types.Message: + visible_file_name: Optional[str]=None, + disable_content_type_detection: Optional[bool]=None) -> types.Message: """ Use this method to send general files. - :param chat_id: - :param data: - :param reply_to_message_id: - :param caption: + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param data: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data + :param reply_to_message_id: If the message is a reply, ID of the original message + :param caption: Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing :param reply_markup: - :param parse_mode: - :param disable_notification: + :param parse_mode: Mode for parsing entities in the document caption + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :param timeout: - :param thumb: InputFile or String : Thumbnail of the file sent + :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 define file name that will be visible in the Telegram instead of original file name + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data :return: API reply. """ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode return types.Message.de_json( apihelper.send_data( - self.token, chat_id, data, 'document', reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, caption, thumb, caption_entities, - allow_sending_without_reply, visible_file_name)) + self.token, chat_id, data, 'document', + reply_to_message_id = reply_to_message_id, reply_markup = reply_markup, parse_mode = parse_mode, + disable_notification = disable_notification, timeout = timeout, caption = caption, thumb = thumb, + caption_entities = caption_entities, allow_sending_without_reply = allow_sending_without_reply, + disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name)) def send_sticker( self, chat_id: Union[int, str], data: Union[Any, str], @@ -1163,7 +1172,7 @@ class TeleBot: """ return types.Message.de_json( apihelper.send_data( - self.token, chat_id=chat_id, data=data, data_type='sticker', + self.token, chat_id, data, 'sticker', reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, disable_notification=disable_notification, timeout=timeout, allow_sending_without_reply=allow_sending_without_reply)) @@ -1831,7 +1840,8 @@ class TeleBot: message_id: Optional[int]=None, inline_message_id: Optional[str]=None, parse_mode: Optional[str]=None, - disable_web_page_preview: Optional[bool]=None, + entities: Optional[List[types.MessageEntity]]=None, + disable_web_page_preview: Optional[bool]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: """ Use this method to edit text and game messages. @@ -1840,6 +1850,7 @@ class TeleBot: :param message_id: :param inline_message_id: :param parse_mode: + :param entities: :param disable_web_page_preview: :param reply_markup: :return: @@ -1847,7 +1858,7 @@ class TeleBot: parse_mode = self.parse_mode if (parse_mode is None) else parse_mode result = apihelper.edit_message_text(self.token, text, chat_id, message_id, inline_message_id, parse_mode, - disable_web_page_preview, reply_markup) + entities, disable_web_page_preview, reply_markup) if type(result) == bool: # if edit inline message return is bool not Message. return result return types.Message.de_json(result) @@ -2126,6 +2137,7 @@ class TeleBot: :param message_id: :param inline_message_id: :param parse_mode: + :param caption_entities: :param reply_markup: :return: """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 7647e12..a3ef5c2 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1104,7 +1104,7 @@ def unpin_all_chat_messages(token, chat_id): # Updating messages def edit_message_text(token, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, - disable_web_page_preview=None, reply_markup=None): + entities = None, disable_web_page_preview=None, reply_markup=None): method_url = r'editMessageText' payload = {'text': text} if chat_id: @@ -1115,6 +1115,8 @@ def edit_message_text(token, text, chat_id=None, message_id=None, inline_message payload['inline_message_id'] = inline_message_id if parse_mode: payload['parse_mode'] = parse_mode + if entities: + payload['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) if disable_web_page_preview is not None: payload['disable_web_page_preview'] = disable_web_page_preview if reply_markup: diff --git a/telebot/types.py b/telebot/types.py index 6d17c9f..04b0d79 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -74,7 +74,7 @@ class JsonDeserializable(object): :return: Dictionary parsed from json or original dict """ if util.is_dict(json_type): - return json_type.copy() + return json_type.copy() if dict_copy else json_type elif util.is_string(json_type): return json.loads(json_type) else: @@ -302,6 +302,8 @@ class Message(JsonDeserializable): chat = Chat.de_json(obj['chat']) content_type = None opts = {} + if 'sender_chat' in obj: + opts['sender_chat'] = Chat.de_json(obj['sender_chat']) if 'forward_from' in obj: opts['forward_from'] = User.de_json(obj['forward_from']) if 'forward_from_chat' in obj: @@ -478,6 +480,7 @@ class Message(JsonDeserializable): self.from_user: User = from_user self.date: int = date self.chat: Chat = chat + self.sender_chat: Optional[Chat] = None self.forward_from: Optional[User] = None self.forward_from_chat: Optional[Chat] = None self.forward_from_message_id: Optional[int] = None @@ -969,9 +972,17 @@ class ReplyKeyboardMarkup(JsonSerializable): return json.dumps(json_dict) +class KeyboardButtonPollType(Dictionaryable): + def __init__(self, type=''): + self.type: str = type + + def to_dict(self): + return {'type': self.type} + + class KeyboardButton(Dictionaryable, JsonSerializable): def __init__(self, text: str, request_contact: Optional[bool]=None, - request_location: Optional[bool]=None, request_poll: Optional[bool]=None): + request_location: Optional[bool]=None, request_poll: Optional[KeyboardButtonPollType]=None): self.text: str = text self.request_contact: bool = request_contact self.request_location: bool = request_location @@ -991,14 +1002,6 @@ class KeyboardButton(Dictionaryable, JsonSerializable): return json_dict -class KeyboardButtonPollType(Dictionaryable): - def __init__(self, type=''): - self.type: str = type - - def to_dict(self): - return {'type': self.type} - - class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable): max_row_keys = 8 @@ -1007,7 +1010,7 @@ class InlineKeyboardMarkup(Dictionaryable, JsonSerializable, JsonDeserializable) if json_string is None: return None obj = cls.check_json(json_string, dict_copy=False) keyboard = [[InlineKeyboardButton.de_json(button) for button in row] for row in obj['inline_keyboard']] - return cls(keyboard) + return cls(keyboard = keyboard) def __init__(self, keyboard=None, row_width=3): """ @@ -1598,9 +1601,45 @@ class ChosenInlineResult(JsonDeserializable): self.query: str = query -class InlineQueryResultArticle(JsonSerializable): - 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): +class InlineQueryResultBase(ABC, Dictionaryable, JsonSerializable): + # noinspection PyShadowingBuiltins + def __init__(self, type, id, title = None, caption = None, input_message_content = None, + reply_markup = None, caption_entities = None, parse_mode = None): + self.type = type + self.id = id + self.title = title + self.caption = caption + self.input_message_content = input_message_content + self.reply_markup = reply_markup + self.caption_entities = caption_entities + self.parse_mode = parse_mode + + def to_json(self): + return json.dumps(self.to_dict()) + + def to_dict(self): + json_dict = { + 'type': self.type, + 'id': self.id + } + if self.title: + json_dict['title'] = self.title + if self.caption: + json_dict['caption'] = self.caption + if self.input_message_content: + json_dict['input_message_content'] = self.input_message_content.to_dict() + if self.reply_markup: + json_dict['reply_markup'] = self.reply_markup.to_dict() + if self.caption_entities: + json_dict['caption_entities'] = MessageEntity.to_list_of_dicts(self.caption_entities) + if self.parse_mode: + json_dict['parse_mode'] = self.parse_mode + return json_dict + + +class InlineQueryResultArticle(InlineQueryResultBase): + 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. @@ -1615,11 +1654,7 @@ class InlineQueryResultArticle(JsonSerializable): :param thumb_height: Thumbnail height :return: """ - self.type = 'article' - self.id = id - self.title = title - self.input_message_content = input_message_content - self.reply_markup = reply_markup + super().__init__('article', id, title = title, input_message_content = input_message_content, reply_markup = reply_markup) self.url = url self.hide_url = hide_url self.description = description @@ -1627,14 +1662,8 @@ class InlineQueryResultArticle(JsonSerializable): self.thumb_width = thumb_width self.thumb_height = thumb_height - def to_json(self): - json_dict = { - 'type': self.type, - 'id': self.id, - 'title': self.title, - 'input_message_content': self.input_message_content.to_dict()} - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() + def to_dict(self): + json_dict = super().to_dict() if self.url: json_dict['url'] = self.url if self.hide_url: @@ -1647,12 +1676,12 @@ class InlineQueryResultArticle(JsonSerializable): json_dict['thumb_width'] = self.thumb_width if self.thumb_height: json_dict['thumb_height'] = self.thumb_height - return json.dumps(json_dict) + return json_dict -class InlineQueryResultPhoto(JsonSerializable): +class InlineQueryResultPhoto(InlineQueryResultBase): def __init__(self, id, photo_url, thumb_url, photo_width=None, photo_height=None, title=None, - description=None, caption=None, parse_mode=None, reply_markup=None, input_message_content=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 @@ -1669,43 +1698,32 @@ class InlineQueryResultPhoto(JsonSerializable): :param input_message_content: InputMessageContent : Content of the message to be sent instead of the photo :return: """ - self.type = 'photo' - self.id = id + 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) self.photo_url = photo_url + self.thumb_url = thumb_url self.photo_width = photo_width self.photo_height = photo_height - self.thumb_url = thumb_url - self.title = title self.description = description - self.caption = caption - self.parse_mode = parse_mode - self.reply_markup = reply_markup - self.input_message_content = input_message_content - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'photo_url': self.photo_url, 'thumb_url': self.thumb_url} + def to_dict(self): + json_dict = super().to_dict() + json_dict['photo_url'] = self.photo_url + json_dict['thumb_url'] = self.thumb_url if self.photo_width: json_dict['photo_width'] = self.photo_width if self.photo_height: json_dict['photo_height'] = self.photo_height - if self.title: - json_dict['title'] = self.title if self.description: json_dict['description'] = self.description - if self.caption: - json_dict['caption'] = self.caption - if self.parse_mode: - json_dict['parse_mode'] = self.parse_mode - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() - return json.dumps(json_dict) + return json_dict -class InlineQueryResultGif(JsonSerializable): - def __init__(self, id, gif_url, thumb_url, gif_width=None, gif_height=None, title=None, caption=None, - reply_markup=None, input_message_content=None, gif_duration=None): +class InlineQueryResultGif(InlineQueryResultBase): + 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): """ Represents a link to an animated GIF file. :param id: Unique identifier for this result, 1-64 bytes. @@ -1719,39 +1737,31 @@ class InlineQueryResultGif(JsonSerializable): :param input_message_content: InputMessageContent : Content of the message to be sent instead of the photo :return: """ - self.type = 'gif' - self.id = id + 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) self.gif_url = gif_url self.gif_width = gif_width self.gif_height = gif_height self.thumb_url = thumb_url - self.title = title - self.caption = caption - self.reply_markup = reply_markup - self.input_message_content = input_message_content self.gif_duration = gif_duration - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'gif_url': self.gif_url, 'thumb_url': self.thumb_url} - if self.gif_height: - json_dict['gif_height'] = self.gif_height + def to_dict(self): + json_dict = super().to_dict() + json_dict['gif_url'] = self.gif_url if self.gif_width: json_dict['gif_width'] = self.gif_width - if self.title: - json_dict['title'] = self.title - if self.caption: - json_dict['caption'] = self.caption - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() + if self.gif_height: + json_dict['gif_height'] = self.gif_height + json_dict['thumb_url'] = self.thumb_url if self.gif_duration: json_dict['gif_duration'] = self.gif_duration - return json.dumps(json_dict) + return json_dict -class InlineQueryResultMpeg4Gif(JsonSerializable): - def __init__(self, id, mpeg4_url, thumb_url, mpeg4_width=None, mpeg4_height=None, title=None, caption=None, +class InlineQueryResultMpeg4Gif(InlineQueryResultBase): + 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): """ Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). @@ -1768,43 +1778,32 @@ class InlineQueryResultMpeg4Gif(JsonSerializable): :param input_message_content: InputMessageContent : Content of the message to be sent instead of the photo :return: """ - self.type = 'mpeg4_gif' - self.id = id + 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) self.mpeg4_url = mpeg4_url self.mpeg4_width = mpeg4_width self.mpeg4_height = mpeg4_height self.thumb_url = thumb_url - self.title = title - self.caption = caption - self.parse_mode = parse_mode - self.reply_markup = reply_markup - self.input_message_content = input_message_content self.mpeg4_duration = mpeg4_duration - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'mpeg4_url': self.mpeg4_url, 'thumb_url': self.thumb_url} + def to_dict(self): + json_dict = super().to_dict() + json_dict['mpeg4_url'] = self.mpeg4_url if self.mpeg4_width: json_dict['mpeg4_width'] = self.mpeg4_width if self.mpeg4_height: json_dict['mpeg4_height'] = self.mpeg4_height - if self.title: - json_dict['title'] = self.title - if self.caption: - json_dict['caption'] = self.caption - if self.parse_mode: - json_dict['parse_mode'] = self.parse_mode - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() + json_dict['thumb_url'] = self.thumb_url if self.mpeg4_duration: json_dict['mpeg4_duration '] = self.mpeg4_duration - return json.dumps(json_dict) + return json_dict -class InlineQueryResultVideo(JsonSerializable): - def __init__(self, id, video_url, mime_type, thumb_url, title, - caption=None, parse_mode=None, video_width=None, video_height=None, video_duration=None, +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. @@ -1821,129 +1820,87 @@ class InlineQueryResultVideo(JsonSerializable): :param description: Short description of the result :return: """ - self.type = 'video' - self.id = id + 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 self.video_duration = video_duration - self.thumb_url = thumb_url - self.title = title - self.caption = caption - self.parse_mode = parse_mode self.description = description - self.input_message_content = input_message_content - self.reply_markup = reply_markup - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'video_url': self.video_url, 'mime_type': self.mime_type, - 'thumb_url': self.thumb_url, 'title': self.title} - if self.video_width: - json_dict['video_width'] = self.video_width + def to_dict(self): + json_dict = super().to_dict() + json_dict['video_url'] = self.video_url + json_dict['mime_type'] = self.mime_type + json_dict['thumb_url'] = self.thumb_url if self.video_height: json_dict['video_height'] = self.video_height if self.video_duration: json_dict['video_duration'] = self.video_duration if self.description: json_dict['description'] = self.description - if self.caption: - json_dict['caption'] = self.caption - if self.parse_mode: - json_dict['parse_mode'] = self.parse_mode - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() - return json.dumps(json_dict) + return json_dict -class InlineQueryResultAudio(JsonSerializable): - def __init__(self, id, audio_url, title, caption=None, parse_mode=None, performer=None, audio_duration=None, - reply_markup=None, input_message_content=None): - self.type = 'audio' - self.id = id +class InlineQueryResultAudio(InlineQueryResultBase): + 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): + super().__init__('audio', id, title = title, caption = caption, + input_message_content = input_message_content, reply_markup = reply_markup, + parse_mode = parse_mode, caption_entities = caption_entities) self.audio_url = audio_url - self.title = title - self.caption = caption - self.parse_mode = parse_mode self.performer = performer self.audio_duration = audio_duration - self.reply_markup = reply_markup - self.input_message_content = input_message_content - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'audio_url': self.audio_url, 'title': self.title} - if self.caption: - json_dict['caption'] = self.caption - if self.parse_mode: - json_dict['parse_mode'] = self.parse_mode + def to_dict(self): + json_dict = super().to_dict() + json_dict['audio_url'] = self.audio_url if self.performer: json_dict['performer'] = self.performer if self.audio_duration: json_dict['audio_duration'] = self.audio_duration - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() - return json.dumps(json_dict) + return json_dict -class InlineQueryResultVoice(JsonSerializable): - def __init__(self, id, voice_url, title, caption=None, parse_mode=None, performer=None, voice_duration=None, - reply_markup=None, input_message_content=None): - self.type = 'voice' - self.id = id +class InlineQueryResultVoice(InlineQueryResultBase): + 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, + input_message_content = input_message_content, reply_markup = reply_markup, + parse_mode = parse_mode, caption_entities = caption_entities) self.voice_url = voice_url - self.title = title - self.caption = caption - self.parse_mode = parse_mode - self.performer = performer self.voice_duration = voice_duration - self.reply_markup = reply_markup - self.input_message_content = input_message_content - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'voice_url': self.voice_url, 'title': self.title} - if self.caption: - json_dict['caption'] = self.caption - if self.parse_mode: - json_dict['parse_mode'] = self.parse_mode - if self.performer: - json_dict['performer'] = self.performer + def to_dict(self): + json_dict = super().to_dict() + json_dict['voice_url'] = self.voice_url if self.voice_duration: json_dict['voice_duration'] = self.voice_duration - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() - return json.dumps(json_dict) + return json_dict -class InlineQueryResultDocument(JsonSerializable): - def __init__(self, id, title, document_url, mime_type, caption=None, parse_mode=None, description=None, - reply_markup=None, input_message_content=None, thumb_url=None, thumb_width=None, thumb_height=None): - self.type = 'document' - self.id = id - self.title = title +class InlineQueryResultDocument(InlineQueryResultBase): + 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): + super().__init__('document', id, title = title, caption = caption, + input_message_content = input_message_content, reply_markup = reply_markup, + parse_mode = parse_mode, caption_entities = caption_entities) self.document_url = document_url self.mime_type = mime_type - self.caption = caption - self.parse_mode = parse_mode self.description = description - self.reply_markup = reply_markup - self.input_message_content = input_message_content self.thumb_url = thumb_url self.thumb_width = thumb_width self.thumb_height = thumb_height - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'title': self.title, 'document_url': self.document_url, - 'mime_type': self.mime_type} - if self.caption: - json_dict['caption'] = self.caption - if self.parse_mode: - json_dict['parse_mode'] = self.parse_mode + def to_dict(self): + json_dict = super().to_dict() + json_dict['document_url'] = self.document_url + json_dict['mime_type'] = self.mime_type if self.description: json_dict['description'] = self.description if self.thumb_url: @@ -1952,129 +1909,127 @@ class InlineQueryResultDocument(JsonSerializable): json_dict['thumb_width'] = self.thumb_width if self.thumb_height: json_dict['thumb_height'] = self.thumb_height - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() - return json.dumps(json_dict) + return json_dict -class InlineQueryResultLocation(JsonSerializable): +class InlineQueryResultLocation(InlineQueryResultBase): 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): - self.type = 'location' - self.id = id - self.title = title + 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, + input_message_content = input_message_content, reply_markup = reply_markup) self.latitude = latitude self.longitude = longitude self.horizontal_accuracy = horizontal_accuracy self.live_period = live_period - self.reply_markup = reply_markup - self.input_message_content = input_message_content + self.heading: int = heading + self.proximity_alert_radius: int = proximity_alert_radius self.thumb_url = thumb_url self.thumb_width = thumb_width self.thumb_height = thumb_height - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'latitude': self.latitude, 'longitude': self.longitude, - 'title': self.title} + def to_dict(self): + json_dict = super().to_dict() + json_dict['latitude'] = self.latitude + json_dict['longitude'] = self.longitude if self.horizontal_accuracy: json_dict['horizontal_accuracy'] = self.horizontal_accuracy if self.live_period: json_dict['live_period'] = self.live_period + if self.heading: + json_dict['heading'] = self.heading + if self.proximity_alert_radius: + json_dict['proximity_alert_radius'] = self.proximity_alert_radius if self.thumb_url: json_dict['thumb_url'] = self.thumb_url if self.thumb_width: json_dict['thumb_width'] = self.thumb_width if self.thumb_height: json_dict['thumb_height'] = self.thumb_height - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() - return json.dumps(json_dict) + return json_dict -class InlineQueryResultVenue(JsonSerializable): +class InlineQueryResultVenue(InlineQueryResultBase): 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): - self.type = 'venue' - self.id = id - self.title = title + super().__init__('venue', id, title = title, + input_message_content = input_message_content, reply_markup = reply_markup) self.latitude = latitude self.longitude = longitude self.address = address self.foursquare_id = foursquare_id self.foursquare_type = foursquare_type - self.reply_markup = reply_markup - self.input_message_content = input_message_content + self.google_place_id = google_place_id + self.google_place_type = google_place_type self.thumb_url = thumb_url self.thumb_width = thumb_width self.thumb_height = thumb_height - self.google_place_id = google_place_id - self.google_place_type = google_place_type - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'title': self.title, 'latitude': self.latitude, - 'longitude': self.longitude, 'address': self.address} + def to_dict(self): + json_dict = super().to_dict() + json_dict['latitude'] = self.latitude + json_dict['longitude'] = self.longitude + json_dict['address'] = self.address if self.foursquare_id: json_dict['foursquare_id'] = self.foursquare_id if self.foursquare_type: json_dict['foursquare_type'] = self.foursquare_type - if self.thumb_url: - json_dict['thumb_url'] = self.thumb_url - if self.thumb_width: - json_dict['thumb_width'] = self.thumb_width - if self.thumb_height: - json_dict['thumb_height'] = self.thumb_height - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() if self.google_place_id: json_dict['google_place_id'] = self.google_place_id if self.google_place_type: json_dict['google_place_type'] = self.google_place_type - return json.dumps(json_dict) - - -class InlineQueryResultContact(JsonSerializable): - 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): - self.type = 'contact' - self.id = id - self.phone_number = phone_number - self.first_name = first_name - self.last_name = last_name - self.vcard = vcard - self.reply_markup = reply_markup - self.input_message_content = input_message_content - self.thumb_url = thumb_url - self.thumb_width = thumb_width - self.thumb_height = thumb_height - - def to_json(self): - json_dict = {'type': self.type, 'id': self.id, 'phone_number': self.phone_number, 'first_name': self.first_name} - if self.last_name: - json_dict['last_name'] = self.last_name - if self.vcard: - json_dict['vcard'] = self.vcard - if self.reply_markup: - json_dict['reply_markup'] = self.reply_markup.to_dict() - if self.input_message_content: - json_dict['input_message_content'] = self.input_message_content.to_dict() if self.thumb_url: json_dict['thumb_url'] = self.thumb_url if self.thumb_width: json_dict['thumb_width'] = self.thumb_width if self.thumb_height: json_dict['thumb_height'] = self.thumb_height - return json.dumps(json_dict) + return json_dict -class BaseInlineQueryResultCached(JsonSerializable): +class InlineQueryResultContact(InlineQueryResultBase): + 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): + super().__init__('contact', id, + input_message_content = input_message_content, reply_markup = reply_markup) + self.phone_number = phone_number + self.first_name = first_name + self.last_name = last_name + self.vcard = vcard + self.thumb_url = thumb_url + self.thumb_width = thumb_width + self.thumb_height = thumb_height + + def to_dict(self): + json_dict = super().to_dict() + json_dict['phone_number'] = self.phone_number + json_dict['first_name'] = self.first_name + if self.last_name: + json_dict['last_name'] = self.last_name + if self.vcard: + json_dict['vcard'] = self.vcard + if self.thumb_url: + json_dict['thumb_url'] = self.thumb_url + if self.thumb_width: + json_dict['thumb_width'] = self.thumb_width + if self.thumb_height: + json_dict['thumb_height'] = self.thumb_height + return json_dict + + +class InlineQueryResultGame(InlineQueryResultBase): + 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 + + def to_dict(self): + json_dict = super().to_dict() + json_dict['game_short_name'] = self.game_short_name + return json_dict + + +class InlineQueryResultCachedBase(ABC, JsonSerializable): def __init__(self): self.type = None self.id = None @@ -2084,6 +2039,7 @@ class BaseInlineQueryResultCached(JsonSerializable): self.reply_markup = None self.input_message_content = None self.parse_mode = None + self.caption_entities = None self.payload_dic = {} def to_json(self): @@ -2102,60 +2058,68 @@ class BaseInlineQueryResultCached(JsonSerializable): json_dict['input_message_content'] = self.input_message_content.to_dict() if self.parse_mode: json_dict['parse_mode'] = self.parse_mode + if self.caption_entities: + json_dict['caption_entities'] = MessageEntity.to_list_of_dicts(self.caption_entities) return json.dumps(json_dict) -class InlineQueryResultCachedPhoto(BaseInlineQueryResultCached): - def __init__(self, id, photo_file_id, title=None, description=None, caption=None, parse_mode=None, +class InlineQueryResultCachedPhoto(InlineQueryResultCachedBase): + 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): - BaseInlineQueryResultCached.__init__(self) + InlineQueryResultCachedBase.__init__(self) self.type = 'photo' self.id = id self.photo_file_id = photo_file_id self.title = title self.description = description self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode self.payload_dic['photo_file_id'] = photo_file_id -class InlineQueryResultCachedGif(BaseInlineQueryResultCached): - def __init__(self, id, gif_file_id, title=None, description=None, caption=None, parse_mode=None, reply_markup=None, - input_message_content=None): - BaseInlineQueryResultCached.__init__(self) +class InlineQueryResultCachedGif(InlineQueryResultCachedBase): + 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): + InlineQueryResultCachedBase.__init__(self) self.type = 'gif' self.id = id self.gif_file_id = gif_file_id self.title = title self.description = description self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode self.payload_dic['gif_file_id'] = gif_file_id -class InlineQueryResultCachedMpeg4Gif(BaseInlineQueryResultCached): - def __init__(self, id, mpeg4_file_id, title=None, description=None, caption=None, parse_mode=None, +class InlineQueryResultCachedMpeg4Gif(InlineQueryResultCachedBase): + 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): - BaseInlineQueryResultCached.__init__(self) + InlineQueryResultCachedBase.__init__(self) self.type = 'mpeg4_gif' self.id = id self.mpeg4_file_id = mpeg4_file_id self.title = title self.description = description self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode self.payload_dic['mpeg4_file_id'] = mpeg4_file_id -class InlineQueryResultCachedSticker(BaseInlineQueryResultCached): +class InlineQueryResultCachedSticker(InlineQueryResultCachedBase): def __init__(self, id, sticker_file_id, reply_markup=None, input_message_content=None): - BaseInlineQueryResultCached.__init__(self) + InlineQueryResultCachedBase.__init__(self) self.type = 'sticker' self.id = id self.sticker_file_id = sticker_file_id @@ -2164,60 +2128,68 @@ class InlineQueryResultCachedSticker(BaseInlineQueryResultCached): self.payload_dic['sticker_file_id'] = sticker_file_id -class InlineQueryResultCachedDocument(BaseInlineQueryResultCached): - def __init__(self, id, document_file_id, title, description=None, caption=None, parse_mode=None, reply_markup=None, - input_message_content=None): - BaseInlineQueryResultCached.__init__(self) +class InlineQueryResultCachedDocument(InlineQueryResultCachedBase): + 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): + InlineQueryResultCachedBase.__init__(self) self.type = 'document' self.id = id self.document_file_id = document_file_id self.title = title self.description = description self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode self.payload_dic['document_file_id'] = document_file_id -class InlineQueryResultCachedVideo(BaseInlineQueryResultCached): - def __init__(self, id, video_file_id, title, description=None, caption=None, parse_mode=None, reply_markup=None, +class InlineQueryResultCachedVideo(InlineQueryResultCachedBase): + def __init__(self, id, video_file_id, title, description=None, + caption=None, caption_entities = None, parse_mode=None, + reply_markup=None, input_message_content=None): - BaseInlineQueryResultCached.__init__(self) + InlineQueryResultCachedBase.__init__(self) self.type = 'video' self.id = id self.video_file_id = video_file_id self.title = title self.description = description self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode self.payload_dic['video_file_id'] = video_file_id -class InlineQueryResultCachedVoice(BaseInlineQueryResultCached): - def __init__(self, id, voice_file_id, title, caption=None, parse_mode=None, reply_markup=None, - input_message_content=None): - BaseInlineQueryResultCached.__init__(self) +class InlineQueryResultCachedVoice(InlineQueryResultCachedBase): + 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) self.type = 'voice' self.id = id self.voice_file_id = voice_file_id self.title = title self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode self.payload_dic['voice_file_id'] = voice_file_id -class InlineQueryResultCachedAudio(BaseInlineQueryResultCached): - def __init__(self, id, audio_file_id, caption=None, parse_mode=None, reply_markup=None, input_message_content=None): - BaseInlineQueryResultCached.__init__(self) +class InlineQueryResultCachedAudio(InlineQueryResultCachedBase): + 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) self.type = 'audio' self.id = id self.audio_file_id = audio_file_id self.caption = caption + self.caption_entities = caption_entities self.reply_markup = reply_markup self.input_message_content = input_message_content self.parse_mode = parse_mode @@ -2226,20 +2198,6 @@ class InlineQueryResultCachedAudio(BaseInlineQueryResultCached): # Games -class InlineQueryResultGame(JsonSerializable): - def __init__(self, id, game_short_name, reply_markup=None): - self.type = 'game' - self.id = id - self.game_short_name = game_short_name - self.reply_markup = reply_markup - - def to_json(self): - json_dic = {'type': self.type, 'id': self.id, 'game_short_name': self.game_short_name} - if self.reply_markup: - json_dic['reply_markup'] = self.reply_markup.to_dict() - return json.dumps(json_dic) - - class Game(JsonDeserializable): @classmethod def de_json(cls, json_string): @@ -2553,7 +2511,7 @@ class InputMedia(Dictionaryable, JsonSerializable): if self.parse_mode: json_dict['parse_mode'] = self.parse_mode if self.caption_entities: - json_dict['caption_entities'] = [MessageEntity.to_dict(entity) for entity in self.caption_entities] + json_dict['caption_entities'] = MessageEntity.to_list_of_dicts(self.caption_entities) return json_dict def convert_input_media(self): @@ -2817,9 +2775,9 @@ class VoiceChatScheduled(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string, dict_copy=False) - return cls(obj['start_date']) + return cls(**obj) - def __init__(self, start_date): + def __init__(self, start_date, **kwargs): self.start_date: int = start_date @@ -2828,9 +2786,9 @@ class VoiceChatEnded(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string, dict_copy=False) - return cls(obj['duration']) + return cls(**obj) - def __init__(self, duration): + def __init__(self, duration, **kwargs): self.duration: int = duration @@ -2839,12 +2797,11 @@ class VoiceChatParticipantsInvited(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string) - users = None if 'users' in obj: - users = [User.de_json(u) for u in obj['users']] - return cls(users) + obj['users'] = [User.de_json(u) for u in obj['users']] + return cls(**obj) - def __init__(self, users=None): + def __init__(self, users=None, **kwargs): self.users: List[User] = users @@ -2853,7 +2810,7 @@ class MessageAutoDeleteTimerChanged(JsonDeserializable): def de_json(cls, json_string): if json_string is None: return None obj = cls.check_json(json_string, dict_copy=False) - return cls(obj['message_auto_delete_time']) + return cls(**obj) - def __init__(self, message_auto_delete_time): + def __init__(self, message_auto_delete_time, **kwargs): self.message_auto_delete_time = message_auto_delete_time From b2b7d90888f260a8e8000fda058bdf221441d017 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 19:32:43 +0300 Subject: [PATCH 213/350] API update fix 01 --- telebot/types.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 04b0d79..ec9635e 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -1723,7 +1723,8 @@ class InlineQueryResultPhoto(InlineQueryResultBase): class InlineQueryResultGif(InlineQueryResultBase): 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): + 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. @@ -1745,6 +1746,7 @@ class InlineQueryResultGif(InlineQueryResultBase): self.gif_height = gif_height self.thumb_url = thumb_url self.gif_duration = gif_duration + self.thumb_mime_type = thumb_mime_type def to_dict(self): json_dict = super().to_dict() @@ -1756,13 +1758,16 @@ class InlineQueryResultGif(InlineQueryResultBase): json_dict['thumb_url'] = self.thumb_url if self.gif_duration: json_dict['gif_duration'] = self.gif_duration + if self.thumb_mime_type: + json_dict['thumb_mime_type'] = self.thumb_mime_type return json_dict class InlineQueryResultMpeg4Gif(InlineQueryResultBase): 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): + 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 @@ -1786,6 +1791,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResultBase): self.mpeg4_height = mpeg4_height self.thumb_url = thumb_url self.mpeg4_duration = mpeg4_duration + self.thumb_mime_type = thumb_mime_type def to_dict(self): json_dict = super().to_dict() @@ -1797,6 +1803,8 @@ class InlineQueryResultMpeg4Gif(InlineQueryResultBase): json_dict['thumb_url'] = self.thumb_url if self.mpeg4_duration: json_dict['mpeg4_duration '] = self.mpeg4_duration + if self.thumb_mime_type: + json_dict['thumb_mime_type'] = self.thumb_mime_type return json_dict From 8053183cb5e5d72172295857d494ab4b98f53c6a Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 19:36:48 +0300 Subject: [PATCH 214/350] API update fix 02 --- telebot/__init__.py | 6 +++--- telebot/apihelper.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 88d6fc7..35cad2b 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2047,7 +2047,7 @@ class TeleBot: open_period: Optional[int]=None, close_date: Optional[Union[int, datetime]]=None, is_closed: Optional[bool]=None, - disable_notifications: Optional[bool]=False, + disable_notification: Optional[bool]=False, reply_to_message_id: Optional[int]=None, reply_markup: Optional[REPLY_MARKUP_TYPES]=None, allow_sending_without_reply: Optional[bool]=None, @@ -2067,7 +2067,7 @@ class TeleBot: :param open_period: :param close_date: :param is_closed: - :param disable_notifications: + :param disable_notification: :param reply_to_message_id: :param allow_sending_without_reply: :param reply_markup: @@ -2085,7 +2085,7 @@ class TeleBot: question, options, is_anonymous, type, allows_multiple_answers, correct_option_id, explanation, explanation_parse_mode, open_period, close_date, is_closed, - disable_notifications, reply_to_message_id, allow_sending_without_reply, + disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, timeout, explanation_entities)) def stop_poll( diff --git a/telebot/apihelper.py b/telebot/apihelper.py index a3ef5c2..4b19f24 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1485,7 +1485,7 @@ def send_poll( question, options, is_anonymous = None, type = None, allows_multiple_answers = None, correct_option_id = None, explanation = None, explanation_parse_mode=None, open_period = None, close_date = None, is_closed = None, - disable_notifications=False, reply_to_message_id=None, allow_sending_without_reply=None, + disable_notification=False, reply_to_message_id=None, allow_sending_without_reply=None, reply_markup=None, timeout=None, explanation_entities=None): method_url = r'sendPoll' payload = { @@ -1515,8 +1515,8 @@ def send_poll( if is_closed is not None: payload['is_closed'] = is_closed - if disable_notifications: - payload['disable_notification'] = disable_notifications + if disable_notification: + payload['disable_notification'] = disable_notification if reply_to_message_id is not None: payload['reply_to_message_id'] = reply_to_message_id if allow_sending_without_reply is not None: From fabcd93dd7a197ce3fcbd0ce08b16d30d0f50fbb Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 21:57:56 +0300 Subject: [PATCH 215/350] API update fix 03 --- telebot/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/types.py b/telebot/types.py index ec9635e..dfcfb8f 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -273,7 +273,7 @@ class Chat(JsonDeserializable): self.pinned_message: Message = pinned_message self.permissions: ChatPermissions = permissions self.slow_mode_delay: int = slow_mode_delay - self.message_auto_delete_time = message_auto_delete_time + self.message_auto_delete_time: int = message_auto_delete_time self.sticker_set_name: str = sticker_set_name self.can_set_sticker_set: bool = can_set_sticker_set self.linked_chat_id: int = linked_chat_id From 022ef6a64cf4a0ef957a35ee6932fa4866de567d Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 22:16:30 +0300 Subject: [PATCH 216/350] Dependecies clearing --- requirements.txt | 1 - setup.py | 1 + telebot/__init__.py | 1 - telebot/util.py | 4 ++-- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index cf92363..3a014e7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ -py==1.10.0 pytest==3.0.2 requests==2.20.0 wheel==0.24.0 diff --git a/setup.py b/setup.py index b3e8158..7b62776 100644 --- a/setup.py +++ b/setup.py @@ -25,6 +25,7 @@ setup(name='pyTelegramBotAPI', install_requires=['requests'], extras_require={ 'json': 'ujson', + 'PIL': 'Pillow', 'redis': 'redis>=3.4.1' }, classifiers=[ diff --git a/telebot/__init__.py b/telebot/__init__.py index 35cad2b..57ed008 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import print_function from datetime import datetime import logging diff --git a/telebot/util.py b/telebot/util.py index 34d08ed..d0a58b0 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -4,16 +4,16 @@ import re import string import threading import traceback -import warnings -import functools from typing import Any, Callable, List, Dict, Optional, Union +# noinspection PyPep8Naming import queue as Queue import logging from telebot import types try: + # noinspection PyPackageRequirements from PIL import Image from io import BytesIO pil_imported = True From 2bc052ad5a4a0d716e33ab36d32b7e94975dcf55 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 23:27:28 +0300 Subject: [PATCH 217/350] Check and update for full compatibility to Bot API up to 5.3 Pre-release of 4.0.0 --- README.md | 24 ++++++++++++++---------- telebot/__init__.py | 2 +- telebot/apihelper.py | 15 +++++++++------ telebot/types.py | 42 ++++++++++++++++++++++++++++++++++-------- telebot/version.py | 2 +- 5 files changed, 59 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 76fe327..93e188c 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,17 @@ -#

pyTelegramBotAPI - -

A simple, but extensible Python implementation for the Telegram Bot API. [![PyPi Package Version](https://img.shields.io/pypi/v/pyTelegramBotAPI.svg)](https://pypi.python.org/pypi/pyTelegramBotAPI) [![Supported Python versions](https://img.shields.io/pypi/pyversions/pyTelegramBotAPI.svg)](https://pypi.python.org/pypi/pyTelegramBotAPI) [![Build Status](https://travis-ci.org/eternnoir/pyTelegramBotAPI.svg?branch=master)](https://travis-ci.org/eternnoir/pyTelegramBotAPI) [![PyPi downloads](https://img.shields.io/pypi/dm/pyTelegramBotAPI.svg)](https://pypi.org/project/pyTelegramBotAPI/) +#

pyTelegramBotAPI

+ +

A simple, but extensible Python implementation for the Telegram Bot API.

+ +##

Supported Bot API version: 5.3!

+ +##Contents + * [Getting started.](#getting-started) * [Writing your first bot](#writing-your-first-bot) * [Prerequisites](#prerequisites) @@ -603,21 +608,20 @@ apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'} ## API conformance -_Checking is in progress..._ - -✅ [Bot API 5.1](https://core.telegram.org/bots/api#march-9-2021) _- To be checked..._ - +* ➕ [Bot API 5.3](https://core.telegram.org/bots/api#june-25-2021) - ChatMemberXXX classes are full copies of ChatMember +* ✔ [Bot API 5.2](https://core.telegram.org/bots/api#april-26-2021) +* ✔ [Bot API 5.1](https://core.telegram.org/bots/api#march-9-2021) * ✔ [Bot API 5.0](https://core.telegram.org/bots/api-changelog#november-4-2020) * ✔ [Bot API 4.9](https://core.telegram.org/bots/api-changelog#june-4-2020) * ✔ [Bot API 4.8](https://core.telegram.org/bots/api-changelog#april-24-2020) * ✔ [Bot API 4.7](https://core.telegram.org/bots/api-changelog#march-30-2020) * ✔ [Bot API 4.6](https://core.telegram.org/bots/api-changelog#january-23-2020) -* ➕ [Bot API 4.5](https://core.telegram.org/bots/api-changelog#december-31-2019) - No nested MessageEntities and Markdown2 support. +* ➕ [Bot API 4.5](https://core.telegram.org/bots/api-changelog#december-31-2019) - No nested MessageEntities and Markdown2 support * ✔ [Bot API 4.4](https://core.telegram.org/bots/api-changelog#july-29-2019) * ✔ [Bot API 4.3](https://core.telegram.org/bots/api-changelog#may-31-2019) * ✔ [Bot API 4.2](https://core.telegram.org/bots/api-changelog#april-14-2019) -* ➕ [Bot API 4.1](https://core.telegram.org/bots/api-changelog#august-27-2018) - No Passport support. -* ➕ [Bot API 4.0](https://core.telegram.org/bots/api-changelog#july-26-2018) - No Passport support. +* ➕ [Bot API 4.1](https://core.telegram.org/bots/api-changelog#august-27-2018) - No Passport support +* ➕ [Bot API 4.0](https://core.telegram.org/bots/api-changelog#july-26-2018) - No Passport support * ✔ [Bot API 3.6](https://core.telegram.org/bots/api-changelog#february-13-2018) * ✔ [Bot API 3.5](https://core.telegram.org/bots/api-changelog#november-17-2017) * ✔ [Bot API 3.4](https://core.telegram.org/bots/api-changelog#october-11-2017) diff --git a/telebot/__init__.py b/telebot/__init__.py index 57ed008..e9aaff6 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1985,7 +1985,7 @@ class TeleBot: timeout: Optional[int]=None, allow_sending_without_reply: Optional[bool]=None, max_tip_amount: Optional[int] = None, - suggested_tip_amounts: Optional[list]=None) -> types.Message: + suggested_tip_amounts: Optional[List[int]]=None) -> types.Message: """ Sends invoice :param chat_id: Unique identifier for the target private chat diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 4b19f24..0d3820f 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -973,11 +973,11 @@ def create_chat_invite_link(token, chat_id, expire_date, member_limit): } if expire_date is not None: - payload['expire_date'] = expire_date if isinstance(payload['expire_date'], datetime): payload['expire_date'] = payload['expire_date'].timestamp() - - if member_limit is not None: + else: + payload['expire_date'] = expire_date + if member_limit: payload['member_limit'] = member_limit return _make_request(token, method_url, params=payload, method='post') @@ -991,9 +991,10 @@ def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit } if expire_date is not None: - payload['expire_date'] = expire_date if isinstance(payload['expire_date'], datetime): payload['expire_date'] = payload['expire_date'].timestamp() + else: + payload['expire_date'] = expire_date if member_limit is not None: payload['member_limit'] = member_limit @@ -1258,7 +1259,7 @@ def get_game_high_scores(token, user_id, chat_id=None, message_id=None, inline_m def send_invoice( token, chat_id, title, description, invoice_payload, provider_token, currency, prices, - start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, + start_parameter = None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, @@ -1298,8 +1299,10 @@ def send_invoice( """ method_url = r'sendInvoice' payload = {'chat_id': chat_id, 'title': title, 'description': description, 'payload': invoice_payload, - 'provider_token': provider_token, 'start_parameter': start_parameter, 'currency': currency, + 'provider_token': provider_token, 'currency': currency, 'prices': _convert_list_json_serializable(prices)} + if start_parameter: + payload['start_parameter'] = start_parameter if photo_url: payload['photo_url'] = photo_url if photo_size: diff --git a/telebot/types.py b/telebot/types.py index dfcfb8f..1d8bdc0 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -441,12 +441,10 @@ class Message(JsonDeserializable): opts['voice_chat_ended'] = VoiceChatEnded.de_json(obj['voice_chat_ended']) content_type = 'voice_chat_ended' if 'voice_chat_participants_invited' in obj: - opts['voice_chat_participants_invited'] = VoiceChatParticipantsInvited.de_json( - obj['voice_chat_participants_invited']) + opts['voice_chat_participants_invited'] = VoiceChatParticipantsInvited.de_json(obj['voice_chat_participants_invited']) content_type = 'voice_chat_participants_invited' if 'message_auto_delete_timer_changed' in obj: - opts['message_auto_delete_timer_changed'] = MessageAutoDeleteTimerChanged.de_json( - obj['message_auto_delete_timer_changed']) + opts['message_auto_delete_timer_changed'] = MessageAutoDeleteTimerChanged.de_json(obj['message_auto_delete_timer_changed']) content_type = 'message_auto_delete_timer_changed' if 'reply_markup' in obj: opts['reply_markup'] = InlineKeyboardMarkup.de_json(obj['reply_markup']) @@ -1232,6 +1230,29 @@ class ChatMember(JsonDeserializable): self.until_date: int = until_date +class ChatMemberOwner(ChatMember): + pass + +class ChatMemberAdministrator(ChatMember): + pass + + +class ChatMemberMember(ChatMember): + pass + + +class ChatMemberRestricted(ChatMember): + pass + + +class ChatMemberLeft(ChatMember): + pass + + +class ChatMemberBanned(ChatMember): + pass + + class ChatPermissions(JsonDeserializable, JsonSerializable, Dictionaryable): @classmethod def de_json(cls, json_string): @@ -2744,14 +2765,18 @@ class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): return json.dumps(self.to_dict()) def to_dict(self): - return { + json_dict = { "invite_link": self.invite_link, "creator": self.creator.to_dict(), "is_primary": self.is_primary, - "is_revoked": self.is_revoked, - "expire_date": self.expire_date, - "member_limit": self.member_limit + "is_revoked": self.is_revoked } + if self.expire_date: + json_dict["expire_date"] = self.expire_date + if self.member_limit: + json_dict["member_limit"] = self.member_limit + return json_dict + class ProximityAlertTriggered(JsonDeserializable): @classmethod @@ -2778,6 +2803,7 @@ class VoiceChatStarted(JsonDeserializable): """ pass + class VoiceChatScheduled(JsonDeserializable): @classmethod def de_json(cls, json_string): diff --git a/telebot/version.py b/telebot/version.py index 80f0f16..afeff55 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.8.2' +__version__ = '3.8.3' From f6359bc32c12a49db9a35cbddb1591f393edda90 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 18 Aug 2021 23:29:40 +0300 Subject: [PATCH 218/350] Readme fix --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 93e188c..d1baef7 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,11 @@ [![Build Status](https://travis-ci.org/eternnoir/pyTelegramBotAPI.svg?branch=master)](https://travis-ci.org/eternnoir/pyTelegramBotAPI) [![PyPi downloads](https://img.shields.io/pypi/dm/pyTelegramBotAPI.svg)](https://pypi.org/project/pyTelegramBotAPI/) -#

pyTelegramBotAPI

+#

pyTelegramBotAPI -

A simple, but extensible Python implementation for the Telegram Bot API.

+

A simple, but extensible Python implementation for the Telegram Bot API. -##

Supported Bot API version: 5.3!

+##

Supported Bot API version: 5.3! ##Contents From f5de0eeacfc6cd8244ff1c0446dd875d6f6d49e5 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 19 Aug 2021 22:46:12 +0300 Subject: [PATCH 219/350] Simplify and speedup _test_filter --- README.md | 18 +----------------- telebot/__init__.py | 33 +++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index d1baef7..09e45a7 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ ##

Supported Bot API version: 5.3! -##Contents +## Contents * [Getting started.](#getting-started) * [Writing your first bot](#writing-your-first-bot) @@ -636,23 +636,8 @@ apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'} * ✔ [Bot API 2.0](https://core.telegram.org/bots/api-changelog#april-9-2016) -## Change log - -27.04.2020 - Poll and Dice are up to date. -Python2 conformance is not checked any more due to EOL. - -11.04.2020 - Refactoring. new_chat_member is out of support. Bugfix in html_text. Started Bot API conformance checking. - -06.06.2019 - Added polls support (Poll). Added functions send_poll, stop_poll - ## F.A.Q. -### Bot 2.0 - -April 9,2016 Telegram release new bot 2.0 API, which has a drastic revision especially for the change of method's interface.If you want to update to the latest version, please make sure you've switched bot's code to bot 2.0 method interface. - -[More information about pyTelegramBotAPI support bot2.0](https://github.com/eternnoir/pyTelegramBotAPI/issues/130) - ### How can I distinguish a User and a GroupChat in message.chat? Telegram Bot API support new type Chat for message.chat. @@ -682,7 +667,6 @@ Bot instances that were idle for a long time might be rejected by the server whe Get help. Discuss. Chat. * Join the [pyTelegramBotAPI Telegram Chat Group](https://telegram.me/joinchat/Bn4ixj84FIZVkwhk2jag6A) -* We now have a Telegram Channel as well! Keep yourself up to date with API changes, and [join it](https://telegram.me/pytelegrambotapi). ## More examples diff --git a/telebot/__init__.py b/telebot/__init__.py index e9aaff6..29fabe0 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3040,19 +3040,28 @@ class TeleBot: def _test_filter(message_filter, filter_value, message): """ Test filters - :param message_filter: - :param filter_value: - :param message: - :return: + :param message_filter: Filter type passed in handler + :param filter_value: Filter value passed in handler + :param message: Message to test + :return: True if filter conforms """ - test_cases = { - 'content_types': lambda msg: msg.content_type in filter_value, - 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), - 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, - 'func': lambda msg: filter_value(msg) - } - - return test_cases.get(message_filter, lambda msg: False)(message) + # test_cases = { + # 'content_types': lambda msg: msg.content_type in filter_value, + # 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), + # 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + # 'func': lambda msg: filter_value(msg) + # } + # return test_cases.get(message_filter, lambda msg: False)(message) + if message_filter == 'content_types': + return message.content_type in filter_value + elif message_filter == 'regexp': + return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) + elif message_filter == 'commands': + return message.content_type == 'text' and util.extract_command(message.text) in filter_value + elif message_filter == 'func': + return filter_value(message) + else: + return False def _notify_command_handlers(self, handlers, new_messages): """ From 3efc2cf86902318cf4e37a78f4ce2e0a1ba352cf Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 19 Aug 2021 23:36:37 +0300 Subject: [PATCH 220/350] Typo --- telebot/__init__.py | 64 ++++++++++++++++++--------------------------- 1 file changed, 26 insertions(+), 38 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 29fabe0..49a24ca 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2544,11 +2544,11 @@ class TeleBot: :return: decorated function """ handler_dict = self._build_handler_dict(callback, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) self.add_message_handler(handler_dict) def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ @@ -2595,11 +2595,11 @@ class TeleBot: :return: decorated function """ handler_dict = self._build_handler_dict(callback, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) self.add_edited_message_handler(handler_dict) def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ @@ -2646,11 +2646,11 @@ class TeleBot: :return: decorated function """ handler_dict = self._build_handler_dict(callback, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) self.add_channel_post_handler(handler_dict) def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ @@ -2697,11 +2697,11 @@ class TeleBot: :return: decorated function """ handler_dict = self._build_handler_dict(callback, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) self.add_edited_channel_post_handler(handler_dict) def inline_handler(self, func, **kwargs): @@ -2734,9 +2734,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_inline_handler(handler_dict) def chosen_inline_handler(self, func, **kwargs): @@ -2769,9 +2767,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_chosen_inline_handler(handler_dict) @@ -2805,9 +2801,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_callback_query_handler(handler_dict) def shipping_query_handler(self, func, **kwargs): @@ -2840,9 +2834,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_shipping_query_handler(handler_dict) def pre_checkout_query_handler(self, func, **kwargs): @@ -2875,9 +2867,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_pre_checkout_query_handler(handler_dict) def poll_handler(self, func, **kwargs): @@ -3015,9 +3005,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_chat_member_handler(handler_dict) def _test_message_handler(self, message_handler, message): From bd3a9bc350be88f6b49f3d1fdcd031af9dd4129d Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 22 Aug 2021 22:16:03 +0300 Subject: [PATCH 221/350] chat_invite_link bugfix --- telebot/apihelper.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 0d3820f..6098053 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -973,8 +973,8 @@ def create_chat_invite_link(token, chat_id, expire_date, member_limit): } if expire_date is not None: - if isinstance(payload['expire_date'], datetime): - payload['expire_date'] = payload['expire_date'].timestamp() + if isinstance(expire_date, datetime): + payload['expire_date'] = expire_date.timestamp() else: payload['expire_date'] = expire_date if member_limit: @@ -991,8 +991,8 @@ def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit } if expire_date is not None: - if isinstance(payload['expire_date'], datetime): - payload['expire_date'] = payload['expire_date'].timestamp() + if isinstance(expire_date, datetime): + payload['expire_date'] = expire_date.timestamp() else: payload['expire_date'] = expire_date From 4eb28df1ab4d09e326eb426982f20c9ba5ee3277 Mon Sep 17 00:00:00 2001 From: Florent Gallaire Date: Tue, 24 Aug 2021 13:01:10 +0200 Subject: [PATCH 222/350] A Google Cloud Functions webhook --- telebot/util.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index d0a58b0..8c338c3 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -440,3 +440,18 @@ def deprecated(warn: bool=False, alternative: Optional[Callable]=None): return wrapper return decorator + +# Cloud helpers +def webhook_functions(bot, request): + """A webhook endpoint for Google Cloud Functions FaaS.""" + if request.is_json: + try: + request_json = request.get_json() + update = types.Update.de_json(request_json) + bot.process_new_updates([update]) + return '' + except Exception as e: + print(e) + return 'Bot FAIL', 400 + else: + return 'Bot ON' From b4f0a6d54666b5f2e7740c061ee7a2ac482f529e Mon Sep 17 00:00:00 2001 From: Florent Gallaire Date: Wed, 25 Aug 2021 14:17:25 +0200 Subject: [PATCH 223/350] add Google in the name --- telebot/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/util.py b/telebot/util.py index 8c338c3..535ffb2 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -442,7 +442,7 @@ def deprecated(warn: bool=False, alternative: Optional[Callable]=None): # Cloud helpers -def webhook_functions(bot, request): +def webhook_google_functions(bot, request): """A webhook endpoint for Google Cloud Functions FaaS.""" if request.is_json: try: From d9e638a7df3052c93fe67cd7361d1c415a0ff91e Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 30 Aug 2021 13:49:28 +0300 Subject: [PATCH 224/350] Bump version to 4.0 release --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index afeff55..8676c8d 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '3.8.3' +__version__ = '4.0.0' From 07ebdeab255ce848306a8fc0a8be806038397f23 Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Thu, 2 Sep 2021 19:46:01 +0200 Subject: [PATCH 225/350] Added missing content_type "animation" --- telebot/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/util.py b/telebot/util.py index 535ffb2..f871f09 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -27,7 +27,7 @@ logger = logging.getLogger('TeleBot') thread_local = threading.local() content_type_media = [ - 'text', 'audio', 'document', 'photo', 'sticker', 'video', 'video_note', 'voice', 'contact', 'dice', 'poll', + 'text', 'audio', 'animation', 'document', 'photo', 'sticker', 'video', 'video_note', 'voice', 'contact', 'dice', 'poll', 'venue', 'location' ] From 644c6b90823327242e6951604a9e2f558d612bc2 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Fri, 10 Sep 2021 17:30:17 +0500 Subject: [PATCH 226/350] is_private --- telebot/__init__.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 49a24ca..b596916 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2476,7 +2476,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. @@ -2491,6 +2491,11 @@ class TeleBot: def command_help(message): bot.send_message(message.chat.id, 'Did someone call for help?') + # Handles messages in private chat + @bot.message_handler(is_private=True) + def command_help(message): + 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']) @@ -2508,6 +2513,7 @@ class TeleBot: :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. Defaults to ['text']. + :param is_private: True for private chat """ if content_types is None: @@ -2518,6 +2524,7 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, + is_private=is_private, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2533,7 +2540,7 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, is_private=None, **kwargs): """ Registers message handler. :param callback: function to be called @@ -2541,6 +2548,7 @@ class TeleBot: :param commands: list of commands :param regexp: :param func: + :param is_private: True for private chat :return: decorated function """ handler_dict = self._build_handler_dict(callback, @@ -2548,15 +2556,17 @@ class TeleBot: commands=commands, regexp=regexp, func=func, + is_private=is_private, **kwargs) self.add_message_handler(handler_dict) - def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, **kwargs): """ Edit message handler decorator :param commands: :param regexp: :param func: :param content_types: + :param is_private: True for private chat :param kwargs: :return: """ @@ -2570,6 +2580,7 @@ class TeleBot: regexp=regexp, func=func, content_types=content_types, + is_private=is_private, **kwargs) self.add_edited_message_handler(handler_dict) return handler @@ -2584,7 +2595,7 @@ class TeleBot: """ self.edited_message_handlers.append(handler_dict) - def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, is_private=None, **kwargs): """ Registers edited message handler. :param callback: function to be called @@ -2592,6 +2603,7 @@ class TeleBot: :param commands: list of commands :param regexp: :param func: + :param is_private: True for private chat :return: decorated function """ handler_dict = self._build_handler_dict(callback, @@ -2599,6 +2611,7 @@ class TeleBot: commands=commands, regexp=regexp, func=func, + is_private=is_private, **kwargs) self.add_edited_message_handler(handler_dict) def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): @@ -3046,6 +3059,8 @@ class TeleBot: return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) elif message_filter == 'commands': return message.content_type == 'text' and util.extract_command(message.text) in filter_value + elif message_filter == 'is_private': + return message.chat.type == 'private' elif message_filter == 'func': return filter_value(message) else: From 944b077c65415b7489fc65f1f569e0cb904f800d Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 10 Sep 2021 17:30:58 +0500 Subject: [PATCH 227/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 09e45a7..5c39687 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ TeleBot supports the following filters: |content_types|list of strings (default `['text']`)|`True` if message.content_type is in the list of strings.| |regexp|a regular expression as a string|`True` if `re.search(regexp_arg)` returns `True` and `message.content_type == 'text'` (See [Python Regular Expressions](https://docs.python.org/2/library/re.html))| |commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.| +|is_private|Private chat|`True` if chat is private |func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` Here are some examples of using the filters and message handlers: From 4035a385078648afd3fb576a62c25ac5021b6a6a Mon Sep 17 00:00:00 2001 From: coder2020official Date: Fri, 10 Sep 2021 17:56:44 +0500 Subject: [PATCH 228/350] Update __init__.py --- telebot/__init__.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index b596916..6d5ea25 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2476,7 +2476,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, only_private=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. @@ -2492,7 +2492,7 @@ class TeleBot: bot.send_message(message.chat.id, 'Did someone call for help?') # Handles messages in private chat - @bot.message_handler(is_private=True) + @bot.message_handler(only_private=True) def command_help(message): bot.send_message(message.chat.id, 'Private chat detected, sir!') @@ -2513,7 +2513,7 @@ class TeleBot: :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. Defaults to ['text']. - :param is_private: True for private chat + :param only_private: True for private chat """ if content_types is None: @@ -2524,7 +2524,7 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, - is_private=is_private, + only_private=only_private, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2540,7 +2540,7 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, is_private=None, **kwargs): + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, only_private=None, **kwargs): """ Registers message handler. :param callback: function to be called @@ -2548,7 +2548,7 @@ class TeleBot: :param commands: list of commands :param regexp: :param func: - :param is_private: True for private chat + :param only_private: True for private chat :return: decorated function """ handler_dict = self._build_handler_dict(callback, @@ -2556,17 +2556,17 @@ class TeleBot: commands=commands, regexp=regexp, func=func, - is_private=is_private, + only_private=only_private, **kwargs) self.add_message_handler(handler_dict) - def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, is_private=None, **kwargs): + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, only_private=None, **kwargs): """ Edit message handler decorator :param commands: :param regexp: :param func: :param content_types: - :param is_private: True for private chat + :param only_private: True for private chat :param kwargs: :return: """ @@ -2580,7 +2580,7 @@ class TeleBot: regexp=regexp, func=func, content_types=content_types, - is_private=is_private, + only_private=only_private, **kwargs) self.add_edited_message_handler(handler_dict) return handler @@ -2595,7 +2595,7 @@ class TeleBot: """ self.edited_message_handlers.append(handler_dict) - def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, is_private=None, **kwargs): + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, only_private=None, **kwargs): """ Registers edited message handler. :param callback: function to be called @@ -2603,7 +2603,7 @@ class TeleBot: :param commands: list of commands :param regexp: :param func: - :param is_private: True for private chat + :param only_private: True for private chat :return: decorated function """ handler_dict = self._build_handler_dict(callback, @@ -2611,7 +2611,7 @@ class TeleBot: commands=commands, regexp=regexp, func=func, - is_private=is_private, + only_private=only_private, **kwargs) self.add_edited_message_handler(handler_dict) def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): @@ -3059,7 +3059,7 @@ class TeleBot: return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) elif message_filter == 'commands': return message.content_type == 'text' and util.extract_command(message.text) in filter_value - elif message_filter == 'is_private': + elif message_filter == 'only_private': return message.chat.type == 'private' elif message_filter == 'func': return filter_value(message) From de6f339cdfe27d5564cb813f77d7b4b59cda0166 Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 10 Sep 2021 17:57:19 +0500 Subject: [PATCH 229/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c39687..7fa9801 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,7 @@ TeleBot supports the following filters: |content_types|list of strings (default `['text']`)|`True` if message.content_type is in the list of strings.| |regexp|a regular expression as a string|`True` if `re.search(regexp_arg)` returns `True` and `message.content_type == 'text'` (See [Python Regular Expressions](https://docs.python.org/2/library/re.html))| |commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.| -|is_private|Private chat|`True` if chat is private +|only_private|Private chat|`True` if chat is private |func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` Here are some examples of using the filters and message handlers: From 0f3a6393fc22b9ca675138ec26b75e2b72ecfb53 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Fri, 10 Sep 2021 20:42:43 +0500 Subject: [PATCH 230/350] Update __init__.py --- telebot/__init__.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 6d5ea25..504e515 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2476,7 +2476,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, only_private=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. @@ -2492,7 +2492,7 @@ class TeleBot: bot.send_message(message.chat.id, 'Did someone call for help?') # Handles messages in private chat - @bot.message_handler(only_private=True) + @bot.message_handler(chat_types=['private']) # You can add more chat types def command_help(message): bot.send_message(message.chat.id, 'Private chat detected, sir!') @@ -2513,7 +2513,7 @@ class TeleBot: :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. Defaults to ['text']. - :param only_private: True for private chat + :param chat_types: list of chat types """ if content_types is None: @@ -2524,7 +2524,7 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, - only_private=only_private, + chat_types=chat_types, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2540,7 +2540,7 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, only_private=None, **kwargs): + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): """ Registers message handler. :param callback: function to be called @@ -2548,7 +2548,7 @@ class TeleBot: :param commands: list of commands :param regexp: :param func: - :param only_private: True for private chat + :param chat_types: True for private chat :return: decorated function """ handler_dict = self._build_handler_dict(callback, @@ -2556,17 +2556,17 @@ class TeleBot: commands=commands, regexp=regexp, func=func, - only_private=only_private, + chat_types=chat_types, **kwargs) self.add_message_handler(handler_dict) - def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, only_private=None, **kwargs): + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ Edit message handler decorator :param commands: :param regexp: :param func: :param content_types: - :param only_private: True for private chat + :param chat_types: list of chat types :param kwargs: :return: """ @@ -2580,7 +2580,7 @@ class TeleBot: regexp=regexp, func=func, content_types=content_types, - only_private=only_private, + chat_types=chat_types, **kwargs) self.add_edited_message_handler(handler_dict) return handler @@ -2595,7 +2595,7 @@ class TeleBot: """ self.edited_message_handlers.append(handler_dict) - def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, only_private=None, **kwargs): + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): """ Registers edited message handler. :param callback: function to be called @@ -2603,7 +2603,7 @@ class TeleBot: :param commands: list of commands :param regexp: :param func: - :param only_private: True for private chat + :param chat_types: True for private chat :return: decorated function """ handler_dict = self._build_handler_dict(callback, @@ -2611,7 +2611,7 @@ class TeleBot: commands=commands, regexp=regexp, func=func, - only_private=only_private, + chat_types=chat_types, **kwargs) self.add_edited_message_handler(handler_dict) def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): @@ -3059,8 +3059,8 @@ class TeleBot: return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) elif message_filter == 'commands': return message.content_type == 'text' and util.extract_command(message.text) in filter_value - elif message_filter == 'only_private': - return message.chat.type == 'private' + elif message_filter == 'chat_types': + return message.chat.type in filter_value elif message_filter == 'func': return filter_value(message) else: From 0f7eb1571e79af4a558668d2da98aabf8eac939c Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 10 Sep 2021 20:42:48 +0500 Subject: [PATCH 231/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7fa9801..a68a957 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,7 @@ TeleBot supports the following filters: |content_types|list of strings (default `['text']`)|`True` if message.content_type is in the list of strings.| |regexp|a regular expression as a string|`True` if `re.search(regexp_arg)` returns `True` and `message.content_type == 'text'` (See [Python Regular Expressions](https://docs.python.org/2/library/re.html))| |commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.| -|only_private|Private chat|`True` if chat is private +|chat_types|list of chat types|`True` if `message.chat.type` in your filter |func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` Here are some examples of using the filters and message handlers: From f70b1353599eadf5a00dda6c4d5b5b34faed3294 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 11 Sep 2021 17:02:40 +0300 Subject: [PATCH 232/350] Filter clearance 1. Filter optimization: should not store empty filters 2. Filter order: chat_type, content, others 3. Default session timeout set to 600 instead of "forever". 4. Type --- telebot/__init__.py | 34 ++++++++++++++++------------------ telebot/apihelper.py | 2 +- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 504e515..125f8ce 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2425,7 +2425,9 @@ class TeleBot: """ return { 'function': handler, - 'filters': filters + 'filters': {ftype: fvalue for ftype, fvalue in filters.items() if fvalue is not None} + # Remove None values, they are skipped in _test_filter anyway + #'filters': filters } def middleware_handler(self, update_types=None): @@ -2521,10 +2523,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, content_types=content_types, commands=commands, regexp=regexp, - chat_types=chat_types, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2552,13 +2554,14 @@ class TeleBot: :return: decorated function """ handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, content_types=content_types, commands=commands, regexp=regexp, func=func, - chat_types=chat_types, **kwargs) self.add_message_handler(handler_dict) + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ Edit message handler decorator @@ -2576,11 +2579,11 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, commands=commands, regexp=regexp, func=func, - content_types=content_types, - chat_types=chat_types, **kwargs) self.add_edited_message_handler(handler_dict) return handler @@ -2607,13 +2610,14 @@ class TeleBot: :return: decorated function """ handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, content_types=content_types, commands=commands, regexp=regexp, func=func, - chat_types=chat_types, **kwargs) self.add_edited_message_handler(handler_dict) + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Channel post handler decorator @@ -2630,10 +2634,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + content_types=content_types, commands=commands, regexp=regexp, func=func, - content_types=content_types, **kwargs) self.add_channel_post_handler(handler_dict) return handler @@ -2665,6 +2669,7 @@ class TeleBot: func=func, **kwargs) self.add_channel_post_handler(handler_dict) + def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Edit channel post handler decorator @@ -2681,10 +2686,10 @@ class TeleBot: def decorator(handler): handler_dict = self._build_handler_dict(handler, + content_types=content_types, commands=commands, regexp=regexp, func=func, - content_types=content_types, **kwargs) self.add_edited_channel_post_handler(handler_dict) return handler @@ -2783,7 +2788,6 @@ class TeleBot: handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_chosen_inline_handler(handler_dict) - def callback_query_handler(self, func, **kwargs): """ Callback request handler decorator @@ -2913,9 +2917,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_poll_handler(handler_dict) def poll_answer_handler(self, func=None, **kwargs): @@ -2948,9 +2950,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_poll_answer_handler(handler_dict) def my_chat_member_handler(self, func=None, **kwargs): @@ -2983,9 +2983,7 @@ class TeleBot: :param func: :return: decorated function """ - handler_dict = self._build_handler_dict(callback, - func=func, - **kwargs) + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_my_chat_member_handler(handler_dict) def chat_member_handler(self, func=None, **kwargs): diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 6098053..9588c4e 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -33,7 +33,7 @@ READ_TIMEOUT = 30 LONG_POLLING_TIMEOUT = 10 # Should be positive, short polling should be used for testing purposes only (https://core.telegram.org/bots/api#getupdates) -SESSION_TIME_TO_LIVE = None # In seconds. None - live forever, 0 - one-time +SESSION_TIME_TO_LIVE = 600 # In seconds. None - live forever, 0 - one-time RETRY_ON_ERROR = False RETRY_TIMEOUT = 2 From 16edfbb9dcdffafb8f9f10abef07e99376493afb Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 11 Sep 2021 19:26:55 +0300 Subject: [PATCH 233/350] Warning if commands or content_types filters are strings --- telebot/__init__.py | 66 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 125f8ce..ae23416 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2521,6 +2521,14 @@ class TeleBot: if content_types is None: content_types = ["text"] + if isinstance(commands, str): + logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + def decorator(handler): handler_dict = self._build_handler_dict(handler, chat_types=chat_types, @@ -2553,6 +2561,14 @@ class TeleBot: :param chat_types: True for private chat :return: decorated function """ + if isinstance(commands, str): + logger.warning("register_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + handler_dict = self._build_handler_dict(callback, chat_types=chat_types, content_types=content_types, @@ -2577,6 +2593,14 @@ class TeleBot: if content_types is None: content_types = ["text"] + if isinstance(commands, str): + logger.warning("edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + def decorator(handler): handler_dict = self._build_handler_dict(handler, chat_types=chat_types, @@ -2609,6 +2633,14 @@ class TeleBot: :param chat_types: True for private chat :return: decorated function """ + if isinstance(commands, str): + logger.warning("register_edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + handler_dict = self._build_handler_dict(callback, chat_types=chat_types, content_types=content_types, @@ -2628,10 +2660,17 @@ class TeleBot: :param kwargs: :return: """ - if content_types is None: content_types = ["text"] + if isinstance(commands, str): + logger.warning("channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + def decorator(handler): handler_dict = self._build_handler_dict(handler, content_types=content_types, @@ -2662,6 +2701,14 @@ class TeleBot: :param func: :return: decorated function """ + if isinstance(commands, str): + logger.warning("register_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + handler_dict = self._build_handler_dict(callback, content_types=content_types, commands=commands, @@ -2680,10 +2727,17 @@ class TeleBot: :param kwargs: :return: """ - if content_types is None: content_types = ["text"] + if isinstance(commands, str): + logger.warning("edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + def decorator(handler): handler_dict = self._build_handler_dict(handler, content_types=content_types, @@ -2714,6 +2768,14 @@ class TeleBot: :param func: :return: decorated function """ + if isinstance(commands, str): + logger.warning("register_edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + handler_dict = self._build_handler_dict(callback, content_types=content_types, commands=commands, From ec8975c9e3791d43793ba80b29ee88d45ab96ac4 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sat, 11 Sep 2021 21:47:59 +0500 Subject: [PATCH 234/350] Custom filters Added new feature - from now you can create your own custom filters --- telebot/__init__.py | 24 +++++++++++++++++++++--- telebot/util.py | 1 + 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 504e515..def8983 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -185,6 +185,7 @@ class TeleBot: self.poll_answer_handlers = [] self.my_chat_member_handlers = [] self.chat_member_handlers = [] + self.custom_filters = {} if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { @@ -3037,8 +3038,16 @@ class TeleBot: return True - @staticmethod - def _test_filter(message_filter, filter_value, message): + def create_filter(self, custom_filter): + """ + Create custom filter. + :params: + custom_filter: Class with check(message) method.""" + self.custom_filters[custom_filter.key] = custom_filter + + + + def _test_filter(self, message_filter, filter_value, message): """ Test filters :param message_filter: Filter type passed in handler @@ -3053,6 +3062,7 @@ class TeleBot: # 'func': lambda msg: filter_value(msg) # } # return test_cases.get(message_filter, lambda msg: False)(message) + if message_filter == 'content_types': return message.content_type in filter_value elif message_filter == 'regexp': @@ -3064,7 +3074,15 @@ class TeleBot: elif message_filter == 'func': return filter_value(message) else: - return False + if message_filter in self.custom_filters: + if message_filter in self.custom_filters: + filter_check = self.custom_filters.get(message_filter) + if filter_value == filter_check.check(message): return True + else: return False + else: + return False + + def _notify_command_handlers(self, handlers, new_messages): """ diff --git a/telebot/util.py b/telebot/util.py index f871f09..310f4c5 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -455,3 +455,4 @@ def webhook_google_functions(bot, request): return 'Bot FAIL', 400 else: return 'Bot ON' + From 8f3371dcd5a42de1be085bfdcaa6de94d97ed06e Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sat, 11 Sep 2021 21:59:28 +0500 Subject: [PATCH 235/350] Update __init__.py --- telebot/__init__.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index def8983..d40bdd7 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3075,10 +3075,9 @@ class TeleBot: return filter_value(message) else: if message_filter in self.custom_filters: - if message_filter in self.custom_filters: - filter_check = self.custom_filters.get(message_filter) - if filter_value == filter_check.check(message): return True - else: return False + filter_check = self.custom_filters.get(message_filter) + if filter_value == filter_check.check(message): return True + else: return False else: return False From 87fb30d57bb20add71b28d34a0e769f4aec0db57 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sat, 11 Sep 2021 22:03:37 +0500 Subject: [PATCH 236/350] Update __init__.py --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index d40bdd7..95b3206 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3038,7 +3038,7 @@ class TeleBot: return True - def create_filter(self, custom_filter): + def add_custom_filter(self, custom_filter): """ Create custom filter. :params: From 8e4d70b9c6161f6692cabb0cf802ab51ca5defa5 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sat, 11 Sep 2021 22:30:53 +0500 Subject: [PATCH 237/350] Update __init__.py --- telebot/__init__.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 95b3206..0b5a503 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3076,8 +3076,13 @@ class TeleBot: else: if message_filter in self.custom_filters: filter_check = self.custom_filters.get(message_filter) - if filter_value == filter_check.check(message): return True - else: return False + if type(filter_value) is bool: + + if filter_value == filter_check.check(message): return True + else: return False + else: + if filter_check.check(message,filter_value) is True: return True + else: return False else: return False From 9d37503442fb73eb2be24e7d8ede2853a846fe4a Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sat, 11 Sep 2021 23:02:56 +0500 Subject: [PATCH 238/350] reupdated --- telebot/__init__.py | 23 +++++++++++++---------- telebot/util.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 0b5a503..c90e12b 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3074,17 +3074,20 @@ class TeleBot: elif message_filter == 'func': return filter_value(message) else: - if message_filter in self.custom_filters: - filter_check = self.custom_filters.get(message_filter) - if type(filter_value) is bool: - - if filter_value == filter_check.check(message): return True - else: return False - else: - if filter_check.check(message,filter_value) is True: return True - else: return False + return self._check_filter(message_filter,filter_value,message) + + def _check_filter(self, message_filter, filter_value, message): + if message_filter in self.custom_filters: + filter_check = self.custom_filters.get(message_filter) + if isinstance(filter_value, util.SimpleCustomFilter): + + if filter_value == filter_check.check(message): return True + else: return False else: - return False + if filter_check.check(message,filter_value) is True: return True + else: return False + else: + return False diff --git a/telebot/util.py b/telebot/util.py index 310f4c5..88019ad 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -456,3 +456,31 @@ def webhook_google_functions(bot, request): else: return 'Bot ON' + +class SimpleCustomFilter: + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts only bool. + """ + + def check(message): + """ + Perform a check. + """ + pass + +class AdvancedCustomFilter: + """ + Simple Custom Filter base class. + Create child class with check() method. + Can accept to parameters. + message: Message class + text: Filter value given in handler + """ + + def check(message, text): + """ + Perform a check. + """ + pass \ No newline at end of file From 14be2b8c183e5887335621f8a3f8f28d39c13c0f Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 11 Sep 2021 21:10:21 +0300 Subject: [PATCH 239/350] Custom filters upd --- telebot/__init__.py | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 4416657..53ea22d 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3101,11 +3101,9 @@ class TeleBot: def add_custom_filter(self, custom_filter): """ Create custom filter. - :params: - custom_filter: Class with check(message) method.""" + custom_filter: Class with check(message) method. + """ self.custom_filters[custom_filter.key] = custom_filter - - def _test_filter(self, message_filter, filter_value, message): """ @@ -3133,23 +3131,22 @@ class TeleBot: return message.chat.type in filter_value elif message_filter == 'func': return filter_value(message) - else: + elif self.custom_filters and message_filter in self.custom_filters: return self._check_filter(message_filter,filter_value,message) - - def _check_filter(self, message_filter, filter_value, message): - if message_filter in self.custom_filters: - filter_check = self.custom_filters.get(message_filter) - if isinstance(filter_value, util.SimpleCustomFilter): - - if filter_value == filter_check.check(message): return True - else: return False - else: - if filter_check.check(message,filter_value) is True: return True - else: return False else: return False - + def _check_filter(self, message_filter, filter_value, message): + filter_check = self.custom_filters.get(message_filter) + if not filter_check: + return False + elif isinstance(filter_value, util.SimpleCustomFilter): + return filter_value == filter_check.check(message) + elif isinstance(filter_value, util.AdvancedCustomFilter): + return filter_check.check(message,filter_value) + else: + logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") + return False def _notify_command_handlers(self, handlers, new_messages): """ From 2da48c0adc6b004b149b6d7de5b4c9df5efc4139 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 11 Sep 2021 21:49:51 +0300 Subject: [PATCH 240/350] Custom filters upd --- telebot/__init__.py | 6 +++--- telebot/util.py | 11 ++++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 53ea22d..e379435 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3140,10 +3140,10 @@ class TeleBot: filter_check = self.custom_filters.get(message_filter) if not filter_check: return False - elif isinstance(filter_value, util.SimpleCustomFilter): + elif isinstance(filter_check, util.SimpleCustomFilter): return filter_value == filter_check.check(message) - elif isinstance(filter_value, util.AdvancedCustomFilter): - return filter_check.check(message,filter_value) + elif isinstance(filter_check, util.AdvancedCustomFilter): + return filter_check.check(message, filter_value) else: logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") return False diff --git a/telebot/util.py b/telebot/util.py index 88019ad..8607ff2 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -5,6 +5,7 @@ import string import threading import traceback from typing import Any, Callable, List, Dict, Optional, Union +from abc import ABC # noinspection PyPep8Naming import queue as Queue @@ -457,20 +458,20 @@ def webhook_google_functions(bot, request): return 'Bot ON' -class SimpleCustomFilter: +class SimpleCustomFilter(ABC): """ Simple Custom Filter base class. Create child class with check() method. Accepts only bool. """ - def check(message): + def check(self, message): """ Perform a check. """ pass -class AdvancedCustomFilter: +class AdvancedCustomFilter(ABC): """ Simple Custom Filter base class. Create child class with check() method. @@ -479,8 +480,8 @@ class AdvancedCustomFilter: text: Filter value given in handler """ - def check(message, text): + def check(self, message, text): """ Perform a check. """ - pass \ No newline at end of file + pass From 5c80f112612e6d1701e554da36d87963811983b7 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 00:21:35 +0500 Subject: [PATCH 241/350] Updated __init__.py --- examples/custom_filters.py | 46 ++++++++++++++++++++++++++++++++++++++ telebot/__init__.py | 4 ++-- 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 examples/custom_filters.py diff --git a/examples/custom_filters.py b/examples/custom_filters.py new file mode 100644 index 0000000..23cebe3 --- /dev/null +++ b/examples/custom_filters.py @@ -0,0 +1,46 @@ +import telebot +from telebot import util + +bot = telebot.TeleBot('TOKEN') + + +# AdvancedCustomFilter is for list, string filter values +class MainFilter(util.AdvancedCustomFilter): + key='text' + @staticmethod + def check(message, text): + return message.text in text + +# SimpleCustomFilter is for boolean values, such as is_admin=True +class IsAdmin(util.SimpleCustomFilter): + key='is_admin' + @staticmethod + def check(message: telebot.types.Message): + if bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator']: + return True + else: + return False + + +@bot.message_handler(is_admin=True, commands=['admin']) # Check if user is admin +def admin_rep(message): + bot.send_message(message.chat.id, "Hi admin") + +@bot.message_handler(is_admin=False, commands=['admin']) # If user is not admin +def not_admin(message): + bot.send_message(message.chat.id, "You are not admin") + +@bot.message_handler(text=['hi']) # Response to hi message +def welcome_hi(message): + bot.send_message(message.chat.id, 'You said hi') + +@bot.message_handler(text=['bye']) # Response to bye message +def bye_user(message): + bot.send_message(message.chat.id, 'You said bye') + + +# Do not forget to register filters +bot.add_custom_filter(MainFilter) +bot.add_custom_filter(IsAdmin) + +bot.polling(skip_pending=True) # Skip old updates \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index e379435..5816cdf 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3140,9 +3140,9 @@ class TeleBot: filter_check = self.custom_filters.get(message_filter) if not filter_check: return False - elif isinstance(filter_check, util.SimpleCustomFilter): + elif isinstance(filter_check(), util.SimpleCustomFilter): return filter_value == filter_check.check(message) - elif isinstance(filter_check, util.AdvancedCustomFilter): + elif isinstance(filter_check(), util.AdvancedCustomFilter): return filter_check.check(message, filter_value) else: logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") From 5d611ea7f3ce34f22626ce4aa91d3c7400a2fa23 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 00:24:52 +0500 Subject: [PATCH 242/350] upd --- examples/custom_filters.py | 2 +- examples/deep_linking.py | 3 +-- examples/echo_bot.py | 2 +- examples/inline_example.py | 2 +- examples/inline_keyboard_example.py | 2 +- examples/payments_example.py | 3 +-- examples/skip_updates_example.py | 2 +- 7 files changed, 7 insertions(+), 9 deletions(-) diff --git a/examples/custom_filters.py b/examples/custom_filters.py index 23cebe3..0294468 100644 --- a/examples/custom_filters.py +++ b/examples/custom_filters.py @@ -43,4 +43,4 @@ def bye_user(message): bot.add_custom_filter(MainFilter) bot.add_custom_filter(IsAdmin) -bot.polling(skip_pending=True) # Skip old updates \ No newline at end of file +bot.polling(skip_pending=True,non_stop=True) # Skip old updates \ No newline at end of file diff --git a/examples/deep_linking.py b/examples/deep_linking.py index f5ea506..e0a7e94 100644 --- a/examples/deep_linking.py +++ b/examples/deep_linking.py @@ -73,5 +73,4 @@ def send_welcome(message): reply = "Please visit me via a provided URL from the website." bot.reply_to(message, reply) - -bot.polling() +bot.polling(skip_pending=True,non_stop=True) # Skip old updates diff --git a/examples/echo_bot.py b/examples/echo_bot.py index b66eb34..ec71f70 100644 --- a/examples/echo_bot.py +++ b/examples/echo_bot.py @@ -25,4 +25,4 @@ def echo_message(message): bot.reply_to(message, message.text) -bot.polling() +bot.polling(skip_pending=True,non_stop=True) # Skip old updates diff --git a/examples/inline_example.py b/examples/inline_example.py index 21f05eb..8bb064d 100644 --- a/examples/inline_example.py +++ b/examples/inline_example.py @@ -61,7 +61,7 @@ def default_query(inline_query): def main_loop(): - bot.polling(True) + bot.polling(skip_pending=True) # Skip old updates while 1: time.sleep(3) diff --git a/examples/inline_keyboard_example.py b/examples/inline_keyboard_example.py index f2b3fce..56b2ae5 100644 --- a/examples/inline_keyboard_example.py +++ b/examples/inline_keyboard_example.py @@ -24,4 +24,4 @@ def callback_query(call): def message_handler(message): bot.send_message(message.chat.id, "Yes/no?", reply_markup=gen_markup()) -bot.polling(none_stop=True) +bot.polling(skip_pending=True,non_stop=True) # Skip old updates diff --git a/examples/payments_example.py b/examples/payments_example.py index d0f52d4..efdddaf 100644 --- a/examples/payments_example.py +++ b/examples/payments_example.py @@ -78,5 +78,4 @@ def got_payment(message): parse_mode='Markdown') -bot.skip_pending = True -bot.polling(none_stop=True, interval=0) +bot.polling(skip_pending=True,non_stop=True) # Skip old updates diff --git a/examples/skip_updates_example.py b/examples/skip_updates_example.py index 0bd631b..01aa414 100644 --- a/examples/skip_updates_example.py +++ b/examples/skip_updates_example.py @@ -10,4 +10,4 @@ def send_welcome(message): def echo_all(message): bot.reply_to(message, message.text) -bot.polling(skip_pending=True)# Skip pending skips old updates +bot.polling(skip_pending=True,non_stop=True) # Skip old updates From e89acc8ba635fd4e7fdac41c9e0acdcfef6e0242 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 00:27:04 +0500 Subject: [PATCH 243/350] Update custom_filters.py --- examples/custom_filters.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/custom_filters.py b/examples/custom_filters.py index 0294468..e9e40e8 100644 --- a/examples/custom_filters.py +++ b/examples/custom_filters.py @@ -40,7 +40,7 @@ def bye_user(message): # Do not forget to register filters -bot.add_custom_filter(MainFilter) -bot.add_custom_filter(IsAdmin) +bot.add_custom_filter(MainFilter()) +bot.add_custom_filter(IsAdmin()) bot.polling(skip_pending=True,non_stop=True) # Skip old updates \ No newline at end of file From 88f91518c7518dc8648f7fd6be2f96714df444d4 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 00:27:51 +0500 Subject: [PATCH 244/350] Update __init__.py --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 5816cdf..e379435 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3140,9 +3140,9 @@ class TeleBot: filter_check = self.custom_filters.get(message_filter) if not filter_check: return False - elif isinstance(filter_check(), util.SimpleCustomFilter): + elif isinstance(filter_check, util.SimpleCustomFilter): return filter_value == filter_check.check(message) - elif isinstance(filter_check(), util.AdvancedCustomFilter): + elif isinstance(filter_check, util.AdvancedCustomFilter): return filter_check.check(message, filter_value) else: logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") From 4e37662ab3048128277a2f85c96bdeaead5c5386 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 00:30:56 +0500 Subject: [PATCH 245/350] upd --- examples/deep_linking.py | 3 ++- examples/echo_bot.py | 2 +- examples/inline_example.py | 2 +- examples/inline_keyboard_example.py | 2 +- examples/payments_example.py | 3 ++- examples/skip_updates_example.py | 2 +- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/examples/deep_linking.py b/examples/deep_linking.py index e0a7e94..f5ea506 100644 --- a/examples/deep_linking.py +++ b/examples/deep_linking.py @@ -73,4 +73,5 @@ def send_welcome(message): reply = "Please visit me via a provided URL from the website." bot.reply_to(message, reply) -bot.polling(skip_pending=True,non_stop=True) # Skip old updates + +bot.polling() diff --git a/examples/echo_bot.py b/examples/echo_bot.py index ec71f70..b66eb34 100644 --- a/examples/echo_bot.py +++ b/examples/echo_bot.py @@ -25,4 +25,4 @@ def echo_message(message): bot.reply_to(message, message.text) -bot.polling(skip_pending=True,non_stop=True) # Skip old updates +bot.polling() diff --git a/examples/inline_example.py b/examples/inline_example.py index 8bb064d..21f05eb 100644 --- a/examples/inline_example.py +++ b/examples/inline_example.py @@ -61,7 +61,7 @@ def default_query(inline_query): def main_loop(): - bot.polling(skip_pending=True) # Skip old updates + bot.polling(True) while 1: time.sleep(3) diff --git a/examples/inline_keyboard_example.py b/examples/inline_keyboard_example.py index 56b2ae5..f2b3fce 100644 --- a/examples/inline_keyboard_example.py +++ b/examples/inline_keyboard_example.py @@ -24,4 +24,4 @@ def callback_query(call): def message_handler(message): bot.send_message(message.chat.id, "Yes/no?", reply_markup=gen_markup()) -bot.polling(skip_pending=True,non_stop=True) # Skip old updates +bot.polling(none_stop=True) diff --git a/examples/payments_example.py b/examples/payments_example.py index efdddaf..d0f52d4 100644 --- a/examples/payments_example.py +++ b/examples/payments_example.py @@ -78,4 +78,5 @@ def got_payment(message): parse_mode='Markdown') -bot.polling(skip_pending=True,non_stop=True) # Skip old updates +bot.skip_pending = True +bot.polling(none_stop=True, interval=0) diff --git a/examples/skip_updates_example.py b/examples/skip_updates_example.py index 01aa414..0bd631b 100644 --- a/examples/skip_updates_example.py +++ b/examples/skip_updates_example.py @@ -10,4 +10,4 @@ def send_welcome(message): def echo_all(message): bot.reply_to(message, message.text) -bot.polling(skip_pending=True,non_stop=True) # Skip old updates +bot.polling(skip_pending=True)# Skip pending skips old updates From 5f8c75816ebb8489224a63c8b561d24bb05dfd35 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 19:34:43 +0500 Subject: [PATCH 246/350] Some useful filters Created useful filters that can be used in message handlers. Created some examples on using them. --- examples/id_filter_example.py | 16 +++++++++ examples/text_filter_example.py | 17 ++++++++++ telebot/__init__.py | 2 +- telebot/util.py | 60 +++++++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 examples/id_filter_example.py create mode 100644 examples/text_filter_example.py diff --git a/examples/id_filter_example.py b/examples/id_filter_example.py new file mode 100644 index 0000000..dbd621b --- /dev/null +++ b/examples/id_filter_example.py @@ -0,0 +1,16 @@ +import telebot + +bot = telebot.TeleBot('TOKEN') + + +# Chat id can be private or supergroups. +@bot.message_handler(chat_id=[12345678], commands=['admin']) # chat_id checks id corresponds to your list or not. +def admin_rep(message): + bot.send_message(message.chat.id, "You are allowed to use this command.") + +@bot.message_handler(commands=['admin']) +def not_admin(message): + bot.send_message(message.chat.id, "You are not allowed to use this command") + + +bot.polling(non_stop=True) \ No newline at end of file diff --git a/examples/text_filter_example.py b/examples/text_filter_example.py new file mode 100644 index 0000000..da0d380 --- /dev/null +++ b/examples/text_filter_example.py @@ -0,0 +1,17 @@ +import telebot + +bot = telebot.TeleBot('TOKEN') + + +# Check if message starts with @admin tag +@bot.message_handler(text_startswith="@admin") +def start_filter(message): + bot.send_message(message.chat.id, "Looks like you are calling admin, wait...") + +# Check if text is hi or hello +@bot.message_handler(text=['hi','hello']) +def text_filter(message): + bot.send_message(message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name)) + + +bot.polling(non_stop=True) \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index e379435..5c85f28 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -185,7 +185,7 @@ class TeleBot: self.poll_answer_handlers = [] self.my_chat_member_handlers = [] self.chat_member_handlers = [] - self.custom_filters = {} + self.custom_filters = {'text': util.TextFilter(), 'text_contains': util.TextContains(), 'chat_id': util.UserFilter(), 'text_startswith': util.TextStarts()} if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { diff --git a/telebot/util.py b/telebot/util.py index 8607ff2..56fa63f 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -485,3 +485,63 @@ class AdvancedCustomFilter(ABC): Perform a check. """ pass + +class TextFilter(AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + @bot.message_handler(text=['account']) + """ + + key = 'text' + + def check(self, message, text): + if type(text) is list:return message.text in text + else: return text == message.text + +class TextContains(AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + # Will respond if any message.text contains word 'account' + @bot.message_handler(text_contains=['account']) + """ + + key = 'text_contains' + + def check(self, message, text): + return text in message.text + +class UserFilter(AdvancedCustomFilter): + """ + Check whether chat_id corresponds to given chat_id. + + Example: + @bot.message_handler(chat_id=[99999]) + + """ + + key = 'chat_id' + def check(self, message, text): + return message.chat.id in text + + +class TextStarts(AdvancedCustomFilter): + """ + Filter to check whether message starts with some text. + + Example: + # Will work if message.text starts with 'Sir'. + @bot.message_handler(text_startswith='Sir') + + """ + + key = 'text_startswith' + def check(self, message, text): + return message.text.startswith(text) + + \ No newline at end of file From 1ceec3cb54593a5613c804e64d08116d45723e1b Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 19:38:54 +0500 Subject: [PATCH 247/350] Update custom_filters.py --- examples/custom_filters.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/examples/custom_filters.py b/examples/custom_filters.py index e9e40e8..18c8c26 100644 --- a/examples/custom_filters.py +++ b/examples/custom_filters.py @@ -16,10 +16,7 @@ class IsAdmin(util.SimpleCustomFilter): key='is_admin' @staticmethod def check(message: telebot.types.Message): - if bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator']: - return True - else: - return False + return bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator'] @bot.message_handler(is_admin=True, commands=['admin']) # Check if user is admin From 7d5e9e5111379c1de3afae2074a80bcc145ef093 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Sun, 12 Sep 2021 20:22:26 +0500 Subject: [PATCH 248/350] Added file custom_filters Added file with custom filters. Updated the examples --- examples/id_filter_example.py | 7 +++- examples/text_filter_example.py | 4 +++ telebot/__init__.py | 2 +- telebot/custom_filters.py | 61 +++++++++++++++++++++++++++++++++ telebot/util.py | 58 ------------------------------- 5 files changed, 72 insertions(+), 60 deletions(-) create mode 100644 telebot/custom_filters.py diff --git a/examples/id_filter_example.py b/examples/id_filter_example.py index dbd621b..3c83841 100644 --- a/examples/id_filter_example.py +++ b/examples/id_filter_example.py @@ -1,6 +1,7 @@ import telebot +from telebot import custom_filters -bot = telebot.TeleBot('TOKEN') +bot = telebot.TeleBot('token') # Chat id can be private or supergroups. @@ -13,4 +14,8 @@ def not_admin(message): bot.send_message(message.chat.id, "You are not allowed to use this command") +# Do not forget to register +bot.add_custom_filter(custom_filters.UserFilter()) + + bot.polling(non_stop=True) \ No newline at end of file diff --git a/examples/text_filter_example.py b/examples/text_filter_example.py index da0d380..12b62f1 100644 --- a/examples/text_filter_example.py +++ b/examples/text_filter_example.py @@ -1,4 +1,5 @@ import telebot +from telebot import custom_filters bot = telebot.TeleBot('TOKEN') @@ -13,5 +14,8 @@ def start_filter(message): def text_filter(message): bot.send_message(message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name)) +# Do not forget to register filters +bot.add_custom_filter(custom_filters.TextFilter()) +bot.add_custom_filter(custom_filters.TextStarts()) bot.polling(non_stop=True) \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index 5c85f28..e379435 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -185,7 +185,7 @@ class TeleBot: self.poll_answer_handlers = [] self.my_chat_member_handlers = [] self.chat_member_handlers = [] - self.custom_filters = {'text': util.TextFilter(), 'text_contains': util.TextContains(), 'chat_id': util.UserFilter(), 'text_startswith': util.TextStarts()} + self.custom_filters = {} if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py new file mode 100644 index 0000000..00b0f75 --- /dev/null +++ b/telebot/custom_filters.py @@ -0,0 +1,61 @@ +from telebot import util + + + +class TextFilter(util.AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + @bot.message_handler(text=['account']) + """ + + key = 'text' + + def check(self, message, text): + if type(text) is list:return message.text in text + else: return text == message.text + +class TextContains(util.AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + # Will respond if any message.text contains word 'account' + @bot.message_handler(text_contains=['account']) + """ + + key = 'text_contains' + + def check(self, message, text): + return text in message.text + +class UserFilter(util.AdvancedCustomFilter): + """ + Check whether chat_id corresponds to given chat_id. + + Example: + @bot.message_handler(chat_id=[99999]) + + """ + + key = 'chat_id' + def check(self, message, text): + return message.chat.id in text + + +class TextStarts(util.AdvancedCustomFilter): + """ + Filter to check whether message starts with some text. + + Example: + # Will work if message.text starts with 'Sir'. + @bot.message_handler(text_startswith='Sir') + + """ + + key = 'text_startswith' + def check(self, message, text): + return message.text.startswith(text) diff --git a/telebot/util.py b/telebot/util.py index 56fa63f..7bcb257 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -486,62 +486,4 @@ class AdvancedCustomFilter(ABC): """ pass -class TextFilter(AdvancedCustomFilter): - """ - Filter to check Text message. - key: text - - Example: - @bot.message_handler(text=['account']) - """ - - key = 'text' - - def check(self, message, text): - if type(text) is list:return message.text in text - else: return text == message.text - -class TextContains(AdvancedCustomFilter): - """ - Filter to check Text message. - key: text - - Example: - # Will respond if any message.text contains word 'account' - @bot.message_handler(text_contains=['account']) - """ - - key = 'text_contains' - - def check(self, message, text): - return text in message.text - -class UserFilter(AdvancedCustomFilter): - """ - Check whether chat_id corresponds to given chat_id. - - Example: - @bot.message_handler(chat_id=[99999]) - - """ - - key = 'chat_id' - def check(self, message, text): - return message.chat.id in text - - -class TextStarts(AdvancedCustomFilter): - """ - Filter to check whether message starts with some text. - - Example: - # Will work if message.text starts with 'Sir'. - @bot.message_handler(text_startswith='Sir') - - """ - - key = 'text_startswith' - def check(self, message, text): - return message.text.startswith(text) - \ No newline at end of file From cf75e76e5c7034921c1fb4d9ab71561cc6a5ca18 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:27:01 +0500 Subject: [PATCH 249/350] Update README.md --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index a68a957..bcfc517 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,15 @@ TeleBot supports the following filters: |chat_types|list of chat types|`True` if `message.chat.type` in your filter |func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` +### Custom filters +Also, you can use built-in custom filters. Or, you can create your own filter. + +[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py) + +You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py) +Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py) +Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py) + Here are some examples of using the filters and message handlers: ```python From 8534804c0c5d55ac80a05492520a2060e68008bf Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:28:01 +0500 Subject: [PATCH 250/350] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index bcfc517..a2d80d5 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,9 @@ Also, you can use built-in custom filters. Or, you can create your own filter. [Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py) You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py) + Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py) + Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py) Here are some examples of using the filters and message handlers: From 5f4cd09490841c4a38ead7633a7057f051eb5d0d Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:28:46 +0500 Subject: [PATCH 251/350] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a2d80d5..e92cef9 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,8 @@ Also, you can use built-in custom filters. Or, you can create your own filter. [Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py) +Also, we have examples on them. Check this links: + You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py) Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py) From cf78234e3a36da72e55e60364c4bebcadf1ca1cd Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:30:32 +0500 Subject: [PATCH 252/350] Update README.md --- README.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index e92cef9..2204efd 100644 --- a/README.md +++ b/README.md @@ -169,19 +169,6 @@ TeleBot supports the following filters: |commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.| |chat_types|list of chat types|`True` if `message.chat.type` in your filter |func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` - -### Custom filters -Also, you can use built-in custom filters. Or, you can create your own filter. - -[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py) - -Also, we have examples on them. Check this links: - -You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py) - -Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py) - -Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py) Here are some examples of using the filters and message handlers: @@ -300,6 +287,21 @@ def start(message): assert message.another_text == message.text + ':changed' ``` There are other examples using middleware handler in the [examples/middleware](examples/middleware) directory. + + +### Custom filters +Also, you can use built-in custom filters. Or, you can create your own filter. + +[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py) + +Also, we have examples on them. Check this links: + +You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py) + +Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py) + +Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py) + #### TeleBot ```python From 43d2d8583e7f7cd70d91189ecfbf160534a52c77 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:32:16 +0500 Subject: [PATCH 253/350] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2204efd..52524b4 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,8 @@ Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/ Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py) +If you want to add some built-in filter, you are welcome to add it in custom_filters.py file. + #### TeleBot ```python From 5c715dabc3e7bb1bee22982276c2c7e6494d2495 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:40:31 +0500 Subject: [PATCH 254/350] Update README.md --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 52524b4..1adc743 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,28 @@ Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blo If you want to add some built-in filter, you are welcome to add it in custom_filters.py file. +Here is example of creating filter-class: + +``` +class IsAdmin(util.SimpleCustomFilter): + # Class will check whether the user is admin or creator in group or not + key='is_admin' + @staticmethod + def check(message: telebot.types.Message): + return bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator'] + + + # To register filter, you need to use method add_custom_filter. + + bot.add_custom_filter(IsAdmin()) + + + # Now, you can use it in handler. + + @bot.message_handler(is_admin=True) + +``` + #### TeleBot ```python From 4071ab91244d793d4e8b5dd8c6ccbfc9fd92fd51 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:41:26 +0500 Subject: [PATCH 255/350] Update README.md --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 1adc743..a40e5ff 100644 --- a/README.md +++ b/README.md @@ -306,7 +306,7 @@ If you want to add some built-in filter, you are welcome to add it in custom_fil Here is example of creating filter-class: -``` +```python class IsAdmin(util.SimpleCustomFilter): # Class will check whether the user is admin or creator in group or not key='is_admin' @@ -314,14 +314,10 @@ class IsAdmin(util.SimpleCustomFilter): def check(message: telebot.types.Message): return bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator'] - # To register filter, you need to use method add_custom_filter. - bot.add_custom_filter(IsAdmin()) - # Now, you can use it in handler. - @bot.message_handler(is_admin=True) ``` From c86af0496bf15befe81a56ff6b4beadbc0dc734f Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 12 Sep 2021 20:43:09 +0500 Subject: [PATCH 256/350] Update README.md --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a40e5ff..849efad 100644 --- a/README.md +++ b/README.md @@ -314,11 +314,13 @@ class IsAdmin(util.SimpleCustomFilter): def check(message: telebot.types.Message): return bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator'] - # To register filter, you need to use method add_custom_filter. - bot.add_custom_filter(IsAdmin()) +# To register filter, you need to use method add_custom_filter. +bot.add_custom_filter(IsAdmin()) - # Now, you can use it in handler. - @bot.message_handler(is_admin=True) +# Now, you can use it in handler. +@bot.message_handler(is_admin=True) +def admin_of_group(message): + bot.send_message(message.chat.id, 'You are admin of this group'!) ``` From 4ced4d29f5c006be34b612ca27310d240218e9fe Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 12 Sep 2021 19:36:23 +0300 Subject: [PATCH 257/350] Update custom filters readme and examples --- README.md | 10 +-- .../general_custom_filters.py} | 5 +- .../{ => custom_filters}/id_filter_example.py | 5 +- .../text_filter_example.py | 4 +- telebot/__init__.py | 6 +- telebot/custom_filters.py | 63 +++++++++++++------ telebot/util.py | 32 ---------- 7 files changed, 59 insertions(+), 66 deletions(-) rename examples/{custom_filters.py => custom_filters/general_custom_filters.py} (91%) rename examples/{ => custom_filters}/id_filter_example.py (86%) rename examples/{ => custom_filters}/text_filter_example.py (82%) diff --git a/README.md b/README.md index 849efad..919ff74 100644 --- a/README.md +++ b/README.md @@ -289,25 +289,25 @@ def start(message): There are other examples using middleware handler in the [examples/middleware](examples/middleware) directory. -### Custom filters +#### Custom filters Also, you can use built-in custom filters. Or, you can create your own filter. -[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py) +[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters/general_custom_filters.py) Also, we have examples on them. Check this links: You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py) -Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py) +Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters/id_filter_example.py) -Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py) +Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters/text_filter_example.py) If you want to add some built-in filter, you are welcome to add it in custom_filters.py file. Here is example of creating filter-class: ```python -class IsAdmin(util.SimpleCustomFilter): +class IsAdmin(telebot.custom_filters.SimpleCustomFilter): # Class will check whether the user is admin or creator in group or not key='is_admin' @staticmethod diff --git a/examples/custom_filters.py b/examples/custom_filters/general_custom_filters.py similarity index 91% rename from examples/custom_filters.py rename to examples/custom_filters/general_custom_filters.py index 18c8c26..382b68c 100644 --- a/examples/custom_filters.py +++ b/examples/custom_filters/general_custom_filters.py @@ -1,18 +1,17 @@ import telebot -from telebot import util bot = telebot.TeleBot('TOKEN') # AdvancedCustomFilter is for list, string filter values -class MainFilter(util.AdvancedCustomFilter): +class MainFilter(telebot.custom_filters.AdvancedCustomFilter): key='text' @staticmethod def check(message, text): return message.text in text # SimpleCustomFilter is for boolean values, such as is_admin=True -class IsAdmin(util.SimpleCustomFilter): +class IsAdmin(telebot.custom_filters.SimpleCustomFilter): key='is_admin' @staticmethod def check(message: telebot.types.Message): diff --git a/examples/id_filter_example.py b/examples/custom_filters/id_filter_example.py similarity index 86% rename from examples/id_filter_example.py rename to examples/custom_filters/id_filter_example.py index 3c83841..06a6ce3 100644 --- a/examples/id_filter_example.py +++ b/examples/custom_filters/id_filter_example.py @@ -15,7 +15,8 @@ def not_admin(message): # Do not forget to register -bot.add_custom_filter(custom_filters.UserFilter()) +bot.add_custom_filter(custom_filters.ChatFilter()) -bot.polling(non_stop=True) \ No newline at end of file +bot.polling(non_stop=True) + diff --git a/examples/text_filter_example.py b/examples/custom_filters/text_filter_example.py similarity index 82% rename from examples/text_filter_example.py rename to examples/custom_filters/text_filter_example.py index 12b62f1..2476097 100644 --- a/examples/text_filter_example.py +++ b/examples/custom_filters/text_filter_example.py @@ -15,7 +15,7 @@ def text_filter(message): bot.send_message(message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name)) # Do not forget to register filters -bot.add_custom_filter(custom_filters.TextFilter()) -bot.add_custom_filter(custom_filters.TextStarts()) +bot.add_custom_filter(custom_filters.TextMatchFilter()) +bot.add_custom_filter(custom_filters.TextStartsFilter()) bot.polling(non_stop=True) \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index e379435..790fff0 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -12,7 +12,7 @@ from typing import Any, Callable, List, Optional, Union # this imports are used to avoid circular import error import telebot.util import telebot.types - +from custom_filters import SimpleCustomFilter, AdvancedCustomFilter logger = logging.getLogger('TeleBot') @@ -3140,9 +3140,9 @@ class TeleBot: filter_check = self.custom_filters.get(message_filter) if not filter_check: return False - elif isinstance(filter_check, util.SimpleCustomFilter): + elif isinstance(filter_check, SimpleCustomFilter): return filter_value == filter_check.check(message) - elif isinstance(filter_check, util.AdvancedCustomFilter): + elif isinstance(filter_check, AdvancedCustomFilter): return filter_check.check(message, filter_value) else: logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 00b0f75..2491185 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -1,8 +1,36 @@ -from telebot import util +from abc import ABC + +class SimpleCustomFilter(ABC): + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts only message, returns bool value, that is compared with given in handler. + """ + + def check(self, message): + """ + Perform a check. + """ + pass +class AdvancedCustomFilter(ABC): + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts two parameters, returns bool: True - filter passed, False - filter failed. + message: Message class + text: Filter value given in handler + """ -class TextFilter(util.AdvancedCustomFilter): + def check(self, message, text): + """ + Perform a check. + """ + pass + + +class TextMatchFilter(AdvancedCustomFilter): """ Filter to check Text message. key: text @@ -17,7 +45,7 @@ class TextFilter(util.AdvancedCustomFilter): if type(text) is list:return message.text in text else: return text == message.text -class TextContains(util.AdvancedCustomFilter): +class TextContainsFilter(AdvancedCustomFilter): """ Filter to check Text message. key: text @@ -32,30 +60,27 @@ class TextContains(util.AdvancedCustomFilter): def check(self, message, text): return text in message.text -class UserFilter(util.AdvancedCustomFilter): - """ - Check whether chat_id corresponds to given chat_id. - - Example: - @bot.message_handler(chat_id=[99999]) - - """ - - key = 'chat_id' - def check(self, message, text): - return message.chat.id in text - - -class TextStarts(util.AdvancedCustomFilter): +class TextStartsFilter(AdvancedCustomFilter): """ Filter to check whether message starts with some text. Example: # Will work if message.text starts with 'Sir'. @bot.message_handler(text_startswith='Sir') - """ key = 'text_startswith' def check(self, message, text): return message.text.startswith(text) + +class ChatFilter(AdvancedCustomFilter): + """ + Check whether chat_id corresponds to given chat_id. + + Example: + @bot.message_handler(chat_id=[99999]) + """ + + key = 'chat_id' + def check(self, message, text): + return message.chat.id in text diff --git a/telebot/util.py b/telebot/util.py index 7bcb257..f871f09 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -5,7 +5,6 @@ import string import threading import traceback from typing import Any, Callable, List, Dict, Optional, Union -from abc import ABC # noinspection PyPep8Naming import queue as Queue @@ -456,34 +455,3 @@ def webhook_google_functions(bot, request): return 'Bot FAIL', 400 else: return 'Bot ON' - - -class SimpleCustomFilter(ABC): - """ - Simple Custom Filter base class. - Create child class with check() method. - Accepts only bool. - """ - - def check(self, message): - """ - Perform a check. - """ - pass - -class AdvancedCustomFilter(ABC): - """ - Simple Custom Filter base class. - Create child class with check() method. - Can accept to parameters. - message: Message class - text: Filter value given in handler - """ - - def check(self, message, text): - """ - Perform a check. - """ - pass - - \ No newline at end of file From 97e99b491030cde3f1e3a0ddb4cd31e38ec1bf7f Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 12 Sep 2021 19:39:26 +0300 Subject: [PATCH 258/350] Fix --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 790fff0..78cf29d 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -12,7 +12,7 @@ from typing import Any, Callable, List, Optional, Union # this imports are used to avoid circular import error import telebot.util import telebot.types -from custom_filters import SimpleCustomFilter, AdvancedCustomFilter +from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter logger = logging.getLogger('TeleBot') From 38851bce220cc4af32bb0b08633712d1fe6d637d Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 12 Sep 2021 20:02:49 +0300 Subject: [PATCH 259/350] README contents update --- README.md | 125 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 66 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 919ff74..ad8c434 100644 --- a/README.md +++ b/README.md @@ -21,12 +21,27 @@ * [Methods](#methods) * [General use of the API](#general-use-of-the-api) * [Message handlers](#message-handlers) + * [Edited Message handler](#edited-message-handler) + * [Channel Post handler](#channel-post-handler) + * [Edited Channel Post handler](#edited-channel-post-handler) * [Callback Query handlers](#callback-query-handler) - * [Middleware handlers](#middleware-handler) + * [Shipping Query Handler](#shipping-query-handler) + * [Pre Checkout Query Handler](#pre-checkout-query-handler) + * [Poll Handler](#poll-handler) + * [Poll Answer Handler](#poll-answer-handler) + * [My Chat Member Handler](#my-chat-member-handler) + * [Chat Member Handler](#chat-member-handler) + * [Inline Mode](#inline-mode) + * [Inline handler](#inline-handler) + * [Chosen Inline handler](#chosen-inline-handler) + * [Answer Inline Query](#answer-inline-query) + * [Additional API features](#additional-api-features) + * [Middleware handlers](#middleware-handlers) + * [Custom filters](#custom-filters) * [TeleBot](#telebot) * [Reply markup](#reply-markup) - * [Inline Mode](#inline-mode) * [Advanced use of the API](#advanced-use-of-the-api) + * [Using local Bot API Server](#using-local-bot-api-sever) * [Asynchronous delivery of messages](#asynchronous-delivery-of-messages) * [Sending large text messages](#sending-large-text-messages) * [Controlling the amount of Threads used by TeleBot](#controlling-the-amount-of-threads-used-by-telebot) @@ -35,9 +50,7 @@ * [Logging](#logging) * [Proxy](#proxy) * [API conformance](#api-conformance) - * [Change log](#change-log) * [F.A.Q.](#faq) - * [Bot 2.0](#bot-20) * [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat) * [How can I handle reocurring ConnectionResetErrors?](#how-can-i-handle-reocurring-connectionreseterrors) * [The Telegram Chat Group](#the-telegram-chat-group) @@ -46,7 +59,7 @@ ## Getting started. -This API is tested with Python Python 3.6-3.9 and Pypy 3. +This API is tested with Python 3.6-3.9 and Pypy 3. There are two ways to install the library: * Installation using pip (a Python package manager)*: @@ -213,15 +226,15 @@ def send_something(message): ``` **Important: all handlers are tested in the order in which they were declared** -#### Edited Message handlers +#### Edited Message handler Handle edited messages `@bot.edited_message_handler(filters) # <- passes a Message type object to your function` -#### channel_post_handler +#### Channel Post handler Handle channel post messages `@bot.channel_post_handler(filters) # <- passes a Message type object to your function` -#### edited_channel_post_handler +#### Edited Channel Post handler Handle edited channel post messages `@bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function` @@ -233,14 +246,6 @@ def test_callback(call): # <- passes a CallbackQuery type object to your functi logger.info(call) ``` -#### Inline Handler -Handle inline queries -`@bot.inline_handler() # <- passes a InlineQuery type object to your function` - -#### Chosen Inline Handler -Handle chosen inline results -`@bot.chosen_inline_handler() # <- passes a ChosenInlineResult type object to your function` - #### Shipping Query Handler Handle shipping queries `@bot.shipping_query_handeler() # <- passes a ShippingQuery type object to your function` @@ -266,8 +271,51 @@ Handle updates of a chat member's status in a chat `@bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function` *Note: "chat_member" updates are not requested by default. If you want to allow all update types, set `allowed_updates` in `bot.polling()` / `bot.infinity_polling()` to `util.update_types`* +### Inline Mode -#### Middleware Handler +More information about [Inline mode](https://core.telegram.org/bots/inline). + +#### Inline handler + +Now, you can use inline_handler to get inline queries in telebot. + +```python + +@bot.inline_handler(lambda query: query.query == 'text') +def query_text(inline_query): + # Query message is text +``` + +#### Chosen Inline handler + +Use chosen_inline_handler to get chosen_inline_result in telebot. Don't forgot add the /setinlinefeedback +command for @Botfather. + +More information : [collecting-feedback](https://core.telegram.org/bots/inline#collecting-feedback) + +```python +@bot.chosen_inline_handler(func=lambda chosen_inline_result: True) +def test_chosen(chosen_inline_result): + # Process all chosen_inline_result. +``` + +#### Answer Inline Query + +```python +@bot.inline_handler(lambda query: query.query == 'text') +def query_text(inline_query): + try: + r = types.InlineQueryResultArticle('1', 'Result', types.InputTextMessageContent('Result message.')) + r2 = types.InlineQueryResultArticle('2', 'Result2', types.InputTextMessageContent('Result message2.')) + bot.answer_inline_query(inline_query.id, [r, r2]) + except Exception as e: + print(e) + +``` + +### Additional API features + +#### Middleware Handlers A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are @@ -471,49 +519,8 @@ ForceReply: ![ForceReply](https://farm4.staticflickr.com/3809/32418726814_d1baec0fc2_o_d.jpg "ForceReply") -### Inline Mode -More information about [Inline mode](https://core.telegram.org/bots/inline). - -#### inline_handler - -Now, you can use inline_handler to get inline queries in telebot. - -```python - -@bot.inline_handler(lambda query: query.query == 'text') -def query_text(inline_query): - # Query message is text -``` - - -#### chosen_inline_handler - -Use chosen_inline_handler to get chosen_inline_result in telebot. Don't forgot add the /setinlinefeedback -command for @Botfather. - -More information : [collecting-feedback](https://core.telegram.org/bots/inline#collecting-feedback) - -```python -@bot.chosen_inline_handler(func=lambda chosen_inline_result: True) -def test_chosen(chosen_inline_result): - # Process all chosen_inline_result. -``` - -#### answer_inline_query - -```python -@bot.inline_handler(lambda query: query.query == 'text') -def query_text(inline_query): - try: - r = types.InlineQueryResultArticle('1', 'Result', types.InputTextMessageContent('Result message.')) - r2 = types.InlineQueryResultArticle('2', 'Result2', types.InputTextMessageContent('Result message2.')) - bot.answer_inline_query(inline_query.id, [r, r2]) - except Exception as e: - print(e) - -``` -### Working with entities: +### Working with entities This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes: * `type` From 7913e25be21130ca9db01875b73647702c1a2260 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 12 Sep 2021 21:12:19 +0300 Subject: [PATCH 260/350] 4.0.1 beta release --- README.md | 43 +++++++------------------------------------ telebot/version.py | 2 +- 2 files changed, 8 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index ad8c434..257b744 100644 --- a/README.md +++ b/README.md @@ -722,72 +722,43 @@ Get help. Discuss. Chat. ## Bots using this API * [SiteAlert bot](https://telegram.me/SiteAlert_bot) ([source](https://github.com/ilteoood/SiteAlert-Python)) by *ilteoood* - Monitors websites and sends a notification on changes * [TelegramLoggingBot](https://github.com/aRandomStranger/TelegramLoggingBot) by *aRandomStranger* -* [Send to Kindle Bot](https://telegram.me/Send2KindleBot) by *GabrielRF* - Send to Kindle files or links to files. -* [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) ([source](https://github.com/GabrielRF/telegram-lmgtfy_bot)) by *GabrielRF* - Let me Google that for you. -* [Telegram UrlProBot](https://github.com/GabrielRF/telegram-urlprobot) ([source](https://github.com/GabrielRF/telegram-urlprobot)) by *GabrielRF* - URL shortener and URL expander. -* [Telegram Proxy Bot](https://github.com/mrgigabyte/proxybot) by *mrgigabyte* - `Credits for the original version of this bot goes to` **Groosha** `, simply added certain features which I thought were needed`. +* [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) by *GabrielRF* - Let me Google that for you. +* [Telegram Proxy Bot](https://github.com/mrgigabyte/proxybot) by *mrgigabyte* * [RadRetroRobot](https://github.com/Tronikart/RadRetroRobot) by *Tronikart* - Multifunctional Telegram Bot RadRetroRobot. * [League of Legends bot](https://telegram.me/League_of_Legends_bot) ([source](https://github.com/i32ropie/lol)) by *i32ropie* * [NeoBot](https://github.com/neoranger/NeoBot) by [@NeoRanger](https://github.com/neoranger) -* [TagAlertBot](https://github.com/pitasi/TagAlertBot) by *pitasi* * [ColorCodeBot](https://t.me/colorcodebot) ([source](https://github.com/andydecleyre/colorcodebot)) - Share code snippets as beautifully syntax-highlighted HTML and/or images. * [ComedoresUGRbot](http://telegram.me/ComedoresUGRbot) ([source](https://github.com/alejandrocq/ComedoresUGRbot)) by [*alejandrocq*](https://github.com/alejandrocq) - Telegram bot to check the menu of Universidad de Granada dining hall. -* [picpingbot](https://web.telegram.org/#/im?p=%40picpingbot) - Fun anonymous photo exchange by Boogie Muffin. -* [TheZigZagProject](https://github.com/WebShark025/TheZigZagProject) - The 'All In One' bot for Telegram! by WebShark025 * [proxybot](https://github.com/p-hash/proxybot) - Simple Proxy Bot for Telegram. by p-hash -* [DonantesMalagaBot](https://github.com/vfranch/DonantesMalagaBot)- DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. It also records the date of the last donation so that it helps the donors to know when they can donate again. - by vfranch +* [DonantesMalagaBot](https://github.com/vfranch/DonantesMalagaBot) - DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. It also records the date of the last donation so that it helps the donors to know when they can donate again. - by vfranch * [DuttyBot](https://github.com/DmytryiStriletskyi/DuttyBot) by *Dmytryi Striletskyi* - Timetable for one university in Kiev. -* [dailypepebot](https://telegram.me/dailypepebot) by [*Jaime*](https://github.com/jiwidi/Dailypepe) - Get's you random pepe images and gives you their id, then you can call this image with the number. -* [DailyQwertee](https://t.me/DailyQwertee) by [*Jaime*](https://github.com/jiwidi/DailyQwertee) - Bot that manages a channel that sends qwertee daily tshirts every day at 00:00 * [wat-bridge](https://github.com/rmed/wat-bridge) by [*rmed*](https://github.com/rmed) - Send and receive messages to/from WhatsApp through Telegram -* [flibusta_bot](https://github.com/Kurbezz/flibusta_bot) by [*Kurbezz*](https://github.com/Kurbezz) -* [EmaProject](https://github.com/halkliff/emaproject) by [*halkliff*](https://github.com/halkliff) - Ema - Eastern Media Assistant was made thinking on the ease-to-use feature. Coding here is simple, as much as is fast and powerful. * [filmratingbot](http://t.me/filmratingbot)([source](https://github.com/jcolladosp/film-rating-bot)) by [*jcolladosp*](https://github.com/jcolladosp) - Telegram bot using the Python API that gets films rating from IMDb and metacritic -* [you2mp3bot](http://t.me/you2mp3bot)([link](https://storebot.me/bot/you2mp3bot)) - This bot can convert a Youtube video to Mp3. All you need is send the URL video. * [Send2Kindlebot](http://t.me/Send2KindleBot) ([source](https://github.com/GabrielRF/Send2KindleBot)) by *GabrielRF* - Send to Kindle service. * [RastreioBot](http://t.me/RastreioBot) ([source](https://github.com/GabrielRF/RastreioBot)) by *GabrielRF* - Bot used to track packages on the Brazilian Mail Service. -* [filex_bot](http://t.me/filex_bot)([link](https://github.com/victor141516/FileXbot-telegram)) * [Spbu4UBot](http://t.me/Spbu4UBot)([link](https://github.com/EeOneDown/spbu4u)) by *EeOneDown* - Bot with timetables for SPbU students. * [SmartySBot](http://t.me/ZDU_bot)([link](https://github.com/0xVK/SmartySBot)) by *0xVK* - Telegram timetable bot, for Zhytomyr Ivan Franko State University students. -* [yandex_music_bot](http://t.me/yandex_music_bot)- Downloads tracks/albums/public playlists from Yandex.Music streaming service for free. * [LearnIt](https://t.me/LearnItbot)([link](https://github.com/tiagonapoli/LearnIt)) - A Telegram Bot created to help people to memorize other languages’ vocabulary. -* [MusicQuiz_bot](https://t.me/MusicQuiz_bot) by [Etoneja](https://github.com/Etoneja) - Listen to audio samples and try to name the performer of the song. * [Bot-Telegram-Shodan ](https://github.com/rubenleon/Bot-Telegram-Shodan) by [rubenleon](https://github.com/rubenleon) -* [MandangoBot](https://t.me/MandangoBot) by @Alvaricias - Bot for managing Marvel Strike Force alliances (only in spanish, atm). -* [ManjaroBot](https://t.me/ManjaroBot) by [@NeoRanger](https://github.com/neoranger) - Bot for Manjaro Linux Spanish group with a lot of info for Manjaro Newbies. * [VigoBusTelegramBot](https://t.me/vigobusbot) ([GitHub](https://github.com/Pythoneiro/VigoBus-TelegramBot)) - Bot that provides buses coming to a certain stop and their remaining time for the city of Vigo (Galicia - Spain) * [kaishnik-bot](https://t.me/kaishnik_bot) ([source](https://github.com/airatk/kaishnik-bot)) by *airatk* - bot which shows all the necessary information to KNTRU-KAI students. -* [Creation Date](https://t.me/creationdatebot) by @karipov - interpolates account creation dates based on telegram given ID’s -* [m0xbot](https://t.me/m0xbot) by [kor0p](https://github.com/kor0p) - tic-tac-toe. -* [kboardbot](https://t.me/kboardbot) by [kor0p](https://github.com/kor0p) - inline switches keyboard layout (English, Hebrew, Ukrainian, Russian). * [Robbie](https://t.me/romdeliverybot) ([source](https://github.com/FacuM/romdeliverybot_support)) by @FacuM - Support Telegram bot for developers and maintainers. * [AsadovBot](https://t.me/asadov_bot) ([source](https://github.com/desexcile/BotApi)) by @DesExcile - Сatalog of poems by Eduard Asadov. * [thesaurus_com_bot](https://t.me/thesaurus_com_bot) ([source](https://github.com/LeoSvalov/words-i-learn-bot)) by @LeoSvalov - words and synonyms from [dictionary.com](https://www.dictionary.com) and [thesaurus.com](https://www.thesaurus.com) in the telegram. * [InfoBot](https://t.me/info2019_bot) ([source](https://github.com/irevenko/info-bot)) by @irevenko - An all-round bot that displays some statistics (weather, time, crypto etc...) * [FoodBot](https://t.me/ChensonUz_bot) ([source](https://github.com/Fliego/old_restaurant_telegram_chatbot)) by @Fliego - a simple bot for food ordering * [Sporty](https://t.me/SportydBot) ([source](https://github.com/0xnu/sporty)) by @0xnu - Telegram bot for displaying the latest news, sports schedules and injury updates. -* [Neural style transfer](https://t.me/ebanyivolshebnikBot) ([source](https://github.com/timbyxty/StyleTransfer-tgbot)) by @timbyxty - bot for transferring style from one picture to another based on neural network. * [JoinGroup Silencer Bot](https://t.me/joingroup_silencer_bot) ([source](https://github.com/zeph1997/Telegram-Group-Silencer-Bot)) by [@zeph1997](https://github.com/zeph1997) - A Telegram Bot to remove "join group" and "removed from group" notifications. -* [AdviceBook](https://t.me/adviceokbot) by [@barbax7](https://github.com/barbax7) - A Telegram Bot that allows you to receive random reading tips when you don't know which book to read. -* [Blue_CC_Bot](https://t.me/Blue_CC_Bot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Checks Your Given Credit Cards And Says Which Is A Real,Card And Which Is Fake. -* [RandomInfoBot](https://t.me/RandomInfoBot) by [@Akash](https://github.com/BLUE-DEVIL1134) - A Telegram Bot Which Generates Random Information Of Humans Scraped From Over 13 Websites. * [TasksListsBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/TasksListsBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - A (tasks) lists manager bot for Telegram. * [MyElizaPsychologistBot](https://t.me/TasksListsBot) ([source](https://github.com/Pablo-Davila/MyElizaPsychologistBot)) by [@Pablo-Davila](https://github.com/Pablo-Davila) - An implementation of the famous Eliza psychologist chatbot. -* [Evdembot](https://t.me/Evdembot) by Adem Kavak. A bot that informs you about everything you want. * [Frcstbot](https://t.me/frcstbot) ([source](https://github.com/Mrsqd/frcstbot_public)) by [Mrsqd](https://github.com/Mrsqd). A Telegram bot that will always be happy to show you the weather forecast. -* [Bot Hour](https://t.me/roadtocode_bot) a little bot that say the time in different countries by [@diegop384](https://github.com/diegop384) [repo](https://github.com/diegop384/telegrambothour) -* [moodforfood_bot](https://t.me/moodforfood_bot) This bot will provide you with a list of food place(s) near your current Telegram location, which you are prompted to share. The API for all this info is from https://foursquare.com/. by [@sophiamarani](https://github.com/sophiamarani) -* [Donation with Amazon](https://t.me/donamazonbot) by [@barbax7](https://github.com/barbax7) This bot donates amazon advertising commissions to the non-profit organization chosen by the user. -* [COVID-19 Galicia Bot](https://t.me/covid19_galicia_bot) by [@dgarcoe](https://github.com/dgarcoe) This bot provides daily data related to the COVID19 crisis in Galicia (Spain) obtained from official government sources. * [MineGramBot](https://github.com/ModischFabrications/MineGramBot) by [ModischFabrications](https://github.com/ModischFabrications). This bot can start, stop and monitor a minecraft server. * [Tabletop DiceBot](https://github.com/dexpiper/tabletopdicebot) by [dexpiper](https://github.com/dexpiper). This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. * [BarnameKon](https://t.me/BarnameKonBot) by [Anvaari](https://github.com/anvaari). This Bot make "Add to google calendar" link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. [Source code](https://github.com/anvaari/BarnameKon) -* [Price Tracker](https://t.me/trackokbot) by [@barbax7](https://github.com/barbax7). This bot tracks amazon.it product's prices the user is interested to and notify him when one price go down. -* [Torrent Hunt](https://t.me/torrenthuntbot) by [@Hemantapkh](https://github.com/hemantapkh/torrenthunt). Torrent Hunt bot is a multilingual bot with inline mode support to search and explore torrents from 1337x.to. -* Translator bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/translate_text_bot). This bot can be use to translate texts. -* Digital Cryptocurrency bot by [Areeg Fahad (source)](https://github.com/AREEG94FAHAD/currencies_bot). With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. -* [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by [Leon Heess (source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. +* [Translator bot](https://github.com/AREEG94FAHAD/translate_text_bot) by Areeg Fahad. This bot can be used to translate texts. +* [Digital Cryptocurrency bot](https://github.com/AREEG94FAHAD/currencies_bot) by Areeg Fahad. With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. +* [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by Leon Heess [(source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. * [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) * [oneIPO bot](https://github.com/aaditya2200/IPO-proj) by [Aadithya](https://github.com/aaditya2200) & [Amol Soans](https://github.com/AmolDerickSoans) This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) -**Want to have your bot listed here? Just make a pull request.** +**Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.** diff --git a/telebot/version.py b/telebot/version.py index 8676c8d..9001d30 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '4.0.0' +__version__ = '4.0.1' From b95ab104e38775c9c214d945cc0ca01cb3528a55 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Mon, 13 Sep 2021 23:09:06 +0500 Subject: [PATCH 261/350] Update custom_filters.py --- telebot/custom_filters.py | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 2491185..dd1f1a2 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -84,3 +84,49 @@ class ChatFilter(AdvancedCustomFilter): key = 'chat_id' def check(self, message, text): return message.chat.id in text + +class ForwardFilter(SimpleCustomFilter): + """ + Check whether message was forwarded. + + Example: + + @bot.message_handler(is_forwarded=True) + """ + + key = 'is_forwarded' + + def check(self, message): + return message.forward_from_chat is not None + +class IsReplyFilter(SimpleCustomFilter): + """ + Check whether message is a reply. + + Example: + + @bot.message_handler(is_reply=True) + """ + + key = 'is_reply' + + def check(self, message): + return message.reply_to_message is not None + + + +class LanguageFilter(AdvancedCustomFilter): + """ + Check users language_code. + + Example: + + @bot.message_handler(language_code=['ru']) + """ + + key = 'language_code' + + def check(self, message, text): + if type(text) is list:return message.from_user.language_code in text + else: return message.from_user.language_code == text + From 86a0a8cd6850f6f35dfe147ae54ae33e27a11702 Mon Sep 17 00:00:00 2001 From: coder2020official Date: Tue, 14 Sep 2021 15:00:27 +0500 Subject: [PATCH 262/350] Little fixes and example Fixed is_forwarded custom filter & created example --- examples/custom_filters/is_filter_example.py | 21 ++++++++++++++++++++ telebot/custom_filters.py | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 examples/custom_filters/is_filter_example.py diff --git a/examples/custom_filters/is_filter_example.py b/examples/custom_filters/is_filter_example.py new file mode 100644 index 0000000..46d769c --- /dev/null +++ b/examples/custom_filters/is_filter_example.py @@ -0,0 +1,21 @@ +import telebot +from telebot import custom_filters + +bot = telebot.TeleBot('TOKEN') + + +# Check if message is a reply +@bot.message_handler(is_reply=True) +def start_filter(message): + bot.send_message(message.chat.id, "Looks like you replied to my message.") + +# Check if message was forwarded +@bot.message_handler(is_forwarded=True) +def text_filter(message): + bot.send_message(message.chat.id, "I do not accept forwarded messages!") + +# Do not forget to register filters +bot.add_custom_filter(custom_filters.IsReplyFilter()) +bot.add_custom_filter(custom_filters.ForwardFilter()) + +bot.polling(non_stop=True) \ No newline at end of file diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index dd1f1a2..9a3c233 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -97,7 +97,7 @@ class ForwardFilter(SimpleCustomFilter): key = 'is_forwarded' def check(self, message): - return message.forward_from_chat is not None + return message.forward_from is not None class IsReplyFilter(SimpleCustomFilter): """ From fc31a2d466e5d4e252fb9668f2929e7f3a43c98c Mon Sep 17 00:00:00 2001 From: coder2020official Date: Tue, 14 Sep 2021 15:02:54 +0500 Subject: [PATCH 263/350] Update custom_filters.py --- telebot/custom_filters.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 9a3c233..7fc1866 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -87,7 +87,7 @@ class ChatFilter(AdvancedCustomFilter): class ForwardFilter(SimpleCustomFilter): """ - Check whether message was forwarded. + Check whether message was forwarded from channel or group. Example: @@ -97,7 +97,7 @@ class ForwardFilter(SimpleCustomFilter): key = 'is_forwarded' def check(self, message): - return message.forward_from is not None + return message.forward_from_chat is not None class IsReplyFilter(SimpleCustomFilter): """ From c5c4d081ea42c2330a4f86eb910cbc54a2dfd0c4 Mon Sep 17 00:00:00 2001 From: bim-ba Date: Sat, 18 Sep 2021 19:46:53 +0300 Subject: [PATCH 264/350] Added new example: anonymous chat-bot --- examples/anonymous_bot.py | 150 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 examples/anonymous_bot.py diff --git a/examples/anonymous_bot.py b/examples/anonymous_bot.py new file mode 100644 index 0000000..f83bd42 --- /dev/null +++ b/examples/anonymous_bot.py @@ -0,0 +1,150 @@ +# This bot is needed to connect two people and their subsequent anonymous communication +# +# Avaiable commands: +# `/start` - Just send you a messsage how to start +# `/find` - Find a person you can contact +# `/stop` - Stop active conversation + +import telebot +from telebot import types + +# Initialize bot with your token +bot = telebot.TeleBot(TOKEN) + +# The `users` variable is needed to contain chat ids that are either in the search or in the active dialog, like {chat_id, chat_id} +users = {} +# The `freeid` variable is needed to contain chat id, that want to start conversation +# Or, in other words: chat id of user in the search +freeid = None + +# `/start` command handler +# +# That command only sends you 'Just use /find command!' +# +@bot.message_handler(commands=['start']) +def start(message: types.Message): + bot.send_message(message.chat.id, 'Just use /find command!') + +# `/find` command handler +# +# That command finds opponent for you +# +# That command according to the following principle: +# 1. You have written `/find` command +# 2. If you are already in the search or have an active dialog, bot sends you 'Shut up!' +# 3. If not: +# 3.1. Bot sends you 'Finding...' +# 3.2. If there is no user in the search: +# 3.2.2. `freeid` updated with `your_chat_id` +# 3.3. If there is user in the search: +# 3.3.1. Both you and the user in the search recieve the message 'Founded!' +# 3.3.2. `users` updated with a {user_in_the_search_chat_id, your_chat_id} +# 3.3.3. `users` updated with a {your_chat_id, user_in_the_search_id} +# 3.3.4. `freeid` updated with `None` +# +@bot.message_handler(commands=['find']) +def find(message: types.Message): + global freeid + + if message.chat.id not in users: + bot.send_message(message.chat.id, 'Finding...') + + if freeid == None: + freeid = message.chat.id + else: + # Question: + # Is there any way to simplify this like `bot.send_message([message.chat.id, freeid], 'Founded!')`? + bot.send_message(message.chat.id, 'Founded!') + bot.send_message(freeid, 'Founded!') + + users[freeid] = message.chat.id + users[message.chat.id] = freeid + freeid = None + + print(users, freeid) # Debug purpose, you can remove that line + else: + bot.send_message(message.chat.id, 'Shut up!') + +# `/stop` command handler +# +# That command stops your current conversation (if it exist) +# +# That command according to the following principle: +# 1. You have written `/stop` command +# 2. If you are not have active dialog or you are not in search, bot sends you 'You are not in search!' +# 3. If you are in active dialog: +# 3.1. Bot sends you 'Stopping...' +# 3.2. Bot sends 'Your opponent is leavin`...' to your opponent +# 3.3. {your_opponent_chat_id, your_chat_id} removes from `users` +# 3.4. {your_chat_id, your_opponent_chat_id} removes from `users` +# 4. If you are only in search: +# 4.1. Bot sends you 'Stopping...' +# 4.2. `freeid` updated with `None` +# +@bot.message_handler(commands=['stop']) +def stop(message: types.Message): + global freeid + + if message.chat.id in users: + bot.send_message(message.chat.id, 'Stopping...') + bot.send_message(users[message.chat.id], 'Your opponent is leavin`...') + + del users[users[message.chat.id]] + del users[message.chat.id] + + print(users, freeid) # Debug purpose, you can remove that line + elif message.chat.id == freeid: + bot.send_message(message.chat.id, 'Stopping...') + freeid = None + + print(users, freeid) # Debug purpose, you can remove that line + else: + bot.send_message(message.chat.id, 'You are not in search!') + +# message handler for conversation +# +# That handler needed to send message from one opponent to another +# If you are not in `users`, you will recieve a message 'No one can hear you...' +# Otherwise all your messages are sent to your opponent +# +# Questions: +# Is there any way to improve readability like `content_types=['all']`? +# Is there any way to improve "elif-zone"? Like: +# `bot.send_message(users[message.chat.id], message.data)` +# +@bot.message_handler(content_types=['animation', 'audio', 'contact', 'dice', 'document', 'location', 'photo', 'sticker', 'text', 'venue', 'video', 'video_note', 'voice']) +def chatting(message: types.Message): + if message.chat.id in users and users[message.chat.id] != None: + + if message.content_type == 'animation': + bot.send_animation(users[message.chat.id], message.animation.file_id) + elif message.content_type == 'audio': + bot.send_audio(users[message.chat.id], message.audio.file_id) + elif message.content_type == 'contact': + bot.send_contact(users[message.chat.id], message.contact.phone_number, message.contact.first_name) + elif message.content_type == 'dice': + bot.send_dice(users[message.chat.id], message.dice.emoji) + elif message.content_type == 'document': + bot.send_document(users[message.chat.id], message.document.file_id) + elif message.content_type == 'location': + bot.send_location(users[message.chat.id], message.location.latitude, message.location.longitude) + elif message.content_type == 'photo': + bot.send_photo(users[message.chat.id], message.photo) + elif message.content_type == 'sticker': + bot.send_sticker(users[message.chat.id], message.sticker.file_id) + elif message.content_type == 'text': + bot.send_message(users[message.chat.id], message.text) + elif message.content_type == 'venue': + bot.send_venue(users[message.chat.id], message.venue.location.latitude, message.venue.location.longitude, message.venue.title, message.venue.address) + elif message.content_type == 'video': + bot.send_video(users[message.chat.id], message.video.file_id) + elif message.content_type == 'video_note': + bot.send_video_note(users[message.chat.id], message.video_note.file_id) + elif message.content_type == 'voice': + bot.send_voice(users[message.chat.id], message.voice.file_id) + + else: + bot.send_message(message.chat.id, 'No one can hear you...') + +# Start retrieving updates +bot.polling() \ No newline at end of file From aba2a9e1792fc07addd3b1133c5ee4fffd1b93c1 Mon Sep 17 00:00:00 2001 From: bim-ba <81964109+bim-ba@users.noreply.github.com> Date: Sun, 19 Sep 2021 17:41:07 +0300 Subject: [PATCH 265/350] Improve readabilty of "elif-zone" --- examples/anonymous_bot.py | 52 +++++++++++---------------------------- 1 file changed, 14 insertions(+), 38 deletions(-) diff --git a/examples/anonymous_bot.py b/examples/anonymous_bot.py index f83bd42..da0c00e 100644 --- a/examples/anonymous_bot.py +++ b/examples/anonymous_bot.py @@ -20,7 +20,6 @@ freeid = None # `/start` command handler # # That command only sends you 'Just use /find command!' -# @bot.message_handler(commands=['start']) def start(message: types.Message): bot.send_message(message.chat.id, 'Just use /find command!') @@ -41,7 +40,6 @@ def start(message: types.Message): # 3.3.2. `users` updated with a {user_in_the_search_chat_id, your_chat_id} # 3.3.3. `users` updated with a {your_chat_id, user_in_the_search_id} # 3.3.4. `freeid` updated with `None` -# @bot.message_handler(commands=['find']) def find(message: types.Message): global freeid @@ -80,7 +78,6 @@ def find(message: types.Message): # 4. If you are only in search: # 4.1. Bot sends you 'Stopping...' # 4.2. `freeid` updated with `None` -# @bot.message_handler(commands=['stop']) def stop(message: types.Message): global freeid @@ -108,43 +105,22 @@ def stop(message: types.Message): # Otherwise all your messages are sent to your opponent # # Questions: -# Is there any way to improve readability like `content_types=['all']`? -# Is there any way to improve "elif-zone"? Like: -# `bot.send_message(users[message.chat.id], message.data)` -# -@bot.message_handler(content_types=['animation', 'audio', 'contact', 'dice', 'document', 'location', 'photo', 'sticker', 'text', 'venue', 'video', 'video_note', 'voice']) +# 1. Is there any way to improve readability like `content_types=['all']`? +# 2. Is there any way to register this message handler only when i found the opponent? +@bot.message_handler(content_types=['animation', 'audio', 'contact', 'dice', 'document', 'location', 'photo', 'poll', 'sticker', 'text', 'venue', 'video', 'video_note', 'voice']) def chatting(message: types.Message): - if message.chat.id in users and users[message.chat.id] != None: - - if message.content_type == 'animation': - bot.send_animation(users[message.chat.id], message.animation.file_id) - elif message.content_type == 'audio': - bot.send_audio(users[message.chat.id], message.audio.file_id) - elif message.content_type == 'contact': - bot.send_contact(users[message.chat.id], message.contact.phone_number, message.contact.first_name) - elif message.content_type == 'dice': - bot.send_dice(users[message.chat.id], message.dice.emoji) - elif message.content_type == 'document': - bot.send_document(users[message.chat.id], message.document.file_id) - elif message.content_type == 'location': - bot.send_location(users[message.chat.id], message.location.latitude, message.location.longitude) - elif message.content_type == 'photo': - bot.send_photo(users[message.chat.id], message.photo) - elif message.content_type == 'sticker': - bot.send_sticker(users[message.chat.id], message.sticker.file_id) - elif message.content_type == 'text': - bot.send_message(users[message.chat.id], message.text) - elif message.content_type == 'venue': - bot.send_venue(users[message.chat.id], message.venue.location.latitude, message.venue.location.longitude, message.venue.title, message.venue.address) - elif message.content_type == 'video': - bot.send_video(users[message.chat.id], message.video.file_id) - elif message.content_type == 'video_note': - bot.send_video_note(users[message.chat.id], message.video_note.file_id) - elif message.content_type == 'voice': - bot.send_voice(users[message.chat.id], message.voice.file_id) - + if message.chat.id in users: + bot.copy_message(users[message.chat.id], users[users[message.chat.id]], message.id) else: bot.send_message(message.chat.id, 'No one can hear you...') # Start retrieving updates -bot.polling() \ No newline at end of file +# Questions: +# 1. Is there any way not to process messages sent earlier? +# +# For example: +# If the bot is turned off, and i tried to type `/find` nothing will happen, but... +# When i start the bot, `/find` command will processed, and i will be added to search +# +# I tried `skip_pending=True`, but thats was not helpful +bot.polling() From 38cc96d0f3de26ac341365e76a63f30ddd468c0f Mon Sep 17 00:00:00 2001 From: SwissCorePy <51398037+SwissCorePy@users.noreply.github.com> Date: Mon, 20 Sep 2021 14:31:00 +0200 Subject: [PATCH 266/350] added property `user` to TeleBot class Added property `user` to TeleBot class. The idea is to have easy access to the user object representing the bot without doing an API call every time. --- telebot/__init__.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/telebot/__init__.py b/telebot/__init__.py index 49a24ca..cdcbec2 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -207,6 +207,16 @@ class TeleBot: self.threaded = threaded if self.threaded: self.worker_pool = util.ThreadPool(num_threads=num_threads) + + @property + def user(self) -> types.User: + """ + The User object representing this bot. + Equivalent to bot.get_me() but the result is cached so only one API call is needed + """ + if not hasattr(self, "_user"): + self._user = types.User.de_json(self.get_me()) + return self._user def enable_save_next_step_handlers(self, delay=120, filename="./.handler-saves/step.save"): """ From 9c86ed623d8233bb1453061771dc538b1b9391b0 Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 22 Sep 2021 22:37:18 +0500 Subject: [PATCH 267/350] Update custom_filters.py --- telebot/custom_filters.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 7fc1866..2f3b9b1 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -130,3 +130,19 @@ class LanguageFilter(AdvancedCustomFilter): if type(text) is list:return message.from_user.language_code in text else: return message.from_user.language_code == text +class IsAdminFilter(SimpleCustomFilter): + """ + Check whether the user is administrator / owner of the chat. + + Example: + @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + """ + + key = 'is_chat_admin' + + def __init__(self, bot): + self._bot = bot + + def check(self, message): + return self._bot.get_chat_member(message.chat.id, message.from_user.id).status in ['creator', 'administrator'] + From cd92d95f9126a61ec9a67111ad1a8af8ca331074 Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 22 Sep 2021 22:37:57 +0500 Subject: [PATCH 268/350] Create admin_filter_example.py --- examples/custom_filters/admin_filter_example.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 examples/custom_filters/admin_filter_example.py diff --git a/examples/custom_filters/admin_filter_example.py b/examples/custom_filters/admin_filter_example.py new file mode 100644 index 0000000..98993e1 --- /dev/null +++ b/examples/custom_filters/admin_filter_example.py @@ -0,0 +1,12 @@ +import telebot +from telebot import custom_filters +bot = telebot.TeleBot('TOKEN') + +# Handler +@bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) +def answer_for_admin(message): + bot.send_message(message.chat.id,"hello my admin") + +# Register filter +bot.add_custom_filter(custom_filters.IsAdminFilter(bot)) +bot.polling() \ No newline at end of file From 716323e56adb08c7a6acf5bc66b78fea1218a41b Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 22 Sep 2021 22:46:19 +0500 Subject: [PATCH 269/350] Register_XXX_Handler --- examples/register_handler/config.py | 5 +++++ examples/register_handler/handlers.py | 9 +++++++++ examples/register_handler/main.py | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 examples/register_handler/config.py create mode 100644 examples/register_handler/handlers.py create mode 100644 examples/register_handler/main.py diff --git a/examples/register_handler/config.py b/examples/register_handler/config.py new file mode 100644 index 0000000..50f8a62 --- /dev/null +++ b/examples/register_handler/config.py @@ -0,0 +1,5 @@ +import telebot + +api_token = '' + +bot = telebot.TeleBot(api_token) \ No newline at end of file diff --git a/examples/register_handler/handlers.py b/examples/register_handler/handlers.py new file mode 100644 index 0000000..5d65b35 --- /dev/null +++ b/examples/register_handler/handlers.py @@ -0,0 +1,9 @@ +# All handlers can be written in this file +from config import bot + +def start_executor(message): + bot.send_message(message.chat.id, 'Hello!') + +# Write more handlers here if you wish. You don't need a decorator + +# Just create function and register in main file. \ No newline at end of file diff --git a/examples/register_handler/main.py b/examples/register_handler/main.py new file mode 100644 index 0000000..1d670e9 --- /dev/null +++ b/examples/register_handler/main.py @@ -0,0 +1,19 @@ +import telebot +from telebot import custom_filters +import config +bot = telebot.TeleBot(config.api_token) + +import handlers + +bot.register_message_handler(handlers.start_executor, commands=['start']) # Start command executor + +# See also +# bot.register_callback_query_handler(*args, **kwargs) +# bot.register_channel_post_handler(*args, **kwargs) +# bot.register_chat_member_handler(*args, **kwargs) +# bot.register_inline_handler(*args, **kwargs) +# bot.register_my_chat_member_handler(*args, **kwargs) +# bot.register_edited_message_handler(*args, **kwargs) +# And other functions.. + +bot.polling() \ No newline at end of file From 92ac5a41666e80bd273bc5ba3f96d3febc1b8d72 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 17:12:32 +0500 Subject: [PATCH 270/350] States, and some minor improvements --- examples/custom_states.py | 34 +++++++ .../main.py => register_handler.py} | 12 +-- examples/register_handler/config.py | 5 -- examples/register_handler/handlers.py | 9 -- telebot/__init__.py | 89 ++++++++++++++++++- telebot/handler_backends.py | 76 ++++++++++++++++ 6 files changed, 205 insertions(+), 20 deletions(-) create mode 100644 examples/custom_states.py rename examples/{register_handler/main.py => register_handler.py} (59%) delete mode 100644 examples/register_handler/config.py delete mode 100644 examples/register_handler/handlers.py diff --git a/examples/custom_states.py b/examples/custom_states.py new file mode 100644 index 0000000..9ad9b1c --- /dev/null +++ b/examples/custom_states.py @@ -0,0 +1,34 @@ +import telebot + +from telebot.handler_backends import State + +bot = telebot.TeleBot("") + +@bot.message_handler(commands=['start']) +def start_ex(message): + bot.set_state(message.chat.id, 1) + bot.send_message(message.chat.id, 'Hi, write me a name') + + +@bot.state_handler(state=1) +def name_get(message, state:State): + bot.send_message(message.chat.id, f'Now write me a surname') + state.set(message.chat.id, 2) + with state.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + +@bot.state_handler(state=2) +def ask_age(message, state:State): + bot.send_message(message.chat.id, "What is your age?") + state.set(message.chat.id, 3) + with state.retrieve_data(message.chat.id) as data: + data['surname'] = message.text + +@bot.state_handler(state=3) +def ready_for_answer(message, state: State): + with state.retrieve_data(message.chat.id) as data: + bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") + state.finish(message.chat.id) + +bot.polling() \ No newline at end of file diff --git a/examples/register_handler/main.py b/examples/register_handler.py similarity index 59% rename from examples/register_handler/main.py rename to examples/register_handler.py index 1d670e9..f733a3b 100644 --- a/examples/register_handler/main.py +++ b/examples/register_handler.py @@ -1,11 +1,13 @@ import telebot -from telebot import custom_filters -import config -bot = telebot.TeleBot(config.api_token) -import handlers +api_token = '1297441208:AAH5THRzLXvY5breGFzkrEOIj7zwCGzbQ-Y' -bot.register_message_handler(handlers.start_executor, commands=['start']) # Start command executor +bot = telebot.TeleBot(api_token) + +def start_executor(message): + bot.send_message(message.chat.id, 'Hello!') + +bot.register_message_handler(start_executor, commands=['start']) # Start command executor # See also # bot.register_callback_query_handler(*args, **kwargs) diff --git a/examples/register_handler/config.py b/examples/register_handler/config.py deleted file mode 100644 index 50f8a62..0000000 --- a/examples/register_handler/config.py +++ /dev/null @@ -1,5 +0,0 @@ -import telebot - -api_token = '' - -bot = telebot.TeleBot(api_token) \ No newline at end of file diff --git a/examples/register_handler/handlers.py b/examples/register_handler/handlers.py deleted file mode 100644 index 5d65b35..0000000 --- a/examples/register_handler/handlers.py +++ /dev/null @@ -1,9 +0,0 @@ -# All handlers can be written in this file -from config import bot - -def start_executor(message): - bot.send_message(message.chat.id, 'Hello!') - -# Write more handlers here if you wish. You don't need a decorator - -# Just create function and register in main file. \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index 32f7b1d..fe0d256 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -27,7 +27,7 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) from telebot import apihelper, util, types -from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend +from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, StateMachine, State REPLY_MARKUP_TYPES = Union[ @@ -186,6 +186,9 @@ class TeleBot: self.my_chat_member_handlers = [] self.chat_member_handlers = [] self.custom_filters = {} + self.state_handlers = [] + + self.current_states = StateMachine() if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { @@ -495,6 +498,7 @@ class TeleBot: def process_new_messages(self, new_messages): self._notify_next_handlers(new_messages) + self._notify_state_handlers(new_messages) self._notify_reply_handlers(new_messages) self.__notify_update(new_messages) self._notify_command_handlers(self.message_handlers, new_messages) @@ -2362,6 +2366,31 @@ class TeleBot: chat_id = message.chat.id self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) + def set_state(self, chat_id, state): + """ + Sets a new state of a user. + :param chat_id: + :param state: new state. can be string or integer. + """ + self.current_states.add_state(chat_id, state) + + def delete_state(self, chat_id): + """ + Delete the current state of a user. + :param chat_id: + :return: + """ + self.current_states.delete_state(chat_id) + + def get_state(self, chat_id): + """ + Get current state of a user. + :param chat_id: + :return: state of a user + """ + return self.current_states.current_state(chat_id) + + def register_next_step_handler_by_chat_id( self, chat_id: Union[int, str], callback: Callable, *args, **kwargs) -> None: """ @@ -2426,6 +2455,26 @@ class TeleBot: if need_pop: new_messages.pop(i) # removing message that was detected with next_step_handler + + def _notify_state_handlers(self, new_messages): + """ + Description: TBD + :param new_messages: + :return: + """ + for i, message in enumerate(new_messages): + need_pop = False + user_state = self.current_states.current_state(message.from_user.id) + if user_state: + for handler in self.state_handlers: + if handler['filters']['state'] == user_state: + need_pop = True + state = State(self.current_states) + self._exec_task(handler["function"], message, state) + if need_pop: + new_messages.pop(i) # removing message that was detected by states + + @staticmethod def _build_handler_dict(handler, **filters): """ @@ -2661,6 +2710,44 @@ class TeleBot: **kwargs) self.add_edited_message_handler(handler_dict) + + def state_handler(self, state=None, content_types=None, func=None,**kwargs): + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + state=state, + content_types=content_types, + func=func, + **kwargs) + self.add_state_handler(handler_dict) + return handler + + return decorator + + def add_state_handler(self, handler_dict): + """ + Adds the edit message handler + :param handler_dict: + :return: + """ + self.state_handlers.append(handler_dict) + + def register_state_handler(self, callback, state=None, content_types=None, func=None, **kwargs): + """ + Register a state handler. + :param callback: function to be called + :param state: state to be checked + :param content_types: + :param func: + """ + handler_dict = self._build_handler_dict(callback, + state=state, + content_types=content_types, + func=func, + **kwargs) + self.add_state_handler(handler_dict) + + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Channel post handler decorator diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index 9b54f7c..721aba6 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -141,3 +141,79 @@ class RedisHandlerBackend(HandlerBackend): handlers = pickle.loads(value) self.clear_handlers(handler_group_id) return handlers + + + +class StateMachine: + def __init__(self): + self._states = {} + + def add_state(self, chat_id, state): + """ + Add a state. + """ + if chat_id in self._states: + + self._states[int(chat_id)]['state'] = state + else: + self._states[chat_id] = {'state': state,'data': {}} + + def current_state(self, chat_id): + """Current state""" + if chat_id in self._states: return self._states[chat_id]['state'] + else: return False + + def delete_state(self, chat_id): + """Delete a state""" + return self._states.pop(chat_id) + + +class State: + """ + Base class for state managing. + """ + def __init__(self, obj: StateMachine) -> None: + self.obj = obj + + def set(self, chat_id, new_state): + """ + Set a new state for a user. + :param chat_id: + :param new_state: new_state of a user + """ + self.obj._states[chat_id]['state'] = new_state + + def finish(self, chat_id): + """ + Finish(delete) state of a user. + :param chat_id: + """ + self.obj._states.pop(chat_id) + + def retrieve_data(self, chat_id): + """ + Save input text. + + Usage: + with state.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + Also, at the end of your 'Form' you can get the name: + data['name'] + """ + return StateContext(self.obj, chat_id) + +class StateContext: + """ + Class for data. + """ + def __init__(self , obj: StateMachine, chat_id) -> None: + self.obj = obj + self.chat_id = chat_id + self.data = obj._states[chat_id]['data'] + + def __enter__(self): + return self.data + + def __exit__(self, exc_type, exc_val, exc_tb): + return \ No newline at end of file From beb4f8df44799df78f629fc3bbf56c84b8ff5a3c Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 17:15:33 +0500 Subject: [PATCH 271/350] Update register_handler.py --- examples/register_handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/register_handler.py b/examples/register_handler.py index f733a3b..2ca423a 100644 --- a/examples/register_handler.py +++ b/examples/register_handler.py @@ -1,6 +1,6 @@ import telebot -api_token = '1297441208:AAH5THRzLXvY5breGFzkrEOIj7zwCGzbQ-Y' +api_token = 'token' bot = telebot.TeleBot(api_token) From 2df6f00ba558804891dbbb226312890f31ea7c8e Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 18:22:54 +0500 Subject: [PATCH 272/350] Optimization Optimized code, added filters support --- telebot/__init__.py | 26 ++++++++++++++++++++++---- telebot/handler_backends.py | 5 ++++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index fe0d256..3b9bc65 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2468,6 +2468,11 @@ class TeleBot: if user_state: for handler in self.state_handlers: if handler['filters']['state'] == user_state: + for message_filter, filter_value in handler['filters'].items(): + if filter_value is None: + continue + if not self._test_filter(message_filter, filter_value, message): + return False need_pop = True state = State(self.current_states) self._exec_task(handler["function"], message, state) @@ -2711,12 +2716,21 @@ class TeleBot: self.add_edited_message_handler(handler_dict) - def state_handler(self, state=None, content_types=None, func=None,**kwargs): - + def state_handler(self, state, content_types=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + State handler for getting input from a user. + :param state: state of a user + :param content_types: + :param regexp: + :param func: + :param chat_types: + """ def decorator(handler): handler_dict = self._build_handler_dict(handler, state=state, content_types=content_types, + regexp=regexp, + chat_types=chat_types, func=func, **kwargs) self.add_state_handler(handler_dict) @@ -2732,7 +2746,7 @@ class TeleBot: """ self.state_handlers.append(handler_dict) - def register_state_handler(self, callback, state=None, content_types=None, func=None, **kwargs): + def register_state_handler(self, state, content_types=None, regexp=None, func=None, chat_types=None, **kwargs): """ Register a state handler. :param callback: function to be called @@ -2740,9 +2754,11 @@ class TeleBot: :param content_types: :param func: """ - handler_dict = self._build_handler_dict(callback, + handler_dict = self._build_handler_dict(handler, state=state, content_types=content_types, + regexp=regexp, + chat_types=chat_types, func=func, **kwargs) self.add_state_handler(handler_dict) @@ -3226,6 +3242,8 @@ class TeleBot: return message.content_type == 'text' and util.extract_command(message.text) in filter_value elif message_filter == 'chat_types': return message.chat.type in filter_value + elif message_filter == 'state': + return True elif message_filter == 'func': return filter_value(message) elif self.custom_filters and message_filter in self.custom_filters: diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index 721aba6..a3b8944 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -167,6 +167,9 @@ class StateMachine: """Delete a state""" return self._states.pop(chat_id) + def _get_data(self, chat_id): + return self._states[chat_id]['data'] + class State: """ @@ -210,7 +213,7 @@ class StateContext: def __init__(self , obj: StateMachine, chat_id) -> None: self.obj = obj self.chat_id = chat_id - self.data = obj._states[chat_id]['data'] + self.data = obj._get_data(chat_id) def __enter__(self): return self.data From 967b94b14f621e2277dd1f14440f1049ee4426df Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 20:27:03 +0500 Subject: [PATCH 273/350] Update handler_backends.py --- telebot/handler_backends.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index a3b8944..673bb46 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -151,6 +151,8 @@ class StateMachine: def add_state(self, chat_id, state): """ Add a state. + :param chat_id: + :param state: new state """ if chat_id in self._states: From 9287eced495e9cd49dba9548277b31d8514629f7 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 21:10:29 +0500 Subject: [PATCH 274/350] Update a typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 257b744..34d955b 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,7 @@ Handle edited channel post messages Handle callback queries ```python @bot.callback_query_handler(func=lambda call: True) -def test_callback(call): # <- passes a CallbackQuery type object to your function +def test_callback(call): # <- passes a CallbackQuery type object to your function logger.info(call) ``` From e721910c0c5c3c38517d4dca55aec68c71f26f10 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 22:19:07 +0500 Subject: [PATCH 275/350] Update __init__.py --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3b9bc65..3e90279 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2746,7 +2746,7 @@ class TeleBot: """ self.state_handlers.append(handler_dict) - def register_state_handler(self, state, content_types=None, regexp=None, func=None, chat_types=None, **kwargs): + def register_state_handler(self, callback, state, content_types=None, regexp=None, func=None, chat_types=None, **kwargs): """ Register a state handler. :param callback: function to be called @@ -2754,7 +2754,7 @@ class TeleBot: :param content_types: :param func: """ - handler_dict = self._build_handler_dict(handler, + handler_dict = self._build_handler_dict(callback=callback, state=state, content_types=content_types, regexp=regexp, From 8149551a154b97d5dd7fc30aa67dbdccf5604d8e Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 25 Sep 2021 20:33:32 +0300 Subject: [PATCH 276/350] Release 4.1.0 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 9001d30..c48449f 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '4.0.1' +__version__ = '4.1.0' From 39e875c1eab56d8f959940fb9d490080c62f5c0a Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 22:49:32 +0500 Subject: [PATCH 277/350] Update handler_backends.py --- telebot/handler_backends.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index 673bb46..a6a2dc6 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -156,7 +156,7 @@ class StateMachine: """ if chat_id in self._states: - self._states[int(chat_id)]['state'] = state + self._states[chat_id]['state'] = state else: self._states[chat_id] = {'state': state,'data': {}} @@ -186,14 +186,14 @@ class State: :param chat_id: :param new_state: new_state of a user """ - self.obj._states[chat_id]['state'] = new_state + self.obj.add_state(chat_id,new_state) def finish(self, chat_id): """ Finish(delete) state of a user. :param chat_id: """ - self.obj._states.pop(chat_id) + self.obj.delete_state(chat_id) def retrieve_data(self, chat_id): """ From 44b44ac2c55d697ee2ade34b67f4e2d746c1c84f Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 25 Sep 2021 23:05:36 +0500 Subject: [PATCH 278/350] Optimization --- telebot/__init__.py | 6 +++--- telebot/handler_backends.py | 18 +++++------------- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3e90279..ce25250 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -27,7 +27,7 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) from telebot import apihelper, util, types -from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, StateMachine, State +from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, State REPLY_MARKUP_TYPES = Union[ @@ -188,7 +188,7 @@ class TeleBot: self.custom_filters = {} self.state_handlers = [] - self.current_states = StateMachine() + self.current_states = State() if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { @@ -2474,7 +2474,7 @@ class TeleBot: if not self._test_filter(message_filter, filter_value, message): return False need_pop = True - state = State(self.current_states) + state = self.current_states self._exec_task(handler["function"], message, state) if need_pop: new_messages.pop(i) # removing message that was detected by states diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index a6a2dc6..fd55384 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -144,7 +144,7 @@ class RedisHandlerBackend(HandlerBackend): -class StateMachine: +class State: def __init__(self): self._states = {} @@ -172,28 +172,20 @@ class StateMachine: def _get_data(self, chat_id): return self._states[chat_id]['data'] - -class State: - """ - Base class for state managing. - """ - def __init__(self, obj: StateMachine) -> None: - self.obj = obj - def set(self, chat_id, new_state): """ Set a new state for a user. :param chat_id: :param new_state: new_state of a user """ - self.obj.add_state(chat_id,new_state) + self.add_state(chat_id,new_state) def finish(self, chat_id): """ Finish(delete) state of a user. :param chat_id: """ - self.obj.delete_state(chat_id) + self.delete_state(chat_id) def retrieve_data(self, chat_id): """ @@ -206,13 +198,13 @@ class State: Also, at the end of your 'Form' you can get the name: data['name'] """ - return StateContext(self.obj, chat_id) + return StateContext(self, chat_id) class StateContext: """ Class for data. """ - def __init__(self , obj: StateMachine, chat_id) -> None: + def __init__(self , obj: State, chat_id) -> None: self.obj = obj self.chat_id = chat_id self.data = obj._get_data(chat_id) From b35f17124f4b77b6b2d4c1416d913ea647574c82 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 25 Sep 2021 21:15:24 +0300 Subject: [PATCH 279/350] States minor update --- telebot/__init__.py | 9 +++++---- telebot/handler_backends.py | 4 +--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 3e90279..a9ce65c 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -498,8 +498,8 @@ class TeleBot: def process_new_messages(self, new_messages): self._notify_next_handlers(new_messages) - self._notify_state_handlers(new_messages) self._notify_reply_handlers(new_messages) + self._notify_state_handlers(new_messages) self.__notify_update(new_messages) self._notify_command_handlers(self.message_handlers, new_messages) @@ -2390,7 +2390,6 @@ class TeleBot: """ return self.current_states.current_state(chat_id) - def register_next_step_handler_by_chat_id( self, chat_id: Union[int, str], callback: Callable, *args, **kwargs) -> None: """ @@ -2462,6 +2461,8 @@ class TeleBot: :param new_messages: :return: """ + if not self.current_states: return + for i, message in enumerate(new_messages): need_pop = False user_state = self.current_states.current_state(message.from_user.id) @@ -3242,12 +3243,12 @@ class TeleBot: return message.content_type == 'text' and util.extract_command(message.text) in filter_value elif message_filter == 'chat_types': return message.chat.type in filter_value - elif message_filter == 'state': - return True elif message_filter == 'func': return filter_value(message) elif self.custom_filters and message_filter in self.custom_filters: return self._check_filter(message_filter,filter_value,message) + elif message_filter == 'state': + return True else: return False diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index 673bb46..a4d2f08 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -143,7 +143,6 @@ class RedisHandlerBackend(HandlerBackend): return handlers - class StateMachine: def __init__(self): self._states = {} @@ -172,7 +171,6 @@ class StateMachine: def _get_data(self, chat_id): return self._states[chat_id]['data'] - class State: """ Base class for state managing. @@ -221,4 +219,4 @@ class StateContext: return self.data def __exit__(self, exc_type, exc_val, exc_tb): - return \ No newline at end of file + return From 062fababf2d3e7b7728355abf891ba5cba01cf6e Mon Sep 17 00:00:00 2001 From: Badiboy Date: Tue, 28 Sep 2021 19:17:09 +0300 Subject: [PATCH 280/350] polling should leave our world. :) --- README.md | 15 +++++++-------- examples/anonymous_bot.py | 11 +---------- examples/chat_member_example.py | 2 +- examples/custom_filters/admin_filter_example.py | 2 +- examples/custom_filters/general_custom_filters.py | 2 +- examples/custom_filters/id_filter_example.py | 5 +---- examples/custom_filters/is_filter_example.py | 2 +- examples/custom_filters/text_filter_example.py | 2 +- examples/custom_states.py | 2 +- examples/deep_linking.py | 2 +- examples/detailed_example/detailed_example.py | 2 +- examples/echo_bot.py | 2 +- examples/inline_example.py | 2 +- examples/inline_keyboard_example.py | 2 +- examples/middleware/i18n.py | 2 +- examples/middleware/session.py | 2 +- examples/payments_example.py | 3 +-- examples/register_handler.py | 2 +- examples/skip_updates_example.py | 2 +- examples/step_example.py | 2 +- examples/telebot_bot/telebot_bot.py | 2 +- telebot/__init__.py | 10 +++++++--- 22 files changed, 34 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 34d955b..01f1bbd 100644 --- a/README.md +++ b/README.md @@ -121,13 +121,13 @@ This one echoes all incoming text messages back to the sender. It uses a lambda We now have a basic bot which replies a static message to "/start" and "/help" commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file: ```python -bot.polling() +bot.infinity_polling() ``` Alright, that's it! Our source file now looks like this: ```python import telebot -bot = telebot.TeleBot("TOKEN") +bot = telebot.TeleBot("YOUR_BOT_TOKEN") @bot.message_handler(commands=['start', 'help']) def send_welcome(message): @@ -137,7 +137,7 @@ def send_welcome(message): def echo_all(message): bot.reply_to(message, message.text) -bot.polling() +bot.infinity_polling() ``` To start the bot, simply open up a terminal and enter `python echo_bot.py` to run the bot! Test it by sending commands ('/start' and '/help') and arbitrary text messages. @@ -381,12 +381,10 @@ TOKEN = '' tb = telebot.TeleBot(TOKEN) #create a new Telegram Bot object # Upon calling this function, TeleBot starts polling the Telegram servers for new messages. -# - none_stop: True/False (default False) - Don't stop polling when receiving an error from the Telegram servers -# - interval: True/False (default False) - The interval between polling requests -# Note: Editing this parameter harms the bot's response time +# - interval: int (default 0) - The interval between polling requests # - timeout: integer (default 20) - Timeout in seconds for long polling. # - allowed_updates: List of Strings (default None) - List of update types to request -tb.polling(none_stop=False, interval=0, timeout=20) +tb.infinity_polling(interval=0, timeout=20) # getMe user = tb.get_me() @@ -398,6 +396,7 @@ tb.remove_webhook() # getUpdates updates = tb.get_updates() +# or updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout): # sendMessage @@ -614,7 +613,7 @@ def handle_messages(messages): bot.reply_to(message, 'Hi') bot.set_update_listener(handle_messages) -bot.polling() +bot.infinity_polling() ``` ### Using web hooks diff --git a/examples/anonymous_bot.py b/examples/anonymous_bot.py index da0c00e..db7eaf7 100644 --- a/examples/anonymous_bot.py +++ b/examples/anonymous_bot.py @@ -114,13 +114,4 @@ def chatting(message: types.Message): else: bot.send_message(message.chat.id, 'No one can hear you...') -# Start retrieving updates -# Questions: -# 1. Is there any way not to process messages sent earlier? -# -# For example: -# If the bot is turned off, and i tried to type `/find` nothing will happen, but... -# When i start the bot, `/find` command will processed, and i will be added to search -# -# I tried `skip_pending=True`, but thats was not helpful -bot.polling() +bot.infinity_polling(skip_pending=True) diff --git a/examples/chat_member_example.py b/examples/chat_member_example.py index b6fca73..36dbfb2 100644 --- a/examples/chat_member_example.py +++ b/examples/chat_member_example.py @@ -30,4 +30,4 @@ def my_chat_m(message: types.ChatMemberUpdated): @bot.message_handler(content_types=util.content_type_service) def delall(message: types.Message): bot.delete_message(message.chat.id,message.message_id) -bot.polling(allowed_updates=util.update_types) \ No newline at end of file +bot.infinity_polling(allowed_updates=util.update_types) diff --git a/examples/custom_filters/admin_filter_example.py b/examples/custom_filters/admin_filter_example.py index 98993e1..2aa683e 100644 --- a/examples/custom_filters/admin_filter_example.py +++ b/examples/custom_filters/admin_filter_example.py @@ -9,4 +9,4 @@ def answer_for_admin(message): # Register filter bot.add_custom_filter(custom_filters.IsAdminFilter(bot)) -bot.polling() \ No newline at end of file +bot.infinity_polling() diff --git a/examples/custom_filters/general_custom_filters.py b/examples/custom_filters/general_custom_filters.py index 382b68c..5eab569 100644 --- a/examples/custom_filters/general_custom_filters.py +++ b/examples/custom_filters/general_custom_filters.py @@ -39,4 +39,4 @@ def bye_user(message): bot.add_custom_filter(MainFilter()) bot.add_custom_filter(IsAdmin()) -bot.polling(skip_pending=True,non_stop=True) # Skip old updates \ No newline at end of file +bot.infinity_polling(skip_pending=True) # Skip old updates diff --git a/examples/custom_filters/id_filter_example.py b/examples/custom_filters/id_filter_example.py index 06a6ce3..4a5b883 100644 --- a/examples/custom_filters/id_filter_example.py +++ b/examples/custom_filters/id_filter_example.py @@ -13,10 +13,7 @@ def admin_rep(message): def not_admin(message): bot.send_message(message.chat.id, "You are not allowed to use this command") - # Do not forget to register bot.add_custom_filter(custom_filters.ChatFilter()) - -bot.polling(non_stop=True) - +bot.infinity_polling() diff --git a/examples/custom_filters/is_filter_example.py b/examples/custom_filters/is_filter_example.py index 46d769c..414ac0d 100644 --- a/examples/custom_filters/is_filter_example.py +++ b/examples/custom_filters/is_filter_example.py @@ -18,4 +18,4 @@ def text_filter(message): bot.add_custom_filter(custom_filters.IsReplyFilter()) bot.add_custom_filter(custom_filters.ForwardFilter()) -bot.polling(non_stop=True) \ No newline at end of file +bot.infinity_polling() diff --git a/examples/custom_filters/text_filter_example.py b/examples/custom_filters/text_filter_example.py index 2476097..73b6682 100644 --- a/examples/custom_filters/text_filter_example.py +++ b/examples/custom_filters/text_filter_example.py @@ -18,4 +18,4 @@ def text_filter(message): bot.add_custom_filter(custom_filters.TextMatchFilter()) bot.add_custom_filter(custom_filters.TextStartsFilter()) -bot.polling(non_stop=True) \ No newline at end of file +bot.infinity_polling() diff --git a/examples/custom_states.py b/examples/custom_states.py index 9ad9b1c..309fa6c 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -31,4 +31,4 @@ def ready_for_answer(message, state: State): bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") state.finish(message.chat.id) -bot.polling() \ No newline at end of file +bot.infinity_polling() diff --git a/examples/deep_linking.py b/examples/deep_linking.py index f5ea506..039e3a7 100644 --- a/examples/deep_linking.py +++ b/examples/deep_linking.py @@ -74,4 +74,4 @@ def send_welcome(message): bot.reply_to(message, reply) -bot.polling() +bot.infinity_polling() diff --git a/examples/detailed_example/detailed_example.py b/examples/detailed_example/detailed_example.py index 8f2878a..76359cf 100644 --- a/examples/detailed_example/detailed_example.py +++ b/examples/detailed_example/detailed_example.py @@ -130,4 +130,4 @@ def command_default(m): bot.send_message(m.chat.id, "I don't understand \"" + m.text + "\"\nMaybe try the help page at /help") -bot.polling() +bot.infinity_polling() diff --git a/examples/echo_bot.py b/examples/echo_bot.py index b66eb34..c55a004 100644 --- a/examples/echo_bot.py +++ b/examples/echo_bot.py @@ -25,4 +25,4 @@ def echo_message(message): bot.reply_to(message, message.text) -bot.polling() +bot.infinity_polling() diff --git a/examples/inline_example.py b/examples/inline_example.py index 21f05eb..b0dc106 100644 --- a/examples/inline_example.py +++ b/examples/inline_example.py @@ -61,7 +61,7 @@ def default_query(inline_query): def main_loop(): - bot.polling(True) + bot.infinity_polling() while 1: time.sleep(3) diff --git a/examples/inline_keyboard_example.py b/examples/inline_keyboard_example.py index f2b3fce..41f088a 100644 --- a/examples/inline_keyboard_example.py +++ b/examples/inline_keyboard_example.py @@ -24,4 +24,4 @@ def callback_query(call): def message_handler(message): bot.send_message(message.chat.id, "Yes/no?", reply_markup=gen_markup()) -bot.polling(none_stop=True) +bot.infinity_polling() diff --git a/examples/middleware/i18n.py b/examples/middleware/i18n.py index 3cea875..aafbdd0 100644 --- a/examples/middleware/i18n.py +++ b/examples/middleware/i18n.py @@ -50,4 +50,4 @@ def start(message): bot.send_message(message.chat.id, _('hello')) -bot.polling() +bot.infinity_polling() diff --git a/examples/middleware/session.py b/examples/middleware/session.py index a1a30e5..ccda6fc 100644 --- a/examples/middleware/session.py +++ b/examples/middleware/session.py @@ -58,4 +58,4 @@ def start(message): bot.send_message(message.chat.id, bot.session['state']) -bot.polling() +bot.infinity_polling() diff --git a/examples/payments_example.py b/examples/payments_example.py index d0f52d4..c8dbfc5 100644 --- a/examples/payments_example.py +++ b/examples/payments_example.py @@ -78,5 +78,4 @@ def got_payment(message): parse_mode='Markdown') -bot.skip_pending = True -bot.polling(none_stop=True, interval=0) +bot.infinity_polling(skip_pending = True) diff --git a/examples/register_handler.py b/examples/register_handler.py index 2ca423a..9ee074e 100644 --- a/examples/register_handler.py +++ b/examples/register_handler.py @@ -18,4 +18,4 @@ bot.register_message_handler(start_executor, commands=['start']) # Start command # bot.register_edited_message_handler(*args, **kwargs) # And other functions.. -bot.polling() \ No newline at end of file +bot.infinity_polling() diff --git a/examples/skip_updates_example.py b/examples/skip_updates_example.py index 0bd631b..dee5dd2 100644 --- a/examples/skip_updates_example.py +++ b/examples/skip_updates_example.py @@ -10,4 +10,4 @@ def send_welcome(message): def echo_all(message): bot.reply_to(message, message.text) -bot.polling(skip_pending=True)# Skip pending skips old updates +bot.infinity_polling(skip_pending=True)# Skip pending skips old updates diff --git a/examples/step_example.py b/examples/step_example.py index 0291c66..7c35bad 100644 --- a/examples/step_example.py +++ b/examples/step_example.py @@ -83,4 +83,4 @@ bot.enable_save_next_step_handlers(delay=2) # WARNING It will work only if enable_save_next_step_handlers was called! bot.load_next_step_handlers() -bot.polling() +bot.infinity_polling() diff --git a/examples/telebot_bot/telebot_bot.py b/examples/telebot_bot/telebot_bot.py index ac6b63c..1120707 100644 --- a/examples/telebot_bot/telebot_bot.py +++ b/examples/telebot_bot/telebot_bot.py @@ -81,4 +81,4 @@ def listener(messages): bot.set_update_listener(listener) -bot.polling() +bot.infinity_polling() diff --git a/telebot/__init__.py b/telebot/__init__.py index a9ce65c..5f96ee8 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -563,8 +563,9 @@ class TeleBot: for listener in self.update_listener: self._exec_task(listener, new_messages) - def infinity_polling(self, timeout=20, skip_pending=False, long_polling_timeout=20, logger_level=logging.ERROR, - allowed_updates=None, *args, **kwargs): + + def infinity_polling(self, timeout: int=20, skip_pending: bool=False, long_polling_timeout: int=20, logger_level=logging.ERROR, + allowed_updates: Optional[List[str]]=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. @@ -673,7 +674,10 @@ class TeleBot: # self.worker_pool.clear_exceptions() logger.info("Waiting for {0} seconds until retry".format(error_interval)) time.sleep(error_interval) - error_interval *= 2 + if error_interval * 2 < 60: + error_interval *= 2 + else: + error_interval = 60 else: # polling_thread.clear_exceptions() # self.worker_pool.clear_exceptions() From a28af3903d7ccc07b8c9e4a4678e18b489407f71 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Thu, 30 Sep 2021 11:56:36 +0300 Subject: [PATCH 281/350] Bugfix with one_time_keyboard = False --- telebot/types.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/telebot/types.py b/telebot/types.py index 1d8bdc0..8f68218 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -873,7 +873,7 @@ class ForceReply(JsonSerializable): def to_json(self): json_dict = {'force_reply': True} if self.selective is not None: - json_dict['selective'] = True + json_dict['selective'] = self.selective if self.input_field_placeholder: json_dict['input_field_placeholder'] = self.input_field_placeholder return json.dumps(json_dict) @@ -886,7 +886,7 @@ class ReplyKeyboardRemove(JsonSerializable): def to_json(self): json_dict = {'remove_keyboard': True} if self.selective: - json_dict['selective'] = True + json_dict['selective'] = self.selective return json.dumps(json_dict) @@ -960,11 +960,11 @@ class ReplyKeyboardMarkup(JsonSerializable): """ json_dict = {'keyboard': self.keyboard} if self.one_time_keyboard is not None: - json_dict['one_time_keyboard'] = True + json_dict['one_time_keyboard'] = self.one_time_keyboard if self.resize_keyboard is not None: - json_dict['resize_keyboard'] = True + json_dict['resize_keyboard'] = self.resize_keyboard if self.selective is not None: - json_dict['selective'] = True + json_dict['selective'] = self.selective if self.input_field_placeholder: json_dict['input_field_placeholder'] = self.input_field_placeholder return json.dumps(json_dict) From 2e4280a94747f2572d3e78b2edef7929c79c1e71 Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 1 Oct 2021 15:56:54 +0500 Subject: [PATCH 282/350] Update of state handlers No need to create state handlers --- examples/custom_states.py | 42 ++++++++++------ telebot/__init__.py | 97 +++++++------------------------------ telebot/custom_filters.py | 27 +++++++++++ telebot/handler_backends.py | 4 ++ 4 files changed, 77 insertions(+), 93 deletions(-) diff --git a/examples/custom_states.py b/examples/custom_states.py index 309fa6c..1d46f6c 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -1,34 +1,48 @@ import telebot -from telebot.handler_backends import State +from telebot import custom_filters bot = telebot.TeleBot("") + + @bot.message_handler(commands=['start']) def start_ex(message): bot.set_state(message.chat.id, 1) bot.send_message(message.chat.id, 'Hi, write me a name') + -@bot.state_handler(state=1) -def name_get(message, state:State): +@bot.message_handler(state="*", commands='cancel') +def any_state(message): + bot.send_message(message.chat.id, "Your state was cancelled.") + bot.delete_state(message.chat.id) + +@bot.message_handler(state=1) +def name_get(message): bot.send_message(message.chat.id, f'Now write me a surname') - state.set(message.chat.id, 2) - with state.retrieve_data(message.chat.id) as data: + bot.set_state(message.chat.id, 2) + with bot.retrieve_data(message.chat.id) as data: data['name'] = message.text -@bot.state_handler(state=2) -def ask_age(message, state:State): +@bot.message_handler(state=2) +def ask_age(message): bot.send_message(message.chat.id, "What is your age?") - state.set(message.chat.id, 3) - with state.retrieve_data(message.chat.id) as data: + bot.set_state(message.chat.id, 3) + with bot.retrieve_data(message.chat.id) as data: data['surname'] = message.text -@bot.state_handler(state=3) -def ready_for_answer(message, state: State): - with state.retrieve_data(message.chat.id) as data: +@bot.message_handler(state=3, is_digit=True) +def ready_for_answer(message): + with bot.retrieve_data(message.chat.id) as data: bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") - state.finish(message.chat.id) + bot.delete_state(message.chat.id) -bot.infinity_polling() +@bot.message_handler(state=3, is_digit=False) +def age_incorrect(message): + bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number') + +bot.add_custom_filter(custom_filters.StateFilter(bot)) +bot.add_custom_filter(custom_filters.IsDigitFilter()) +bot.infinity_polling(skip_pending=True) \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index bfefd92..d3cc2e5 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -499,7 +499,6 @@ class TeleBot: def process_new_messages(self, new_messages): self._notify_next_handlers(new_messages) self._notify_reply_handlers(new_messages) - self._notify_state_handlers(new_messages) self.__notify_update(new_messages) self._notify_command_handlers(self.message_handlers, new_messages) @@ -2386,6 +2385,9 @@ class TeleBot: """ self.current_states.delete_state(chat_id) + def retrieve_data(self, chat_id): + return self.current_states.retrieve_data(chat_id) + def get_state(self, chat_id): """ Get current state of a user. @@ -2394,6 +2396,14 @@ class TeleBot: """ return self.current_states.current_state(chat_id) + def add_data(self, chat_id, **kwargs): + """ + Add data to states. + :param chat_id: + """ + for key, value in kwargs.items(): + self.current_states._add_data(chat_id, key, value) + def register_next_step_handler_by_chat_id( self, chat_id: Union[int, str], callback: Callable, *args, **kwargs) -> None: """ @@ -2459,32 +2469,6 @@ class TeleBot: new_messages.pop(i) # removing message that was detected with next_step_handler - def _notify_state_handlers(self, new_messages): - """ - Description: TBD - :param new_messages: - :return: - """ - if not self.current_states: return - - for i, message in enumerate(new_messages): - need_pop = False - user_state = self.current_states.current_state(message.from_user.id) - if user_state: - for handler in self.state_handlers: - if handler['filters']['state'] == user_state: - for message_filter, filter_value in handler['filters'].items(): - if filter_value is None: - continue - if not self._test_filter(message_filter, filter_value, message): - return False - need_pop = True - state = self.current_states - self._exec_task(handler["function"], message, state) - if need_pop: - new_messages.pop(i) # removing message that was detected by states - - @staticmethod def _build_handler_dict(handler, **filters): """ @@ -2548,7 +2532,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, state=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. @@ -2591,6 +2575,9 @@ class TeleBot: if content_types is None: content_types = ["text"] + if type(state) is not list and state is not None: + state = [state] + if isinstance(commands, str): logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") commands = [commands] @@ -2605,6 +2592,7 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, + state=state, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2620,7 +2608,7 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, state=None, **kwargs): """ Registers message handler. :param callback: function to be called @@ -2644,6 +2632,7 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, + state=state, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2721,54 +2710,6 @@ class TeleBot: self.add_edited_message_handler(handler_dict) - def state_handler(self, state, content_types=None, regexp=None, func=None, chat_types=None, **kwargs): - """ - State handler for getting input from a user. - :param state: state of a user - :param content_types: - :param regexp: - :param func: - :param chat_types: - """ - def decorator(handler): - handler_dict = self._build_handler_dict(handler, - state=state, - content_types=content_types, - regexp=regexp, - chat_types=chat_types, - func=func, - **kwargs) - self.add_state_handler(handler_dict) - return handler - - return decorator - - def add_state_handler(self, handler_dict): - """ - Adds the edit message handler - :param handler_dict: - :return: - """ - self.state_handlers.append(handler_dict) - - def register_state_handler(self, callback, state, content_types=None, regexp=None, func=None, chat_types=None, **kwargs): - """ - Register a state handler. - :param callback: function to be called - :param state: state to be checked - :param content_types: - :param func: - """ - handler_dict = self._build_handler_dict(callback=callback, - state=state, - content_types=content_types, - regexp=regexp, - chat_types=chat_types, - func=func, - **kwargs) - self.add_state_handler(handler_dict) - - def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): """ Channel post handler decorator @@ -3251,8 +3192,6 @@ class TeleBot: return filter_value(message) elif self.custom_filters and message_filter in self.custom_filters: return self._check_filter(message_filter,filter_value,message) - elif message_filter == 'state': - return True else: return False diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 2f3b9b1..20b42c3 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -146,3 +146,30 @@ class IsAdminFilter(SimpleCustomFilter): def check(self, message): return self._bot.get_chat_member(message.chat.id, message.from_user.id).status in ['creator', 'administrator'] +class StateFilter(AdvancedCustomFilter): + """ + Filter to check state. + + Example: + @bot.message_handler(state=1) + """ + def __init__(self, bot): + self.bot = bot + key = 'state' + + def check(self, message, text): + if self.bot.current_states.current_state(message.from_user.id) is False:return False + elif '*' in text:return True + return self.bot.current_states.current_state(message.from_user.id) in text + +class IsDigitFilter(SimpleCustomFilter): + """ + Filter to check whether the string is made up of only digits. + + Example: + @bot.message_handler(is_digit=True) + """ + key = 'is_digit' + + def check(self, message): + return message.text.isdigit() diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index 9a37fad..d695b82 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -179,6 +179,10 @@ class State: """ self.add_state(chat_id,new_state) + def _add_data(self, chat_id, key, value): + result = self._states[chat_id]['data'][key] = value + return result + def finish(self, chat_id): """ Finish(delete) state of a user. From ff35f2521161651631876f1b766111d5b893fe6f Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 1 Oct 2021 16:08:01 +0500 Subject: [PATCH 283/350] Update __init__.py --- telebot/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index d3cc2e5..de6d76a 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2532,7 +2532,7 @@ class TeleBot: else: self.default_middleware_handlers.append(handler) - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, state=None, **kwargs): + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. From f337abe06eb20cf1938eebac4245af8835bf0d79 Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 1 Oct 2021 16:09:20 +0500 Subject: [PATCH 284/350] Update __init__.py --- telebot/__init__.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index de6d76a..8f46afc 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -2575,9 +2575,6 @@ class TeleBot: if content_types is None: content_types = ["text"] - if type(state) is not list and state is not None: - state = [state] - if isinstance(commands, str): logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") commands = [commands] @@ -2592,7 +2589,6 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, - state=state, func=func, **kwargs) self.add_message_handler(handler_dict) @@ -2608,7 +2604,7 @@ class TeleBot: """ self.message_handlers.append(handler_dict) - def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, state=None, **kwargs): + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): """ Registers message handler. :param callback: function to be called @@ -2632,7 +2628,6 @@ class TeleBot: content_types=content_types, commands=commands, regexp=regexp, - state=state, func=func, **kwargs) self.add_message_handler(handler_dict) From bf8736e17e432f67464614fd3f9446b15c9580a6 Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 1 Oct 2021 23:29:59 +0500 Subject: [PATCH 285/350] Critical fix --- examples/custom_states.py | 16 ++++++++++++++++ telebot/custom_filters.py | 5 +++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/examples/custom_states.py b/examples/custom_states.py index 1d46f6c..ac70bb9 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -8,6 +8,9 @@ bot = telebot.TeleBot("") @bot.message_handler(commands=['start']) def start_ex(message): + """ + Start command. Here we are starting state + """ bot.set_state(message.chat.id, 1) bot.send_message(message.chat.id, 'Hi, write me a name') @@ -15,11 +18,17 @@ def start_ex(message): @bot.message_handler(state="*", commands='cancel') def any_state(message): + """ + Cancel state + """ bot.send_message(message.chat.id, "Your state was cancelled.") bot.delete_state(message.chat.id) @bot.message_handler(state=1) def name_get(message): + """ + State 1. Will process when user's state is 1. + """ bot.send_message(message.chat.id, f'Now write me a surname') bot.set_state(message.chat.id, 2) with bot.retrieve_data(message.chat.id) as data: @@ -28,21 +37,28 @@ def name_get(message): @bot.message_handler(state=2) def ask_age(message): + """ + State 2. Will process when user's state is 2. + """ bot.send_message(message.chat.id, "What is your age?") bot.set_state(message.chat.id, 3) with bot.retrieve_data(message.chat.id) as data: data['surname'] = message.text +# result @bot.message_handler(state=3, is_digit=True) def ready_for_answer(message): with bot.retrieve_data(message.chat.id) as data: bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") bot.delete_state(message.chat.id) +#incorrect number @bot.message_handler(state=3, is_digit=False) def age_incorrect(message): bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number') +# register filters + bot.add_custom_filter(custom_filters.StateFilter(bot)) bot.add_custom_filter(custom_filters.IsDigitFilter()) bot.infinity_polling(skip_pending=True) \ No newline at end of file diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index 20b42c3..bce2399 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -159,8 +159,9 @@ class StateFilter(AdvancedCustomFilter): def check(self, message, text): if self.bot.current_states.current_state(message.from_user.id) is False:return False - elif '*' in text:return True - return self.bot.current_states.current_state(message.from_user.id) in text + elif text == '*':return True + elif type(text) is list:return self.bot.current_states.current_state(message.from_user.id) in text + return self.bot.current_states.current_state(message.from_user.id) == text class IsDigitFilter(SimpleCustomFilter): """ From eead303d473c654372fde0891df54beb4645bd04 Mon Sep 17 00:00:00 2001 From: TrevorWinstral Date: Wed, 6 Oct 2021 14:13:05 +0200 Subject: [PATCH 286/350] Updated README with my bots --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 01f1bbd..efeb297 100644 --- a/README.md +++ b/README.md @@ -719,6 +719,8 @@ Get help. Discuss. Chat. * [next_step_handler Example](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py) ## Bots using this API +* [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user +* [ETHLecture Bot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded to the video portal * [SiteAlert bot](https://telegram.me/SiteAlert_bot) ([source](https://github.com/ilteoood/SiteAlert-Python)) by *ilteoood* - Monitors websites and sends a notification on changes * [TelegramLoggingBot](https://github.com/aRandomStranger/TelegramLoggingBot) by *aRandomStranger* * [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) by *GabrielRF* - Let me Google that for you. From 585f627e1fed3d84fac86ea60c8ffbef4d10e183 Mon Sep 17 00:00:00 2001 From: TrevorWinstral Date: Wed, 6 Oct 2021 14:14:05 +0200 Subject: [PATCH 287/350] Updated README with my bots --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index efeb297..df13db9 100644 --- a/README.md +++ b/README.md @@ -720,7 +720,7 @@ Get help. Discuss. Chat. ## Bots using this API * [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user -* [ETHLecture Bot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded to the video portal +* [ETHLecture Bot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded * [SiteAlert bot](https://telegram.me/SiteAlert_bot) ([source](https://github.com/ilteoood/SiteAlert-Python)) by *ilteoood* - Monitors websites and sends a notification on changes * [TelegramLoggingBot](https://github.com/aRandomStranger/TelegramLoggingBot) by *aRandomStranger* * [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) by *GabrielRF* - Let me Google that for you. From dadfdc2f1328f84b14a29b06c418ae9268bdc15e Mon Sep 17 00:00:00 2001 From: TrevorWinstral Date: Wed, 6 Oct 2021 14:15:30 +0200 Subject: [PATCH 288/350] Updated README with my bots --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df13db9..b976944 100644 --- a/README.md +++ b/README.md @@ -720,7 +720,7 @@ Get help. Discuss. Chat. ## Bots using this API * [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user -* [ETHLecture Bot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded +* [ETHLectureBot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded * [SiteAlert bot](https://telegram.me/SiteAlert_bot) ([source](https://github.com/ilteoood/SiteAlert-Python)) by *ilteoood* - Monitors websites and sends a notification on changes * [TelegramLoggingBot](https://github.com/aRandomStranger/TelegramLoggingBot) by *aRandomStranger* * [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) by *GabrielRF* - Let me Google that for you. From bf79e8341eaf0983b46e5d934510b0ba0b0b51f5 Mon Sep 17 00:00:00 2001 From: TrevorWinstral <31442534+TrevorWinstral@users.noreply.github.com> Date: Fri, 8 Oct 2021 10:39:59 +0000 Subject: [PATCH 289/350] Moved bots to bottom of list --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b976944..39406d4 100644 --- a/README.md +++ b/README.md @@ -719,8 +719,6 @@ Get help. Discuss. Chat. * [next_step_handler Example](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py) ## Bots using this API -* [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user -* [ETHLectureBot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded * [SiteAlert bot](https://telegram.me/SiteAlert_bot) ([source](https://github.com/ilteoood/SiteAlert-Python)) by *ilteoood* - Monitors websites and sends a notification on changes * [TelegramLoggingBot](https://github.com/aRandomStranger/TelegramLoggingBot) by *aRandomStranger* * [Telegram LMGTFY_bot](https://github.com/GabrielRF/telegram-lmgtfy_bot) by *GabrielRF* - Let me Google that for you. @@ -761,5 +759,9 @@ Get help. Discuss. Chat. * [Anti-Tracking Bot](https://t.me/AntiTrackingBot) by Leon Heess [(source)](https://github.com/leonheess/AntiTrackingBot). Send any link, and the bot tries its best to remove all tracking from the link you sent. * [Developer Bot](https://t.me/IndDeveloper_bot) by [Vishal Singh](https://github.com/vishal2376) [(source code)](https://github.com/vishal2376/telegram-bot) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) * [oneIPO bot](https://github.com/aaditya2200/IPO-proj) by [Aadithya](https://github.com/aaditya2200) & [Amol Soans](https://github.com/AmolDerickSoans) This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) +* [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user +* [ETHLectureBot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded + + **Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.** From 5c9d4edca964bd16fd8fe98127e992765874f752 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 9 Oct 2021 22:31:34 +0300 Subject: [PATCH 290/350] Bump version 4.1.1 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index c48449f..205c523 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '4.1.0' +__version__ = '4.1.1' From 98044d6faa8f8b34df46f596e4442b57d98c9434 Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 13 Oct 2021 18:34:36 +0500 Subject: [PATCH 291/350] File support for states File support. Now states can be saved in pickle file --- examples/custom_states.py | 4 ++ telebot/__init__.py | 16 ++++- telebot/custom_filters.py | 6 +- telebot/handler_backends.py | 131 ++++++++++++++++++++++++++++++++++-- 4 files changed, 148 insertions(+), 9 deletions(-) diff --git a/examples/custom_states.py b/examples/custom_states.py index ac70bb9..c7acfe5 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -61,4 +61,8 @@ def age_incorrect(message): bot.add_custom_filter(custom_filters.StateFilter(bot)) bot.add_custom_filter(custom_filters.IsDigitFilter()) + +# set saving states into file. +bot.enable_saving_states() # you can delete this if you do not need to save states + bot.infinity_polling(skip_pending=True) \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index 8f46afc..b8b0c6e 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -27,7 +27,7 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) from telebot import apihelper, util, types -from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, State +from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, StateMemory, StateFile REPLY_MARKUP_TYPES = Union[ @@ -188,7 +188,8 @@ class TeleBot: self.custom_filters = {} self.state_handlers = [] - self.current_states = State() + self.current_states = StateMemory() + if apihelper.ENABLE_MIDDLEWARE: self.typed_middleware_handlers = { @@ -237,6 +238,17 @@ class TeleBot: """ self.next_step_backend = FileHandlerBackend(self.next_step_backend.handlers, filename, delay) + def enable_saving_states(self, filename="./.state-save/states.pkl"): + """ + Enable saving states (by default saving disabled) + + :param filename: Filename of saving file + + """ + + self.current_states = StateFile(filename=filename) + self.current_states._create_dir() + def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"): """ Enable saving reply handlers (by default saving disable) diff --git a/telebot/custom_filters.py b/telebot/custom_filters.py index bce2399..0b95523 100644 --- a/telebot/custom_filters.py +++ b/telebot/custom_filters.py @@ -158,9 +158,9 @@ class StateFilter(AdvancedCustomFilter): key = 'state' def check(self, message, text): - if self.bot.current_states.current_state(message.from_user.id) is False:return False - elif text == '*':return True - elif type(text) is list:return self.bot.current_states.current_state(message.from_user.id) in text + if self.bot.current_states.current_state(message.from_user.id) is False: return False + elif text == '*': return True + elif type(text) is list: return self.bot.current_states.current_state(message.from_user.id) in text return self.bot.current_states.current_state(message.from_user.id) == text class IsDigitFilter(SimpleCustomFilter): diff --git a/telebot/handler_backends.py b/telebot/handler_backends.py index d695b82..45b903b 100644 --- a/telebot/handler_backends.py +++ b/telebot/handler_backends.py @@ -143,7 +143,7 @@ class RedisHandlerBackend(HandlerBackend): return handlers -class State: +class StateMemory: def __init__(self): self._states = {} @@ -166,7 +166,7 @@ class State: def delete_state(self, chat_id): """Delete a state""" - return self._states.pop(chat_id) + self._states.pop(chat_id) def _get_data(self, chat_id): return self._states[chat_id]['data'] @@ -195,7 +195,7 @@ class State: Save input text. Usage: - with state.retrieve_data(message.chat.id) as data: + with bot.retrieve_data(message.chat.id) as data: data['name'] = message.text Also, at the end of your 'Form' you can get the name: @@ -203,11 +203,114 @@ class State: """ return StateContext(self, chat_id) + +class StateFile: + """ + Class to save states in a file. + """ + def __init__(self, filename): + self.file_path = filename + + def add_state(self, chat_id, state): + """ + Add a state. + :param chat_id: + :param state: new state + """ + states_data = self._read_data() + if chat_id in states_data: + states_data[chat_id]['state'] = state + return self._save_data(states_data) + else: + new_data = states_data[chat_id] = {'state': state,'data': {}} + return self._save_data(states_data) + + + def current_state(self, chat_id): + """Current state.""" + states_data = self._read_data() + if chat_id in states_data: return states_data[chat_id]['state'] + else: return False + + def delete_state(self, chat_id): + """Delete a state""" + states_data = self._read_data() + states_data.pop(chat_id) + self._save_data(states_data) + + def _read_data(self): + """ + Read the data from file. + """ + file = open(self.file_path, 'rb') + states_data = pickle.load(file) + file.close() + return states_data + + def _create_dir(self): + """ + Create directory .save-handlers. + """ + dirs = self.file_path.rsplit('/', maxsplit=1)[0] + os.makedirs(dirs, exist_ok=True) + if not os.path.isfile(self.file_path): + with open(self.file_path,'wb') as file: + pickle.dump({}, file) + + def _save_data(self, new_data): + """ + Save data after editing. + :param new_data: + """ + with open(self.file_path, 'wb+') as state_file: + pickle.dump(new_data, state_file, protocol=pickle.HIGHEST_PROTOCOL) + return True + + def _get_data(self, chat_id): + return self._read_data()[chat_id]['data'] + + def set(self, chat_id, new_state): + """ + Set a new state for a user. + :param chat_id: + :param new_state: new_state of a user + + """ + self.add_state(chat_id,new_state) + + def _add_data(self, chat_id, key, value): + states_data = self._read_data() + result = states_data[chat_id]['data'][key] = value + self._save_data(result) + + return result + + def finish(self, chat_id): + """ + Finish(delete) state of a user. + :param chat_id: + """ + self.delete_state(chat_id) + + def retrieve_data(self, chat_id): + """ + Save input text. + + Usage: + with bot.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + Also, at the end of your 'Form' you can get the name: + data['name'] + """ + return StateFileContext(self, chat_id) + + class StateContext: """ Class for data. """ - def __init__(self , obj: State, chat_id) -> None: + def __init__(self , obj: StateMemory, chat_id) -> None: self.obj = obj self.chat_id = chat_id self.data = obj._get_data(chat_id) @@ -217,3 +320,23 @@ class StateContext: def __exit__(self, exc_type, exc_val, exc_tb): return + +class StateFileContext: + """ + Class for data. + """ + def __init__(self , obj: StateFile, chat_id) -> None: + self.obj = obj + self.chat_id = chat_id + self.data = self.obj._get_data(self.chat_id) + + def __enter__(self): + return self.data + + def __exit__(self, exc_type, exc_val, exc_tb): + old_data = self.obj._read_data() + for i in self.data: + old_data[self.chat_id]['data'][i] = self.data.get(i) + self.obj._save_data(old_data) + + return From b6625baec63038cb2733c1ba5a951a3275713457 Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 13 Oct 2021 19:02:17 +0500 Subject: [PATCH 292/350] Update __init__.py --- telebot/__init__.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index b8b0c6e..64cf2c7 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -357,7 +357,7 @@ class TeleBot: """ return apihelper.delete_webhook(self.token, drop_pending_updates, timeout) - def get_webhook_info(self, timeout=None): + def get_webhook_info(self, timeout: Optional[int]=None): """ Use this method to get current webhook status. Requires no parameters. If the bot is using getUpdates, will return an object with the url field empty. @@ -2381,7 +2381,7 @@ class TeleBot: chat_id = message.chat.id self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) - def set_state(self, chat_id, state): + def set_state(self, chat_id: int, state: Union[int, str]): """ Sets a new state of a user. :param chat_id: @@ -2389,7 +2389,7 @@ class TeleBot: """ self.current_states.add_state(chat_id, state) - def delete_state(self, chat_id): + def delete_state(self, chat_id: int): """ Delete the current state of a user. :param chat_id: @@ -2397,10 +2397,10 @@ class TeleBot: """ self.current_states.delete_state(chat_id) - def retrieve_data(self, chat_id): + def retrieve_data(self, chat_id: int): return self.current_states.retrieve_data(chat_id) - def get_state(self, chat_id): + def get_state(self, chat_id: int): """ Get current state of a user. :param chat_id: @@ -2408,7 +2408,7 @@ class TeleBot: """ return self.current_states.current_state(chat_id) - def add_data(self, chat_id, **kwargs): + def add_data(self, chat_id: int, **kwargs): """ Add data to states. :param chat_id: From 5fb48e68a05324b2acda4733a4f792d5136f61e2 Mon Sep 17 00:00:00 2001 From: Andrea Barbagallo Date: Sat, 16 Oct 2021 17:45:15 +0200 Subject: [PATCH 293/350] Added description of the ApiTelegramException as attribute of the class --- .gitignore | 1 + telebot/apihelper.py | 1 + 2 files changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index c9919ab..e2bc744 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ var/ .idea/ venv/ +.venv/ # PyInstaller # Usually these files are written by a python script from a template diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 9588c4e..07e0528 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1661,4 +1661,5 @@ class ApiTelegramException(ApiException): result) self.result_json = result_json self.error_code = result_json['error_code'] + self.description = result_json['description'] From bb58d3fead6b399cf1d2784ecb01b7874fac6971 Mon Sep 17 00:00:00 2001 From: resinprotein2333 Date: Sun, 24 Oct 2021 16:45:49 +0800 Subject: [PATCH 294/350] Update README.md Add my bot into the bot list --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 39406d4..e870e7e 100644 --- a/README.md +++ b/README.md @@ -761,6 +761,7 @@ Get help. Discuss. Chat. * [oneIPO bot](https://github.com/aaditya2200/IPO-proj) by [Aadithya](https://github.com/aaditya2200) & [Amol Soans](https://github.com/AmolDerickSoans) This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) * [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user * [ETHLectureBot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded +* [Vlun Finder Bot](https://github.com/resinprotein2333/Vlun-Finder-bot) by [Resinprotein2333](https://github.com/resinprotein2333). This bot can help you to find The information of CVE vulnerabilities. From 1a351bc8c76756792c79cf0fc5aeb1eb42def157 Mon Sep 17 00:00:00 2001 From: Advik Singh Somvanshi Date: Sun, 24 Oct 2021 20:38:15 +0530 Subject: [PATCH 295/350] Added A New Bot --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e870e7e..10682a7 100644 --- a/README.md +++ b/README.md @@ -762,6 +762,7 @@ Get help. Discuss. Chat. * [CoronaGraphsBot](https://t.me/CovidGraph_bot) ([source](https://github.com/TrevorWinstral/CoronaGraphsBot)) by *TrevorWinstral* - Gets live COVID Country data, plots it, and briefs the user * [ETHLectureBot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded * [Vlun Finder Bot](https://github.com/resinprotein2333/Vlun-Finder-bot) by [Resinprotein2333](https://github.com/resinprotein2333). This bot can help you to find The information of CVE vulnerabilities. +* [ETHGasFeeTrackerBot](https://t.me/ETHGasFeeTrackerBot) ([Source](https://github.com/DevAdvik/ETHGasFeeTrackerBot]) by *DevAdvik* - Get Live Ethereum Gas Fees in GWEI From 558b37b1c3b0beba02e15d24db0ed6b3bf6a91f4 Mon Sep 17 00:00:00 2001 From: Andrea Barbagallo Date: Wed, 3 Nov 2021 15:30:10 +0100 Subject: [PATCH 296/350] New antiflood function --- telebot/util.py | 22 ++++++++++++++++++++++ tests/test_telebot.py | 7 +++++++ 2 files changed, 29 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index f871f09..b33aaa1 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -455,3 +455,25 @@ def webhook_google_functions(bot, request): return 'Bot FAIL', 400 else: return 'Bot ON' + +def antiflood(function, *args, **kwargs): + """ + Use this function inside loops in order to avoid getting TooManyRequests error. + Example: + + from telebot.util import antiflood + for chat_id in chat_id_list: + msg = antiflood(bot.send_message, chat_id, text) + + You want get the + """ + from telebot.apihelper import ApiTelegramException + from time import sleep + try: + msg = function(*args, **kwargs) + except ApiTelegramException as ex: + if ex.error_code == 429: + sleep(ex.result_json['parameters']['retry_after']) + msg = function(*args, **kwargs) + finally: + return msg \ No newline at end of file diff --git a/tests/test_telebot.py b/tests/test_telebot.py index 6e8f341..2426b0f 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -455,6 +455,13 @@ class TestTeleBot: new_msg = tb.edit_message_reply_markup(chat_id=CHAT_ID, message_id=ret_msg.message_id, reply_markup=markup) assert new_msg.message_id + def test_antiflood(self): + text = "Flooding" + tb = telebot.TeleBot(TOKEN) + for _ in range(0,100): + util.antiflood(tb.send_message, CHAT_ID, text) + assert _ + @staticmethod def create_text_message(text): params = {'text': text} From 4a274ba4403433bd6db098eee6ee801b9da2ed56 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 3 Nov 2021 18:48:46 +0300 Subject: [PATCH 297/350] Custom request sender Added apihelper.CUSTOM_REQUEST_SENDER option. It allows to substitute requests.request to your own function. --- README.md | 34 ++++++++++++++++++++++++++++++---- telebot/apihelper.py | 13 ++++++++++--- telebot/util.py | 15 +++++++++++++++ 3 files changed, 55 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 39406d4..62e77c1 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ ## Contents - * [Getting started.](#getting-started) + * [Getting started](#getting-started) * [Writing your first bot](#writing-your-first-bot) * [Prerequisites](#prerequisites) * [A simple echo bot](#a-simple-echo-bot) @@ -49,6 +49,7 @@ * [Using web hooks](#using-web-hooks) * [Logging](#logging) * [Proxy](#proxy) + * [Testing](#testing) * [API conformance](#api-conformance) * [F.A.Q.](#faq) * [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat) @@ -57,7 +58,7 @@ * [More examples](#more-examples) * [Bots using this API](#bots-using-this-api) -## Getting started. +## Getting started This API is tested with Python 3.6-3.9 and Pypy 3. There are two ways to install the library: @@ -622,7 +623,6 @@ When using webhooks telegram sends one Update per call, for processing it you sh There are some examples using webhooks in the [examples/webhook_examples](examples/webhook_examples) directory. ### Logging - You can use the Telebot module logger to log debug info about Telebot. Use `telebot.logger` to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the [Python logging module page](https://docs.python.org/2/library/logging.html) for more info. @@ -634,7 +634,6 @@ telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console. ``` ### Proxy - You can use proxy for request. `apihelper.proxy` object will use by call `requests` proxies argument. ```python @@ -649,6 +648,33 @@ If you want to use socket5 proxy you need install dependency `pip install reques apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'} ``` +### Testing +You can disable or change the interaction with real Telegram server by using +```python +apihelper.CUSTOM_REQUEST_SENDER = your_handler +``` +parameter. You can pass there your own function that will be called instead of _requests.request_. + +For example: +```python +def custom_sender(method, url, **kwargs): + print("custom_sender. method: {}, url: {}, params: {}".format(method, url, kwargs.get("params"))) + result = util.CustomRequestResponse('{"ok":true,"result":{"message_id": 1, "date": 1, "chat": {"id": 1, "type": "private"}}}') + return result +``` + +Then you can use API and proceed requests in your handler code. +```python +apihelper.CUSTOM_REQUEST_SENDER = custom_sender +tb = TeleBot("test") +res = tb.send_message(123, "Test") +``` + +Result will be: + +`custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params: {'chat_id': '123', 'text': 'Test'}` + + ## API conformance diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 9588c4e..e9162ce 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -40,10 +40,12 @@ RETRY_TIMEOUT = 2 MAX_RETRIES = 15 CUSTOM_SERIALIZER = None +CUSTOM_REQUEST_SENDER = None ENABLE_MIDDLEWARE = False + def _get_req_session(reset=False): if SESSION_TIME_TO_LIVE: # If session TTL is set - check time passed @@ -136,9 +138,14 @@ def _make_request(token, method_name, method='get', params=None, files=None): method, request_url, params=params, files=files, timeout=(connect_timeout, read_timeout), proxies=proxy) else: - result = _get_req_session().request( - method, request_url, params=params, files=files, - timeout=(connect_timeout, read_timeout), proxies=proxy) + if CUSTOM_REQUEST_SENDER: + result = CUSTOM_REQUEST_SENDER( + method, request_url, params=params, files=files, + timeout=(connect_timeout, read_timeout), proxies=proxy) + else: + result = _get_req_session().request( + method, request_url, params=params, files=files, + timeout=(connect_timeout, read_timeout), proxies=proxy) logger.debug("The server returned: '{0}'".format(result.text.encode('utf8'))) diff --git a/telebot/util.py b/telebot/util.py index f871f09..05105ef 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -12,6 +12,11 @@ import logging from telebot import types +try: + import ujson as json +except ImportError: + import json + try: # noinspection PyPackageRequirements from PIL import Image @@ -165,6 +170,16 @@ class AsyncTask: return self.result +class CustomRequestResponse(): + def __init__(self, json_text, status_code = 200, reason = ""): + self.status_code = status_code + self.text = json_text + self.reason = reason + + def json(self): + return json.loads(self.text) + + def async_dec(): def decorator(fn): def wrapper(*args, **kwargs): From 06c878212704cc5e41622d9d18a2faaa2028da83 Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 5 Nov 2021 23:22:03 +0500 Subject: [PATCH 298/350] Little update Allowed other handlers, checked methods and other things --- telebot/__init__.py | 63 +++++++++++++++++++++++++++++++++++++++----- telebot/apihelper.py | 12 +++++++-- telebot/types.py | 31 +++++++++++++++++++--- 3 files changed, 94 insertions(+), 12 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 64cf2c7..185d1ee 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -185,6 +185,7 @@ class TeleBot: self.poll_answer_handlers = [] self.my_chat_member_handlers = [] self.chat_member_handlers = [] + self.chat_join_request_handlers = [] self.custom_filters = {} self.state_handlers = [] @@ -205,7 +206,8 @@ class TeleBot: 'poll': [], 'poll_answer': [], 'my_chat_member': [], - 'chat_member': [] + 'chat_member': [], + 'chat_join_request': [] } self.default_middleware_handlers = [] @@ -426,6 +428,7 @@ class TeleBot: new_poll_answers = None new_my_chat_members = None new_chat_members = None + chat_join_request = None for update in updates: if apihelper.ENABLE_MIDDLEWARE: @@ -480,6 +483,9 @@ class TeleBot: if update.chat_member: if new_chat_members is None: new_chat_members = [] new_chat_members.append(update.chat_member) + if update.chat_join_request: + if chat_join_request is None: chat_join_request = [] + chat_join_request.append(update.chat_join_request) if new_messages: self.process_new_messages(new_messages) @@ -507,6 +513,9 @@ class TeleBot: self.process_new_my_chat_member(new_my_chat_members) if new_chat_members: self.process_new_chat_member(new_chat_members) + if chat_join_request: + self.process_chat_join_request(chat_join_request) + def process_new_messages(self, new_messages): self._notify_next_handlers(new_messages) @@ -550,6 +559,9 @@ class TeleBot: def process_new_chat_member(self, chat_members): self._notify_command_handlers(self.chat_member_handlers, chat_members) + def process_chat_join_request(self, chat_join_request): + self._notify_command_handlers(self.chat_join_request_handlers, chat_join_request) + def process_middlewares(self, update): for update_type, middlewares in self.typed_middleware_handlers.items(): if getattr(update, update_type) is not None: @@ -1667,9 +1679,11 @@ class TeleBot: return apihelper.set_chat_permissions(self.token, chat_id, permissions) def create_chat_invite_link( - self, chat_id: Union[int, str], + self, chat_id: Union[int, str], + name: Optional[str]=None, expire_date: Optional[Union[int, datetime]]=None, - member_limit: Optional[int]=None) -> types.ChatInviteLink: + 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. @@ -1681,13 +1695,15 @@ class TeleBot: :return: """ return types.ChatInviteLink.de_json( - apihelper.create_chat_invite_link(self.token, chat_id, expire_date, member_limit) + apihelper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request) ) def edit_chat_invite_link( - self, chat_id: Union[int, str], invite_link: str, + self, chat_id: Union[int, str], name: Optional[str]=None, + invite_link: Optional[str] = None, expire_date: Optional[Union[int, datetime]]=None, - member_limit: Optional[int]=None) -> types.ChatInviteLink: + member_limit: Optional[int]=None , + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: """ Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -1701,7 +1717,7 @@ class TeleBot: :return: """ return types.ChatInviteLink.de_json( - apihelper.edit_chat_invite_link(self.token, chat_id, invite_link, expire_date, member_limit) + apihelper.edit_chat_invite_link(self.token, chat_id, name, invite_link, expire_date, member_limit, creates_join_request) ) def revoke_chat_invite_link( @@ -3148,6 +3164,39 @@ class TeleBot: handler_dict = self._build_handler_dict(callback, func=func, **kwargs) self.add_chat_member_handler(handler_dict) + def chat_join_request_handler(self, func=None, **kwargs): + """ + chat_join_request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + return handler + + return decorator + + def add_chat_join_request_handler(self, handler_dict): + """ + Adds a chat_join_request handler + :param handler_dict: + :return: + """ + self.chat_join_request_handlers.append(handler_dict) + + def register_chat_join_request_handler(self, callback, func=None, **kwargs): + """ + Registers chat join request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + def _test_message_handler(self, message_handler, message): """ Test message handler diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 7b7ee96..4d4f919 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -973,7 +973,7 @@ def set_chat_permissions(token, chat_id, permissions): return _make_request(token, method_url, params=payload, method='post') -def create_chat_invite_link(token, chat_id, expire_date, member_limit): +def create_chat_invite_link(token, chat_id, name, expire_date, member_limit, creates_join_request): method_url = 'createChatInviteLink' payload = { 'chat_id': chat_id @@ -986,11 +986,15 @@ def create_chat_invite_link(token, chat_id, expire_date, member_limit): payload['expire_date'] = expire_date if member_limit: payload['member_limit'] = member_limit + if creates_join_request: + payload['creates_join_request'] = creates_join_request + if name: + payload['name'] = name return _make_request(token, method_url, params=payload, method='post') -def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit): +def edit_chat_invite_link(token, chat_id, invite_link, name, expire_date, member_limit, creates_join_request): method_url = 'editChatInviteLink' payload = { 'chat_id': chat_id, @@ -1005,6 +1009,10 @@ def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit if member_limit is not None: payload['member_limit'] = member_limit + if name: + payload['name'] = name + if creates_join_request: + payload['creates_join_request'] = creates_join_request return _make_request(token, method_url, params=payload, method='post') diff --git a/telebot/types.py b/telebot/types.py index 8f68218..99b2559 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -107,6 +107,7 @@ class Update(JsonDeserializable): poll_answer = PollAnswer.de_json(obj.get('poll_answer')) my_chat_member = ChatMemberUpdated.de_json(obj.get('my_chat_member')) chat_member = ChatMemberUpdated.de_json(obj.get('chat_member')) + chat_join_request = ChatJoinRequest.de_json(obj.get('chat_join_request')) return cls(update_id, message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, my_chat_member, chat_member) @@ -166,6 +167,22 @@ class ChatMemberUpdated(JsonDeserializable): dif[key] = [old[key], new[key]] return dif +class ChatJoinRequest(JsonDeserializable): + @classmethod + def de_json(cls, json_string): + if json_string is None: return None + obj = cls.check_json(json_string) + obj['chat'] = Chat.de_json(obj['chat']) + obj['from'] = User.de_json(obj['from']) + + return cls(**obj) + + def __init__(self, chat, from_user, date, bio=None, invite_link=None, **kwargs): + self.chat = Chat = chat + self.from_user: User = from_user + self.date: int = date + self.bio: Optional[str] = bio + self.invite_link: Optional[ChatInviteLink] = invite_link class WebhookInfo(JsonDeserializable): @classmethod @@ -2752,14 +2769,17 @@ class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): obj['creator'] = User.de_json(obj['creator']) return cls(**obj) - def __init__(self, invite_link, creator, is_primary, is_revoked, - expire_date=None, member_limit=None, **kwargs): + def __init__(self, invite_link, creator, creates_join_request , is_primary, is_revoked, + name=None, expire_date=None, member_limit=None, pending_join_request_count=None, **kwargs): self.invite_link: str = invite_link self.creator: User = creator + self.creates_join_request: bool = creates_join_request self.is_primary: bool = is_primary self.is_revoked: bool = is_revoked + self.name: str = name self.expire_date: int = expire_date self.member_limit: int = member_limit + self.pending_join_request_count: int = pending_join_request_count def to_json(self): return json.dumps(self.to_dict()) @@ -2769,12 +2789,17 @@ class ChatInviteLink(JsonSerializable, JsonDeserializable, Dictionaryable): "invite_link": self.invite_link, "creator": self.creator.to_dict(), "is_primary": self.is_primary, - "is_revoked": self.is_revoked + "is_revoked": self.is_revoked, + "creates_join_request": self.creates_join_request } if self.expire_date: json_dict["expire_date"] = self.expire_date if self.member_limit: json_dict["member_limit"] = self.member_limit + if self.pending_join_request_count: + json_dict["pending_join_request_count"] = self.pending_join_request_count + if self.name: + json_dict["name"] = self.name return json_dict From 953e2286b854a84364f3b50ae2793841e408f8a9 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 12:15:28 +0500 Subject: [PATCH 299/350] Bot API 5.4 --- examples/chat_join_request.py | 11 +++++++++++ telebot/__init__.py | 28 ++++++++++++++++++++++++++++ telebot/apihelper.py | 15 ++++++++++++++- telebot/types.py | 7 ++++--- telebot/util.py | 2 +- 5 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 examples/chat_join_request.py diff --git a/examples/chat_join_request.py b/examples/chat_join_request.py new file mode 100644 index 0000000..6ab29ed --- /dev/null +++ b/examples/chat_join_request.py @@ -0,0 +1,11 @@ +import telebot + + +bot = telebot.TeleBot('TOKEN') + +@bot.chat_join_request_handler() +def make_some(message: telebot.types.ChatJoinRequest): + bot.send_message(message.chat.id, 'I accepted a new user!') + bot.approve_chat_join_request(message.chat.id, message.from_user.id) + +bot.infinity_polling(allowed_updates=telebot.util.update_types) \ No newline at end of file diff --git a/telebot/__init__.py b/telebot/__init__.py index 185d1ee..4aba9f9 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -484,6 +484,7 @@ class TeleBot: if new_chat_members is None: new_chat_members = [] new_chat_members.append(update.chat_member) if update.chat_join_request: + print('we received1') if chat_join_request is None: chat_join_request = [] chat_join_request.append(update.chat_join_request) @@ -514,6 +515,7 @@ class TeleBot: if new_chat_members: self.process_new_chat_member(new_chat_members) if chat_join_request: + print('we received2') self.process_chat_join_request(chat_join_request) @@ -1747,6 +1749,32 @@ class TeleBot: """ return apihelper.export_chat_invite_link(self.token, chat_id) + def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to approve a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return apihelper.approve_chat_join_request(self.token, chat_id, user_id) + + def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to decline a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return apihelper.decline_chat_join_request(self.token, chat_id, user_id) + 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. diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 4d4f919..f66db8a 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1031,7 +1031,20 @@ def export_chat_invite_link(token, chat_id): payload = {'chat_id': chat_id} return _make_request(token, method_url, params=payload, method='post') - +def approve_chat_join_request(token, chat_id, user_id): + method_url = 'approveChatJoinRequest' + payload = { + 'chat_id': chat_id, + 'user_id': user_id + } + return _make_request(token, method_url, params=payload, method='post') +def decline_chat_join_request(token, chat_id, user_id): + method_url = 'declineChatJoinRequest' + payload = { + 'chat_id': chat_id, + 'user_id': user_id + } + return _make_request(token, method_url, params=payload, method='post') def set_chat_photo(token, chat_id, photo): method_url = 'setChatPhoto' payload = {'chat_id': chat_id} diff --git a/telebot/types.py b/telebot/types.py index 99b2559..972e2fd 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -110,11 +110,11 @@ class Update(JsonDeserializable): chat_join_request = ChatJoinRequest.de_json(obj.get('chat_join_request')) return cls(update_id, message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, - my_chat_member, chat_member) + my_chat_member, chat_member, chat_join_request) def __init__(self, update_id, message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, - my_chat_member, chat_member): + my_chat_member, chat_member, chat_join_request): self.update_id = update_id self.message = message self.edited_message = edited_message @@ -129,6 +129,7 @@ class Update(JsonDeserializable): self.poll_answer = poll_answer self.my_chat_member = my_chat_member self.chat_member = chat_member + self.chat_join_request = chat_join_request class ChatMemberUpdated(JsonDeserializable): @@ -173,7 +174,7 @@ class ChatJoinRequest(JsonDeserializable): if json_string is None: return None obj = cls.check_json(json_string) obj['chat'] = Chat.de_json(obj['chat']) - obj['from'] = User.de_json(obj['from']) + obj['from_user'] = User.de_json(obj['from']) return cls(**obj) diff --git a/telebot/util.py b/telebot/util.py index 5eb99bc..1ab6201 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -46,7 +46,7 @@ content_type_service = [ update_types = [ "update_id", "message", "edited_message", "channel_post", "edited_channel_post", "inline_query", "chosen_inline_result", "callback_query", "shipping_query", "pre_checkout_query", "poll", "poll_answer", - "my_chat_member", "chat_member" + "my_chat_member", "chat_member", "chat_join_request" ] class WorkerThread(threading.Thread): From ed6616e4c72aba45ed9a53c52de57acbf8dda29f Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 12:21:02 +0500 Subject: [PATCH 300/350] Bot API 5.4 --- telebot/__init__.py | 2 -- telebot/types.py | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 4aba9f9..0919f6d 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -484,7 +484,6 @@ class TeleBot: if new_chat_members is None: new_chat_members = [] new_chat_members.append(update.chat_member) if update.chat_join_request: - print('we received1') if chat_join_request is None: chat_join_request = [] chat_join_request.append(update.chat_join_request) @@ -515,7 +514,6 @@ class TeleBot: if new_chat_members: self.process_new_chat_member(new_chat_members) if chat_join_request: - print('we received2') self.process_chat_join_request(chat_join_request) diff --git a/telebot/types.py b/telebot/types.py index 972e2fd..fdf6467 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -175,6 +175,7 @@ class ChatJoinRequest(JsonDeserializable): obj = cls.check_json(json_string) obj['chat'] = Chat.de_json(obj['chat']) obj['from_user'] = User.de_json(obj['from']) + obj['invite_link'] = ChatInviteLink.de_json(obj['invite_link']) return cls(**obj) From d49c57699eb470f5c4a299ee23e5b42cd2b168b9 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 12:27:19 +0500 Subject: [PATCH 301/350] Tests --- tests/test_handler_backends.py | 6 ++++-- tests/test_telebot.py | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_handler_backends.py b/tests/test_handler_backends.py index 638cb27..21cf8f9 100644 --- a/tests/test_handler_backends.py +++ b/tests/test_handler_backends.py @@ -64,9 +64,10 @@ def update_type(message): poll_answer = None my_chat_member = None chat_member = None + chat_join_request = None return types.Update(1001234038283, message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, - my_chat_member, chat_member) + my_chat_member, chat_member, chat_join_request) @pytest.fixture() @@ -83,9 +84,10 @@ def reply_to_message_update_type(reply_to_message): poll_answer = None my_chat_member = None chat_member = None + chat_join_request = None return types.Update(1001234038284, reply_to_message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, - poll, poll_answer, my_chat_member, chat_member) + poll, poll_answer, my_chat_member, chat_member, chat_join_request) def next_handler(message): diff --git a/tests/test_telebot.py b/tests/test_telebot.py index 2426b0f..2976a9a 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -485,9 +485,10 @@ class TestTeleBot: poll_answer = None my_chat_member = None chat_member = None + chat_join_request = None return types.Update(-1001234038283, message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, - my_chat_member, chat_member) + my_chat_member, chat_member, chat_join_request) def test_is_string_unicode(self): s1 = u'string' From 31097c5380cb8fde8b6999685ce82246be94d720 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 12:34:49 +0500 Subject: [PATCH 302/350] Update test_types.py --- tests/test_types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_types.py b/tests/test_types.py index 417a678..4669f82 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -222,7 +222,7 @@ def test_KeyboardButtonPollType(): def test_json_chat_invite_link(): - json_string = r'{"invite_link": "https://t.me/joinchat/z-abCdEFghijKlMn", "creator": {"id": 329343347, "is_bot": false, "first_name": "Test", "username": "test_user", "last_name": "User", "language_code": "en"}, "is_primary": false, "is_revoked": false, "expire_date": 1624119999, "member_limit": 10}' + json_string = r'{"invite_link":{"invite_link":"https://t.me/joinchat/MeASP-Wi...","creator":{"id":927266710,"is_bot":false,"first_name":">_run","username":"coder2020","language_code":"ru"},"pending_join_request_count":1,"creates_join_request":true,"is_primary":false,"is_revoked":false }}' invite_link = types.ChatInviteLink.de_json(json_string) assert invite_link.invite_link == 'https://t.me/joinchat/z-abCdEFghijKlMn' assert isinstance(invite_link.creator, types.User) From 6808ab3ebeb2da79e0b4bffc6f6bb6e6a375878d Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 12:42:48 +0500 Subject: [PATCH 303/350] Update test_types.py --- tests/test_types.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/test_types.py b/tests/test_types.py index 4669f82..d23f8fa 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -222,14 +222,18 @@ def test_KeyboardButtonPollType(): def test_json_chat_invite_link(): - json_string = r'{"invite_link":{"invite_link":"https://t.me/joinchat/MeASP-Wi...","creator":{"id":927266710,"is_bot":false,"first_name":">_run","username":"coder2020","language_code":"ru"},"pending_join_request_count":1,"creates_join_request":true,"is_primary":false,"is_revoked":false }}' + json_string = r'{"invite_link":"https://t.me/joinchat/MeASP-Wi...","creator":{"id":927266710,"is_bot":false,"first_name":">_run","username":"coder2020","language_code":"ru"},"pending_join_request_count":1,"creates_join_request":true,"is_primary":false,"is_revoked":false}' invite_link = types.ChatInviteLink.de_json(json_string) - assert invite_link.invite_link == 'https://t.me/joinchat/z-abCdEFghijKlMn' + assert invite_link.invite_link == 'https://t.me/joinchat/MeASP-Wi...' assert isinstance(invite_link.creator, types.User) assert not invite_link.is_primary assert not invite_link.is_revoked - assert invite_link.expire_date == 1624119999 - assert invite_link.member_limit == 10 + assert invite_link.expire_date is None + assert invite_link.member_limit is None + assert invite_link.name is None + assert invite_link.creator.id == 927266710 + assert invite_link.pending_join_request_count == 1 + assert invite_link.creates_join_request def test_chat_member_updated(): json_string = r'{"chat": {"id": -1234567890123, "type": "supergroup", "title": "No Real Group", "username": "NoRealGroup"}, "from": {"id": 133869498, "is_bot": false, "first_name": "Vincent"}, "date": 1624119999, "old_chat_member": {"user": {"id": 77777777, "is_bot": false, "first_name": "Pepe"}, "status": "member"}, "new_chat_member": {"user": {"id": 77777777, "is_bot": false, "first_name": "Pepe"}, "status": "administrator"}}' From 8dcfa0c2826caa210f625ae918d011b4a092970f Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 12:52:41 +0500 Subject: [PATCH 304/350] Little fix for states --- examples/custom_states.py | 14 ++++++++++---- tests/.state-save/states.pkl | 1 + tests/test_types.py | 1 + 3 files changed, 12 insertions(+), 4 deletions(-) create mode 100644 tests/.state-save/states.pkl diff --git a/examples/custom_states.py b/examples/custom_states.py index c7acfe5..3d16b5a 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -5,6 +5,12 @@ from telebot import custom_filters bot = telebot.TeleBot("") +class MyStates: + name = 1 + surname = 2 + age = 3 + + @bot.message_handler(commands=['start']) def start_ex(message): @@ -24,7 +30,7 @@ def any_state(message): bot.send_message(message.chat.id, "Your state was cancelled.") bot.delete_state(message.chat.id) -@bot.message_handler(state=1) +@bot.message_handler(state=MyStates.name) def name_get(message): """ State 1. Will process when user's state is 1. @@ -35,7 +41,7 @@ def name_get(message): data['name'] = message.text -@bot.message_handler(state=2) +@bot.message_handler(state=MyStates.surname) def ask_age(message): """ State 2. Will process when user's state is 2. @@ -46,14 +52,14 @@ def ask_age(message): data['surname'] = message.text # result -@bot.message_handler(state=3, is_digit=True) +@bot.message_handler(state=MyStates.age, is_digit=True) def ready_for_answer(message): with bot.retrieve_data(message.chat.id) as data: bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") bot.delete_state(message.chat.id) #incorrect number -@bot.message_handler(state=3, is_digit=False) +@bot.message_handler(state=MyStates.age, is_digit=False) def age_incorrect(message): bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number') diff --git a/tests/.state-save/states.pkl b/tests/.state-save/states.pkl new file mode 100644 index 0000000..e2ecf72 --- /dev/null +++ b/tests/.state-save/states.pkl @@ -0,0 +1 @@ +}. \ No newline at end of file diff --git a/tests/test_types.py b/tests/test_types.py index d23f8fa..7f9b32f 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -235,6 +235,7 @@ def test_json_chat_invite_link(): assert invite_link.pending_join_request_count == 1 assert invite_link.creates_join_request + def test_chat_member_updated(): json_string = r'{"chat": {"id": -1234567890123, "type": "supergroup", "title": "No Real Group", "username": "NoRealGroup"}, "from": {"id": 133869498, "is_bot": false, "first_name": "Vincent"}, "date": 1624119999, "old_chat_member": {"user": {"id": 77777777, "is_bot": false, "first_name": "Pepe"}, "status": "member"}, "new_chat_member": {"user": {"id": 77777777, "is_bot": false, "first_name": "Pepe"}, "status": "administrator"}}' cm_updated = types.ChatMemberUpdated.de_json(json_string) From fc347ae166f2c9aed80601a21383150f38b7384e Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 13:06:43 +0500 Subject: [PATCH 305/350] Update custom_states.py --- examples/custom_states.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/custom_states.py b/examples/custom_states.py index 3d16b5a..22691b2 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -17,7 +17,7 @@ def start_ex(message): """ Start command. Here we are starting state """ - bot.set_state(message.chat.id, 1) + bot.set_state(message.from_user.id, 1) bot.send_message(message.chat.id, 'Hi, write me a name') @@ -28,7 +28,7 @@ def any_state(message): Cancel state """ bot.send_message(message.chat.id, "Your state was cancelled.") - bot.delete_state(message.chat.id) + bot.delete_state(message.from_user.id) @bot.message_handler(state=MyStates.name) def name_get(message): @@ -36,8 +36,8 @@ def name_get(message): State 1. Will process when user's state is 1. """ bot.send_message(message.chat.id, f'Now write me a surname') - bot.set_state(message.chat.id, 2) - with bot.retrieve_data(message.chat.id) as data: + bot.set_state(message.from_user.id, 2) + with bot.retrieve_data(message.from_user.id) as data: data['name'] = message.text @@ -47,16 +47,16 @@ def ask_age(message): State 2. Will process when user's state is 2. """ bot.send_message(message.chat.id, "What is your age?") - bot.set_state(message.chat.id, 3) - with bot.retrieve_data(message.chat.id) as data: + bot.set_state(message.from_user.id, 3) + with bot.retrieve_data(message.from_user.id) as data: data['surname'] = message.text # result @bot.message_handler(state=MyStates.age, is_digit=True) def ready_for_answer(message): - with bot.retrieve_data(message.chat.id) as data: + with bot.retrieve_data(message.from_user.id) as data: bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") - bot.delete_state(message.chat.id) + bot.delete_state(message.from_user.id) #incorrect number @bot.message_handler(state=MyStates.age, is_digit=False) From 3a6073e3a0bcf9779eeab53a69aa49baf5de7392 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 13:08:49 +0500 Subject: [PATCH 306/350] Update custom_states.py --- examples/custom_states.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/custom_states.py b/examples/custom_states.py index 22691b2..5acc8f2 100644 --- a/examples/custom_states.py +++ b/examples/custom_states.py @@ -17,7 +17,7 @@ def start_ex(message): """ Start command. Here we are starting state """ - bot.set_state(message.from_user.id, 1) + bot.set_state(message.from_user.id, MyStates.name) bot.send_message(message.chat.id, 'Hi, write me a name') @@ -36,7 +36,7 @@ def name_get(message): State 1. Will process when user's state is 1. """ bot.send_message(message.chat.id, f'Now write me a surname') - bot.set_state(message.from_user.id, 2) + bot.set_state(message.from_user.id, MyStates.surname) with bot.retrieve_data(message.from_user.id) as data: data['name'] = message.text @@ -47,7 +47,7 @@ def ask_age(message): State 2. Will process when user's state is 2. """ bot.send_message(message.chat.id, "What is your age?") - bot.set_state(message.from_user.id, 3) + bot.set_state(message.from_user.id, MyStates.age) with bot.retrieve_data(message.from_user.id) as data: data['surname'] = message.text From becce1f580d5d1bb1ca6c8ef84e497f420781223 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 19:51:05 +0500 Subject: [PATCH 307/350] Update apihelper.py --- telebot/apihelper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index f66db8a..3ae004d 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -986,7 +986,7 @@ def create_chat_invite_link(token, chat_id, name, expire_date, member_limit, cre payload['expire_date'] = expire_date if member_limit: payload['member_limit'] = member_limit - if creates_join_request: + if creates_join_request is not None: payload['creates_join_request'] = creates_join_request if name: payload['name'] = name From 8003ff5e5937d1946a5f241c3763aa0d26c744aa Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 19:51:29 +0500 Subject: [PATCH 308/350] Delete states.pkl --- tests/.state-save/states.pkl | 1 - 1 file changed, 1 deletion(-) delete mode 100644 tests/.state-save/states.pkl diff --git a/tests/.state-save/states.pkl b/tests/.state-save/states.pkl deleted file mode 100644 index e2ecf72..0000000 --- a/tests/.state-save/states.pkl +++ /dev/null @@ -1 +0,0 @@ -}. \ No newline at end of file From e412d2f08402da0b3e414419300f15a9dd2023a1 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 19:56:10 +0500 Subject: [PATCH 309/350] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 54cc769..41ce353 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ * [Poll Answer Handler](#poll-answer-handler) * [My Chat Member Handler](#my-chat-member-handler) * [Chat Member Handler](#chat-member-handler) + * [Chat Join request handler](#chat-join-request-handler) * [Inline Mode](#inline-mode) * [Inline handler](#inline-handler) * [Chosen Inline handler](#chosen-inline-handler) @@ -272,6 +273,10 @@ Handle updates of a chat member's status in a chat `@bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function` *Note: "chat_member" updates are not requested by default. If you want to allow all update types, set `allowed_updates` in `bot.polling()` / `bot.infinity_polling()` to `util.update_types`* +#### Chat Join Request Handler +Handle chat join requests using: +`@bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function` + ### Inline Mode More information about [Inline mode](https://core.telegram.org/bots/inline). From 62b1ec04ab47c232697835e5567a9ab7b2c16b78 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 6 Nov 2021 19:59:44 +0500 Subject: [PATCH 310/350] Update __init__.py --- telebot/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 0919f6d..80b3818 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -514,7 +514,7 @@ class TeleBot: if new_chat_members: self.process_new_chat_member(new_chat_members) if chat_join_request: - self.process_chat_join_request(chat_join_request) + self.process_new_chat_join_request(chat_join_request) def process_new_messages(self, new_messages): @@ -559,7 +559,7 @@ class TeleBot: def process_new_chat_member(self, chat_members): self._notify_command_handlers(self.chat_member_handlers, chat_members) - def process_chat_join_request(self, chat_join_request): + def process_new_chat_join_request(self, chat_join_request): self._notify_command_handlers(self.chat_join_request_handlers, chat_join_request) def process_middlewares(self, update): From 5ac71baafed01bd7fa65eea7b101260134b8b6ae Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sun, 7 Nov 2021 23:02:23 +0300 Subject: [PATCH 311/350] RETRY_ENGINE Added RETRY_ENGINE var to api_helper. Added RETRY_ENGINE = 2 based on native "requests" retry mechanism. --- telebot/apihelper.py | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index e9162ce..e236723 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -9,6 +9,7 @@ except ImportError: import requests from requests.exceptions import HTTPError, ConnectionError, Timeout +from requests.adapters import HTTPAdapter try: # noinspection PyUnresolvedReferences @@ -38,6 +39,7 @@ SESSION_TIME_TO_LIVE = 600 # In seconds. None - live forever, 0 - one-time RETRY_ON_ERROR = False RETRY_TIMEOUT = 2 MAX_RETRIES = 15 +RETRY_ENGINE = 1 CUSTOM_SERIALIZER = None CUSTOM_REQUEST_SENDER = None @@ -107,45 +109,48 @@ def _make_request(token, method_name, method='get', params=None, files=None): params = params or None # Set params to None if empty result = None - if RETRY_ON_ERROR: + if RETRY_ON_ERROR and RETRY_ENGINE == 1: got_result = False current_try = 0 - while not got_result and current_try Date: Mon, 8 Nov 2021 18:35:55 +0300 Subject: [PATCH 312/350] Bump to version 4.2.0 --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 205c523..24f8550 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '4.1.1' +__version__ = '4.2.0' From 9b99bb5f217e41facc930c5e2758cd3f8b288407 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 8 Nov 2021 18:51:42 +0300 Subject: [PATCH 313/350] Update readme and typo --- README.md | 1 + telebot/__init__.py | 15 +++++++++------ telebot/apihelper.py | 7 ++++++- telebot/types.py | 13 ++++++------- 4 files changed, 22 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 41ce353..41081da 100644 --- a/README.md +++ b/README.md @@ -683,6 +683,7 @@ Result will be: ## API conformance +* ✔ [Bot API 5.4](https://core.telegram.org/bots/api#november-5-2021) * ➕ [Bot API 5.3](https://core.telegram.org/bots/api#june-25-2021) - ChatMemberXXX classes are full copies of ChatMember * ✔ [Bot API 5.2](https://core.telegram.org/bots/api#april-26-2021) * ✔ [Bot API 5.1](https://core.telegram.org/bots/api#march-9-2021) diff --git a/telebot/__init__.py b/telebot/__init__.py index 80b3818..cab3714 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -245,7 +245,6 @@ class TeleBot: Enable saving states (by default saving disabled) :param filename: Filename of saving file - """ self.current_states = StateFile(filename=filename) @@ -1690,8 +1689,10 @@ class TeleBot: :param chat_id: Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param name: Invite link name; 0-32 characters :param expire_date: Point in time (Unix timestamp) when the link will expire :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified :return: """ return types.ChatInviteLink.de_json( @@ -1699,21 +1700,23 @@ class TeleBot: ) def edit_chat_invite_link( - self, chat_id: Union[int, str], name: Optional[str]=None, - invite_link: Optional[str] = None, - expire_date: Optional[Union[int, datetime]]=None, - member_limit: Optional[int]=None , + self, chat_id: Union[int, str], + invite_link: Optional[str] = None, + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: """ Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - :param invite_link: :param chat_id: Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param name: Invite link name; 0-32 characters :param invite_link: The invite link to edit :param expire_date: Point in time (Unix timestamp) when the link will expire :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified :return: """ return types.ChatInviteLink.de_json( diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 37c7520..0ca982e 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -1016,7 +1016,7 @@ def edit_chat_invite_link(token, chat_id, invite_link, name, expire_date, member payload['member_limit'] = member_limit if name: payload['name'] = name - if creates_join_request: + if creates_join_request is not None: payload['creates_join_request'] = creates_join_request return _make_request(token, method_url, params=payload, method='post') @@ -1036,6 +1036,7 @@ def export_chat_invite_link(token, chat_id): payload = {'chat_id': chat_id} return _make_request(token, method_url, params=payload, method='post') + def approve_chat_join_request(token, chat_id, user_id): method_url = 'approveChatJoinRequest' payload = { @@ -1043,6 +1044,8 @@ def approve_chat_join_request(token, chat_id, user_id): 'user_id': user_id } return _make_request(token, method_url, params=payload, method='post') + + def decline_chat_join_request(token, chat_id, user_id): method_url = 'declineChatJoinRequest' payload = { @@ -1050,6 +1053,8 @@ def decline_chat_join_request(token, chat_id, user_id): 'user_id': user_id } return _make_request(token, method_url, params=payload, method='post') + + def set_chat_photo(token, chat_id, photo): method_url = 'setChatPhoto' payload = {'chat_id': chat_id} diff --git a/telebot/types.py b/telebot/types.py index fdf6467..263b327 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -175,16 +175,15 @@ class ChatJoinRequest(JsonDeserializable): obj = cls.check_json(json_string) obj['chat'] = Chat.de_json(obj['chat']) obj['from_user'] = User.de_json(obj['from']) - obj['invite_link'] = ChatInviteLink.de_json(obj['invite_link']) - + obj['invite_link'] = ChatInviteLink.de_json(obj.get('invite_link')) return cls(**obj) def __init__(self, chat, from_user, date, bio=None, invite_link=None, **kwargs): - self.chat = Chat = chat - self.from_user: User = from_user - self.date: int = date - self.bio: Optional[str] = bio - self.invite_link: Optional[ChatInviteLink] = invite_link + self.chat = chat + self.from_user = from_user + self.date = date + self.bio = bio + self.invite_link = invite_link class WebhookInfo(JsonDeserializable): @classmethod From e22a7fecea7501540c8efc4f2d97d7aefb942162 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Mon, 8 Nov 2021 18:53:10 +0300 Subject: [PATCH 314/350] One more readme update... --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41081da..849a249 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@

A simple, but extensible Python implementation for the Telegram Bot API. -##

Supported Bot API version: 5.3! +##

Supported Bot API version: 5.4! ## Contents From 7925bdc6c98197fafe0928ac75bebd6471038592 Mon Sep 17 00:00:00 2001 From: JoachimStanislaus Date: Thu, 11 Nov 2021 17:21:56 +0800 Subject: [PATCH 315/350] added Google Sheet bot to list of bot examples. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 849a249..37d56c7 100644 --- a/README.md +++ b/README.md @@ -795,6 +795,7 @@ Get help. Discuss. Chat. * [ETHLectureBot](https://t.me/ETHLectureBot) ([source](https://github.com/TrevorWinstral/ETHLectureBot)) by *TrevorWinstral* - Notifies ETH students when their lectures have been uploaded * [Vlun Finder Bot](https://github.com/resinprotein2333/Vlun-Finder-bot) by [Resinprotein2333](https://github.com/resinprotein2333). This bot can help you to find The information of CVE vulnerabilities. * [ETHGasFeeTrackerBot](https://t.me/ETHGasFeeTrackerBot) ([Source](https://github.com/DevAdvik/ETHGasFeeTrackerBot]) by *DevAdvik* - Get Live Ethereum Gas Fees in GWEI +* [Google Sheet Bot](https://github.com/JoachimStanislaus/Tele_Sheet_bot) by [JoachimStanislaus](https://github.com/JoachimStanislaus). This bot can help you to track your expenses by uploading your bot entries to your google sheet. From 1f05b47ad663c50dba6f7cc60ffa0b0f8394b377 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 20 Nov 2021 15:47:55 +0500 Subject: [PATCH 316/350] Asynchronous Telebot --- telebot/__init__.py | 3073 ++++++++++++++++++++++++--- telebot/asyncio_filters.py | 176 ++ telebot/asyncio_handler_backends.py | 343 +++ telebot/asyncio_helper.py | 1607 ++++++++++++++ 4 files changed, 4937 insertions(+), 262 deletions(-) create mode 100644 telebot/asyncio_filters.py create mode 100644 telebot/asyncio_handler_backends.py create mode 100644 telebot/asyncio_helper.py diff --git a/telebot/__init__.py b/telebot/__init__.py index cab3714..65906f2 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -12,10 +12,9 @@ from typing import Any, Callable, List, Optional, Union # this imports are used to avoid circular import error import telebot.util import telebot.types -from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter - logger = logging.getLogger('TeleBot') + formatter = logging.Formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' ) @@ -26,8 +25,13 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) -from telebot import apihelper, util, types +from telebot import apihelper, util, types, asyncio_helper from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, StateMemory, StateFile +from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter +import asyncio +from telebot import asyncio_handler_backends +from telebot import asyncio_filters + REPLY_MARKUP_TYPES = Union[ @@ -35,6 +39,7 @@ REPLY_MARKUP_TYPES = Union[ types.ReplyKeyboardRemove, types.ForceReply] + """ Module : telebot """ @@ -3308,338 +3313,2882 @@ class TeleBot: break -class AsyncTeleBot(TeleBot): - def __init__(self, *args, **kwargs): - TeleBot.__init__(self, *args, **kwargs) +class AsyncTeleBot: - # I'm not sure if `get_updates` should be added here too - @util.async_dec() - def enable_save_next_step_handlers(self, delay=120, filename="./.handler-saves/step.save"): - return TeleBot.enable_save_next_step_handlers(self, delay, filename) + def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, + exception_handler=None,suppress_middleware_excepions=False) -> None: # TODO: ADD TYPEHINTS + self.token = token + logger.info('creating some objects..') + self.loop = asyncio.get_event_loop() + self.offset = offset + self.token = token + self.parse_mode = parse_mode + self.update_listener = [] + self.suppress_middleware_excepions = suppress_middleware_excepions - @util.async_dec() - def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"): - return TeleBot.enable_save_reply_handlers(self, delay, filename) + self.exc_info = None - @util.async_dec() - def disable_save_next_step_handlers(self): - return TeleBot.disable_save_next_step_handlers(self) + self.exception_handler = exception_handler - @util.async_dec() - def disable_save_reply_handlers(self): - return TeleBot.enable_save_reply_handlers(self) + self.message_handlers = [] + self.edited_message_handlers = [] + self.channel_post_handlers = [] + self.edited_channel_post_handlers = [] + self.inline_handlers = [] + self.chosen_inline_handlers = [] + self.callback_query_handlers = [] + self.shipping_query_handlers = [] + self.pre_checkout_query_handlers = [] + self.poll_handlers = [] + self.poll_answer_handlers = [] + self.my_chat_member_handlers = [] + self.chat_member_handlers = [] + self.chat_join_request_handlers = [] + self.custom_filters = {} + self.state_handlers = [] - @util.async_dec() - def load_next_step_handlers(self, filename="./.handler-saves/step.save", del_file_after_loading=True): - return TeleBot.load_next_step_handlers(self, filename, del_file_after_loading) + self.current_states = asyncio_handler_backends.StateMemory() - @util.async_dec() - def load_reply_handlers(self, filename="./.handler-saves/reply.save", del_file_after_loading=True): - return TeleBot.load_reply_handlers(self, filename, del_file_after_loading) - @util.async_dec() - def get_me(self): - return TeleBot.get_me(self) + if asyncio_helper.ENABLE_MIDDLEWARE: + self.typed_middleware_handlers = { + 'message': [], + 'edited_message': [], + 'channel_post': [], + 'edited_channel_post': [], + 'inline_query': [], + 'chosen_inline_result': [], + 'callback_query': [], + 'shipping_query': [], + 'pre_checkout_query': [], + 'poll': [], + 'poll_answer': [], + 'my_chat_member': [], + 'chat_member': [], + 'chat_join_request': [] + } + self.default_middleware_handlers = [] - @util.async_dec() - def log_out(self): - return TeleBot.log_out(self) - @util.async_dec() - def close(self): - return TeleBot.close(self) + async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, + timeout: Optional[int]=None, allowed_updates: Optional[List]=None) -> types.Update: + json_updates = await asyncio_helper.get_updates(self.token, offset, limit, timeout, allowed_updates) + return [types.Update.de_json(ju) for ju in json_updates] - @util.async_dec() - def get_my_commands(self, *args, **kwargs): # needed args because new scope and language_code - return TeleBot.get_my_commands(self, *args, **kwargs) + async def polling(self, non_stop: bool=False, skip_pending=False, interval: int=0, timeout: int=20, + long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None, + none_stop: Optional[bool]=None): + """ + This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly. - @util.async_dec() - def set_my_commands(self, *args, **kwargs): - return TeleBot.set_my_commands(self, *args, **kwargs) + Warning: Do not call this function more than once! + + Always get updates. + :param interval: Delay between two update retrivals + :param non_stop: Do not stop polling when an ApiException occurs. + :param timeout: Request connection timeout + :param skip_pending: skip old updates + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + :param none_stop: Deprecated, use non_stop. Old typo f***up compatibility + :return: + """ + if none_stop is not None: + non_stop = none_stop + + if skip_pending: + await self.skip_updates() + await self._process_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates) + + async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, long_polling_timeout: int=20, logger_level=logging.ERROR, + allowed_updates: Optional[List[str]]=None, *args, **kwargs): + """ + Wrap polling with infinite loop and exception handling to avoid bot stops polling. + + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param skip_pending: skip old updates + :param logger_level: Custom logging level for infinity_polling logging. + Use logger levels from logging as a value. None/NOTSET = no error logging + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + """ + if skip_pending: + await self.skip_updates() + self._polling = True + while self._polling: + try: + await self._process_polling(non_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, + allowed_updates=allowed_updates, *args, **kwargs) + except Exception as e: + if logger_level and logger_level >= logging.ERROR: + logger.error("Infinity polling exception: %s", str(e)) + if logger_level and logger_level >= logging.DEBUG: + logger.error("Exception traceback:\n%s", traceback.format_exc()) + time.sleep(3) + continue + if logger_level and logger_level >= logging.INFO: + logger.error("Infinity polling: polling exited") + if logger_level and logger_level >= logging.INFO: + logger.error("Break infinity polling") + + async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20, + long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): + """ + Function to process polling. + :param non_stop: Do not stop polling when an ApiException occurs. + :param interval: Delay between two update retrivals + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + :return: + + """ + self._polling = True + + try: + while self._polling: + try: + + updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout) + + if updates: + logger.debug(f"Received {len(updates)} updates.") + + await self.process_new_updates(updates) + if interval: await asyncio.sleep(interval) + except KeyboardInterrupt: + logger.info("KeyboardInterrupt received.") + break + except asyncio.CancelledError: + break + except asyncio_helper.ApiTelegramException as e: + logger.info(str(e)) + + continue + except Exception as e: + print('Cause exception while getting updates.') + logger.critical(str(e)) + await asyncio.sleep(3) + continue + + finally: + self._polling = False + logger.warning('Polling is stopped.') + + + async def _loop_create_task(self, coro): + return asyncio.create_task(coro) + + async def _process_updates(self, handlers, messages): + for message in messages: + for message_handler in handlers: + process_update = await self._test_message_handler(message_handler, message) + if not process_update: + continue + elif process_update: + try: + await self._loop_create_task(message_handler['function'](message)) + break + except Exception as e: + print(str(e)) + + # update handling + async def process_new_updates(self, updates): + upd_count = len(updates) + logger.info('Received {0} new updates'.format(upd_count)) + if upd_count == 0: return + + new_messages = None + new_edited_messages = None + new_channel_posts = None + new_edited_channel_posts = None + new_inline_queries = None + new_chosen_inline_results = None + new_callback_queries = None + new_shipping_queries = None + new_pre_checkout_queries = None + new_polls = None + new_poll_answers = None + new_my_chat_members = None + new_chat_members = None + chat_join_request = None + for update in updates: + if asyncio_helper.ENABLE_MIDDLEWARE: + try: + self.process_middlewares(update) + except Exception as e: + logger.error(str(e)) + if not self.suppress_middleware_excepions: + raise + else: + if update.update_id > self.offset: self.offset = update.update_id + continue + logger.debug('Processing updates: {0}'.format(update)) + if update.update_id: + self.offset = update.update_id + 1 + if update.message: + logger.info('Processing message') + if new_messages is None: new_messages = [] + new_messages.append(update.message) + if update.edited_message: + if new_edited_messages is None: new_edited_messages = [] + new_edited_messages.append(update.edited_message) + if update.channel_post: + if new_channel_posts is None: new_channel_posts = [] + new_channel_posts.append(update.channel_post) + if update.edited_channel_post: + if new_edited_channel_posts is None: new_edited_channel_posts = [] + new_edited_channel_posts.append(update.edited_channel_post) + if update.inline_query: + if new_inline_queries is None: new_inline_queries = [] + new_inline_queries.append(update.inline_query) + if update.chosen_inline_result: + if new_chosen_inline_results is None: new_chosen_inline_results = [] + new_chosen_inline_results.append(update.chosen_inline_result) + if update.callback_query: + if new_callback_queries is None: new_callback_queries = [] + new_callback_queries.append(update.callback_query) + if update.shipping_query: + if new_shipping_queries is None: new_shipping_queries = [] + new_shipping_queries.append(update.shipping_query) + if update.pre_checkout_query: + if new_pre_checkout_queries is None: new_pre_checkout_queries = [] + new_pre_checkout_queries.append(update.pre_checkout_query) + if update.poll: + if new_polls is None: new_polls = [] + new_polls.append(update.poll) + if update.poll_answer: + if new_poll_answers is None: new_poll_answers = [] + new_poll_answers.append(update.poll_answer) + if update.my_chat_member: + if new_my_chat_members is None: new_my_chat_members = [] + new_my_chat_members.append(update.my_chat_member) + if update.chat_member: + if new_chat_members is None: new_chat_members = [] + new_chat_members.append(update.chat_member) + if update.chat_join_request: + if chat_join_request is None: chat_join_request = [] + chat_join_request.append(update.chat_join_request) + + if new_messages: + await self.process_new_messages(new_messages) + if new_edited_messages: + await self.process_new_edited_messages(new_edited_messages) + if new_channel_posts: + await self.process_new_channel_posts(new_channel_posts) + if new_edited_channel_posts: + await self.process_new_edited_channel_posts(new_edited_channel_posts) + if new_inline_queries: + await self.process_new_inline_query(new_inline_queries) + if new_chosen_inline_results: + await self.process_new_chosen_inline_query(new_chosen_inline_results) + if new_callback_queries: + await self.process_new_callback_query(new_callback_queries) + if new_shipping_queries: + await self.process_new_shipping_query(new_shipping_queries) + if new_pre_checkout_queries: + await self.process_new_pre_checkout_query(new_pre_checkout_queries) + if new_polls: + await self.process_new_poll(new_polls) + if new_poll_answers: + await self.process_new_poll_answer(new_poll_answers) + if new_my_chat_members: + await self.process_new_my_chat_member(new_my_chat_members) + if new_chat_members: + await self.process_new_chat_member(new_chat_members) + if chat_join_request: + await self.process_chat_join_request(chat_join_request) + + + async def process_new_messages(self, new_messages): + await self.__notify_update(new_messages) + await self._process_updates(self.message_handlers, new_messages) + + async def process_new_edited_messages(self, edited_message): + await self._process_updates(self.edited_message_handlers, edited_message) + + async def process_new_channel_posts(self, channel_post): + await self._process_updates(self.channel_post_handlers, channel_post) + + async def process_new_edited_channel_posts(self, edited_channel_post): + await self._process_updates(self.edited_channel_post_handlers, edited_channel_post) + + async def process_new_inline_query(self, new_inline_querys): + await self._process_updates(self.inline_handlers, new_inline_querys) + + async def process_new_chosen_inline_query(self, new_chosen_inline_querys): + await self._process_updates(self.chosen_inline_handlers, new_chosen_inline_querys) + + async def process_new_callback_query(self, new_callback_querys): + await self._process_updates(self.callback_query_handlers, new_callback_querys) + + async def process_new_shipping_query(self, new_shipping_querys): + await self._process_updates(self.shipping_query_handlers, new_shipping_querys) + + async def process_new_pre_checkout_query(self, pre_checkout_querys): + await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys) + + async def process_new_poll(self, polls): + await self._process_updates(self.poll_handlers, polls) + + async def process_new_poll_answer(self, poll_answers): + await self._process_updates(self.poll_answer_handlers, poll_answers) - @util.async_dec() - def delete_my_commands(self, *args, **kwargs): - return TeleBot.delete_my_commands(self, *args, **kwargs) + async def process_new_my_chat_member(self, my_chat_members): + await self._process_updates(self.my_chat_member_handlers, my_chat_members) - @util.async_dec() - def get_file(self, *args): - return TeleBot.get_file(self, *args) + async def process_new_chat_member(self, chat_members): + await self._process_updates(self.chat_member_handlers, chat_members) - @util.async_dec() - def download_file(self, *args): - return TeleBot.download_file(self, *args) + async def process_chat_join_request(self, chat_join_request): + await self._process_updates(self.chat_join_request_handlers, chat_join_request) - @util.async_dec() - def get_user_profile_photos(self, *args, **kwargs): - return TeleBot.get_user_profile_photos(self, *args, **kwargs) + async def process_middlewares(self, update): + for update_type, middlewares in self.typed_middleware_handlers.items(): + if getattr(update, update_type) is not None: + for typed_middleware_handler in middlewares: + try: + typed_middleware_handler(self, getattr(update, update_type)) + except Exception as e: + e.args = e.args + (f'Typed middleware handler "{typed_middleware_handler.__qualname__}"',) + raise - @util.async_dec() - def get_chat(self, *args): - return TeleBot.get_chat(self, *args) + if len(self.default_middleware_handlers) > 0: + for default_middleware_handler in self.default_middleware_handlers: + try: + default_middleware_handler(self, update) + except Exception as e: + e.args = e.args + (f'Default middleware handler "{default_middleware_handler.__qualname__}"',) + raise - @util.async_dec() - def leave_chat(self, *args): - return TeleBot.leave_chat(self, *args) - - @util.async_dec() - def get_chat_administrators(self, *args): - return TeleBot.get_chat_administrators(self, *args) - - @util.async_dec() - def get_chat_members_count(self, *args): - logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead') - return TeleBot.get_chat_member_count(self, *args) - @util.async_dec() - def get_chat_member_count(self, *args): - return TeleBot.get_chat_member_count(self, *args) + async def __notify_update(self, new_messages): + if len(self.update_listener) == 0: + return + for listener in self.update_listener: + self._loop_create_task(listener, new_messages) - @util.async_dec() - def set_chat_sticker_set(self, *args): - return TeleBot.set_chat_sticker_set(self, *args) + async def _test_message_handler(self, message_handler, message): + """ + Test message handler + :param message_handler: + :param message: + :return: + """ + for message_filter, filter_value in message_handler['filters'].items(): + if filter_value is None: + continue - @util.async_dec() - def delete_chat_sticker_set(self, *args): - return TeleBot.delete_chat_sticker_set(self, *args) + if not await self._test_filter(message_filter, filter_value, message): + return False - @util.async_dec() - def get_chat_member(self, *args): - return TeleBot.get_chat_member(self, *args) + return True - @util.async_dec() - def send_message(self, *args, **kwargs): - return TeleBot.send_message(self, *args, **kwargs) + def add_custom_filter(self, custom_filter): + """ + Create custom filter. + custom_filter: Class with check(message) method. + """ + self.custom_filters[custom_filter.key] = custom_filter - @util.async_dec() - def send_dice(self, *args, **kwargs): - return TeleBot.send_dice(self, *args, **kwargs) + async def _test_filter(self, message_filter, filter_value, message): + """ + Test filters + :param message_filter: Filter type passed in handler + :param filter_value: Filter value passed in handler + :param message: Message to test + :return: True if filter conforms + """ + # test_cases = { + # 'content_types': lambda msg: msg.content_type in filter_value, + # 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), + # 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + # 'func': lambda msg: filter_value(msg) + # } + # return test_cases.get(message_filter, lambda msg: False)(message) + if message_filter == 'content_types': + return message.content_type in filter_value + elif message_filter == 'regexp': + return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) + elif message_filter == 'commands': + return message.content_type == 'text' and util.extract_command(message.text) in filter_value + elif message_filter == 'chat_types': + return message.chat.type in filter_value + elif message_filter == 'func': + return filter_value(message) + elif self.custom_filters and message_filter in self.custom_filters: + return await self._check_filter(message_filter,filter_value,message) + else: + return False - @util.async_dec() - def send_animation(self, *args, **kwargs): - return TeleBot.send_animation(self, *args, **kwargs) + async def _check_filter(self, message_filter, filter_value, message): + """ + Check up the filter + :param message_filter: + :param filter_value: + :param message: + :return: + """ + filter_check = self.custom_filters.get(message_filter) + if not filter_check: + return False + elif isinstance(filter_check, asyncio_filters.SimpleCustomFilter): + return filter_value == await filter_check.check(message) + elif isinstance(filter_check, asyncio_filters.AdvancedCustomFilter): + return await filter_check.check(message, filter_value) + else: + logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter!") + return False - @util.async_dec() - def forward_message(self, *args, **kwargs): - return TeleBot.forward_message(self, *args, **kwargs) + def middleware_handler(self, update_types=None): + """ + Middleware handler decorator. - @util.async_dec() - def copy_message(self, *args, **kwargs): - return TeleBot.copy_message(self, *args, **kwargs) + This decorator can be used to decorate functions that must be handled as middlewares before entering any other + message handlers + But, be careful and check type of the update inside the handler if more than one update_type is given - @util.async_dec() - def delete_message(self, *args): - return TeleBot.delete_message(self, *args) + Example: - @util.async_dec() - def send_photo(self, *args, **kwargs): - return TeleBot.send_photo(self, *args, **kwargs) + bot = TeleBot('TOKEN') - @util.async_dec() - def send_audio(self, *args, **kwargs): - return TeleBot.send_audio(self, *args, **kwargs) + # Print post message text before entering to any post_channel handlers + @bot.middleware_handler(update_types=['channel_post', 'edited_channel_post']) + def print_channel_post_text(bot_instance, channel_post): + print(channel_post.text) - @util.async_dec() - def send_voice(self, *args, **kwargs): - return TeleBot.send_voice(self, *args, **kwargs) + # Print update id before entering to any handlers + @bot.middleware_handler() + def print_channel_post_text(bot_instance, update): + print(update.update_id) - @util.async_dec() - def send_document(self, *args, **kwargs): - return TeleBot.send_document(self, *args, **kwargs) + :param update_types: Optional list of update types that can be passed into the middleware handler. - @util.async_dec() - def send_sticker(self, *args, **kwargs): - return TeleBot.send_sticker(self, *args, **kwargs) + """ - @util.async_dec() - def send_video(self, *args, **kwargs): - return TeleBot.send_video(self, *args, **kwargs) + def decorator(handler): + self.add_middleware_handler(handler, update_types) + return handler - @util.async_dec() - def send_video_note(self, *args, **kwargs): - return TeleBot.send_video_note(self, *args, **kwargs) + return decorator - @util.async_dec() - def send_media_group(self, *args, **kwargs): - return TeleBot.send_media_group(self, *args, **kwargs) + def add_middleware_handler(self, handler, update_types=None): + """ + Add middleware handler + :param handler: + :param update_types: + :return: + """ + if not asyncio_helper.ENABLE_MIDDLEWARE: + raise RuntimeError("Middleware is not enabled. Use asyncio_helper.ENABLE_MIDDLEWARE.") - @util.async_dec() - def send_location(self, *args, **kwargs): - return TeleBot.send_location(self, *args, **kwargs) + if update_types: + for update_type in update_types: + self.typed_middleware_handlers[update_type].append(handler) + else: + self.default_middleware_handlers.append(handler) - @util.async_dec() - def edit_message_live_location(self, *args, **kwargs): - return TeleBot.edit_message_live_location(self, *args, **kwargs) + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + """ + Message handler decorator. + This decorator can be used to decorate functions that must handle certain types of messages. + All message handlers are tested in the order they were added. - @util.async_dec() - def stop_message_live_location(self, *args, **kwargs): - return TeleBot.stop_message_live_location(self, *args, **kwargs) + Example: - @util.async_dec() - def send_venue(self, *args, **kwargs): - return TeleBot.send_venue(self, *args, **kwargs) + bot = TeleBot('TOKEN') - @util.async_dec() - def send_contact(self, *args, **kwargs): - return TeleBot.send_contact(self, *args, **kwargs) + # Handles all messages which text matches regexp. + @bot.message_handler(regexp='someregexp') + async def command_help(message): + bot.send_message(message.chat.id, 'Did someone call for help?') - @util.async_dec() - def send_chat_action(self, *args, **kwargs): - return TeleBot.send_chat_action(self, *args, **kwargs) + # Handles messages in private chat + @bot.message_handler(chat_types=['private']) # You can add more chat types + async def command_help(message): + bot.send_message(message.chat.id, 'Private chat detected, sir!') - @util.async_dec() - def kick_chat_member(self, *args, **kwargs): + # Handle all sent documents of type 'text/plain'. + @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', + content_types=['document']) + async def command_handle_document(message): + bot.send_message(message.chat.id, 'Document received, sir!') + + # Handle all other messages. + @bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document', + 'text', 'location', 'contact', 'sticker']) + async def async default_command(message): + bot.send_message(message.chat.id, "This is the async default command handler.") + + :param commands: Optional list of strings (commands to handle). + :param regexp: Optional regular expression. + :param func: Optional lambda function. The lambda receives the message to test as the first parameter. + It must return True if the command should handle the message. + :param content_types: Supported message content types. Must be a list. async defaults to ['text']. + :param chat_types: list of chat types + """ + + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) + return handler + + return decorator + + def add_message_handler(self, handler_dict): + """ + Adds a message handler + :param handler_dict: + :return: + """ + self.message_handlers.append(handler_dict) + + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + Registers message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :param chat_types: True for private chat + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) + + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + """ + Edit message handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param chat_types: list of chat types + :param kwargs: + :return: + """ + + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) + return handler + + return decorator + + def add_edited_message_handler(self, handler_dict): + """ + Adds the edit message handler + :param handler_dict: + :return: + """ + self.edited_message_handlers.append(handler_dict) + + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + Registers edited message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :param chat_types: True for private chat + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) + + + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + """ + Channel post handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param kwargs: + :return: + """ + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) + return handler + + return decorator + + def add_channel_post_handler(self, handler_dict): + """ + Adds channel post handler + :param handler_dict: + :return: + """ + self.channel_post_handlers.append(handler_dict) + + def register_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) + + def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + """ + Edit channel post handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param kwargs: + :return: + """ + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + return handler + + return decorator + + def add_edited_channel_post_handler(self, handler_dict): + """ + Adds the edit channel post handler + :param handler_dict: + :return: + """ + self.edited_channel_post_handlers.append(handler_dict) + + def register_edited_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers edited channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + + def inline_handler(self, func, **kwargs): + """ + Inline call handler decorator + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_inline_handler(handler_dict) + return handler + + return decorator + + def add_inline_handler(self, handler_dict): + """ + Adds inline call handler + :param handler_dict: + :return: + """ + self.inline_handlers.append(handler_dict) + + def register_inline_handler(self, callback, func, **kwargs): + """ + Registers inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_inline_handler(handler_dict) + + def chosen_inline_handler(self, func, **kwargs): + """ + Description: TBD + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chosen_inline_handler(handler_dict) + return handler + + return decorator + + def add_chosen_inline_handler(self, handler_dict): + """ + Description: TBD + :param handler_dict: + :return: + """ + self.chosen_inline_handlers.append(handler_dict) + + def register_chosen_inline_handler(self, callback, func, **kwargs): + """ + Registers chosen inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chosen_inline_handler(handler_dict) + + def callback_query_handler(self, func, **kwargs): + """ + Callback request handler decorator + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_callback_query_handler(handler_dict) + return handler + + return decorator + + def add_callback_query_handler(self, handler_dict): + """ + Adds a callback request handler + :param handler_dict: + :return: + """ + self.callback_query_handlers.append(handler_dict) + + def register_callback_query_handler(self, callback, func, **kwargs): + """ + Registers callback query handler.. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_callback_query_handler(handler_dict) + + def shipping_query_handler(self, func, **kwargs): + """ + Shipping request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_shipping_query_handler(handler_dict) + return handler + + return decorator + + def add_shipping_query_handler(self, handler_dict): + """ + Adds a shipping request handler + :param handler_dict: + :return: + """ + self.shipping_query_handlers.append(handler_dict) + + def register_shipping_query_handler(self, callback, func, **kwargs): + """ + Registers shipping query handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_shipping_query_handler(handler_dict) + + def pre_checkout_query_handler(self, func, **kwargs): + """ + Pre-checkout request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_pre_checkout_query_handler(handler_dict) + return handler + + return decorator + + def add_pre_checkout_query_handler(self, handler_dict): + """ + Adds a pre-checkout request handler + :param handler_dict: + :return: + """ + self.pre_checkout_query_handlers.append(handler_dict) + + def register_pre_checkout_query_handler(self, callback, func, **kwargs): + """ + Registers pre-checkout request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_pre_checkout_query_handler(handler_dict) + + def poll_handler(self, func, **kwargs): + """ + Poll request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_poll_handler(handler_dict) + return handler + + return decorator + + def add_poll_handler(self, handler_dict): + """ + Adds a poll request handler + :param handler_dict: + :return: + """ + self.poll_handlers.append(handler_dict) + + def register_poll_handler(self, callback, func, **kwargs): + """ + Registers poll handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_poll_handler(handler_dict) + + def poll_answer_handler(self, func=None, **kwargs): + """ + Poll_answer request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_poll_answer_handler(handler_dict) + return handler + + return decorator + + def add_poll_answer_handler(self, handler_dict): + """ + Adds a poll_answer request handler + :param handler_dict: + :return: + """ + self.poll_answer_handlers.append(handler_dict) + + def register_poll_answer_handler(self, callback, func, **kwargs): + """ + Registers poll answer handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_poll_answer_handler(handler_dict) + + def my_chat_member_handler(self, func=None, **kwargs): + """ + my_chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_my_chat_member_handler(self, handler_dict): + """ + Adds a my_chat_member handler + :param handler_dict: + :return: + """ + self.my_chat_member_handlers.append(handler_dict) + + def register_my_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers my chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + + def chat_member_handler(self, func=None, **kwargs): + """ + chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_chat_member_handler(self, handler_dict): + """ + Adds a chat_member handler + :param handler_dict: + :return: + """ + self.chat_member_handlers.append(handler_dict) + + def register_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + + def chat_join_request_handler(self, func=None, **kwargs): + """ + chat_join_request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + return handler + + return decorator + + def add_chat_join_request_handler(self, handler_dict): + """ + Adds a chat_join_request handler + :param handler_dict: + :return: + """ + self.chat_join_request_handlers.append(handler_dict) + + def register_chat_join_request_handler(self, callback, func=None, **kwargs): + """ + Registers chat join request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + + @staticmethod + def _build_handler_dict(handler, **filters): + """ + Builds a dictionary for a handler + :param handler: + :param filters: + :return: + """ + return { + 'function': handler, + 'filters': {ftype: fvalue for ftype, fvalue in filters.items() if fvalue is not None} + # Remove None values, they are skipped in _test_filter anyway + #'filters': filters + } + + async def skip_updates(self): + await self.get_updates(-1) + return True + + # all methods begin here + + async def get_me(self) -> types.User: + """ + Returns basic information about the bot in form of a User object. + """ + result = await asyncio_helper.get_me(self.token) + return types.User.de_json(result) + + async def get_file(self, file_id: str) -> types.File: + """ + Use this method to get basic info about a file and prepare it for downloading. + For the moment, bots can download files of up to 20MB in size. + On success, a File object is returned. + It is guaranteed that the link will be valid for at least 1 hour. + When the link expires, a new one can be requested by calling get_file again. + """ + return types.File.de_json(await asyncio_helper.get_file(self.token, file_id)) + + async def get_file_url(self, file_id: str) -> str: + return await asyncio_helper.get_file_url(self.token, file_id) + + async def download_file(self, file_path: str) -> bytes: + return await asyncio_helper.download_file(self.token, file_path) + + async def log_out(self) -> bool: + """ + Use this method to log out from the cloud Bot API server before launching the bot locally. + You MUST log out the bot before running it locally, otherwise there is no guarantee + that the bot will receive updates. + After a successful call, you can immediately log in on a local server, + but will not be able to log in back to the cloud Bot API server for 10 minutes. + Returns True on success. + """ + return await asyncio_helper.log_out(self.token) + + async def close(self) -> bool: + """ + Use this method to close the bot instance before moving it from one local server to another. + You need to delete the webhook before calling this method to ensure that the bot isn't launched again + after server restart. + The method will return error 429 in the first 10 minutes after the bot is launched. + Returns True on success. + """ + return await asyncio_helper.close(self.token) + + async def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): + """ + Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an + update for the bot, we will send an HTTPS POST request to the specified url, + containing a JSON-serialized Update. + In case of an unsuccessful request, we will give up after a reasonable amount of attempts. + Returns True on success. + + :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration + :param certificate: Upload your public key certificate so that the root certificate in use can be checked. + See our self-signed guide for details. + :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook + for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, + and higher values to increase your bot's throughput. + :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates + of these types. See Update for a complete list of available update types. + Specify an empty list to receive all updates regardless of type (default). + If not specified, the previous setting will be used. + :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address + resolved through DNS + :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout + :return: + """ + return await asyncio_helper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, + drop_pending_updates, timeout) + + async def delete_webhook(self, drop_pending_updates=None, timeout=None): + """ + Use this method to remove webhook integration if you decide to switch back to getUpdates. + + :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout + :return: bool + """ + return await asyncio_helper.delete_webhook(self.token, drop_pending_updates, timeout) + + async def get_webhook_info(self, timeout=None): + """ + Use this method to get current webhook status. Requires no parameters. + If the bot is using getUpdates, will return an object with the url field empty. + + :param timeout: Integer. Request connection timeout + :return: On success, returns a WebhookInfo object. + """ + result = await asyncio_helper.get_webhook_info(self.token, timeout) + return types.WebhookInfo.de_json(result) + + async def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None, + limit: Optional[int]=None) -> types.UserProfilePhotos: + """ + Retrieves the user profile photos of the person with 'user_id' + See https://core.telegram.org/bots/api#getuserprofilephotos + :param user_id: + :param offset: + :param limit: + :return: API reply. + """ + result = await asyncio_helper.get_user_profile_photos(self.token, user_id, offset, limit) + return types.UserProfilePhotos.de_json(result) + + async def get_chat(self, chat_id: Union[int, str]) -> types.Chat: + """ + Use this method to get up to date information about the chat (current name of the user for one-on-one + conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.get_chat(self.token, chat_id) + return types.Chat.de_json(result) + + async def leave_chat(self, chat_id: Union[int, str]) -> bool: + """ + Use this method for your bot to leave a group, supergroup or channel. Returns True on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.leave_chat(self.token, chat_id) + return result + + async def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: + """ + Use this method to get a list of administrators in a chat. + On success, returns an Array of ChatMember objects that contains + information about all chat administrators except other bots. + :param chat_id: Unique identifier for the target chat or username + of the target supergroup or channel (in the format @channelusername) + :return: + """ + result = await asyncio_helper.get_chat_administrators(self.token, chat_id) + return [types.ChatMember.de_json(r) for r in result] + + async def get_chat_members_count(self, chat_id: Union[int, str]) -> int: + """ + This function is deprecated. Use `get_chat_member_count` instead + """ + logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.') + result = await asyncio_helper.get_chat_member_count(self.token, chat_id) + return result + + async def get_chat_member_count(self, chat_id: Union[int, str]) -> int: + """ + Use this method to get the number of members in a chat. Returns Int on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.get_chat_member_count(self.token, chat_id) + return result + + async def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str) -> types.StickerSet: + """ + Use this method to set a new group sticker set for a supergroup. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + Use the field can_set_sticker_set optionally returned in getChat requests to check + if the bot can use this method. Returns True on success. + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param sticker_set_name: Name of the sticker set to be set as the group sticker set + :return: + """ + result = await asyncio_helper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) + return result + + async def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat + for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set + optionally returned in getChat requests to check if the bot can use this method. Returns True on success. + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :return: + """ + result = await asyncio_helper.delete_chat_sticker_set(self.token, chat_id) + return result + + async def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: + """ + Use this method to get information about a member of a chat. Returns a ChatMember object on success. + :param chat_id: + :param user_id: + :return: + """ + result = await asyncio_helper.get_chat_member(self.token, chat_id, user_id) + return types.ChatMember.de_json(result) + + async def send_message( + self, chat_id: Union[int, str], text: str, + disable_web_page_preview: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send text messages. + + Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error. + If you must send more than 4000 characters, + use the `split_string` or `smart_split` function in util.py. + + :param chat_id: + :param text: + :param disable_web_page_preview: + :param reply_to_message_id: + :param reply_markup: + :param parse_mode: + :param disable_notification: Boolean, Optional. Sends the message silently. + :param timeout: + :param entities: + :param allow_sending_without_reply: + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_message( + self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, + entities, allow_sending_without_reply)) + + async def forward_message( + self, chat_id: Union[int, str], from_chat_id: Union[int, str], + message_id: int, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None) -> types.Message: + """ + Use this method to forward messages of any kind. + :param disable_notification: + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param timeout: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) + + async def copy_message( + self, chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + caption: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> int: + """ + Use this method to copy messages of any kind. + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param caption: + :param parse_mode: + :param caption_entities: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: + :param timeout: + :return: API reply. + """ + return types.MessageID.de_json( + await asyncio_helper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, + disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, + timeout)) + + async def delete_message(self, chat_id: Union[int, str], message_id: int, + timeout: Optional[int]=None) -> bool: + """ + Use this method to delete message. Returns True on success. + :param chat_id: in which chat to delete + :param message_id: which message to delete + :param timeout: + :return: API reply. + """ + return await asyncio_helper.delete_message(self.token, chat_id, message_id, timeout) + + async def send_dice( + self, chat_id: Union[int, str], + emoji: Optional[str]=None, disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send dices. + :param chat_id: + :param emoji: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :return: Message + """ + return types.Message.de_json( + await asyncio_helper.send_dice( + self.token, chat_id, emoji, disable_notification, reply_to_message_id, + reply_markup, timeout, allow_sending_without_reply) + ) + + async def send_photo( + self, chat_id: Union[int, str], photo: Union[Any, str], + caption: Optional[str]=None, reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send photos. + :param chat_id: + :param photo: + :param caption: + :param parse_mode: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param caption_entities: + :param allow_sending_without_reply: + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_photo( + self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) + + async def send_audio( + self, chat_id: Union[int, str], audio: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + performer: Optional[str]=None, title: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send audio files, if you want Telegram clients to display them in the music player. + Your audio must be in the .mp3 format. + :param chat_id:Unique identifier for the message recipient + :param audio:Audio file to send. + :param caption: + :param duration:Duration of the audio in seconds + :param performer:Performer + :param title:Track name + :param reply_to_message_id:If the message is a reply, ID of the original message + :param reply_markup: + :param parse_mode + :param disable_notification: + :param timeout: + :param thumb: + :param caption_entities: + :param allow_sending_without_reply: + :return: Message + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_audio( + self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) + + async def send_voice( + self, chat_id: Union[int, str], voice: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send audio files, if you want Telegram clients to display the file + as a playable voice message. + :param chat_id:Unique identifier for the message recipient. + :param voice: + :param caption: + :param duration:Duration of sent audio in seconds + :param reply_to_message_id: + :param reply_markup: + :param parse_mode + :param disable_notification: + :param timeout: + :param caption_entities: + :param allow_sending_without_reply: + :return: Message + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_voice( + self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) + + async def send_document( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + caption: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None, + visible_file_name: Optional[str]=None, + disable_content_type_detection: Optional[bool]=None) -> types.Message: + """ + Use this method to send general files. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param data: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data + :param reply_to_message_id: If the message is a reply, ID of the original message + :param caption: Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing + :param reply_markup: + :param parse_mode: Mode for parsing entities in the document caption + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under + :param caption_entities: + :param allow_sending_without_reply: + :param visible_file_name: allows to async define file name that will be visible in the Telegram instead of original file name + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_data( + self.token, chat_id, data, 'document', + reply_to_message_id = reply_to_message_id, reply_markup = reply_markup, parse_mode = parse_mode, + disable_notification = disable_notification, timeout = timeout, caption = caption, thumb = thumb, + caption_entities = caption_entities, allow_sending_without_reply = allow_sending_without_reply, + disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name)) + + async def send_sticker( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send .webp stickers. + :param chat_id: + :param data: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: to disable the notification + :param timeout: timeout + :param allow_sending_without_reply: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.send_data( + self.token, chat_id, data, 'sticker', + reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, + disable_notification=disable_notification, timeout=timeout, + allow_sending_without_reply=allow_sending_without_reply)) + + async def send_video( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + supports_streaming: Optional[bool]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + width: Optional[int]=None, + height: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send video files, Telegram clients support mp4 videos. + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param caption: String : Video caption (may also be used when resending videos by file_id). + :param parse_mode: + :param supports_streaming: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param width: + :param height: + :param caption_entities: + :param allow_sending_without_reply: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_video( + self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, + parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height, + caption_entities, allow_sending_without_reply)) + + async def send_animation( + self, chat_id: Union[int, str], animation: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param animation: InputFile or String : Animation to send. You can either pass a file_id as String to resend an + animation that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param caption: String : Animation caption (may also be used when resending animation by file_id). + :param parse_mode: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param caption_entities: + :param allow_sending_without_reply: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_animation( + self.token, chat_id, animation, duration, caption, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) + + async def send_video_note( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + length: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send + video messages. + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param length: Integer : Video width and height, Can't be None and should be in range of (0, 640) + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param allow_sending_without_reply: + :return: + """ + return types.Message.de_json( + await asyncio_helper.send_video_note( + self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, + disable_notification, timeout, thumb, allow_sending_without_reply)) + + async def send_media_group( + self, chat_id: Union[int, str], + media: List[Union[ + types.InputMediaAudio, types.InputMediaDocument, + types.InputMediaPhoto, types.InputMediaVideo]], + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> List[types.Message]: + """ + send a group of photos or videos as an album. On success, an array of the sent Messages is returned. + :param chat_id: + :param media: + :param disable_notification: + :param reply_to_message_id: + :param timeout: + :param allow_sending_without_reply: + :return: + """ + result = await asyncio_helper.send_media_group( + self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, + allow_sending_without_reply) + return [types.Message.de_json(msg) for msg in result] + + async def send_location( + self, chat_id: Union[int, str], + latitude: float, longitude: float, + live_period: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + + + """ + Use this method to send point on the map. + :param chat_id: + :param latitude: + :param longitude: + :param live_period: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :param allow_sending_without_reply: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.send_location( + self.token, chat_id, latitude, longitude, live_period, + reply_to_message_id, reply_markup, disable_notification, timeout, + horizontal_accuracy, heading, proximity_alert_radius, + allow_sending_without_reply)) + + async def edit_message_live_location( + self, latitude: float, longitude: float, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None) -> types.Message: + """ + Use this method to edit live location + :param latitude: + :param longitude: + :param chat_id: + :param message_id: + :param reply_markup: + :param timeout: + :param inline_message_id: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :return: + """ + return types.Message.de_json( + await asyncio_helper.edit_message_live_location( + self.token, latitude, longitude, chat_id, message_id, + inline_message_id, reply_markup, timeout, + horizontal_accuracy, heading, proximity_alert_radius)) + + async def stop_message_live_location( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> types.Message: + """ + Use this method to stop updating a live location message sent by the bot + or via the bot (for inline bots) before live_period expires + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :param timeout: + :return: + """ + return types.Message.de_json( + await asyncio_helper.stop_message_live_location( + self.token, chat_id, message_id, inline_message_id, reply_markup, timeout)) + + async def send_venue( + self, chat_id: Union[int, str], + latitude: float, longitude: float, + title: str, address: str, + foursquare_id: Optional[str]=None, + foursquare_type: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + google_place_id: Optional[str]=None, + google_place_type: Optional[str]=None) -> types.Message: + """ + Use this method to send information about a venue. + :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel + :param latitude: Float : Latitude of the venue + :param longitude: Float : Longitude of the venue + :param title: String : Name of the venue + :param address: String : Address of the venue + :param foursquare_id: String : Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, “arts_entertainment/async default”, + “arts_entertainment/aquarium” or “food/icecream”.) + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :param google_place_id: + :param google_place_type: + :return: + """ + return types.Message.de_json( + await asyncio_helper.send_venue( + self.token, chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply, google_place_id, google_place_type) + ) + + async def send_contact( + self, chat_id: Union[int, str], phone_number: str, + first_name: str, last_name: Optional[str]=None, + vcard: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + return types.Message.de_json( + await asyncio_helper.send_contact( + self.token, chat_id, phone_number, first_name, last_name, vcard, + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) + ) + + async def send_chat_action( + self, chat_id: Union[int, str], action: str, timeout: Optional[int]=None) -> bool: + """ + Use this method when you need to tell the user that something is happening on the bot's side. + The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear + its typing status). + :param chat_id: + :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', + 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', + 'upload_video_note'. + :param timeout: + :return: API reply. :type: boolean + """ + return await asyncio_helper.send_chat_action(self.token, chat_id, action, timeout) + + async def kick_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + This function is deprecated. Use `ban_chat_member` instead + """ logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') - return TeleBot.ban_chat_member(self, *args, **kwargs) + return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + + async def ban_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + Use this method to ban a user in a group, a supergroup or a channel. + In the case of supergroups and channels, the user will not be able to return to the chat on their + own using invite links, etc., unless unbanned first. + Returns True on success. + :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or + less than 30 seconds from the current time they are considered to be banned forever + :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. + If False, the user will be able to see messages in the group that were sent before the user was removed. + Always True for supergroups and channels. + :return: boolean + """ + return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + + async def unban_chat_member( + self, chat_id: Union[int, str], user_id: int, + only_if_banned: Optional[bool]=False) -> bool: + """ + Use this method to unban a previously kicked user in a supergroup or channel. + The user will not return to the group or channel automatically, but will be able to join via link, etc. + The bot must be an administrator for this to work. By async default, this method guarantees that after the call + the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat + they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. + + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel + (in the format @username) + :param user_id: Unique identifier of the target user + :param only_if_banned: Do nothing if the user is not banned + :return: True on success + """ + return await asyncio_helper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) + + async def restrict_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date: Optional[Union[int, datetime]]=None, + can_send_messages: Optional[bool]=None, + can_send_media_messages: Optional[bool]=None, + can_send_polls: Optional[bool]=None, + can_send_other_messages: Optional[bool]=None, + can_add_web_page_previews: Optional[bool]=None, + can_change_info: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_pin_messages: Optional[bool]=None) -> bool: + """ + Use this method to restrict a user in a supergroup. + The bot must be an administrator in the supergroup for this to work and must have + the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. + + :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup + or channel (in the format @channelusername) + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when restrictions will be lifted for the user, unix time. + If user is restricted for more than 366 days or less than 30 seconds from the current time, + they are considered to be restricted forever + :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues + :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes + and voice notes, implies can_send_messages + :param can_send_polls: Pass True, if the user is allowed to send polls, implies can_send_messages + :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and + use inline bots, implies can_send_media_messages + :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, + implies can_send_media_messages + :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. + Ignored in public supergroups + :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, + implies can_invite_users + :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups + :return: True on success + """ + return await asyncio_helper.restrict_chat_member( + self.token, chat_id, user_id, until_date, + can_send_messages, can_send_media_messages, + can_send_polls, can_send_other_messages, + can_add_web_page_previews, can_change_info, + can_invite_users, can_pin_messages) + + async def promote_chat_member( + self, chat_id: Union[int, str], user_id: int, + can_change_info: Optional[bool]=None, + can_post_messages: Optional[bool]=None, + can_edit_messages: Optional[bool]=None, + can_delete_messages: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_restrict_members: Optional[bool]=None, + can_pin_messages: Optional[bool]=None, + can_promote_members: Optional[bool]=None, + is_anonymous: Optional[bool]=None, + can_manage_chat: Optional[bool]=None, + can_manage_voice_chats: Optional[bool]=None) -> bool: + """ + Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + Pass False for all boolean parameters to demote a user. + + :param chat_id: Unique identifier for the target chat or username of the target channel ( + in the format @channelusername) + :param user_id: Int : Unique identifier of the target user + :param can_change_info: Bool: Pass True, if the administrator can change chat title, photo and other settings + :param can_post_messages: Bool : Pass True, if the administrator can create channel posts, channels only + :param can_edit_messages: Bool : Pass True, if the administrator can edit messages of other users, channels only + :param can_delete_messages: Bool : Pass True, if the administrator can delete messages of other users + :param can_invite_users: Bool : Pass True, if the administrator can invite new users to the chat + :param can_restrict_members: Bool: Pass True, if the administrator can restrict, ban or unban chat members + :param can_pin_messages: Bool: Pass True, if the administrator can pin messages, supergroups only + :param can_promote_members: Bool: Pass True, if the administrator can add new administrators with a subset + of his own privileges or demote administrators that he has promoted, directly or indirectly + (promoted by administrators that were appointed by him) + :param is_anonymous: Bool: Pass True, if the administrator's presence in the chat is hidden + :param can_manage_chat: Bool: Pass True, if the administrator can access the chat event log, chat statistics, + message statistics in channels, see channel members, + see anonymous administrators in supergroups and ignore slow mode. + Implied by any other administrator privilege + :param can_manage_voice_chats: Bool: Pass True, if the administrator can manage voice chats + For now, bots can use this privilege only for passing to other administrators. + :return: True on success. + """ + return await asyncio_helper.promote_chat_member( + self.token, chat_id, user_id, can_change_info, can_post_messages, + can_edit_messages, can_delete_messages, can_invite_users, + can_restrict_members, can_pin_messages, can_promote_members, + is_anonymous, can_manage_chat, can_manage_voice_chats) + + async def set_chat_administrator_custom_title( + self, chat_id: Union[int, str], user_id: int, custom_title: str) -> bool: + """ + Use this method to set a custom title for an administrator + in a supergroup promoted by the bot. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :param custom_title: New custom title for the administrator; + 0-16 characters, emoji are not allowed + :return: True on success. + """ + return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) + + async def set_chat_permissions( + self, chat_id: Union[int, str], permissions: types.ChatPermissions) -> bool: + """ + Use this method to set async default chat permissions for all members. + The bot must be an administrator in the group or a supergroup for this to work + and must have the can_restrict_members admin rights. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param permissions: New async default chat permissions + :return: True on success + """ + return await asyncio_helper.set_chat_permissions(self.token, chat_id, permissions) + + async def create_chat_invite_link( + self, chat_id: Union[int, str], + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: + """ + Use this method to create an additional invite link for a chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request) + ) + + async def edit_chat_invite_link( + self, chat_id: Union[int, str], + invite_link: Optional[str] = None, + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: + """ + Use this method to edit a non-primary invite link created by the bot. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param name: Invite link name; 0-32 characters + :param invite_link: The invite link to edit + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.edit_chat_invite_link(self.token, chat_id, name, invite_link, expire_date, member_limit, creates_join_request) + ) + + async def revoke_chat_invite_link( + self, chat_id: Union[int, str], invite_link: str) -> types.ChatInviteLink: + """ + Use this method to revoke an invite link created by the bot. + Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param invite_link: The invite link to revoke + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.revoke_chat_invite_link(self.token, chat_id, invite_link) + ) + + async def export_chat_invite_link(self, chat_id: Union[int, str]) -> str: + """ + Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :return: exported invite link as String on success. + """ + return await asyncio_helper.export_chat_invite_link(self.token, chat_id) + + + async def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to approve a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return await asyncio_helper.approve_chat_join_request(self.token, chat_id, user_id) + + async def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to decline a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return await asyncio_helper.decline_chat_join_request(self.token, chat_id, user_id) + + async def set_chat_photo(self, chat_id: Union[int, str], photo: Any) -> bool: + """ + Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param photo: InputFile: New chat photo, uploaded using multipart/form-data + :return: + """ + return await asyncio_helper.set_chat_photo(self.token, chat_id, photo) + + async def delete_chat_photo(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to delete a chat photo. Photos can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + """ + return await asyncio_helper.delete_chat_photo(self.token, chat_id) - @util.async_dec() - def ban_chat_member(self, *args, **kwargs): - return TeleBot.ban_chat_member(self, *args, **kwargs) + async def get_my_commands(self, scope: Optional[types.BotCommandScope], + language_code: Optional[str]) -> List[types.BotCommand]: + """ + Use this method to get the current list of the bot's commands. + Returns List of BotCommand on success. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + """ + result = await asyncio_helper.get_my_commands(self.token, scope, language_code) + return [types.BotCommand.de_json(cmd) for cmd in result] - @util.async_dec() - def unban_chat_member(self, *args, **kwargs): - return TeleBot.unban_chat_member(self, *args, **kwargs) - - @util.async_dec() - def restrict_chat_member(self, *args, **kwargs): - return TeleBot.restrict_chat_member(self, *args, **kwargs) - - @util.async_dec() - def promote_chat_member(self, *args, **kwargs): - return TeleBot.promote_chat_member(self, *args, **kwargs) + async def set_my_commands(self, commands: List[types.BotCommand], + scope: Optional[types.BotCommandScope]=None, + language_code: Optional[str]=None) -> bool: + """ + Use this method to change the list of the bot's commands. + :param commands: List of BotCommand. At most 100 commands can be specified. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + :return: + """ + return await asyncio_helper.set_my_commands(self.token, commands, scope, language_code) - @util.async_dec() - def set_chat_administrator_custom_title(self, *args, **kwargs): - return TeleBot.set_chat_administrator_custom_title(self, *args, **kwargs) + async def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None, + language_code: Optional[int]=None) -> bool: + """ + Use this method to delete the list of the bot's commands for the given scope and user language. + After deletion, higher level commands will be shown to affected users. + Returns True on success. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + """ + return await asyncio_helper.delete_my_commands(self.token, scope, language_code) - @util.async_dec() - def set_chat_permissions(self, *args, **kwargs): - return TeleBot.set_chat_permissions(self, *args, **kwargs) + async def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: + """ + Use this method to change the title of a chat. Titles can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param title: New chat title, 1-255 characters + :return: + """ + return await asyncio_helper.set_chat_title(self.token, chat_id, title) - @util.async_dec() - def create_chat_invite_link(self, *args, **kwargs): - return TeleBot.create_chat_invite_link(self, *args, **kwargs) - - @util.async_dec() - def edit_chat_invite_link(self, *args, **kwargs): - return TeleBot.edit_chat_invite_link(self, *args, **kwargs) - - @util.async_dec() - def revoke_chat_invite_link(self, *args, **kwargs): - return TeleBot.revoke_chat_invite_link(self, *args, **kwargs) - - @util.async_dec() - def export_chat_invite_link(self, *args): - return TeleBot.export_chat_invite_link(self, *args) + async def set_chat_description(self, chat_id: Union[int, str], description: Optional[str]=None) -> bool: + """ + Use this method to change the description of a supergroup or a channel. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - @util.async_dec() - def set_chat_photo(self, *args): - return TeleBot.set_chat_photo(self, *args) + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param description: Str: New chat description, 0-255 characters + :return: True on success. + """ + return await asyncio_helper.set_chat_description(self.token, chat_id, description) - @util.async_dec() - def delete_chat_photo(self, *args): - return TeleBot.delete_chat_photo(self, *args) + async def pin_chat_message( + self, chat_id: Union[int, str], message_id: int, + disable_notification: Optional[bool]=False) -> bool: + """ + Use this method to pin a message in a supergroup. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to pin + :param disable_notification: Bool: Pass True, if it is not necessary to send a notification + to all group members about the new pinned message + :return: + """ + return await asyncio_helper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - @util.async_dec() - def set_chat_title(self, *args): - return TeleBot.set_chat_title(self, *args) + async def unpin_chat_message(self, chat_id: Union[int, str], message_id: Optional[int]=None) -> bool: + """ + Use this method to unpin specific pinned message in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to unpin + :return: + """ + return await asyncio_helper.unpin_chat_message(self.token, chat_id, message_id) - @util.async_dec() - def set_chat_description(self, *args): - return TeleBot.set_chat_description(self, *args) + async def unpin_all_chat_messages(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to unpin a all pinned messages in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :return: + """ + return await asyncio_helper.unpin_all_chat_messages(self.token, chat_id) - @util.async_dec() - def pin_chat_message(self, *args, **kwargs): - return TeleBot.pin_chat_message(self, *args, **kwargs) + async def edit_message_text( + self, text: str, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + entities: Optional[List[types.MessageEntity]]=None, + disable_web_page_preview: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit text and game messages. + :param text: + :param chat_id: + :param message_id: + :param inline_message_id: + :param parse_mode: + :param entities: + :param disable_web_page_preview: + :param reply_markup: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - @util.async_dec() - def unpin_chat_message(self, *args): - return TeleBot.unpin_chat_message(self, *args) + result = await asyncio_helper.edit_message_text(self.token, text, chat_id, message_id, inline_message_id, parse_mode, + entities, disable_web_page_preview, reply_markup) + if type(result) == bool: # if edit inline message return is bool not Message. + return result + return types.Message.de_json(result) - @util.async_dec() - def unpin_all_chat_messages(self, *args): - return TeleBot.unpin_all_chat_messages(self, *args) + async def edit_message_media( + self, media: Any, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit animation, audio, document, photo, or video messages. + If a message is a part of a message album, then it can be edited only to a photo or a video. + Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. + Use previously uploaded file via its file_id or specify a URL. + :param media: + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :return: + """ + result = await asyncio_helper.edit_message_media(self.token, media, chat_id, message_id, inline_message_id, reply_markup) + if type(result) == bool: # if edit inline message return is bool not Message. + return result + return types.Message.de_json(result) - @util.async_dec() - def edit_message_text(self, *args, **kwargs): - return TeleBot.edit_message_text(self, *args, **kwargs) + async def edit_message_reply_markup( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit only the reply markup of messages. + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :return: + """ + result = await asyncio_helper.edit_message_reply_markup(self.token, chat_id, message_id, inline_message_id, reply_markup) + if type(result) == bool: + return result + return types.Message.de_json(result) - @util.async_dec() - def edit_message_media(self, *args, **kwargs): - return TeleBot.edit_message_media(self, *args, **kwargs) + async def send_game( + self, chat_id: Union[int, str], game_short_name: str, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Used to send the game + :param chat_id: + :param game_short_name: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :return: + """ + result = await asyncio_helper.send_game( + self.token, chat_id, game_short_name, disable_notification, + reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) + return types.Message.de_json(result) - @util.async_dec() - def edit_message_reply_markup(self, *args, **kwargs): - return TeleBot.edit_message_reply_markup(self, *args, **kwargs) + async def set_game_score( + self, user_id: Union[int, str], score: int, + force: Optional[bool]=None, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + disable_edit_message: Optional[bool]=None) -> Union[types.Message, bool]: + """ + Sets the value of points in the game to a specific user + :param user_id: + :param score: + :param force: + :param chat_id: + :param message_id: + :param inline_message_id: + :param disable_edit_message: + :return: + """ + result = await asyncio_helper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, + message_id, inline_message_id) + if type(result) == bool: + return result + return types.Message.de_json(result) - @util.async_dec() - def send_game(self, *args, **kwargs): - return TeleBot.send_game(self, *args, **kwargs) + async def get_game_high_scores( + self, user_id: int, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: + """ + Gets top points and game play + :param user_id: + :param chat_id: + :param message_id: + :param inline_message_id: + :return: + """ + result = await asyncio_helper.get_game_high_scores(self.token, user_id, chat_id, message_id, inline_message_id) + return [types.GameHighScore.de_json(r) for r in result] - @util.async_dec() - def set_game_score(self, *args, **kwargs): - return TeleBot.set_game_score(self, *args, **kwargs) + async def send_invoice( + self, chat_id: Union[int, str], title: str, description: str, + invoice_payload: str, provider_token: str, currency: str, + prices: List[types.LabeledPrice], start_parameter: Optional[str]=None, + photo_url: Optional[str]=None, photo_size: Optional[int]=None, + photo_width: Optional[int]=None, photo_height: Optional[int]=None, + need_name: Optional[bool]=None, need_phone_number: Optional[bool]=None, + need_email: Optional[bool]=None, need_shipping_address: Optional[bool]=None, + send_phone_number_to_provider: Optional[bool]=None, + send_email_to_provider: Optional[bool]=None, + is_flexible: Optional[bool]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + provider_data: Optional[str]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]]=None) -> types.Message: + """ + Sends invoice + :param chat_id: Unique identifier for the target private chat + :param title: Product name + :param description: Product description + :param invoice_payload: Bot-async defined invoice payload, 1-128 bytes. This will not be displayed to the user, + use for your internal processes. + :param provider_token: Payments provider token, obtained via @Botfather + :param currency: Three-letter ISO 4217 currency code, + see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components + (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice + when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods + or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass True, if you require the user's full name to complete the order + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :param need_email: Pass True, if you require the user's email to complete the order + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param reply_to_message_id: If the message is a reply, ID of the original message + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, + one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. + A detailed description of required fields should be provided by the payment provider. + :param timeout: + :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest + units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip + amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + :return: + """ + result = await asyncio_helper.send_invoice( + self.token, chat_id, title, description, invoice_payload, provider_token, + currency, prices, start_parameter, photo_url, photo_size, photo_width, + photo_height, need_name, need_phone_number, need_email, need_shipping_address, + send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, + reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply, + max_tip_amount, suggested_tip_amounts) + return types.Message.de_json(result) - @util.async_dec() - def get_game_high_scores(self, *args, **kwargs): - return TeleBot.get_game_high_scores(self, *args, **kwargs) + # noinspection PyShadowingBuiltins + async def send_poll( + self, chat_id: Union[int, str], question: str, options: List[str], + is_anonymous: Optional[bool]=None, type: Optional[str]=None, + allows_multiple_answers: Optional[bool]=None, + correct_option_id: Optional[int]=None, + explanation: Optional[str]=None, + explanation_parse_mode: Optional[str]=None, + open_period: Optional[int]=None, + close_date: Optional[Union[int, datetime]]=None, + is_closed: Optional[bool]=None, + disable_notification: Optional[bool]=False, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + allow_sending_without_reply: Optional[bool]=None, + timeout: Optional[int]=None, + explanation_entities: Optional[List[types.MessageEntity]]=None) -> types.Message: + """ + Send polls + :param chat_id: + :param question: + :param options: array of str with answers + :param is_anonymous: + :param type: + :param allows_multiple_answers: + :param correct_option_id: + :param explanation: + :param explanation_parse_mode: + :param open_period: + :param close_date: + :param is_closed: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: + :param timeout: + :param explanation_entities: + :return: + """ - @util.async_dec() - def send_invoice(self, *args, **kwargs): - return TeleBot.send_invoice(self, *args, **kwargs) + if isinstance(question, types.Poll): + raise RuntimeError("The send_poll signature was changed, please see send_poll function details.") - @util.async_dec() - def answer_shipping_query(self, *args, **kwargs): - return TeleBot.answer_shipping_query(self, *args, **kwargs) + return types.Message.de_json( + await asyncio_helper.send_poll( + self.token, chat_id, + question, options, + is_anonymous, type, allows_multiple_answers, correct_option_id, + explanation, explanation_parse_mode, open_period, close_date, is_closed, + disable_notification, reply_to_message_id, allow_sending_without_reply, + reply_markup, timeout, explanation_entities)) - @util.async_dec() - def answer_pre_checkout_query(self, *args, **kwargs): - return TeleBot.answer_pre_checkout_query(self, *args, **kwargs) + async def stop_poll( + self, chat_id: Union[int, str], message_id: int, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Poll: + """ + Stops poll + :param chat_id: + :param message_id: + :param reply_markup: + :return: + """ + return types.Poll.de_json(await asyncio_helper.stop_poll(self.token, chat_id, message_id, reply_markup)) - @util.async_dec() - def edit_message_caption(self, *args, **kwargs): - return TeleBot.edit_message_caption(self, *args, **kwargs) + async def answer_shipping_query( + self, shipping_query_id: str, ok: bool, + shipping_options: Optional[List[types.ShippingOption]]=None, + error_message: Optional[str]=None) -> bool: + """ + Asks for an answer to a shipping question + :param shipping_query_id: + :param ok: + :param shipping_options: + :param error_message: + :return: + """ + return await asyncio_helper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) - @util.async_dec() - def answer_inline_query(self, *args, **kwargs): - return TeleBot.answer_inline_query(self, *args, **kwargs) + async def answer_pre_checkout_query( + self, pre_checkout_query_id: int, ok: bool, + error_message: Optional[str]=None) -> bool: + """ + Response to a request for pre-inspection + :param pre_checkout_query_id: + :param ok: + :param error_message: + :return: + """ + return await asyncio_helper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) - @util.async_dec() - def answer_callback_query(self, *args, **kwargs): - return TeleBot.answer_callback_query(self, *args, **kwargs) + async def edit_message_caption( + self, caption: str, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit captions of messages + :param caption: + :param chat_id: + :param message_id: + :param inline_message_id: + :param parse_mode: + :param caption_entities: + :param reply_markup: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - @util.async_dec() - def get_sticker_set(self, *args, **kwargs): - return TeleBot.get_sticker_set(self, *args, **kwargs) + result = await asyncio_helper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, + parse_mode, caption_entities, reply_markup) + if type(result) == bool: + return result + return types.Message.de_json(result) - @util.async_dec() - def upload_sticker_file(self, *args, **kwargs): - return TeleBot.upload_sticker_file(self, *args, **kwargs) + async def reply_to(self, message: types.Message, text: str, **kwargs) -> types.Message: + """ + Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` + :param message: + :param text: + :param kwargs: + :return: + """ + return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) - @util.async_dec() - def create_new_sticker_set(self, *args, **kwargs): - return TeleBot.create_new_sticker_set(self, *args, **kwargs) + async def answer_inline_query( + self, inline_query_id: str, + results: List[Any], + cache_time: Optional[int]=None, + is_personal: Optional[bool]=None, + next_offset: Optional[str]=None, + switch_pm_text: Optional[str]=None, + switch_pm_parameter: Optional[str]=None) -> bool: + """ + Use this method to send answers to an inline query. On success, True is returned. + No more than 50 results per query are allowed. + :param inline_query_id: Unique identifier for the answered query + :param results: Array of results for the inline query + :param cache_time: The maximum amount of time in seconds that the result of the inline query + may be cached on the server. + :param is_personal: Pass True, if results may be cached on the server side only for + the user that sent the query. + :param next_offset: Pass the offset that a client should send in the next query with the same text + to receive more results. + :param switch_pm_parameter: If passed, clients will display a button with specified text that switches the user + to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter + :param switch_pm_text: Parameter for the start message sent to the bot when user presses the switch button + :return: True means success. + """ + return await asyncio_helper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset, + switch_pm_text, switch_pm_parameter) - @util.async_dec() - def add_sticker_to_set(self, *args, **kwargs): - return TeleBot.add_sticker_to_set(self, *args, **kwargs) + async def answer_callback_query( + self, callback_query_id: int, + text: Optional[str]=None, show_alert: Optional[bool]=None, + url: Optional[str]=None, cache_time: Optional[int]=None) -> bool: + """ + Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to + the user as a notification at the top of the chat screen or as an alert. + :param callback_query_id: + :param text: + :param show_alert: + :param url: + :param cache_time: + :return: + """ + return await asyncio_helper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) - @util.async_dec() - def set_sticker_position_in_set(self, *args, **kwargs): - return TeleBot.set_sticker_position_in_set(self, *args, **kwargs) + async def set_sticker_set_thumb( + self, name: str, user_id: int, thumb: Union[Any, str]=None): + """ + Use this method to set the thumbnail of a sticker set. + Animated thumbnails can be set for animated sticker sets only. Returns True on success. + """ + return await asyncio_helper.set_sticker_set_thumb(self.token, name, user_id, thumb) - @util.async_dec() - def delete_sticker_from_set(self, *args, **kwargs): - return TeleBot.delete_sticker_from_set(self, *args, **kwargs) - - @util.async_dec() - def set_sticker_set_thumb(self, *args, **kwargs): - return TeleBot.set_sticker_set_thumb(self, *args, **kwargs) + async def get_sticker_set(self, name: str) -> types.StickerSet: + """ + Use this method to get a sticker set. On success, a StickerSet object is returned. + :param name: + :return: + """ + result = await asyncio_helper.get_sticker_set(self.token, name) + return types.StickerSet.de_json(result) - @util.async_dec() - def send_poll(self, *args, **kwargs): - return TeleBot.send_poll(self, *args, **kwargs) + async def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: + """ + Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet + methods (can be used multiple times). Returns the uploaded File on success. + :param user_id: + :param png_sticker: + :return: + """ + result = await asyncio_helper.upload_sticker_file(self.token, user_id, png_sticker) + return types.File.de_json(result) - @util.async_dec() - def stop_poll(self, *args, **kwargs): - return TeleBot.stop_poll(self, *args, **kwargs) + async def create_new_sticker_set( + self, user_id: int, name: str, title: str, + emojis: str, + png_sticker: Union[Any, str], + tgs_sticker: Union[Any, str], + contains_masks: Optional[bool]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to create new sticker set owned by a user. + The bot will be able to edit the created sticker set. + Returns True on success. + :param user_id: + :param name: + :param title: + :param emojis: + :param png_sticker: + :param tgs_sticker: + :param contains_masks: + :param mask_position: + :return: + """ + return await asyncio_helper.create_new_sticker_set( + self.token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks, mask_position) + + + async def add_sticker_to_set( + self, user_id: int, name: str, emojis: str, + png_sticker: Optional[Union[Any, str]]=None, + tgs_sticker: Optional[Union[Any, str]]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to add a new sticker to a set created by the bot. + It's required to pass `png_sticker` or `tgs_sticker`. + Returns True on success. + :param user_id: + :param name: + :param emojis: + :param png_sticker: Required if `tgs_sticker` is None + :param tgs_sticker: Required if `png_sticker` is None + :param mask_position: + :return: + """ + return await asyncio_helper.add_sticker_to_set( + self.token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position) + + + async def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: + """ + Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. + :param sticker: + :param position: + :return: + """ + return await asyncio_helper.set_sticker_position_in_set(self.token, sticker, position) + + async def delete_sticker_from_set(self, sticker: str) -> bool: + """ + Use this method to delete a sticker from a set created by the bot. Returns True on success. + :param sticker: + :return: + """ + return await asyncio_helper.delete_sticker_from_set(self.token, sticker) + + async def register_for_reply( + self, message: types.Message, callback: Callable, *args, **kwargs) -> None: + """ + Registers a callback function to be notified when a reply to `message` arrives. + + Warning: In case `callback` as lambda function, saving reply handlers will not work. + + :param message: The message for which we are awaiting a reply. + :param callback: The callback function to be called when a reply arrives. Must accept one `message` + parameter, which will contain the replied message. + """ + message_id = message.message_id + self.register_for_reply_by_message_id(message_id, callback, *args, **kwargs) + + async def register_for_reply_by_message_id( + self, message_id: int, callback: Callable, *args, **kwargs) -> None: + """ + Registers a callback function to be notified when a reply to `message` arrives. + + Warning: In case `callback` as lambda function, saving reply handlers will not work. + + :param message_id: The id of the message for which we are awaiting a reply. + :param callback: The callback function to be called when a reply arrives. Must accept one `message` + parameter, which will contain the replied message. + """ + self.reply_backend.register_handler(message_id, Handler(callback, *args, **kwargs)) + + async def _notify_reply_handlers(self, new_messages) -> None: + """ + Notify handlers of the answers + :param new_messages: + :return: + """ + for message in new_messages: + if hasattr(message, "reply_to_message") and message.reply_to_message is not None: + handlers = self.reply_backend.get_handlers(message.reply_to_message.message_id) + if handlers: + for handler in handlers: + self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) + + async def register_next_step_handler( + self, message: types.Message, callback: Callable, *args, **kwargs) -> None: + """ + Registers a callback function to be notified when new message arrives after `message`. + + Warning: In case `callback` as lambda function, saving next step handlers will not work. + + :param message: The message for which we want to handle new message in the same chat. + :param callback: The callback function which next new message arrives. + :param args: Args to pass in callback func + :param kwargs: Args to pass in callback func + """ + chat_id = message.chat.id + self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) + + async def set_state(self, chat_id, state): + """ + Sets a new state of a user. + :param chat_id: + :param state: new state. can be string or integer. + """ + await self.current_states.add_state(chat_id, state) + + async def delete_state(self, chat_id): + """ + Delete the current state of a user. + :param chat_id: + :return: + """ + await self.current_states.delete_state(chat_id) + + def retrieve_data(self, chat_id): + return self.current_states.retrieve_data(chat_id) + + async def get_state(self, chat_id): + """ + Get current state of a user. + :param chat_id: + :return: state of a user + """ + return await self.current_states.current_state(chat_id) + + async def add_data(self, chat_id, **kwargs): + """ + Add data to states. + :param chat_id: + """ + for key, value in kwargs.items(): + await self.current_states._add_data(chat_id, key, value) + + \ No newline at end of file diff --git a/telebot/asyncio_filters.py b/telebot/asyncio_filters.py new file mode 100644 index 0000000..c8242fe --- /dev/null +++ b/telebot/asyncio_filters.py @@ -0,0 +1,176 @@ +from abc import ABC + +class SimpleCustomFilter(ABC): + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts only message, returns bool value, that is compared with given in handler. + """ + + async def check(self, message): + """ + Perform a check. + """ + pass + + +class AdvancedCustomFilter(ABC): + """ + Simple Custom Filter base class. + Create child class with check() method. + Accepts two parameters, returns bool: True - filter passed, False - filter failed. + message: Message class + text: Filter value given in handler + """ + + async def check(self, message, text): + """ + Perform a check. + """ + pass + + +class TextMatchFilter(AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + @bot.message_handler(text=['account']) + """ + + key = 'text' + + async def check(self, message, text): + if type(text) is list:return message.text in text + else: return text == message.text + +class TextContainsFilter(AdvancedCustomFilter): + """ + Filter to check Text message. + key: text + + Example: + # Will respond if any message.text contains word 'account' + @bot.message_handler(text_contains=['account']) + """ + + key = 'text_contains' + + async def check(self, message, text): + return text in message.text + +class TextStartsFilter(AdvancedCustomFilter): + """ + Filter to check whether message starts with some text. + + Example: + # Will work if message.text starts with 'Sir'. + @bot.message_handler(text_startswith='Sir') + """ + + key = 'text_startswith' + async def check(self, message, text): + return message.text.startswith(text) + +class ChatFilter(AdvancedCustomFilter): + """ + Check whether chat_id corresponds to given chat_id. + + Example: + @bot.message_handler(chat_id=[99999]) + """ + + key = 'chat_id' + async def check(self, message, text): + return message.chat.id in text + +class ForwardFilter(SimpleCustomFilter): + """ + Check whether message was forwarded from channel or group. + + Example: + + @bot.message_handler(is_forwarded=True) + """ + + key = 'is_forwarded' + + async def check(self, message): + return message.forward_from_chat is not None + +class IsReplyFilter(SimpleCustomFilter): + """ + Check whether message is a reply. + + Example: + + @bot.message_handler(is_reply=True) + """ + + key = 'is_reply' + + async def check(self, message): + return message.reply_to_message is not None + + + +class LanguageFilter(AdvancedCustomFilter): + """ + Check users language_code. + + Example: + + @bot.message_handler(language_code=['ru']) + """ + + key = 'language_code' + + async def check(self, message, text): + if type(text) is list:return message.from_user.language_code in text + else: return message.from_user.language_code == text + +class IsAdminFilter(SimpleCustomFilter): + """ + Check whether the user is administrator / owner of the chat. + + Example: + @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) + """ + + key = 'is_chat_admin' + + def __init__(self, bot): + self._bot = bot + + async def check(self, message): + return self._bot.get_chat_member(message.chat.id, message.from_user.id).status in ['creator', 'administrator'] + +class StateFilter(AdvancedCustomFilter): + """ + Filter to check state. + + Example: + @bot.message_handler(state=1) + """ + def __init__(self, bot): + self.bot = bot + key = 'state' + + async def check(self, message, text): + if await self.bot.current_states.current_state(message.from_user.id) is False: return False + elif text == '*': return True + elif type(text) is list: return await self.bot.current_states.current_state(message.from_user.id) in text + return await self.bot.current_states.current_state(message.from_user.id) == text + +class IsDigitFilter(SimpleCustomFilter): + """ + Filter to check whether the string is made up of only digits. + + Example: + @bot.message_handler(is_digit=True) + """ + key = 'is_digit' + + async def check(self, message): + return message.text.isdigit() diff --git a/telebot/asyncio_handler_backends.py b/telebot/asyncio_handler_backends.py new file mode 100644 index 0000000..001f869 --- /dev/null +++ b/telebot/asyncio_handler_backends.py @@ -0,0 +1,343 @@ +import os +import pickle +import threading + +from telebot import apihelper + + +class HandlerBackend(object): + """ + Class for saving (next step|reply) handlers + """ + def __init__(self, handlers=None): + if handlers is None: + handlers = {} + self.handlers = handlers + + async def register_handler(self, handler_group_id, handler): + raise NotImplementedError() + + async def clear_handlers(self, handler_group_id): + raise NotImplementedError() + + async def get_handlers(self, handler_group_id): + raise NotImplementedError() + + +class MemoryHandlerBackend(HandlerBackend): + async def register_handler(self, handler_group_id, handler): + if handler_group_id in self.handlers: + self.handlers[handler_group_id].append(handler) + else: + self.handlers[handler_group_id] = [handler] + + async def clear_handlers(self, handler_group_id): + self.handlers.pop(handler_group_id, None) + + async def get_handlers(self, handler_group_id): + return self.handlers.pop(handler_group_id, None) + + async def load_handlers(self, filename, del_file_after_loading): + raise NotImplementedError() + + +class FileHandlerBackend(HandlerBackend): + def __init__(self, handlers=None, filename='./.handler-saves/handlers.save', delay=120): + super(FileHandlerBackend, self).__init__(handlers) + self.filename = filename + self.delay = delay + self.timer = threading.Timer(delay, self.save_handlers) + + async def register_handler(self, handler_group_id, handler): + if handler_group_id in self.handlers: + self.handlers[handler_group_id].append(handler) + else: + self.handlers[handler_group_id] = [handler] + await self.start_save_timer() + + async def clear_handlers(self, handler_group_id): + self.handlers.pop(handler_group_id, None) + await self.start_save_timer() + + async def get_handlers(self, handler_group_id): + handlers = self.handlers.pop(handler_group_id, None) + await self.start_save_timer() + return handlers + + async def start_save_timer(self): + if not self.timer.is_alive(): + if self.delay <= 0: + self.save_handlers() + else: + self.timer = threading.Timer(self.delay, self.save_handlers) + self.timer.start() + + async def save_handlers(self): + await self.dump_handlers(self.handlers, self.filename) + + async def load_handlers(self, filename=None, del_file_after_loading=True): + if not filename: + filename = self.filename + tmp = await self.return_load_handlers(filename, del_file_after_loading=del_file_after_loading) + if tmp is not None: + self.handlers.update(tmp) + + @staticmethod + async def dump_handlers(handlers, filename, file_mode="wb"): + dirs = filename.rsplit('/', maxsplit=1)[0] + os.makedirs(dirs, exist_ok=True) + + with open(filename + ".tmp", file_mode) as file: + if (apihelper.CUSTOM_SERIALIZER is None): + pickle.dump(handlers, file) + else: + apihelper.CUSTOM_SERIALIZER.dump(handlers, file) + + if os.path.isfile(filename): + os.remove(filename) + + os.rename(filename + ".tmp", filename) + + @staticmethod + async def return_load_handlers(filename, del_file_after_loading=True): + if os.path.isfile(filename) and os.path.getsize(filename) > 0: + with open(filename, "rb") as file: + if (apihelper.CUSTOM_SERIALIZER is None): + handlers = pickle.load(file) + else: + handlers = apihelper.CUSTOM_SERIALIZER.load(file) + + if del_file_after_loading: + os.remove(filename) + + return handlers + + +class RedisHandlerBackend(HandlerBackend): + def __init__(self, handlers=None, host='localhost', port=6379, db=0, prefix='telebot', password=None): + super(RedisHandlerBackend, self).__init__(handlers) + from redis import Redis + self.prefix = prefix + self.redis = Redis(host, port, db, password) + + async def _key(self, handle_group_id): + return ':'.join((self.prefix, str(handle_group_id))) + + async def register_handler(self, handler_group_id, handler): + handlers = [] + value = self.redis.get(self._key(handler_group_id)) + if value: + handlers = pickle.loads(value) + handlers.append(handler) + self.redis.set(self._key(handler_group_id), pickle.dumps(handlers)) + + async def clear_handlers(self, handler_group_id): + self.redis.delete(self._key(handler_group_id)) + + async def get_handlers(self, handler_group_id): + handlers = None + value = self.redis.get(self._key(handler_group_id)) + if value: + handlers = pickle.loads(value) + self.clear_handlers(handler_group_id) + return handlers + + +class StateMemory: + def __init__(self): + self._states = {} + + async def add_state(self, chat_id, state): + """ + Add a state. + :param chat_id: + :param state: new state + """ + if chat_id in self._states: + + self._states[chat_id]['state'] = state + else: + self._states[chat_id] = {'state': state,'data': {}} + + async def current_state(self, chat_id): + """Current state""" + if chat_id in self._states: return self._states[chat_id]['state'] + else: return False + + async def delete_state(self, chat_id): + """Delete a state""" + self._states.pop(chat_id) + + def _get_data(self, chat_id): + return self._states[chat_id]['data'] + + async def set(self, chat_id, new_state): + """ + Set a new state for a user. + :param chat_id: + :param new_state: new_state of a user + """ + await self.add_state(chat_id,new_state) + + async def _add_data(self, chat_id, key, value): + result = self._states[chat_id]['data'][key] = value + return result + + async def finish(self, chat_id): + """ + Finish(delete) state of a user. + :param chat_id: + """ + await self.delete_state(chat_id) + + def retrieve_data(self, chat_id): + """ + Save input text. + + Usage: + with bot.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + Also, at the end of your 'Form' you can get the name: + data['name'] + """ + return StateContext(self, chat_id) + + +class StateFile: + """ + Class to save states in a file. + """ + def __init__(self, filename): + self.file_path = filename + + async def add_state(self, chat_id, state): + """ + Add a state. + :param chat_id: + :param state: new state + """ + states_data = self._read_data() + if chat_id in states_data: + states_data[chat_id]['state'] = state + return await self._save_data(states_data) + else: + new_data = states_data[chat_id] = {'state': state,'data': {}} + return await self._save_data(states_data) + + + async def current_state(self, chat_id): + """Current state.""" + states_data = self._read_data() + if chat_id in states_data: return states_data[chat_id]['state'] + else: return False + + async def delete_state(self, chat_id): + """Delete a state""" + states_data = await self._read_data() + states_data.pop(chat_id) + await self._save_data(states_data) + + async def _read_data(self): + """ + Read the data from file. + """ + file = open(self.file_path, 'rb') + states_data = pickle.load(file) + file.close() + return states_data + + async def _create_dir(self): + """ + Create directory .save-handlers. + """ + dirs = self.file_path.rsplit('/', maxsplit=1)[0] + os.makedirs(dirs, exist_ok=True) + if not os.path.isfile(self.file_path): + with open(self.file_path,'wb') as file: + pickle.dump({}, file) + + async def _save_data(self, new_data): + """ + Save data after editing. + :param new_data: + """ + with open(self.file_path, 'wb+') as state_file: + pickle.dump(new_data, state_file, protocol=pickle.HIGHEST_PROTOCOL) + return True + + def _get_data(self, chat_id): + return self._read_data()[chat_id]['data'] + + async def set(self, chat_id, new_state): + """ + Set a new state for a user. + :param chat_id: + :param new_state: new_state of a user + + """ + await self.add_state(chat_id,new_state) + + async def _add_data(self, chat_id, key, value): + states_data = self._read_data() + result = states_data[chat_id]['data'][key] = value + await self._save_data(result) + + return result + + async def finish(self, chat_id): + """ + Finish(delete) state of a user. + :param chat_id: + """ + await self.delete_state(chat_id) + + async def retrieve_data(self, chat_id): + """ + Save input text. + + Usage: + with bot.retrieve_data(message.chat.id) as data: + data['name'] = message.text + + Also, at the end of your 'Form' you can get the name: + data['name'] + """ + return StateFileContext(self, chat_id) + + +class StateContext: + """ + Class for data. + """ + def __init__(self , obj: StateMemory, chat_id) -> None: + self.obj = obj + self.chat_id = chat_id + self.data = obj._get_data(chat_id) + + async def __aenter__(self): + return self.data + + async def __aexit__(self, exc_type, exc_val, exc_tb): + return + +class StateFileContext: + """ + Class for data. + """ + def __init__(self , obj: StateFile, chat_id) -> None: + self.obj = obj + self.chat_id = chat_id + self.data = None + + async def __aenter__(self): + self.data = self.obj._get_data(self.chat_id) + return self.data + + async def __aexit__(self, exc_type, exc_val, exc_tb): + old_data = await self.obj._read_data() + for i in self.data: + old_data[self.chat_id]['data'][i] = self.data.get(i) + await self.obj._save_data(old_data) + + return diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py new file mode 100644 index 0000000..7bb649e --- /dev/null +++ b/telebot/asyncio_helper.py @@ -0,0 +1,1607 @@ +import asyncio +from time import time +import aiohttp +from telebot import types +import json +import logging + +try: + import ujson as json +except ImportError: + import json + +import requests +from requests.exceptions import HTTPError, ConnectionError, Timeout + +try: + # noinspection PyUnresolvedReferences + from requests.packages.urllib3 import fields + format_header_param = fields.format_header_param +except ImportError: + format_header_param = None + +API_URL = 'https://api.telegram.org/bot{0}/{1}' + +from datetime import datetime +from telebot import util + +class SessionBase: + def __init__(self) -> None: + self.session = None + async def _get_new_session(self): + self.session = aiohttp.ClientSession() + return self.session + +session_manager = SessionBase() + +proxy = None +session = None + +FILE_URL = None + +CONNECT_TIMEOUT = 15 +READ_TIMEOUT = 30 + +LONG_POLLING_TIMEOUT = 10 # Should be positive, short polling should be used for testing purposes only (https://core.telegram.org/bots/api#getupdates) + + +RETRY_ON_ERROR = False +RETRY_TIMEOUT = 2 +MAX_RETRIES = 15 + +CUSTOM_SERIALIZER = None +CUSTOM_REQUEST_SENDER = None + +ENABLE_MIDDLEWARE = False + +async def _process_request(token, url, method='get', params=None, files=None): + async with await session_manager._get_new_session() as session: + async with session.get(API_URL.format(token, url), params=params, data=files) as response: + json_result = await _check_result(url, response) + if json_result: + return json_result['result'] + + +async def _convert_markup(markup): + if isinstance(markup, types.JsonSerializable): + return markup.to_json() + return markup + + + +async def get_me(token): + method_url = r'getMe' + return await _process_request(token, method_url) + + +async def log_out(token): + method_url = r'logOut' + return await _process_request(token, method_url) + + +async def close(token): + method_url = r'close' + return await _process_request(token, method_url) + + +async def get_file(token, file_id): + method_url = r'getFile' + return await _process_request(token, method_url, params={'file_id': file_id}) + + +async def get_file_url(token, file_id): + if FILE_URL is None: + return "https://api.telegram.org/file/bot{0}/{1}".format(token, get_file(token, file_id)['file_path']) + else: + # noinspection PyUnresolvedReferences + return FILE_URL.format(token, get_file(token, file_id)['file_path']) + + +async def download_file(token, file_path): + if FILE_URL is None: + url = "https://api.telegram.org/file/bot{0}/{1}".format(token, file_path) + else: + # noinspection PyUnresolvedReferences + url = FILE_URL.format(token, file_path) + # TODO: rewrite this method + async with await session_manager._get_new_session() as session: + async with session.get(url, proxy=proxy) as response: + result = await response.read() + if response.status != 200: + raise ApiHTTPException('Download file', result) + + return result + + +async def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): + method_url = r'setWebhook' + payload = { + 'url': url if url else "", + } + files = None + if certificate: + files = {'certificate': certificate} + if max_connections: + payload['max_connections'] = max_connections + if allowed_updates is not None: # Empty lists should pass + payload['allowed_updates'] = json.dumps(allowed_updates) + if ip_address is not None: # Empty string should pass + payload['ip_address'] = ip_address + if drop_pending_updates is not None: # Any bool value should pass + payload['drop_pending_updates'] = drop_pending_updates + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload, files=files) + + +async def delete_webhook(token, drop_pending_updates=None, timeout=None): + method_url = r'deleteWebhook' + payload = {} + if drop_pending_updates is not None: # Any bool value should pass + payload['drop_pending_updates'] = drop_pending_updates + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def get_webhook_info(token, timeout=None): + method_url = r'getWebhookInfo' + payload = {} + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + + +async def get_updates(token, offset=None, limit=None, + timeout=None, allowed_updates=None, long_polling_timeout=None): + method_name = 'getUpdates' + params = {} + if offset: + params['offset'] = offset + elif limit: + params['limit'] = limit + elif timeout: + params['timeout'] = timeout + elif allowed_updates: + params['allowed_updates'] = allowed_updates + params['long_polling_timeout'] = long_polling_timeout if long_polling_timeout else LONG_POLLING_TIMEOUT + return await _process_request(token, method_name, params=params) + +async def _check_result(method_name, result): + """ + Checks whether `result` is a valid API response. + A result is considered invalid if: + - The server returned an HTTP response code other than 200 + - The content of the result is invalid JSON. + - The method call was unsuccessful (The JSON 'ok' field equals False) + + :raises ApiException: if one of the above listed cases is applicable + :param method_name: The name of the method called + :param result: The returned result of the method request + :return: The result parsed to a JSON dictionary. + """ + try: + result_json = await result.json(encoding="utf-8") + except: + if result.status_code != 200: + raise ApiHTTPException(method_name, result) + else: + raise ApiInvalidJSONException(method_name, result) + else: + if not result_json['ok']: + raise ApiTelegramException(method_name, result, result_json) + + return result_json + + +async def send_message( + token, chat_id, text, + disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, + entities=None, allow_sending_without_reply=None): + """ + Use this method to send text messages. On success, the sent Message is returned. + :param token: + :param chat_id: + :param text: + :param disable_web_page_preview: + :param reply_to_message_id: + :param reply_markup: + :param parse_mode: + :param disable_notification: + :param timeout: + :param entities: + :param allow_sending_without_reply: + :return: + """ + method_name = 'sendMessage' + params = {'chat_id': str(chat_id), 'text': text} + if disable_web_page_preview is not None: + params['disable_web_page_preview'] = disable_web_page_preview + if reply_to_message_id: + params['reply_to_message_id'] = reply_to_message_id + if reply_markup: + params['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + params['parse_mode'] = parse_mode + if disable_notification is not None: + params['disable_notification'] = disable_notification + if timeout: + params['timeout'] = timeout + if entities: + params['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) + if allow_sending_without_reply is not None: + params['allow_sending_without_reply'] = allow_sending_without_reply + + return await _process_request(token, method_name, params=params) + +# here shit begins + +async def get_user_profile_photos(token, user_id, offset=None, limit=None): + method_url = r'getUserProfilePhotos' + payload = {'user_id': user_id} + if offset: + payload['offset'] = offset + if limit: + payload['limit'] = limit + return await _process_request(token, method_url, params=payload) + + +async def get_chat(token, chat_id): + method_url = r'getChat' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def leave_chat(token, chat_id): + method_url = r'leaveChat' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def get_chat_administrators(token, chat_id): + method_url = r'getChatAdministrators' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def get_chat_member_count(token, chat_id): + method_url = r'getChatMemberCount' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def set_sticker_set_thumb(token, name, user_id, thumb): + method_url = r'setStickerSetThumb' + payload = {'name': name, 'user_id': user_id} + files = {} + if thumb: + if not isinstance(thumb, str): + files['thumb'] = thumb + else: + payload['thumb'] = thumb + return await _process_request(token, method_url, params=payload, files=files or None) + + +async def set_chat_sticker_set(token, chat_id, sticker_set_name): + method_url = r'setChatStickerSet' + payload = {'chat_id': chat_id, 'sticker_set_name': sticker_set_name} + return await _process_request(token, method_url, params=payload) + + +async def delete_chat_sticker_set(token, chat_id): + method_url = r'deleteChatStickerSet' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload) + + +async def get_chat_member(token, chat_id, user_id): + method_url = r'getChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + return await _process_request(token, method_url, params=payload) + + +async def forward_message( + token, chat_id, from_chat_id, message_id, + disable_notification=None, timeout=None): + method_url = r'forwardMessage' + payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def copy_message(token, chat_id, from_chat_id, message_id, caption=None, parse_mode=None, caption_entities=None, + disable_notification=None, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None): + method_url = r'copyMessage' + payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} + if caption is not None: + payload['caption'] = caption + if parse_mode: + payload['parse_mode'] = parse_mode + if caption_entities is not None: + payload['caption_entities'] = await _convert_entites(caption_entities) + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup is not None: + payload['reply_markup'] = await _convert_markup(reply_markup) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def send_dice( + token, chat_id, + emoji=None, disable_notification=None, reply_to_message_id=None, + reply_markup=None, timeout=None, allow_sending_without_reply=None): + method_url = r'sendDice' + payload = {'chat_id': chat_id} + if emoji: + payload['emoji'] = emoji + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload) + + +async def send_photo( + token, chat_id, photo, + caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, + caption_entities=None, allow_sending_without_reply=None): + method_url = r'sendPhoto' + payload = {'chat_id': chat_id} + files = None + if util.is_string(photo): + payload['photo'] = photo + elif util.is_pil_image(photo): + files = {'photo': util.pil_image_to_file(photo)} + else: + files = {'photo': photo} + if caption: + payload['caption'] = caption + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_media_group( + token, chat_id, media, + disable_notification=None, reply_to_message_id=None, + timeout=None, allow_sending_without_reply=None): + method_url = r'sendMediaGroup' + media_json, files = await convert_input_media_array(media) + payload = {'chat_id': chat_id, 'media': media_json} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request( + token, method_url, params=payload, + method='post' if files else 'get', + files=files if files else None) + + +async def send_location( + token, chat_id, latitude, longitude, + live_period=None, reply_to_message_id=None, + reply_markup=None, disable_notification=None, + timeout=None, horizontal_accuracy=None, heading=None, + proximity_alert_radius=None, allow_sending_without_reply=None): + method_url = r'sendLocation' + payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude} + if live_period: + payload['live_period'] = live_period + if horizontal_accuracy: + payload['horizontal_accuracy'] = horizontal_accuracy + if heading: + payload['heading'] = heading + if proximity_alert_radius: + payload['proximity_alert_radius'] = proximity_alert_radius + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def edit_message_live_location( + token, latitude, longitude, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None, timeout=None, + horizontal_accuracy=None, heading=None, proximity_alert_radius=None): + method_url = r'editMessageLiveLocation' + payload = {'latitude': latitude, 'longitude': longitude} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if horizontal_accuracy: + payload['horizontal_accuracy'] = horizontal_accuracy + if heading: + payload['heading'] = heading + if proximity_alert_radius: + payload['proximity_alert_radius'] = proximity_alert_radius + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def stop_message_live_location( + token, chat_id=None, message_id=None, + inline_message_id=None, reply_markup=None, timeout=None): + method_url = r'stopMessageLiveLocation' + payload = {} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def send_venue( + token, chat_id, latitude, longitude, title, address, + foursquare_id=None, foursquare_type=None, disable_notification=None, + reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None, google_place_id=None, + google_place_type=None): + method_url = r'sendVenue' + payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address} + if foursquare_id: + payload['foursquare_id'] = foursquare_id + if foursquare_type: + payload['foursquare_type'] = foursquare_type + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if google_place_id: + payload['google_place_id'] = google_place_id + if google_place_type: + payload['google_place_type'] = google_place_type + return await _process_request(token, method_url, params=payload) + + +async def send_contact( + token, chat_id, phone_number, first_name, last_name=None, vcard=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None): + method_url = r'sendContact' + payload = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name} + if last_name: + payload['last_name'] = last_name + if vcard: + payload['vcard'] = vcard + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload) + + +async def send_chat_action(token, chat_id, action, timeout=None): + method_url = r'sendChatAction' + payload = {'chat_id': chat_id, 'action': action} + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload) + + +async def send_video(token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None, + thumb=None, width=None, height=None, caption_entities=None, allow_sending_without_reply=None): + method_url = r'sendVideo' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + files = {'video': data} + else: + payload['video'] = data + if duration: + payload['duration'] = duration + if caption: + payload['caption'] = caption + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if supports_streaming is not None: + payload['supports_streaming'] = supports_streaming + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if width: + payload['width'] = width + if height: + payload['height'] = height + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_animation( + token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, thumb=None, caption_entities=None, + allow_sending_without_reply=None): + method_url = r'sendAnimation' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + files = {'animation': data} + else: + payload['animation'] = data + if duration: + payload['duration'] = duration + if caption: + payload['caption'] = caption + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, + parse_mode=None, disable_notification=None, timeout=None, caption_entities=None, + allow_sending_without_reply=None): + method_url = r'sendVoice' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(voice): + files = {'voice': voice} + else: + payload['voice'] = voice + if caption: + payload['caption'] = caption + if duration: + payload['duration'] = duration + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_video_note(token, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, + disable_notification=None, timeout=None, thumb=None, allow_sending_without_reply=None): + method_url = r'sendVideoNote' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + files = {'video_note': data} + else: + payload['video_note'] = data + if duration: + payload['duration'] = duration + if length and (str(length).isdigit() and int(length) <= 639): + payload['length'] = length + else: + payload['length'] = 639 # seems like it is MAX length size + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_audio(token, chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, + reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, thumb=None, + caption_entities=None, allow_sending_without_reply=None): + method_url = r'sendAudio' + payload = {'chat_id': chat_id} + files = None + if not util.is_string(audio): + files = {'audio': audio} + else: + payload['audio'] = audio + if caption: + payload['caption'] = caption + if duration: + payload['duration'] = duration + if performer: + payload['performer'] = performer + if title: + payload['title'] = title + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode: + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, + disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, + allow_sending_without_reply=None, disable_content_type_detection=None, visible_file_name=None): + method_url = get_method_by_type(data_type) + payload = {'chat_id': chat_id} + files = None + if not util.is_string(data): + file_data = data + if visible_file_name: + file_data = (visible_file_name, data) + files = {data_type: file_data} + else: + payload[data_type] = data + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if parse_mode and data_type == 'document': + payload['parse_mode'] = parse_mode + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if timeout: + payload['timeout'] = timeout + if caption: + payload['caption'] = caption + if thumb: + if not util.is_string(thumb): + if files: + files['thumb'] = thumb + else: + files = {'thumb': thumb} + else: + payload['thumb'] = thumb + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if method_url == 'sendDocument' and disable_content_type_detection is not None: + payload['disable_content_type_detection'] = disable_content_type_detection + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def get_method_by_type(data_type): + if data_type == 'document': + return r'sendDocument' + if data_type == 'sticker': + return r'sendSticker' + + +async def ban_chat_member(token, chat_id, user_id, until_date=None, revoke_messages=None): + method_url = 'banChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if isinstance(until_date, datetime): + payload['until_date'] = until_date.timestamp() + else: + payload['until_date'] = until_date + if revoke_messages is not None: + payload['revoke_messages'] = revoke_messages + return await _process_request(token, method_url, params=payload, method='post') + + +async def unban_chat_member(token, chat_id, user_id, only_if_banned): + method_url = 'unbanChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if only_if_banned is not None: # None / True / False + payload['only_if_banned'] = only_if_banned + return await _process_request(token, method_url, params=payload, method='post') + + +async def restrict_chat_member( + token, chat_id, user_id, until_date=None, + can_send_messages=None, can_send_media_messages=None, + can_send_polls=None, can_send_other_messages=None, + can_add_web_page_previews=None, can_change_info=None, + can_invite_users=None, can_pin_messages=None): + method_url = 'restrictChatMember' + permissions = {} + if can_send_messages is not None: + permissions['can_send_messages'] = can_send_messages + if can_send_media_messages is not None: + permissions['can_send_media_messages'] = can_send_media_messages + if can_send_polls is not None: + permissions['can_send_polls'] = can_send_polls + if can_send_other_messages is not None: + permissions['can_send_other_messages'] = can_send_other_messages + if can_add_web_page_previews is not None: + permissions['can_add_web_page_previews'] = can_add_web_page_previews + if can_change_info is not None: + permissions['can_change_info'] = can_change_info + if can_invite_users is not None: + permissions['can_invite_users'] = can_invite_users + if can_pin_messages is not None: + permissions['can_pin_messages'] = can_pin_messages + permissions_json = json.dumps(permissions) + payload = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions_json} + if until_date is not None: + if isinstance(until_date, datetime): + payload['until_date'] = until_date.timestamp() + else: + payload['until_date'] = until_date + return await _process_request(token, method_url, params=payload, method='post') + + +async def promote_chat_member( + token, chat_id, user_id, can_change_info=None, can_post_messages=None, + can_edit_messages=None, can_delete_messages=None, can_invite_users=None, + can_restrict_members=None, can_pin_messages=None, can_promote_members=None, + is_anonymous=None, can_manage_chat=None, can_manage_voice_chats=None): + method_url = 'promoteChatMember' + payload = {'chat_id': chat_id, 'user_id': user_id} + if can_change_info is not None: + payload['can_change_info'] = can_change_info + if can_post_messages is not None: + payload['can_post_messages'] = can_post_messages + if can_edit_messages is not None: + payload['can_edit_messages'] = can_edit_messages + if can_delete_messages is not None: + payload['can_delete_messages'] = can_delete_messages + if can_invite_users is not None: + payload['can_invite_users'] = can_invite_users + if can_restrict_members is not None: + payload['can_restrict_members'] = can_restrict_members + if can_pin_messages is not None: + payload['can_pin_messages'] = can_pin_messages + if can_promote_members is not None: + payload['can_promote_members'] = can_promote_members + if is_anonymous is not None: + payload['is_anonymous'] = is_anonymous + if can_manage_chat is not None: + payload['can_manage_chat'] = can_manage_chat + if can_manage_voice_chats is not None: + payload['can_manage_voice_chats'] = can_manage_voice_chats + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_administrator_custom_title(token, chat_id, user_id, custom_title): + method_url = 'setChatAdministratorCustomTitle' + payload = { + 'chat_id': chat_id, 'user_id': user_id, 'custom_title': custom_title + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_permissions(token, chat_id, permissions): + method_url = 'setChatPermissions' + payload = { + 'chat_id': chat_id, + 'permissions': permissions.to_json() + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def create_chat_invite_link(token, chat_id, name, expire_date, member_limit, creates_join_request): + method_url = 'createChatInviteLink' + payload = { + 'chat_id': chat_id + } + + if expire_date is not None: + if isinstance(expire_date, datetime): + payload['expire_date'] = expire_date.timestamp() + else: + payload['expire_date'] = expire_date + if member_limit: + payload['member_limit'] = member_limit + if creates_join_request is not None: + payload['creates_join_request'] = creates_join_request + if name: + payload['name'] = name + + return await _process_request(token, method_url, params=payload, method='post') + + +async def edit_chat_invite_link(token, chat_id, invite_link, name, expire_date, member_limit, creates_join_request): + method_url = 'editChatInviteLink' + payload = { + 'chat_id': chat_id, + 'invite_link': invite_link + } + + if expire_date is not None: + if isinstance(expire_date, datetime): + payload['expire_date'] = expire_date.timestamp() + else: + payload['expire_date'] = expire_date + + if member_limit is not None: + payload['member_limit'] = member_limit + if name: + payload['name'] = name + if creates_join_request is not None: + payload['creates_join_request'] = creates_join_request + + return await _process_request(token, method_url, params=payload, method='post') + +async def revoke_chat_invite_link(token, chat_id, invite_link): + method_url = 'revokeChatInviteLink' + payload = { + 'chat_id': chat_id, + 'invite_link': invite_link + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def export_chat_invite_link(token, chat_id): + method_url = 'exportChatInviteLink' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload, method='post') + +async def approve_chat_join_request(token, chat_id, user_id): + method_url = 'approveChatJoinRequest' + payload = { + 'chat_id': chat_id, + 'user_id': user_id + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def decline_chat_join_request(token, chat_id, user_id): + method_url = 'declineChatJoinRequest' + payload = { + 'chat_id': chat_id, + 'user_id': user_id + } + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_photo(token, chat_id, photo): + method_url = 'setChatPhoto' + payload = {'chat_id': chat_id} + files = None + if util.is_string(photo): + payload['photo'] = photo + elif util.is_pil_image(photo): + files = {'photo': util.pil_image_to_file(photo)} + else: + files = {'photo': photo} + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def delete_chat_photo(token, chat_id): + method_url = 'deleteChatPhoto' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_title(token, chat_id, title): + method_url = 'setChatTitle' + payload = {'chat_id': chat_id, 'title': title} + return await _process_request(token, method_url, params=payload, method='post') + + +async def get_my_commands(token, scope=None, language_code=None): + method_url = r'getMyCommands' + payload = {} + if scope: + payload['scope'] = scope.to_json() + if language_code: + payload['language_code'] = language_code + return await _process_request(token, method_url, params=payload) + + +async def set_my_commands(token, commands, scope=None, language_code=None): + method_url = r'setMyCommands' + payload = {'commands': await _convert_list_json_serializable(commands)} + if scope: + payload['scope'] = scope.to_json() + if language_code: + payload['language_code'] = language_code + return await _process_request(token, method_url, params=payload, method='post') + + +async def delete_my_commands(token, scope=None, language_code=None): + method_url = r'deleteMyCommands' + payload = {} + if scope: + payload['scope'] = scope.to_json() + if language_code: + payload['language_code'] = language_code + return await _process_request(token, method_url, params=payload, method='post') + + +async def set_chat_description(token, chat_id, description): + method_url = 'setChatDescription' + payload = {'chat_id': chat_id} + if description is not None: # Allow empty strings + payload['description'] = description + return await _process_request(token, method_url, params=payload, method='post') + + +async def pin_chat_message(token, chat_id, message_id, disable_notification=None): + method_url = 'pinChatMessage' + payload = {'chat_id': chat_id, 'message_id': message_id} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + return await _process_request(token, method_url, params=payload, method='post') + + +async def unpin_chat_message(token, chat_id, message_id): + method_url = 'unpinChatMessage' + payload = {'chat_id': chat_id} + if message_id: + payload['message_id'] = message_id + return await _process_request(token, method_url, params=payload, method='post') + + +async def unpin_all_chat_messages(token, chat_id): + method_url = 'unpinAllChatMessages' + payload = {'chat_id': chat_id} + return await _process_request(token, method_url, params=payload, method='post') + + +# Updating messages + +async def edit_message_text(token, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, + entities = None, disable_web_page_preview=None, reply_markup=None): + method_url = r'editMessageText' + payload = {'text': text} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if parse_mode: + payload['parse_mode'] = parse_mode + if entities: + payload['entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(entities)) + if disable_web_page_preview is not None: + payload['disable_web_page_preview'] = disable_web_page_preview + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, method='post') + + +async def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_message_id=None, + parse_mode=None, caption_entities=None,reply_markup=None): + method_url = r'editMessageCaption' + payload = {'caption': caption} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if parse_mode: + payload['parse_mode'] = parse_mode + if caption_entities: + payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities)) + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, method='post') + + +async def edit_message_media(token, media, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + method_url = r'editMessageMedia' + media_json, file = convert_input_media(media) + payload = {'media': media_json} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, files=file, method='post' if file else 'get') + + +async def edit_message_reply_markup(token, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + method_url = r'editMessageReplyMarkup' + payload = {} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload, method='post') + + +async def delete_message(token, chat_id, message_id, timeout=None): + method_url = r'deleteMessage' + payload = {'chat_id': chat_id, 'message_id': message_id} + if timeout: + payload['timeout'] = timeout + return await _process_request(token, method_url, params=payload, method='post') + + +# Game + +async def send_game( + token, chat_id, game_short_name, + disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, + allow_sending_without_reply=None): + method_url = r'sendGame' + payload = {'chat_id': chat_id, 'game_short_name': game_short_name} + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + return await _process_request(token, method_url, params=payload) + + +# https://core.telegram.org/bots/api#setgamescore +async def set_game_score(token, user_id, score, force=None, disable_edit_message=None, chat_id=None, message_id=None, + inline_message_id=None): + """ + Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. + :param token: Bot's token (you don't need to fill this) + :param user_id: User identifier + :param score: New score, must be non-negative + :param force: (Optional) Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters + :param disable_edit_message: (Optional) Pass True, if the game message should not be automatically edited to include the current scoreboard + :param chat_id: (Optional, required if inline_message_id is not specified) Unique identifier for the target chat (or username of the target channel in the format @channelusername) + :param message_id: (Optional, required if inline_message_id is not specified) Unique identifier of the sent message + :param inline_message_id: (Optional, required if chat_id and message_id are not specified) Identifier of the inline message + :return: + """ + method_url = r'setGameScore' + payload = {'user_id': user_id, 'score': score} + if force is not None: + payload['force'] = force + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + if disable_edit_message is not None: + payload['disable_edit_message'] = disable_edit_message + return await _process_request(token, method_url, params=payload) + + +# https://core.telegram.org/bots/api#getgamehighscores +async def get_game_high_scores(token, user_id, chat_id=None, message_id=None, inline_message_id=None): + """ + Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. + This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. + :param token: Bot's token (you don't need to fill this) + :param user_id: Target user id + :param chat_id: (Optional, required if inline_message_id is not specified) Unique identifier for the target chat (or username of the target channel in the format @channelusername) + :param message_id: (Optional, required if inline_message_id is not specified) Unique identifier of the sent message + :param inline_message_id: (Optional, required if chat_id and message_id are not specified) Identifier of the inline message + :return: + """ + method_url = r'getGameHighScores' + payload = {'user_id': user_id} + if chat_id: + payload['chat_id'] = chat_id + if message_id: + payload['message_id'] = message_id + if inline_message_id: + payload['inline_message_id'] = inline_message_id + return await _process_request(token, method_url, params=payload) + + +# Payments (https://core.telegram.org/bots/api#payments) + +async def send_invoice( + token, chat_id, title, description, invoice_payload, provider_token, currency, prices, + start_parameter = None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, + need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, + send_phone_number_to_provider = None, send_email_to_provider = None, is_flexible=None, + disable_notification=None, reply_to_message_id=None, reply_markup=None, provider_data=None, + timeout=None, allow_sending_without_reply=None, max_tip_amount=None, suggested_tip_amounts=None): + """ + Use this method to send invoices. On success, the sent Message is returned. + :param token: Bot's token (you don't need to fill this) + :param chat_id: Unique identifier for the target private chat + :param title: Product name + :param description: Product description + :param invoice_payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param provider_token: Payments provider token, obtained via @Botfather + :param currency: Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass True, if you require the user's full name to complete the order + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :param need_email: Pass True, if you require the user's email to complete the order + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param reply_to_message_id: If the message is a reply, ID of the original message + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param timeout: + :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest units of the currency. + At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + :return: + """ + method_url = r'sendInvoice' + payload = {'chat_id': chat_id, 'title': title, 'description': description, 'payload': invoice_payload, + 'provider_token': provider_token, 'currency': currency, + 'prices': await _convert_list_json_serializable(prices)} + if start_parameter: + payload['start_parameter'] = start_parameter + if photo_url: + payload['photo_url'] = photo_url + if photo_size: + payload['photo_size'] = photo_size + if photo_width: + payload['photo_width'] = photo_width + if photo_height: + payload['photo_height'] = photo_height + if need_name is not None: + payload['need_name'] = need_name + if need_phone_number is not None: + payload['need_phone_number'] = need_phone_number + if need_email is not None: + payload['need_email'] = need_email + if need_shipping_address is not None: + payload['need_shipping_address'] = need_shipping_address + if send_phone_number_to_provider is not None: + payload['send_phone_number_to_provider'] = send_phone_number_to_provider + if send_email_to_provider is not None: + payload['send_email_to_provider'] = send_email_to_provider + if is_flexible is not None: + payload['is_flexible'] = is_flexible + if disable_notification is not None: + payload['disable_notification'] = disable_notification + if reply_to_message_id: + payload['reply_to_message_id'] = reply_to_message_id + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + if provider_data: + payload['provider_data'] = provider_data + if timeout: + payload['timeout'] = timeout + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if max_tip_amount is not None: + payload['max_tip_amount'] = max_tip_amount + if suggested_tip_amounts is not None: + payload['suggested_tip_amounts'] = json.dumps(suggested_tip_amounts) + return await _process_request(token, method_url, params=payload) + + +async def answer_shipping_query(token, shipping_query_id, ok, shipping_options=None, error_message=None): + """ + If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. + :param token: Bot's token (you don't need to fill this) + :param shipping_query_id: Unique identifier for the query to be answered + :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) + :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options. + :param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. + :return: + """ + method_url = 'answerShippingQuery' + payload = {'shipping_query_id': shipping_query_id, 'ok': ok} + if shipping_options: + payload['shipping_options'] = await _convert_list_json_serializable(shipping_options) + if error_message: + payload['error_message'] = error_message + return await _process_request(token, method_url, params=payload) + + +async def answer_pre_checkout_query(token, pre_checkout_query_id, ok, error_message=None): + """ + Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + :param token: Bot's token (you don't need to fill this) + :param pre_checkout_query_id: Unique identifier for the query to be answered + :param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. + :param error_message: Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. + :return: + """ + method_url = 'answerPreCheckoutQuery' + payload = {'pre_checkout_query_id': pre_checkout_query_id, 'ok': ok} + if error_message: + payload['error_message'] = error_message + return await _process_request(token, method_url, params=payload) + + +# InlineQuery + +async def answer_callback_query(token, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): + """ + Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. + Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via BotFather and accept the terms. Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter. + :param token: Bot's token (you don't need to fill this) + :param callback_query_id: Unique identifier for the query to be answered + :param text: (Optional) Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + :param show_alert: (Optional) If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. + :param url: (Optional) URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button. + Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter. + :param cache_time: (Optional) The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. + :return: + """ + method_url = 'answerCallbackQuery' + payload = {'callback_query_id': callback_query_id} + if text: + payload['text'] = text + if show_alert is not None: + payload['show_alert'] = show_alert + if url: + payload['url'] = url + if cache_time is not None: + payload['cache_time'] = cache_time + return await _process_request(token, method_url, params=payload, method='post') + + +async def answer_inline_query(token, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, + switch_pm_text=None, switch_pm_parameter=None): + method_url = 'answerInlineQuery' + payload = {'inline_query_id': inline_query_id, 'results': await _convert_list_json_serializable(results)} + if cache_time is not None: + payload['cache_time'] = cache_time + if is_personal is not None: + payload['is_personal'] = is_personal + if next_offset is not None: + payload['next_offset'] = next_offset + if switch_pm_text: + payload['switch_pm_text'] = switch_pm_text + if switch_pm_parameter: + payload['switch_pm_parameter'] = switch_pm_parameter + return await _process_request(token, method_url, params=payload, method='post') + + +async def get_sticker_set(token, name): + method_url = 'getStickerSet' + return await _process_request(token, method_url, params={'name': name}) + + +async def upload_sticker_file(token, user_id, png_sticker): + method_url = 'uploadStickerFile' + payload = {'user_id': user_id} + files = {'png_sticker': png_sticker} + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def create_new_sticker_set( + token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks=None, mask_position=None): + method_url = 'createNewStickerSet' + payload = {'user_id': user_id, 'name': name, 'title': title, 'emojis': emojis} + stype = 'png_sticker' if png_sticker else 'tgs_sticker' + sticker = png_sticker or tgs_sticker + files = None + if not util.is_string(sticker): + files = {stype: sticker} + else: + payload[stype] = sticker + if contains_masks is not None: + payload['contains_masks'] = contains_masks + if mask_position: + payload['mask_position'] = mask_position.to_json() + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def add_sticker_to_set(token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position): + method_url = 'addStickerToSet' + payload = {'user_id': user_id, 'name': name, 'emojis': emojis} + stype = 'png_sticker' if png_sticker else 'tgs_sticker' + sticker = png_sticker or tgs_sticker + files = None + if not util.is_string(sticker): + files = {stype: sticker} + else: + payload[stype] = sticker + if mask_position: + payload['mask_position'] = mask_position.to_json() + return await _process_request(token, method_url, params=payload, files=files, method='post') + + +async def set_sticker_position_in_set(token, sticker, position): + method_url = 'setStickerPositionInSet' + payload = {'sticker': sticker, 'position': position} + return await _process_request(token, method_url, params=payload, method='post') + + +async def delete_sticker_from_set(token, sticker): + method_url = 'deleteStickerFromSet' + payload = {'sticker': sticker} + return await _process_request(token, method_url, params=payload, method='post') + + +# noinspection PyShadowingBuiltins +async def send_poll( + token, chat_id, + question, options, + is_anonymous = None, type = None, allows_multiple_answers = None, correct_option_id = None, + explanation = None, explanation_parse_mode=None, open_period = None, close_date = None, is_closed = None, + disable_notification=False, reply_to_message_id=None, allow_sending_without_reply=None, + reply_markup=None, timeout=None, explanation_entities=None): + method_url = r'sendPoll' + payload = { + 'chat_id': str(chat_id), + 'question': question, + 'options': json.dumps(await _convert_poll_options(options))} + + if is_anonymous is not None: + payload['is_anonymous'] = is_anonymous + if type is not None: + payload['type'] = type + if allows_multiple_answers is not None: + payload['allows_multiple_answers'] = allows_multiple_answers + if correct_option_id is not None: + payload['correct_option_id'] = correct_option_id + if explanation is not None: + payload['explanation'] = explanation + if explanation_parse_mode is not None: + payload['explanation_parse_mode'] = explanation_parse_mode + if open_period is not None: + payload['open_period'] = open_period + if close_date is not None: + if isinstance(close_date, datetime): + payload['close_date'] = close_date.timestamp() + else: + payload['close_date'] = close_date + if is_closed is not None: + payload['is_closed'] = is_closed + + if disable_notification: + payload['disable_notification'] = disable_notification + if reply_to_message_id is not None: + payload['reply_to_message_id'] = reply_to_message_id + if allow_sending_without_reply is not None: + payload['allow_sending_without_reply'] = allow_sending_without_reply + if reply_markup is not None: + payload['reply_markup'] = await _convert_markup(reply_markup) + if timeout: + payload['timeout'] = timeout + if explanation_entities: + payload['explanation_entities'] = json.dumps( + types.MessageEntity.to_list_of_dicts(explanation_entities)) + return await _process_request(token, method_url, params=payload) + +async def _convert_list_json_serializable(results): + ret = '' + for r in results: + if isinstance(r, types.JsonSerializable): + ret = ret + r.to_json() + ',' + if len(ret) > 0: + ret = ret[:-1] + return '[' + ret + ']' + + + +async def _convert_entites(entites): + if entites is None: + return None + elif len(entites) == 0: + return [] + elif isinstance(entites[0], types.JsonSerializable): + return [entity.to_json() for entity in entites] + else: + return entites + + +async def _convert_poll_options(poll_options): + if poll_options is None: + return None + elif len(poll_options) == 0: + return [] + elif isinstance(poll_options[0], str): + # Compatibility mode with previous bug when only list of string was accepted as poll_options + return poll_options + elif isinstance(poll_options[0], types.PollOption): + return [option.text for option in poll_options] + else: + return poll_options + + +async def convert_input_media(media): + if isinstance(media, types.InputMedia): + return media.convert_input_media() + return None, None + + +async def convert_input_media_array(array): + media = [] + files = {} + for input_media in array: + if isinstance(input_media, types.InputMedia): + media_dict = input_media.to_dict() + if media_dict['media'].startswith('attach://'): + key = media_dict['media'].replace('attach://', '') + files[key] = input_media.media + media.append(media_dict) + return json.dumps(media), files + + +async def _no_encode(func): + def wrapper(key, val): + if key == 'filename': + return u'{0}={1}'.format(key, val) + else: + return func(key, val) + + return wrapper + +async def stop_poll(token, chat_id, message_id, reply_markup=None): + method_url = r'stopPoll' + payload = {'chat_id': str(chat_id), 'message_id': message_id} + if reply_markup: + payload['reply_markup'] = await _convert_markup(reply_markup) + return await _process_request(token, method_url, params=payload) + +# exceptions +class ApiException(Exception): + """ + This class represents a base Exception thrown when a call to the Telegram API fails. + In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively + contain the name of the failed function and the returned result that made the function to be considered as + failed. + """ + + def __init__(self, msg, function_name, result): + super(ApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg)) + self.function_name = function_name + self.result = result + +class ApiHTTPException(ApiException): + """ + This class represents an Exception thrown when a call to the + Telegram API server returns HTTP code that is not 200. + """ + def __init__(self, function_name, result): + super(ApiHTTPException, self).__init__( + "The server returned HTTP {0} {1}. Response body:\n[{2}]" \ + .format(result.status_code, result.reason, result), + function_name, + result) + +class ApiInvalidJSONException(ApiException): + """ + This class represents an Exception thrown when a call to the + Telegram API server returns invalid json. + """ + def __init__(self, function_name, result): + super(ApiInvalidJSONException, self).__init__( + "The server returned an invalid JSON response. Response body:\n[{0}]" \ + .format(result), + function_name, + result) + +class ApiTelegramException(ApiException): + """ + This class represents an Exception thrown when a Telegram API returns error code. + """ + def __init__(self, function_name, result, result_json): + super(ApiTelegramException, self).__init__( + "Error code: {0}. Description: {1}" \ + .format(result_json['error_code'], result_json['description']), + function_name, + result) + self.result_json = result_json + self.error_code = result_json['error_code'] \ No newline at end of file From 53f9232f369e9f6ffa8866b3886cd9d5a6fb4bca Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 20 Nov 2021 15:54:43 +0500 Subject: [PATCH 317/350] Update requirements.txt --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 3a014e7..8e06e27 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ pytest==3.0.2 requests==2.20.0 wheel==0.24.0 +aiohttp>=3.8.0,<3.9.0 \ No newline at end of file From 1e4477c148e1a86f9ddee51bf6be822f87f8df50 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 20 Nov 2021 16:01:38 +0500 Subject: [PATCH 318/350] Logging fix --- telebot/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 65906f2..68c2e48 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -3488,8 +3488,8 @@ class AsyncTeleBot: continue except Exception as e: - print('Cause exception while getting updates.') - logger.critical(str(e)) + logger.error('Cause exception while getting updates.') + logger.error(str(e)) await asyncio.sleep(3) continue @@ -3512,7 +3512,7 @@ class AsyncTeleBot: await self._loop_create_task(message_handler['function'](message)) break except Exception as e: - print(str(e)) + logger.error(str(e)) # update handling async def process_new_updates(self, updates): From 714ae7d67f26dcc223d3fc7d9ddce0f5c5c743d1 Mon Sep 17 00:00:00 2001 From: abdullaev Date: Tue, 23 Nov 2021 18:01:51 +0500 Subject: [PATCH 319/350] CallbackData class added --- examples/CallbackData_example.py | 86 ++++++++++++++++++++++++++ telebot/callback_data.py | 100 +++++++++++++++++++++++++++++++ 2 files changed, 186 insertions(+) create mode 100644 examples/CallbackData_example.py create mode 100644 telebot/callback_data.py diff --git a/examples/CallbackData_example.py b/examples/CallbackData_example.py new file mode 100644 index 0000000..a0d70ea --- /dev/null +++ b/examples/CallbackData_example.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +""" +This Example will show you how to use CallbackData +""" + +from telebot.callback_data import CallbackData, CallbackDataFilter +from telebot import types, TeleBot +from telebot.custom_filters import AdvancedCustomFilter + +API_TOKEN = '1802978815:AAG6ju32eC-O3s8WRg57BRCT64VkJhQiHNk' +PRODUCTS = [ + {'id': '0', 'name': 'xiaomi mi 10', 'price': 400}, + {'id': '1', 'name': 'samsung s20', 'price': 800}, + {'id': '2', 'name': 'iphone 13', 'price': 1300} +] + +bot = TeleBot(API_TOKEN) +products_factory = CallbackData('product_id', prefix='products') + + +def products_keyboard(): + return types.InlineKeyboardMarkup( + keyboard=[ + [ + types.InlineKeyboardButton( + text=product['name'], + callback_data=products_factory.new(product_id=product["id"]) + ) + ] + for product in PRODUCTS + ] + ) + + +def back_keyboard(): + return types.InlineKeyboardMarkup( + keyboard=[ + [ + types.InlineKeyboardButton( + text='⬅', + callback_data='back' + ) + ] + ] + ) + + +class ProductsCallbackFilter(AdvancedCustomFilter): + key = 'config' + + def check(self, call: types.CallbackQuery, config: CallbackDataFilter): + return config.check(query=call) + + +@bot.message_handler(commands=['products']) +def products_command_handler(message: types.Message): + bot.send_message(message.chat.id, 'Products:', reply_markup=products_keyboard()) + + +# Only product with field - product_id = 2 +@bot.callback_query_handler(func=None, config=products_factory.filter(product_id='2')) +def product_one_callback(call: types.CallbackQuery): + bot.answer_callback_query(callback_query_id=call.id, text='Not available :(', show_alert=True) + + +# Any other products +@bot.callback_query_handler(func=None, config=products_factory.filter()) +def products_callback(call: types.CallbackQuery): + callback_data: dict = products_factory.parse(callback_data=call.data) + product_id = int(callback_data['product_id']) + product = PRODUCTS[product_id] + + text = f"Product name: {product['name']}\n" \ + f"Product price: {product['price']}" + bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, + text=text, reply_markup=back_keyboard()) + + +@bot.callback_query_handler(func=lambda c: c.data == 'back') +def back_callback(call: types.CallbackQuery): + bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, + text='Products:', reply_markup=products_keyboard()) + + +bot.add_custom_filter(ProductsCallbackFilter()) +bot.infinity_polling() diff --git a/telebot/callback_data.py b/telebot/callback_data.py new file mode 100644 index 0000000..2897c40 --- /dev/null +++ b/telebot/callback_data.py @@ -0,0 +1,100 @@ +import typing + + +class CallbackDataFilter: + + def __init__(self, factory, config: typing.Dict[str, str]): + self.config = config + self.factory = factory + + def check(self, query): + try: + data = self.factory.parse(query.data) + except ValueError: + return False + + for key, value in self.config.items(): + if isinstance(value, (list, tuple, set, frozenset)): + if data.get(key) not in value: + return False + elif data.get(key) != value: + return False + return True + + +class CallbackData: + """ + Callback data factory + """ + + def __init__(self, *parts, prefix: str, sep=':'): + if not isinstance(prefix, str): + raise TypeError(f'Prefix must be instance of str not {type(prefix).__name__}') + if not prefix: + raise ValueError("Prefix can't be empty") + if sep in prefix: + raise ValueError(f"Separator {sep!r} can't be used in prefix") + + self.prefix = prefix + self.sep = sep + + self._part_names = parts + + def new(self, *args, **kwargs) -> str: + """ + Generate callback data + """ + args = list(args) + + data = [self.prefix] + + for part in self._part_names: + value = kwargs.pop(part, None) + if value is None: + if args: + value = args.pop(0) + else: + raise ValueError(f'Value for {part!r} was not passed!') + + if value is not None and not isinstance(value, str): + value = str(value) + + if self.sep in value: + raise ValueError(f"Symbol {self.sep!r} is defined as the separator and can't be used in parts' values") + + data.append(value) + + if args or kwargs: + raise TypeError('Too many arguments were passed!') + + callback_data = self.sep.join(data) + + if len(callback_data.encode()) > 64: + raise ValueError('Resulted callback data is too long!') + + return callback_data + + def parse(self, callback_data: str) -> typing.Dict[str, str]: + """ + Parse data from the callback data + """ + + prefix, *parts = callback_data.split(self.sep) + if prefix != self.prefix: + raise ValueError("Passed callback data can't be parsed with that prefix.") + elif len(parts) != len(self._part_names): + raise ValueError('Invalid parts count!') + + result = {'@': prefix} + result.update(zip(self._part_names, parts)) + return result + + def filter(self, **config) -> CallbackDataFilter: + """ + Generate filter + """ + + for key in config.keys(): + if key not in self._part_names: + raise ValueError(f'Invalid field name {key!r}') + return CallbackDataFilter(self, config) From 9c8ea29fc677f878b670da865b15bdc6e1e093aa Mon Sep 17 00:00:00 2001 From: abdullaev Date: Tue, 23 Nov 2021 18:15:52 +0500 Subject: [PATCH 320/350] token removed :) --- examples/CallbackData_example.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/CallbackData_example.py b/examples/CallbackData_example.py index a0d70ea..5f4c0eb 100644 --- a/examples/CallbackData_example.py +++ b/examples/CallbackData_example.py @@ -7,7 +7,7 @@ from telebot.callback_data import CallbackData, CallbackDataFilter from telebot import types, TeleBot from telebot.custom_filters import AdvancedCustomFilter -API_TOKEN = '1802978815:AAG6ju32eC-O3s8WRg57BRCT64VkJhQiHNk' +API_TOKEN = '' PRODUCTS = [ {'id': '0', 'name': 'xiaomi mi 10', 'price': 400}, {'id': '1', 'name': 'samsung s20', 'price': 800}, From 8b6eba82039d5aa603bbce8911ca96a74217c3b8 Mon Sep 17 00:00:00 2001 From: abdullaev Date: Wed, 24 Nov 2021 20:26:58 +0500 Subject: [PATCH 321/350] Docstrings added --- telebot/callback_data.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/telebot/callback_data.py b/telebot/callback_data.py index 2897c40..ecbe81e 100644 --- a/telebot/callback_data.py +++ b/telebot/callback_data.py @@ -8,6 +8,12 @@ class CallbackDataFilter: self.factory = factory def check(self, query): + """ + Checks if query.data appropriates to specified config + :param query: telebot.types.CallbackQuery + :return: bool + """ + try: data = self.factory.parse(query.data) except ValueError: @@ -25,6 +31,7 @@ class CallbackDataFilter: class CallbackData: """ Callback data factory + This class will help you to work with CallbackQuery """ def __init__(self, *parts, prefix: str, sep=':'): @@ -43,6 +50,9 @@ class CallbackData: def new(self, *args, **kwargs) -> str: """ Generate callback data + :param args: positional parameters of CallbackData instance parts + :param kwargs: named parameters + :return: str """ args = list(args) @@ -77,6 +87,8 @@ class CallbackData: def parse(self, callback_data: str) -> typing.Dict[str, str]: """ Parse data from the callback data + :param callback_data: string, use to telebot.types.CallbackQuery to parse it from string to a dict + :return: dict parsed from callback data """ prefix, *parts = callback_data.split(self.sep) @@ -92,6 +104,9 @@ class CallbackData: def filter(self, **config) -> CallbackDataFilter: """ Generate filter + + :param config: specified named parameters will be checked with CallbackQury.data + :return: CallbackDataFilter class """ for key in config.keys(): From 6770011dd77ab5e64255bd842034e1de180e02bb Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 27 Nov 2021 19:04:03 +0500 Subject: [PATCH 322/350] Middleware support --- telebot/__init__.py | 258 ++++++++++++---------------- telebot/asyncio_handler_backends.py | 156 ++--------------- telebot/asyncio_helper.py | 31 +--- 3 files changed, 138 insertions(+), 307 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 68c2e48..89689eb 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -13,6 +13,9 @@ from typing import Any, Callable, List, Optional, Union import telebot.util import telebot.types + +from inspect import signature + logger = logging.getLogger('TeleBot') formatter = logging.Formatter( @@ -69,6 +72,30 @@ class ExceptionHandler: return False +class SkipHandler: + """ + Class for skipping handlers. + Just return instance of this class + in middleware to skip handler. + Update will go to post_process, + but will skip execution of handler. + """ + + def __init__(self) -> None: + pass + +class CancelUpdate: + """ + Class for canceling updates. + Just return instance of this class + in middleware to skip update. + Update will skip handler and execution + of post_process in middlewares. + """ + + def __init__(self) -> None: + pass + class TeleBot: """ This is TeleBot Class Methods: @@ -3351,33 +3378,16 @@ class AsyncTeleBot: self.current_states = asyncio_handler_backends.StateMemory() - if asyncio_helper.ENABLE_MIDDLEWARE: - self.typed_middleware_handlers = { - 'message': [], - 'edited_message': [], - 'channel_post': [], - 'edited_channel_post': [], - 'inline_query': [], - 'chosen_inline_result': [], - 'callback_query': [], - 'shipping_query': [], - 'pre_checkout_query': [], - 'poll': [], - 'poll_answer': [], - 'my_chat_member': [], - 'chat_member': [], - 'chat_join_request': [] - } - self.default_middleware_handlers = [] + self.middlewares = [] async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, - timeout: Optional[int]=None, allowed_updates: Optional[List]=None) -> types.Update: - json_updates = await asyncio_helper.get_updates(self.token, offset, limit, timeout, allowed_updates) + timeout: Optional[int]=None, allowed_updates: Optional[List]=None, request_timeout: Optional[int]=None) -> 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, - long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None, + request_timeout: int=20, allowed_updates: Optional[List[str]]=None, none_stop: Optional[bool]=None): """ This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly. @@ -3389,7 +3399,7 @@ class AsyncTeleBot: :param non_stop: Do not stop polling when an ApiException occurs. :param timeout: Request connection timeout :param skip_pending: skip old updates - :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param request_timeout: Timeout in seconds for a request. :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. @@ -3406,9 +3416,9 @@ class AsyncTeleBot: if skip_pending: await self.skip_updates() - await self._process_polling(non_stop, interval, timeout, long_polling_timeout, allowed_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, long_polling_timeout: int=20, logger_level=logging.ERROR, + async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, request_timeout: int=20, logger_level=logging.ERROR, allowed_updates: Optional[List[str]]=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. @@ -3432,7 +3442,7 @@ class AsyncTeleBot: self._polling = True while self._polling: try: - await self._process_polling(non_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout, + await self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout, allowed_updates=allowed_updates, *args, **kwargs) except Exception as e: if logger_level and logger_level >= logging.ERROR: @@ -3447,13 +3457,13 @@ class AsyncTeleBot: logger.error("Break infinity polling") async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20, - long_polling_timeout: int=20, allowed_updates: Optional[List[str]]=None): + request_timeout: int=20, allowed_updates: Optional[List[str]]=None): """ Function to process polling. :param non_stop: Do not stop polling when an ApiException occurs. :param interval: Delay between two update retrivals :param timeout: Request connection timeout - :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param request_timeout: Timeout in seconds for long polling (see API docs) :param allowed_updates: A list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See util.update_types for a complete list of available update types. @@ -3471,49 +3481,74 @@ class AsyncTeleBot: while self._polling: try: - updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout) - - if updates: - logger.debug(f"Received {len(updates)} updates.") - - await self.process_new_updates(updates) - if interval: await asyncio.sleep(interval) - except KeyboardInterrupt: - logger.info("KeyboardInterrupt received.") - break + updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout, request_timeout=request_timeout) except asyncio.CancelledError: - break + return + except asyncio_helper.ApiTelegramException as e: - logger.info(str(e)) + logger.error(str(e)) continue except Exception as e: logger.error('Cause exception while getting updates.') - logger.error(str(e)) - await asyncio.sleep(3) - continue + if non_stop: + logger.error(str(e)) + await asyncio.sleep(3) + continue + else: + raise e + if updates: + self.offset = updates[-1].update_id + 1 + self._loop_create_task(self.process_new_updates(updates)) # Seperate task for processing updates + if interval: await asyncio.sleep(interval) finally: self._polling = False logger.warning('Polling is stopped.') - async def _loop_create_task(self, coro): + def _loop_create_task(self, coro): return asyncio.create_task(coro) - async def _process_updates(self, handlers, messages): + async def _process_updates(self, handlers, messages, update_type): + """ + Process updates. + :param handlers: + :param messages: + :return: + """ for message in messages: - for message_handler in handlers: - process_update = await self._test_message_handler(message_handler, message) - if not process_update: - continue - elif process_update: - try: - await self._loop_create_task(message_handler['function'](message)) - break - except Exception as e: - logger.error(str(e)) + middleware = await self.process_middlewares(message, update_type) + self._loop_create_task(self._run_middlewares_and_handlers(handlers, message, middleware)) + + async def _run_middlewares_and_handlers(self, handlers, message, middleware): + handler_error = None + data = {} + for message_handler in handlers: + process_update = await self._test_message_handler(message_handler, message) + if not process_update: + continue + elif process_update: + if middleware: + middleware_result = await middleware.pre_process(message, data) + if isinstance(middleware_result, SkipHandler): + await middleware.post_process(message, data, handler_error) + break + if isinstance(middleware_result, CancelUpdate): + return + try: + if "data" in signature(message_handler['function']).parameters: + await message_handler['function'](message, data) + else: + await message_handler['function'](message) + break + except Exception as e: + handler_error = e + logger.info(str(e)) + + if middleware: + await middleware.post_process(message, data, handler_error) # update handling async def process_new_updates(self, updates): upd_count = len(updates) @@ -3535,21 +3570,8 @@ class AsyncTeleBot: new_chat_members = None chat_join_request = None for update in updates: - if asyncio_helper.ENABLE_MIDDLEWARE: - try: - self.process_middlewares(update) - except Exception as e: - logger.error(str(e)) - if not self.suppress_middleware_excepions: - raise - else: - if update.update_id > self.offset: self.offset = update.update_id - continue logger.debug('Processing updates: {0}'.format(update)) - if update.update_id: - self.offset = update.update_id + 1 if update.message: - logger.info('Processing message') if new_messages is None: new_messages = [] new_messages.append(update.message) if update.edited_message: @@ -3620,69 +3642,55 @@ class AsyncTeleBot: await self.process_new_chat_member(new_chat_members) if chat_join_request: await self.process_chat_join_request(chat_join_request) - async def process_new_messages(self, new_messages): await self.__notify_update(new_messages) - await self._process_updates(self.message_handlers, new_messages) + await self._process_updates(self.message_handlers, new_messages, 'message') async def process_new_edited_messages(self, edited_message): - await self._process_updates(self.edited_message_handlers, edited_message) + await self._process_updates(self.edited_message_handlers, edited_message, 'edited_message') async def process_new_channel_posts(self, channel_post): - await self._process_updates(self.channel_post_handlers, channel_post) + await self._process_updates(self.channel_post_handlers, channel_post , 'channel_post') async def process_new_edited_channel_posts(self, edited_channel_post): - await self._process_updates(self.edited_channel_post_handlers, edited_channel_post) + 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): - await self._process_updates(self.inline_handlers, new_inline_querys) + await self._process_updates(self.inline_handlers, new_inline_querys, 'inline_query') async def process_new_chosen_inline_query(self, new_chosen_inline_querys): - await self._process_updates(self.chosen_inline_handlers, new_chosen_inline_querys) + 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): - await self._process_updates(self.callback_query_handlers, new_callback_querys) + await self._process_updates(self.callback_query_handlers, new_callback_querys, 'callback_query') async def process_new_shipping_query(self, new_shipping_querys): - await self._process_updates(self.shipping_query_handlers, new_shipping_querys) + await self._process_updates(self.shipping_query_handlers, new_shipping_querys, 'shipping_query') async def process_new_pre_checkout_query(self, pre_checkout_querys): - await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys) + await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys, 'pre_checkout_query') async def process_new_poll(self, polls): - await self._process_updates(self.poll_handlers, polls) + await self._process_updates(self.poll_handlers, polls, 'poll') async def process_new_poll_answer(self, poll_answers): - await self._process_updates(self.poll_answer_handlers, poll_answers) + await self._process_updates(self.poll_answer_handlers, poll_answers, 'poll_answer') async def process_new_my_chat_member(self, my_chat_members): - await self._process_updates(self.my_chat_member_handlers, my_chat_members) + await self._process_updates(self.my_chat_member_handlers, my_chat_members, 'my_chat_member') async def process_new_chat_member(self, chat_members): - await self._process_updates(self.chat_member_handlers, chat_members) + await self._process_updates(self.chat_member_handlers, chat_members, 'chat_member') async def process_chat_join_request(self, chat_join_request): - await self._process_updates(self.chat_join_request_handlers, chat_join_request) - - async def process_middlewares(self, update): - for update_type, middlewares in self.typed_middleware_handlers.items(): - if getattr(update, update_type) is not None: - for typed_middleware_handler in middlewares: - try: - typed_middleware_handler(self, getattr(update, update_type)) - except Exception as e: - e.args = e.args + (f'Typed middleware handler "{typed_middleware_handler.__qualname__}"',) - raise - - if len(self.default_middleware_handlers) > 0: - for default_middleware_handler in self.default_middleware_handlers: - try: - default_middleware_handler(self, update) - except Exception as e: - e.args = e.args + (f'Default middleware handler "{default_middleware_handler.__qualname__}"',) - raise + await self._process_updates(self.chat_join_request_handlers, chat_join_request, 'chat_join_request') + async def process_middlewares(self, update, update_type): + for middleware in self.middlewares: + if update_type in middleware.update_types: + return middleware + return None async def __notify_update(self, new_messages): if len(self.update_listener) == 0: @@ -3759,56 +3767,16 @@ class AsyncTeleBot: elif isinstance(filter_check, asyncio_filters.AdvancedCustomFilter): return await filter_check.check(message, filter_value) else: - logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter!") + logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") return False - def middleware_handler(self, update_types=None): + def setup_middleware(self, middleware): """ - Middleware handler decorator. - - This decorator can be used to decorate functions that must be handled as middlewares before entering any other - message handlers - But, be careful and check type of the update inside the handler if more than one update_type is given - - Example: - - bot = TeleBot('TOKEN') - - # Print post message text before entering to any post_channel handlers - @bot.middleware_handler(update_types=['channel_post', 'edited_channel_post']) - def print_channel_post_text(bot_instance, channel_post): - print(channel_post.text) - - # Print update id before entering to any handlers - @bot.middleware_handler() - def print_channel_post_text(bot_instance, update): - print(update.update_id) - - :param update_types: Optional list of update types that can be passed into the middleware handler. - - """ - - def decorator(handler): - self.add_middleware_handler(handler, update_types) - return handler - - return decorator - - def add_middleware_handler(self, handler, update_types=None): - """ - Add middleware handler - :param handler: - :param update_types: + Setup middleware + :param middleware: :return: """ - if not asyncio_helper.ENABLE_MIDDLEWARE: - raise RuntimeError("Middleware is not enabled. Use asyncio_helper.ENABLE_MIDDLEWARE.") - - if update_types: - for update_type in update_types: - self.typed_middleware_handlers[update_type].append(handler) - else: - self.default_middleware_handlers.append(handler) + self.middlewares.append(middleware) def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): """ diff --git a/telebot/asyncio_handler_backends.py b/telebot/asyncio_handler_backends.py index 001f869..b46c988 100644 --- a/telebot/asyncio_handler_backends.py +++ b/telebot/asyncio_handler_backends.py @@ -1,146 +1,6 @@ import os import pickle -import threading -from telebot import apihelper - - -class HandlerBackend(object): - """ - Class for saving (next step|reply) handlers - """ - def __init__(self, handlers=None): - if handlers is None: - handlers = {} - self.handlers = handlers - - async def register_handler(self, handler_group_id, handler): - raise NotImplementedError() - - async def clear_handlers(self, handler_group_id): - raise NotImplementedError() - - async def get_handlers(self, handler_group_id): - raise NotImplementedError() - - -class MemoryHandlerBackend(HandlerBackend): - async def register_handler(self, handler_group_id, handler): - if handler_group_id in self.handlers: - self.handlers[handler_group_id].append(handler) - else: - self.handlers[handler_group_id] = [handler] - - async def clear_handlers(self, handler_group_id): - self.handlers.pop(handler_group_id, None) - - async def get_handlers(self, handler_group_id): - return self.handlers.pop(handler_group_id, None) - - async def load_handlers(self, filename, del_file_after_loading): - raise NotImplementedError() - - -class FileHandlerBackend(HandlerBackend): - def __init__(self, handlers=None, filename='./.handler-saves/handlers.save', delay=120): - super(FileHandlerBackend, self).__init__(handlers) - self.filename = filename - self.delay = delay - self.timer = threading.Timer(delay, self.save_handlers) - - async def register_handler(self, handler_group_id, handler): - if handler_group_id in self.handlers: - self.handlers[handler_group_id].append(handler) - else: - self.handlers[handler_group_id] = [handler] - await self.start_save_timer() - - async def clear_handlers(self, handler_group_id): - self.handlers.pop(handler_group_id, None) - await self.start_save_timer() - - async def get_handlers(self, handler_group_id): - handlers = self.handlers.pop(handler_group_id, None) - await self.start_save_timer() - return handlers - - async def start_save_timer(self): - if not self.timer.is_alive(): - if self.delay <= 0: - self.save_handlers() - else: - self.timer = threading.Timer(self.delay, self.save_handlers) - self.timer.start() - - async def save_handlers(self): - await self.dump_handlers(self.handlers, self.filename) - - async def load_handlers(self, filename=None, del_file_after_loading=True): - if not filename: - filename = self.filename - tmp = await self.return_load_handlers(filename, del_file_after_loading=del_file_after_loading) - if tmp is not None: - self.handlers.update(tmp) - - @staticmethod - async def dump_handlers(handlers, filename, file_mode="wb"): - dirs = filename.rsplit('/', maxsplit=1)[0] - os.makedirs(dirs, exist_ok=True) - - with open(filename + ".tmp", file_mode) as file: - if (apihelper.CUSTOM_SERIALIZER is None): - pickle.dump(handlers, file) - else: - apihelper.CUSTOM_SERIALIZER.dump(handlers, file) - - if os.path.isfile(filename): - os.remove(filename) - - os.rename(filename + ".tmp", filename) - - @staticmethod - async def return_load_handlers(filename, del_file_after_loading=True): - if os.path.isfile(filename) and os.path.getsize(filename) > 0: - with open(filename, "rb") as file: - if (apihelper.CUSTOM_SERIALIZER is None): - handlers = pickle.load(file) - else: - handlers = apihelper.CUSTOM_SERIALIZER.load(file) - - if del_file_after_loading: - os.remove(filename) - - return handlers - - -class RedisHandlerBackend(HandlerBackend): - def __init__(self, handlers=None, host='localhost', port=6379, db=0, prefix='telebot', password=None): - super(RedisHandlerBackend, self).__init__(handlers) - from redis import Redis - self.prefix = prefix - self.redis = Redis(host, port, db, password) - - async def _key(self, handle_group_id): - return ':'.join((self.prefix, str(handle_group_id))) - - async def register_handler(self, handler_group_id, handler): - handlers = [] - value = self.redis.get(self._key(handler_group_id)) - if value: - handlers = pickle.loads(value) - handlers.append(handler) - self.redis.set(self._key(handler_group_id), pickle.dumps(handlers)) - - async def clear_handlers(self, handler_group_id): - self.redis.delete(self._key(handler_group_id)) - - async def get_handlers(self, handler_group_id): - handlers = None - value = self.redis.get(self._key(handler_group_id)) - if value: - handlers = pickle.loads(value) - self.clear_handlers(handler_group_id) - return handlers class StateMemory: @@ -341,3 +201,19 @@ class StateFileContext: await self.obj._save_data(old_data) return + + +class BaseMiddleware: + """ + Base class for middleware. + + Your middlewares should be inherited from this class. + """ + def __init__(self): + pass + + async def pre_process(self, message, data): + raise NotImplementedError + async def post_process(self, message, data, exception): + raise NotImplementedError + diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py index 7bb649e..3d1189d 100644 --- a/telebot/asyncio_helper.py +++ b/telebot/asyncio_helper.py @@ -1,28 +1,19 @@ -import asyncio +import asyncio # for future uses from time import time import aiohttp from telebot import types import json -import logging try: import ujson as json except ImportError: import json -import requests -from requests.exceptions import HTTPError, ConnectionError, Timeout - -try: - # noinspection PyUnresolvedReferences - from requests.packages.urllib3 import fields - format_header_param = fields.format_header_param -except ImportError: - format_header_param = None - API_URL = 'https://api.telegram.org/bot{0}/{1}' from datetime import datetime + +import telebot from telebot import util class SessionBase: @@ -44,19 +35,16 @@ READ_TIMEOUT = 30 LONG_POLLING_TIMEOUT = 10 # Should be positive, short polling should be used for testing purposes only (https://core.telegram.org/bots/api#getupdates) +logger = telebot.logger RETRY_ON_ERROR = False RETRY_TIMEOUT = 2 MAX_RETRIES = 15 -CUSTOM_SERIALIZER = None -CUSTOM_REQUEST_SENDER = None - -ENABLE_MIDDLEWARE = False - -async def _process_request(token, url, method='get', params=None, files=None): +async def _process_request(token, url, method='get', params=None, files=None, request_timeout=None): async with await session_manager._get_new_session() as session: - async with session.get(API_URL.format(token, url), params=params, data=files) as response: + async with session.get(API_URL.format(token, url), params=params, data=files, timeout=request_timeout) as response: + logger.debug("Request: method={0} url={1} params={2} files={3} request_timeout={4}".format(method, url, params, files, request_timeout).replace(token, token.split(':')[0] + ":{TOKEN}")) json_result = await _check_result(url, response) if json_result: return json_result['result'] @@ -155,7 +143,7 @@ async def get_webhook_info(token, timeout=None): async def get_updates(token, offset=None, limit=None, - timeout=None, allowed_updates=None, long_polling_timeout=None): + timeout=None, allowed_updates=None, request_timeout=None): method_name = 'getUpdates' params = {} if offset: @@ -166,8 +154,7 @@ async def get_updates(token, offset=None, limit=None, params['timeout'] = timeout elif allowed_updates: params['allowed_updates'] = allowed_updates - params['long_polling_timeout'] = long_polling_timeout if long_polling_timeout else LONG_POLLING_TIMEOUT - return await _process_request(token, method_name, params=params) + return await _process_request(token, method_name, params=params, request_timeout=request_timeout) async def _check_result(method_name, result): """ From f666c15a1fc5ed3bc98015e60256e486c478d2ec Mon Sep 17 00:00:00 2001 From: Carlos Morales Aguilera Date: Sat, 27 Nov 2021 16:32:58 +0100 Subject: [PATCH 323/350] Add GrandQuiz Bot by Carlosma7 --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 37d56c7..49166c7 100644 --- a/README.md +++ b/README.md @@ -796,7 +796,6 @@ Get help. Discuss. Chat. * [Vlun Finder Bot](https://github.com/resinprotein2333/Vlun-Finder-bot) by [Resinprotein2333](https://github.com/resinprotein2333). This bot can help you to find The information of CVE vulnerabilities. * [ETHGasFeeTrackerBot](https://t.me/ETHGasFeeTrackerBot) ([Source](https://github.com/DevAdvik/ETHGasFeeTrackerBot]) by *DevAdvik* - Get Live Ethereum Gas Fees in GWEI * [Google Sheet Bot](https://github.com/JoachimStanislaus/Tele_Sheet_bot) by [JoachimStanislaus](https://github.com/JoachimStanislaus). This bot can help you to track your expenses by uploading your bot entries to your google sheet. - - +* [GrandQuiz Bot](https://github.com/Carlosma7/TFM-GrandQuiz) by [Carlosma7](https://github.com/Carlosma7). This bot is a trivia game that allows you to play with people from different ages. This project addresses the use of a system through chatbots to carry out a social and intergenerational game as an alternative to traditional game development. **Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.** From a9b422783f05b71d09319ee94d019c1b8252a9bc Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 27 Nov 2021 23:41:39 +0500 Subject: [PATCH 324/350] Middlewares, new file, and examples --- .../asynchronous_telebot/chat_join_request.py | 11 + .../chat_member_example.py | 33 + .../custom_filters/admin_filter_example.py | 13 + .../custom_filters/general_custom_filters.py | 44 + .../custom_filters/id_filter_example.py | 19 + .../custom_filters/is_filter_example.py | 22 + .../custom_filters/text_filter_example.py | 21 + .../asynchronous_telebot/custom_states.py | 75 + examples/asynchronous_telebot/echo_bot.py | 27 + .../asynchronous_telebot/register_handler.py | 19 + .../skip_updates_example.py | 13 + telebot/__init__.py | 2823 +--------------- telebot/async_telebot.py | 2869 +++++++++++++++++ telebot/asyncio_filters.py | 10 +- telebot/asyncio_handler_backends.py | 10 +- 15 files changed, 3178 insertions(+), 2831 deletions(-) create mode 100644 examples/asynchronous_telebot/chat_join_request.py create mode 100644 examples/asynchronous_telebot/chat_member_example.py create mode 100644 examples/asynchronous_telebot/custom_filters/admin_filter_example.py create mode 100644 examples/asynchronous_telebot/custom_filters/general_custom_filters.py create mode 100644 examples/asynchronous_telebot/custom_filters/id_filter_example.py create mode 100644 examples/asynchronous_telebot/custom_filters/is_filter_example.py create mode 100644 examples/asynchronous_telebot/custom_filters/text_filter_example.py create mode 100644 examples/asynchronous_telebot/custom_states.py create mode 100644 examples/asynchronous_telebot/echo_bot.py create mode 100644 examples/asynchronous_telebot/register_handler.py create mode 100644 examples/asynchronous_telebot/skip_updates_example.py create mode 100644 telebot/async_telebot.py diff --git a/examples/asynchronous_telebot/chat_join_request.py b/examples/asynchronous_telebot/chat_join_request.py new file mode 100644 index 0000000..6b2bfb7 --- /dev/null +++ b/examples/asynchronous_telebot/chat_join_request.py @@ -0,0 +1,11 @@ +from telebot.async_telebot import AsyncTeleBot +import asyncio +import telebot +bot = AsyncTeleBot('TOKEN') + +@bot.chat_join_request_handler() +async def make_some(message: telebot.types.ChatJoinRequest): + await bot.send_message(message.chat.id, 'I accepted a new user!') + await bot.approve_chat_join_request(message.chat.id, message.from_user.id) + +asyncio.run(bot.polling(skip_pending=True)) \ No newline at end of file diff --git a/examples/asynchronous_telebot/chat_member_example.py b/examples/asynchronous_telebot/chat_member_example.py new file mode 100644 index 0000000..7806cfd --- /dev/null +++ b/examples/asynchronous_telebot/chat_member_example.py @@ -0,0 +1,33 @@ +from telebot import types,util +from telebot.async_telebot import AsyncTeleBot +import asyncio +bot = AsyncTeleBot('TOKEN') + +#chat_member_handler. When status changes, telegram gives update. check status from old_chat_member and new_chat_member. +@bot.chat_member_handler() +async def chat_m(message: types.ChatMemberUpdated): + old = message.old_chat_member + new = message.new_chat_member + if new.status == "member": + await bot.send_message(message.chat.id,"Hello {name}!".format(name=new.user.first_name)) # Welcome message + +#if bot is added to group, this handler will work +@bot.my_chat_member_handler() +async def my_chat_m(message: types.ChatMemberUpdated): + old = message.old_chat_member + new = message.new_chat_member + if new.status == "member": + await bot.send_message(message.chat.id,"Somebody added me to group") # Welcome message, if bot was added to group + await bot.leave_chat(message.chat.id) + +#content_Type_service is: +#'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', +#'proximity_alert_triggered', 'voice_chat_scheduled', 'voice_chat_started', 'voice_chat_ended', +#'voice_chat_participants_invited', 'message_auto_delete_timer_changed' +# this handler deletes service messages + +@bot.message_handler(content_types=util.content_type_service) +async def delall(message: types.Message): + await bot.delete_message(message.chat.id,message.message_id) +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/custom_filters/admin_filter_example.py b/examples/asynchronous_telebot/custom_filters/admin_filter_example.py new file mode 100644 index 0000000..3aee738 --- /dev/null +++ b/examples/asynchronous_telebot/custom_filters/admin_filter_example.py @@ -0,0 +1,13 @@ +import asyncio +from telebot.async_telebot import AsyncTeleBot +from telebot import asyncio_filters +bot = AsyncTeleBot('TOKEN') + +# Handler +@bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) +async def answer_for_admin(message): + await bot.send_message(message.chat.id,"hello my admin") + +# Register filter +bot.add_custom_filter(asyncio_filters.IsAdminFilter(bot)) +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/custom_filters/general_custom_filters.py b/examples/asynchronous_telebot/custom_filters/general_custom_filters.py new file mode 100644 index 0000000..dfeeb88 --- /dev/null +++ b/examples/asynchronous_telebot/custom_filters/general_custom_filters.py @@ -0,0 +1,44 @@ +from telebot.async_telebot import AsyncTeleBot +import telebot +bot = AsyncTeleBot('TOKEN') + + +# AdvancedCustomFilter is for list, string filter values +class MainFilter(telebot.asyncio_filters.AdvancedCustomFilter): + key='text' + @staticmethod + async def check(message, text): + return message.text in text + +# SimpleCustomFilter is for boolean values, such as is_admin=True +class IsAdmin(telebot.asyncio_filters.SimpleCustomFilter): + key='is_admin' + @staticmethod + async def check(message: telebot.types.Message): + result = await bot.get_chat_member(message.chat.id,message.from_user.id) + return result.status in ['administrator','creator'] + + +@bot.message_handler(is_admin=True, commands=['admin']) # Check if user is admin +async def admin_rep(message): + await bot.send_message(message.chat.id, "Hi admin") + +@bot.message_handler(is_admin=False, commands=['admin']) # If user is not admin +async def not_admin(message): + await bot.send_message(message.chat.id, "You are not admin") + +@bot.message_handler(text=['hi']) # Response to hi message +async def welcome_hi(message): + await bot.send_message(message.chat.id, 'You said hi') + +@bot.message_handler(text=['bye']) # Response to bye message +async def bye_user(message): + await bot.send_message(message.chat.id, 'You said bye') + + +# Do not forget to register filters +bot.add_custom_filter(MainFilter()) +bot.add_custom_filter(IsAdmin()) + +import asyncio +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/custom_filters/id_filter_example.py b/examples/asynchronous_telebot/custom_filters/id_filter_example.py new file mode 100644 index 0000000..5878bc7 --- /dev/null +++ b/examples/asynchronous_telebot/custom_filters/id_filter_example.py @@ -0,0 +1,19 @@ +from telebot.async_telebot import AsyncTeleBot +import telebot +import asyncio +bot = AsyncTeleBot('TOKEN') + + +# Chat id can be private or supergroups. +@bot.message_handler(chat_id=[12345678], commands=['admin']) # chat_id checks id corresponds to your list or not. +async def admin_rep(message): + await bot.send_message(message.chat.id, "You are allowed to use this command.") + +@bot.message_handler(commands=['admin']) +async def not_admin(message): + await bot.send_message(message.chat.id, "You are not allowed to use this command") + +# Do not forget to register +bot.add_custom_filter(telebot.asyncio_filters.ChatFilter()) + +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/custom_filters/is_filter_example.py b/examples/asynchronous_telebot/custom_filters/is_filter_example.py new file mode 100644 index 0000000..20857be --- /dev/null +++ b/examples/asynchronous_telebot/custom_filters/is_filter_example.py @@ -0,0 +1,22 @@ +from telebot.async_telebot import AsyncTeleBot +import telebot +import asyncio +bot = AsyncTeleBot('TOKEN') + + + +# Check if message is a reply +@bot.message_handler(is_reply=True) +async def start_filter(message): + await bot.send_message(message.chat.id, "Looks like you replied to my message.") + +# Check if message was forwarded +@bot.message_handler(is_forwarded=True) +async def text_filter(message): + await bot.send_message(message.chat.id, "I do not accept forwarded messages!") + +# Do not forget to register filters +bot.add_custom_filter(telebot.asyncio_filters.IsReplyFilter()) +bot.add_custom_filter(telebot.asyncio_filters.ForwardFilter()) + +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/custom_filters/text_filter_example.py b/examples/asynchronous_telebot/custom_filters/text_filter_example.py new file mode 100644 index 0000000..57513ea --- /dev/null +++ b/examples/asynchronous_telebot/custom_filters/text_filter_example.py @@ -0,0 +1,21 @@ +from telebot.async_telebot import AsyncTeleBot +import telebot +import asyncio +bot = AsyncTeleBot('TOKEN') + + +# Check if message starts with @admin tag +@bot.message_handler(text_startswith="@admin") +async def start_filter(message): + await bot.send_message(message.chat.id, "Looks like you are calling admin, wait...") + +# Check if text is hi or hello +@bot.message_handler(text=['hi','hello']) +async def text_filter(message): + await bot.send_message(message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name)) + +# Do not forget to register filters +bot.add_custom_filter(telebot.asyncio_filters.TextMatchFilter()) +bot.add_custom_filter(telebot.asyncio_filters.TextStartsFilter()) + +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/custom_states.py b/examples/asynchronous_telebot/custom_states.py new file mode 100644 index 0000000..2f0257a --- /dev/null +++ b/examples/asynchronous_telebot/custom_states.py @@ -0,0 +1,75 @@ +import telebot +from telebot import asyncio_filters +from telebot.async_telebot import AsyncTeleBot +import asyncio +bot = AsyncTeleBot('TOKEN') + + + +class MyStates: + name = 1 + surname = 2 + age = 3 + + + +@bot.message_handler(commands=['start']) +async def start_ex(message): + """ + Start command. Here we are starting state + """ + await bot.set_state(message.from_user.id, MyStates.name) + await bot.send_message(message.chat.id, 'Hi, write me a name') + + + +@bot.message_handler(state="*", commands='cancel') +async def any_state(message): + """ + Cancel state + """ + await bot.send_message(message.chat.id, "Your state was cancelled.") + await bot.delete_state(message.from_user.id) + +@bot.message_handler(state=MyStates.name) +async def name_get(message): + """ + State 1. Will process when user's state is 1. + """ + await bot.send_message(message.chat.id, f'Now write me a surname') + await bot.set_state(message.from_user.id, MyStates.surname) + async with bot.retrieve_data(message.from_user.id) as data: + data['name'] = message.text + + +@bot.message_handler(state=MyStates.surname) +async def ask_age(message): + """ + State 2. Will process when user's state is 2. + """ + await bot.send_message(message.chat.id, "What is your age?") + await bot.set_state(message.from_user.id, MyStates.age) + async with bot.retrieve_data(message.from_user.id) as data: + data['surname'] = message.text + +# result +@bot.message_handler(state=MyStates.age, is_digit=True) +async def ready_for_answer(message): + async with bot.retrieve_data(message.from_user.id) as data: + await bot.send_message(message.chat.id, "Ready, take a look:\nName: {name}\nSurname: {surname}\nAge: {age}".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html") + await bot.delete_state(message.from_user.id) + +#incorrect number +@bot.message_handler(state=MyStates.age, is_digit=False) +async def age_incorrect(message): + await bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number') + +# register filters + +bot.add_custom_filter(asyncio_filters.StateFilter(bot)) +bot.add_custom_filter(asyncio_filters.IsDigitFilter()) + +# set saving states into file. +bot.enable_saving_states() # you can delete this if you do not need to save states + +asyncio.run(bot.polling()) \ No newline at end of file diff --git a/examples/asynchronous_telebot/echo_bot.py b/examples/asynchronous_telebot/echo_bot.py new file mode 100644 index 0000000..24cbe3f --- /dev/null +++ b/examples/asynchronous_telebot/echo_bot.py @@ -0,0 +1,27 @@ +#!/usr/bin/python + +# This is a simple echo bot using the decorator mechanism. +# It echoes any incoming text messages. + +from telebot.async_telebot import AsyncTeleBot +import asyncio +bot = AsyncTeleBot('TOKEN') + + + +# Handle '/start' and '/help' +@bot.message_handler(commands=['help', 'start']) +async def send_welcome(message): + await bot.reply_to(message, """\ +Hi there, I am EchoBot. +I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\ +""") + + +# Handle all other messages with content_type 'text' (content_types defaults to ['text']) +@bot.message_handler(func=lambda message: True) +async def echo_message(message): + await bot.reply_to(message, message.text) + + +asyncio.run(bot.polling()) diff --git a/examples/asynchronous_telebot/register_handler.py b/examples/asynchronous_telebot/register_handler.py new file mode 100644 index 0000000..04dabd4 --- /dev/null +++ b/examples/asynchronous_telebot/register_handler.py @@ -0,0 +1,19 @@ +from telebot.async_telebot import AsyncTeleBot +import asyncio +bot = AsyncTeleBot('TOKEN') + +async def start_executor(message): + await bot.send_message(message.chat.id, 'Hello!') + +bot.register_message_handler(start_executor, commands=['start']) # Start command executor + +# See also +# bot.register_callback_query_handler(*args, **kwargs) +# bot.register_channel_post_handler(*args, **kwargs) +# bot.register_chat_member_handler(*args, **kwargs) +# bot.register_inline_handler(*args, **kwargs) +# bot.register_my_chat_member_handler(*args, **kwargs) +# bot.register_edited_message_handler(*args, **kwargs) +# And other functions.. + +asyncio.run(bot.polling(skip_pending=True)) diff --git a/examples/asynchronous_telebot/skip_updates_example.py b/examples/asynchronous_telebot/skip_updates_example.py new file mode 100644 index 0000000..dc2c157 --- /dev/null +++ b/examples/asynchronous_telebot/skip_updates_example.py @@ -0,0 +1,13 @@ +from telebot.async_telebot import AsyncTeleBot +import asyncio +bot = AsyncTeleBot('TOKEN') + +@bot.message_handler(commands=['start', 'help']) +async def send_welcome(message): + await bot.reply_to(message, "Howdy, how are you doing?") + +@bot.message_handler(func=lambda message: True) +async def echo_all(message): + await bot.reply_to(message, message.text) + +asyncio.run(bot.polling(skip_pending=True))# Skip pending skips old updates diff --git a/telebot/__init__.py b/telebot/__init__.py index 89689eb..7983a26 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -14,7 +14,6 @@ import telebot.util import telebot.types -from inspect import signature logger = logging.getLogger('TeleBot') @@ -28,12 +27,9 @@ logger.addHandler(console_output_handler) logger.setLevel(logging.ERROR) -from telebot import apihelper, util, types, asyncio_helper +from telebot import apihelper, util, types from telebot.handler_backends import MemoryHandlerBackend, FileHandlerBackend, StateMemory, StateFile from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter -import asyncio -from telebot import asyncio_handler_backends -from telebot import asyncio_filters @@ -3340,2823 +3336,6 @@ class TeleBot: break -class AsyncTeleBot: - - def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, - exception_handler=None,suppress_middleware_excepions=False) -> None: # TODO: ADD TYPEHINTS - self.token = token - logger.info('creating some objects..') - self.loop = asyncio.get_event_loop() - self.offset = offset - self.token = token - self.parse_mode = parse_mode - self.update_listener = [] - self.suppress_middleware_excepions = suppress_middleware_excepions - - self.exc_info = None - - self.exception_handler = exception_handler - - self.message_handlers = [] - self.edited_message_handlers = [] - self.channel_post_handlers = [] - self.edited_channel_post_handlers = [] - self.inline_handlers = [] - self.chosen_inline_handlers = [] - self.callback_query_handlers = [] - self.shipping_query_handlers = [] - self.pre_checkout_query_handlers = [] - self.poll_handlers = [] - self.poll_answer_handlers = [] - self.my_chat_member_handlers = [] - self.chat_member_handlers = [] - self.chat_join_request_handlers = [] - self.custom_filters = {} - self.state_handlers = [] - - self.current_states = asyncio_handler_backends.StateMemory() - - - self.middlewares = [] - - - async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, - timeout: Optional[int]=None, allowed_updates: Optional[List]=None, request_timeout: Optional[int]=None) -> 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=20, allowed_updates: Optional[List[str]]=None, - none_stop: Optional[bool]=None): - """ - This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly. - - Warning: Do not call this function more than once! - - Always get updates. - :param interval: Delay between two update retrivals - :param non_stop: Do not stop polling when an ApiException occurs. - :param timeout: Request connection timeout - :param skip_pending: skip old updates - :param request_timeout: Timeout in seconds for a request. - :param allowed_updates: A list of the update types you want your bot to receive. - For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. - See util.update_types for a complete list of available update types. - Specify an empty list to receive all update types except chat_member (default). - If not specified, the previous setting will be used. - - Please note that this parameter doesn't affect updates created before the call to the get_updates, - so unwanted updates may be received for a short period of time. - :param none_stop: Deprecated, use non_stop. Old typo f***up compatibility - :return: - """ - if none_stop is not None: - non_stop = none_stop - - if skip_pending: - await self.skip_updates() - await self._process_polling(non_stop, interval, timeout, request_timeout, allowed_updates) - - async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, request_timeout: int=20, logger_level=logging.ERROR, - allowed_updates: Optional[List[str]]=None, *args, **kwargs): - """ - Wrap polling with infinite loop and exception handling to avoid bot stops polling. - - :param timeout: Request connection timeout - :param long_polling_timeout: Timeout in seconds for long polling (see API docs) - :param skip_pending: skip old updates - :param logger_level: Custom logging level for infinity_polling logging. - Use logger levels from logging as a value. None/NOTSET = no error logging - :param allowed_updates: A list of the update types you want your bot to receive. - For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. - See util.update_types for a complete list of available update types. - Specify an empty list to receive all update types except chat_member (default). - If not specified, the previous setting will be used. - - Please note that this parameter doesn't affect updates created before the call to the get_updates, - so unwanted updates may be received for a short period of time. - """ - if skip_pending: - await self.skip_updates() - self._polling = True - while self._polling: - try: - await self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout, - allowed_updates=allowed_updates, *args, **kwargs) - except Exception as e: - if logger_level and logger_level >= logging.ERROR: - logger.error("Infinity polling exception: %s", str(e)) - if logger_level and logger_level >= logging.DEBUG: - logger.error("Exception traceback:\n%s", traceback.format_exc()) - time.sleep(3) - continue - if logger_level and logger_level >= logging.INFO: - logger.error("Infinity polling: polling exited") - if logger_level and logger_level >= logging.INFO: - logger.error("Break infinity polling") - - async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20, - request_timeout: int=20, allowed_updates: Optional[List[str]]=None): - """ - Function to process polling. - :param non_stop: Do not stop polling when an ApiException occurs. - :param interval: Delay between two update retrivals - :param timeout: Request connection timeout - :param request_timeout: Timeout in seconds for long polling (see API docs) - :param allowed_updates: A list of the update types you want your bot to receive. - For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. - See util.update_types for a complete list of available update types. - Specify an empty list to receive all update types except chat_member (default). - If not specified, the previous setting will be used. - - Please note that this parameter doesn't affect updates created before the call to the get_updates, - so unwanted updates may be received for a short period of time. - :return: - - """ - self._polling = True - - try: - while self._polling: - try: - - updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout, request_timeout=request_timeout) - except asyncio.CancelledError: - return - - except asyncio_helper.ApiTelegramException as e: - logger.error(str(e)) - - continue - except Exception as e: - logger.error('Cause exception while getting updates.') - if non_stop: - logger.error(str(e)) - await asyncio.sleep(3) - continue - else: - raise e - if updates: - self.offset = updates[-1].update_id + 1 - self._loop_create_task(self.process_new_updates(updates)) # Seperate task for processing updates - if interval: await asyncio.sleep(interval) - - finally: - self._polling = False - logger.warning('Polling is stopped.') - - - def _loop_create_task(self, coro): - return asyncio.create_task(coro) - - async def _process_updates(self, handlers, messages, update_type): - """ - Process updates. - :param handlers: - :param messages: - :return: - """ - for message in messages: - middleware = await self.process_middlewares(message, update_type) - self._loop_create_task(self._run_middlewares_and_handlers(handlers, message, middleware)) - - - async def _run_middlewares_and_handlers(self, handlers, message, middleware): - handler_error = None - data = {} - for message_handler in handlers: - process_update = await self._test_message_handler(message_handler, message) - if not process_update: - continue - elif process_update: - if middleware: - middleware_result = await middleware.pre_process(message, data) - if isinstance(middleware_result, SkipHandler): - await middleware.post_process(message, data, handler_error) - break - if isinstance(middleware_result, CancelUpdate): - return - try: - if "data" in signature(message_handler['function']).parameters: - await message_handler['function'](message, data) - else: - await message_handler['function'](message) - break - except Exception as e: - handler_error = e - logger.info(str(e)) - - if middleware: - await middleware.post_process(message, data, handler_error) - # update handling - async def process_new_updates(self, updates): - upd_count = len(updates) - logger.info('Received {0} new updates'.format(upd_count)) - if upd_count == 0: return - - new_messages = None - new_edited_messages = None - new_channel_posts = None - new_edited_channel_posts = None - new_inline_queries = None - new_chosen_inline_results = None - new_callback_queries = None - new_shipping_queries = None - new_pre_checkout_queries = None - new_polls = None - new_poll_answers = None - new_my_chat_members = None - new_chat_members = None - chat_join_request = None - for update in updates: - logger.debug('Processing updates: {0}'.format(update)) - if update.message: - if new_messages is None: new_messages = [] - new_messages.append(update.message) - if update.edited_message: - if new_edited_messages is None: new_edited_messages = [] - new_edited_messages.append(update.edited_message) - if update.channel_post: - if new_channel_posts is None: new_channel_posts = [] - new_channel_posts.append(update.channel_post) - if update.edited_channel_post: - if new_edited_channel_posts is None: new_edited_channel_posts = [] - new_edited_channel_posts.append(update.edited_channel_post) - if update.inline_query: - if new_inline_queries is None: new_inline_queries = [] - new_inline_queries.append(update.inline_query) - if update.chosen_inline_result: - if new_chosen_inline_results is None: new_chosen_inline_results = [] - new_chosen_inline_results.append(update.chosen_inline_result) - if update.callback_query: - if new_callback_queries is None: new_callback_queries = [] - new_callback_queries.append(update.callback_query) - if update.shipping_query: - if new_shipping_queries is None: new_shipping_queries = [] - new_shipping_queries.append(update.shipping_query) - if update.pre_checkout_query: - if new_pre_checkout_queries is None: new_pre_checkout_queries = [] - new_pre_checkout_queries.append(update.pre_checkout_query) - if update.poll: - if new_polls is None: new_polls = [] - new_polls.append(update.poll) - if update.poll_answer: - if new_poll_answers is None: new_poll_answers = [] - new_poll_answers.append(update.poll_answer) - if update.my_chat_member: - if new_my_chat_members is None: new_my_chat_members = [] - new_my_chat_members.append(update.my_chat_member) - if update.chat_member: - if new_chat_members is None: new_chat_members = [] - new_chat_members.append(update.chat_member) - if update.chat_join_request: - if chat_join_request is None: chat_join_request = [] - chat_join_request.append(update.chat_join_request) - - if new_messages: - await self.process_new_messages(new_messages) - if new_edited_messages: - await self.process_new_edited_messages(new_edited_messages) - if new_channel_posts: - await self.process_new_channel_posts(new_channel_posts) - if new_edited_channel_posts: - await self.process_new_edited_channel_posts(new_edited_channel_posts) - if new_inline_queries: - await self.process_new_inline_query(new_inline_queries) - if new_chosen_inline_results: - await self.process_new_chosen_inline_query(new_chosen_inline_results) - if new_callback_queries: - await self.process_new_callback_query(new_callback_queries) - if new_shipping_queries: - await self.process_new_shipping_query(new_shipping_queries) - if new_pre_checkout_queries: - await self.process_new_pre_checkout_query(new_pre_checkout_queries) - if new_polls: - await self.process_new_poll(new_polls) - if new_poll_answers: - await self.process_new_poll_answer(new_poll_answers) - if new_my_chat_members: - await self.process_new_my_chat_member(new_my_chat_members) - if new_chat_members: - await self.process_new_chat_member(new_chat_members) - if chat_join_request: - await self.process_chat_join_request(chat_join_request) - - async def process_new_messages(self, new_messages): - await self.__notify_update(new_messages) - await self._process_updates(self.message_handlers, new_messages, 'message') - - async def process_new_edited_messages(self, edited_message): - await self._process_updates(self.edited_message_handlers, edited_message, 'edited_message') - - async def process_new_channel_posts(self, channel_post): - await self._process_updates(self.channel_post_handlers, channel_post , 'channel_post') - - async def process_new_edited_channel_posts(self, edited_channel_post): - await self._process_updates(self.edited_channel_post_handlers, edited_channel_post, 'edited_channel_post') - - async def process_new_inline_query(self, new_inline_querys): - await self._process_updates(self.inline_handlers, new_inline_querys, 'inline_query') - - async def process_new_chosen_inline_query(self, new_chosen_inline_querys): - 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): - await self._process_updates(self.callback_query_handlers, new_callback_querys, 'callback_query') - - async def process_new_shipping_query(self, new_shipping_querys): - await self._process_updates(self.shipping_query_handlers, new_shipping_querys, 'shipping_query') - - async def process_new_pre_checkout_query(self, pre_checkout_querys): - await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys, 'pre_checkout_query') - - async def process_new_poll(self, polls): - await self._process_updates(self.poll_handlers, polls, 'poll') - - async def process_new_poll_answer(self, poll_answers): - await self._process_updates(self.poll_answer_handlers, poll_answers, 'poll_answer') - - async def process_new_my_chat_member(self, my_chat_members): - await self._process_updates(self.my_chat_member_handlers, my_chat_members, 'my_chat_member') - - async def process_new_chat_member(self, chat_members): - await self._process_updates(self.chat_member_handlers, chat_members, 'chat_member') - - async def process_chat_join_request(self, chat_join_request): - await self._process_updates(self.chat_join_request_handlers, chat_join_request, 'chat_join_request') - - async def process_middlewares(self, update, update_type): - for middleware in self.middlewares: - if update_type in middleware.update_types: - return middleware - return None - - async def __notify_update(self, new_messages): - if len(self.update_listener) == 0: - return - for listener in self.update_listener: - self._loop_create_task(listener, new_messages) - - async def _test_message_handler(self, message_handler, message): - """ - Test message handler - :param message_handler: - :param message: - :return: - """ - for message_filter, filter_value in message_handler['filters'].items(): - if filter_value is None: - continue - - if not await self._test_filter(message_filter, filter_value, message): - return False - - return True - - def add_custom_filter(self, custom_filter): - """ - Create custom filter. - custom_filter: Class with check(message) method. - """ - self.custom_filters[custom_filter.key] = custom_filter - - async def _test_filter(self, message_filter, filter_value, message): - """ - Test filters - :param message_filter: Filter type passed in handler - :param filter_value: Filter value passed in handler - :param message: Message to test - :return: True if filter conforms - """ - # test_cases = { - # 'content_types': lambda msg: msg.content_type in filter_value, - # 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), - # 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, - # 'func': lambda msg: filter_value(msg) - # } - # return test_cases.get(message_filter, lambda msg: False)(message) - if message_filter == 'content_types': - return message.content_type in filter_value - elif message_filter == 'regexp': - return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) - elif message_filter == 'commands': - return message.content_type == 'text' and util.extract_command(message.text) in filter_value - elif message_filter == 'chat_types': - return message.chat.type in filter_value - elif message_filter == 'func': - return filter_value(message) - elif self.custom_filters and message_filter in self.custom_filters: - return await self._check_filter(message_filter,filter_value,message) - else: - return False - - async def _check_filter(self, message_filter, filter_value, message): - """ - Check up the filter - :param message_filter: - :param filter_value: - :param message: - :return: - """ - filter_check = self.custom_filters.get(message_filter) - if not filter_check: - return False - elif isinstance(filter_check, asyncio_filters.SimpleCustomFilter): - return filter_value == await filter_check.check(message) - elif isinstance(filter_check, asyncio_filters.AdvancedCustomFilter): - return await filter_check.check(message, filter_value) - else: - logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") - return False - - def setup_middleware(self, middleware): - """ - Setup middleware - :param middleware: - :return: - """ - self.middlewares.append(middleware) - - def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): - """ - Message handler decorator. - This decorator can be used to decorate functions that must handle certain types of messages. - All message handlers are tested in the order they were added. - - Example: - - 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?') - - # 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!') - - # Handle all sent documents of type 'text/plain'. - @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', - content_types=['document']) - async def command_handle_document(message): - bot.send_message(message.chat.id, 'Document received, sir!') - - # Handle all other messages. - @bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document', - 'text', 'location', 'contact', 'sticker']) - async def async default_command(message): - bot.send_message(message.chat.id, "This is the async default command handler.") - - :param commands: Optional list of strings (commands to handle). - :param regexp: Optional regular expression. - :param func: Optional lambda function. The lambda receives the message to test as the first parameter. - It must return True if the command should handle the message. - :param content_types: Supported message content types. Must be a list. async defaults to ['text']. - :param chat_types: list of chat types - """ - - if content_types is None: - content_types = ["text"] - - if isinstance(commands, str): - logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("message_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, - chat_types=chat_types, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_message_handler(handler_dict) - return handler - - return decorator - - def add_message_handler(self, handler_dict): - """ - Adds a message handler - :param handler_dict: - :return: - """ - self.message_handlers.append(handler_dict) - - def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): - """ - Registers message handler. - :param callback: function to be called - :param content_types: list of content_types - :param commands: list of commands - :param regexp: - :param func: - :param chat_types: True for private chat - :return: decorated function - """ - if isinstance(commands, str): - logger.warning("register_message_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("register_message_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - handler_dict = self._build_handler_dict(callback, - chat_types=chat_types, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_message_handler(handler_dict) - - def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): - """ - Edit message handler decorator - :param commands: - :param regexp: - :param func: - :param content_types: - :param chat_types: list of chat types - :param kwargs: - :return: - """ - - if content_types is None: - content_types = ["text"] - - if isinstance(commands, str): - logger.warning("edited_message_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, - chat_types=chat_types, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_edited_message_handler(handler_dict) - return handler - - return decorator - - def add_edited_message_handler(self, handler_dict): - """ - Adds the edit message handler - :param handler_dict: - :return: - """ - self.edited_message_handlers.append(handler_dict) - - def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): - """ - Registers edited message handler. - :param callback: function to be called - :param content_types: list of content_types - :param commands: list of commands - :param regexp: - :param func: - :param chat_types: True for private chat - :return: decorated function - """ - if isinstance(commands, str): - logger.warning("register_edited_message_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("register_edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - handler_dict = self._build_handler_dict(callback, - chat_types=chat_types, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_edited_message_handler(handler_dict) - - - def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): - """ - Channel post handler decorator - :param commands: - :param regexp: - :param func: - :param content_types: - :param kwargs: - :return: - """ - if content_types is None: - content_types = ["text"] - - if isinstance(commands, str): - logger.warning("channel_post_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_channel_post_handler(handler_dict) - return handler - - return decorator - - def add_channel_post_handler(self, handler_dict): - """ - Adds channel post handler - :param handler_dict: - :return: - """ - self.channel_post_handlers.append(handler_dict) - - def register_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): - """ - Registers channel post message handler. - :param callback: function to be called - :param content_types: list of content_types - :param commands: list of commands - :param regexp: - :param func: - :return: decorated function - """ - if isinstance(commands, str): - logger.warning("register_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("register_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - handler_dict = self._build_handler_dict(callback, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_channel_post_handler(handler_dict) - - def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): - """ - Edit channel post handler decorator - :param commands: - :param regexp: - :param func: - :param content_types: - :param kwargs: - :return: - """ - if content_types is None: - content_types = ["text"] - - if isinstance(commands, str): - logger.warning("edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_edited_channel_post_handler(handler_dict) - return handler - - return decorator - - def add_edited_channel_post_handler(self, handler_dict): - """ - Adds the edit channel post handler - :param handler_dict: - :return: - """ - self.edited_channel_post_handlers.append(handler_dict) - - def register_edited_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): - """ - Registers edited channel post message handler. - :param callback: function to be called - :param content_types: list of content_types - :param commands: list of commands - :param regexp: - :param func: - :return: decorated function - """ - if isinstance(commands, str): - logger.warning("register_edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") - commands = [commands] - - if isinstance(content_types, str): - logger.warning("register_edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") - content_types = [content_types] - - handler_dict = self._build_handler_dict(callback, - content_types=content_types, - commands=commands, - regexp=regexp, - func=func, - **kwargs) - self.add_edited_channel_post_handler(handler_dict) - - def inline_handler(self, func, **kwargs): - """ - Inline call handler decorator - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_inline_handler(handler_dict) - return handler - - return decorator - - def add_inline_handler(self, handler_dict): - """ - Adds inline call handler - :param handler_dict: - :return: - """ - self.inline_handlers.append(handler_dict) - - def register_inline_handler(self, callback, func, **kwargs): - """ - Registers inline handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_inline_handler(handler_dict) - - def chosen_inline_handler(self, func, **kwargs): - """ - Description: TBD - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_chosen_inline_handler(handler_dict) - return handler - - return decorator - - def add_chosen_inline_handler(self, handler_dict): - """ - Description: TBD - :param handler_dict: - :return: - """ - self.chosen_inline_handlers.append(handler_dict) - - def register_chosen_inline_handler(self, callback, func, **kwargs): - """ - Registers chosen inline handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_chosen_inline_handler(handler_dict) - - def callback_query_handler(self, func, **kwargs): - """ - Callback request handler decorator - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_callback_query_handler(handler_dict) - return handler - - return decorator - - def add_callback_query_handler(self, handler_dict): - """ - Adds a callback request handler - :param handler_dict: - :return: - """ - self.callback_query_handlers.append(handler_dict) - - def register_callback_query_handler(self, callback, func, **kwargs): - """ - Registers callback query handler.. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_callback_query_handler(handler_dict) - - def shipping_query_handler(self, func, **kwargs): - """ - Shipping request handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_shipping_query_handler(handler_dict) - return handler - - return decorator - - def add_shipping_query_handler(self, handler_dict): - """ - Adds a shipping request handler - :param handler_dict: - :return: - """ - self.shipping_query_handlers.append(handler_dict) - - def register_shipping_query_handler(self, callback, func, **kwargs): - """ - Registers shipping query handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_shipping_query_handler(handler_dict) - - def pre_checkout_query_handler(self, func, **kwargs): - """ - Pre-checkout request handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_pre_checkout_query_handler(handler_dict) - return handler - - return decorator - - def add_pre_checkout_query_handler(self, handler_dict): - """ - Adds a pre-checkout request handler - :param handler_dict: - :return: - """ - self.pre_checkout_query_handlers.append(handler_dict) - - def register_pre_checkout_query_handler(self, callback, func, **kwargs): - """ - Registers pre-checkout request handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_pre_checkout_query_handler(handler_dict) - - def poll_handler(self, func, **kwargs): - """ - Poll request handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_poll_handler(handler_dict) - return handler - - return decorator - - def add_poll_handler(self, handler_dict): - """ - Adds a poll request handler - :param handler_dict: - :return: - """ - self.poll_handlers.append(handler_dict) - - def register_poll_handler(self, callback, func, **kwargs): - """ - Registers poll handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_poll_handler(handler_dict) - - def poll_answer_handler(self, func=None, **kwargs): - """ - Poll_answer request handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_poll_answer_handler(handler_dict) - return handler - - return decorator - - def add_poll_answer_handler(self, handler_dict): - """ - Adds a poll_answer request handler - :param handler_dict: - :return: - """ - self.poll_answer_handlers.append(handler_dict) - - def register_poll_answer_handler(self, callback, func, **kwargs): - """ - Registers poll answer handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_poll_answer_handler(handler_dict) - - def my_chat_member_handler(self, func=None, **kwargs): - """ - my_chat_member handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_my_chat_member_handler(handler_dict) - return handler - - return decorator - - def add_my_chat_member_handler(self, handler_dict): - """ - Adds a my_chat_member handler - :param handler_dict: - :return: - """ - self.my_chat_member_handlers.append(handler_dict) - - def register_my_chat_member_handler(self, callback, func=None, **kwargs): - """ - Registers my chat member handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_my_chat_member_handler(handler_dict) - - def chat_member_handler(self, func=None, **kwargs): - """ - chat_member handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_chat_member_handler(handler_dict) - return handler - - return decorator - - def add_chat_member_handler(self, handler_dict): - """ - Adds a chat_member handler - :param handler_dict: - :return: - """ - self.chat_member_handlers.append(handler_dict) - - def register_chat_member_handler(self, callback, func=None, **kwargs): - """ - Registers chat member handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_chat_member_handler(handler_dict) - - def chat_join_request_handler(self, func=None, **kwargs): - """ - chat_join_request handler - :param func: - :param kwargs: - :return: - """ - - def decorator(handler): - handler_dict = self._build_handler_dict(handler, func=func, **kwargs) - self.add_chat_join_request_handler(handler_dict) - return handler - - return decorator - - def add_chat_join_request_handler(self, handler_dict): - """ - Adds a chat_join_request handler - :param handler_dict: - :return: - """ - self.chat_join_request_handlers.append(handler_dict) - - def register_chat_join_request_handler(self, callback, func=None, **kwargs): - """ - Registers chat join request handler. - :param callback: function to be called - :param func: - :return: decorated function - """ - handler_dict = self._build_handler_dict(callback, func=func, **kwargs) - self.add_chat_join_request_handler(handler_dict) - - @staticmethod - def _build_handler_dict(handler, **filters): - """ - Builds a dictionary for a handler - :param handler: - :param filters: - :return: - """ - return { - 'function': handler, - 'filters': {ftype: fvalue for ftype, fvalue in filters.items() if fvalue is not None} - # Remove None values, they are skipped in _test_filter anyway - #'filters': filters - } - - async def skip_updates(self): - await self.get_updates(-1) - return True - - # all methods begin here - - async def get_me(self) -> types.User: - """ - Returns basic information about the bot in form of a User object. - """ - result = await asyncio_helper.get_me(self.token) - return types.User.de_json(result) - - async def get_file(self, file_id: str) -> types.File: - """ - Use this method to get basic info about a file and prepare it for downloading. - For the moment, bots can download files of up to 20MB in size. - On success, a File object is returned. - It is guaranteed that the link will be valid for at least 1 hour. - When the link expires, a new one can be requested by calling get_file again. - """ - return types.File.de_json(await asyncio_helper.get_file(self.token, file_id)) - - async def get_file_url(self, file_id: str) -> str: - return await asyncio_helper.get_file_url(self.token, file_id) - - async def download_file(self, file_path: str) -> bytes: - return await asyncio_helper.download_file(self.token, file_path) - - async def log_out(self) -> bool: - """ - Use this method to log out from the cloud Bot API server before launching the bot locally. - You MUST log out the bot before running it locally, otherwise there is no guarantee - that the bot will receive updates. - After a successful call, you can immediately log in on a local server, - but will not be able to log in back to the cloud Bot API server for 10 minutes. - Returns True on success. - """ - return await asyncio_helper.log_out(self.token) - - async def close(self) -> bool: - """ - Use this method to close the bot instance before moving it from one local server to another. - You need to delete the webhook before calling this method to ensure that the bot isn't launched again - after server restart. - The method will return error 429 in the first 10 minutes after the bot is launched. - Returns True on success. - """ - return await asyncio_helper.close(self.token) - - async def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, - drop_pending_updates = None, timeout=None): - """ - Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an - update for the bot, we will send an HTTPS POST request to the specified url, - containing a JSON-serialized Update. - In case of an unsuccessful request, we will give up after a reasonable amount of attempts. - Returns True on success. - - :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration - :param certificate: Upload your public key certificate so that the root certificate in use can be checked. - See our self-signed guide for details. - :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook - for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, - and higher values to increase your bot's throughput. - :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. - For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates - of these types. See Update for a complete list of available update types. - Specify an empty list to receive all updates regardless of type (default). - If not specified, the previous setting will be used. - :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address - resolved through DNS - :param drop_pending_updates: Pass True to drop all pending updates - :param timeout: Integer. Request connection timeout - :return: - """ - return await asyncio_helper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, - drop_pending_updates, timeout) - - async def delete_webhook(self, drop_pending_updates=None, timeout=None): - """ - Use this method to remove webhook integration if you decide to switch back to getUpdates. - - :param drop_pending_updates: Pass True to drop all pending updates - :param timeout: Integer. Request connection timeout - :return: bool - """ - return await asyncio_helper.delete_webhook(self.token, drop_pending_updates, timeout) - - async def get_webhook_info(self, timeout=None): - """ - Use this method to get current webhook status. Requires no parameters. - If the bot is using getUpdates, will return an object with the url field empty. - - :param timeout: Integer. Request connection timeout - :return: On success, returns a WebhookInfo object. - """ - result = await asyncio_helper.get_webhook_info(self.token, timeout) - return types.WebhookInfo.de_json(result) - - async def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None, - limit: Optional[int]=None) -> types.UserProfilePhotos: - """ - Retrieves the user profile photos of the person with 'user_id' - See https://core.telegram.org/bots/api#getuserprofilephotos - :param user_id: - :param offset: - :param limit: - :return: API reply. - """ - result = await asyncio_helper.get_user_profile_photos(self.token, user_id, offset, limit) - return types.UserProfilePhotos.de_json(result) - - async def get_chat(self, chat_id: Union[int, str]) -> types.Chat: - """ - Use this method to get up to date information about the chat (current name of the user for one-on-one - conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. - :param chat_id: - :return: - """ - result = await asyncio_helper.get_chat(self.token, chat_id) - return types.Chat.de_json(result) - - async def leave_chat(self, chat_id: Union[int, str]) -> bool: - """ - Use this method for your bot to leave a group, supergroup or channel. Returns True on success. - :param chat_id: - :return: - """ - result = await asyncio_helper.leave_chat(self.token, chat_id) - return result - - async def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: - """ - Use this method to get a list of administrators in a chat. - On success, returns an Array of ChatMember objects that contains - information about all chat administrators except other bots. - :param chat_id: Unique identifier for the target chat or username - of the target supergroup or channel (in the format @channelusername) - :return: - """ - result = await asyncio_helper.get_chat_administrators(self.token, chat_id) - return [types.ChatMember.de_json(r) for r in result] - - async def get_chat_members_count(self, chat_id: Union[int, str]) -> int: - """ - This function is deprecated. Use `get_chat_member_count` instead - """ - logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.') - result = await asyncio_helper.get_chat_member_count(self.token, chat_id) - return result - - async def get_chat_member_count(self, chat_id: Union[int, str]) -> int: - """ - Use this method to get the number of members in a chat. Returns Int on success. - :param chat_id: - :return: - """ - result = await asyncio_helper.get_chat_member_count(self.token, chat_id) - return result - - async def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str) -> types.StickerSet: - """ - Use this method to set a new group sticker set for a supergroup. The bot must be an administrator - in the chat for this to work and must have the appropriate admin rights. - Use the field can_set_sticker_set optionally returned in getChat requests to check - if the bot can use this method. Returns True on success. - :param chat_id: Unique identifier for the target chat or username of the target supergroup - (in the format @supergroupusername) - :param sticker_set_name: Name of the sticker set to be set as the group sticker set - :return: - """ - result = await asyncio_helper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) - return result - - async def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool: - """ - Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat - for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set - optionally returned in getChat requests to check if the bot can use this method. Returns True on success. - :param chat_id: Unique identifier for the target chat or username of the target supergroup - (in the format @supergroupusername) - :return: - """ - result = await asyncio_helper.delete_chat_sticker_set(self.token, chat_id) - return result - - async def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: - """ - Use this method to get information about a member of a chat. Returns a ChatMember object on success. - :param chat_id: - :param user_id: - :return: - """ - result = await asyncio_helper.get_chat_member(self.token, chat_id, user_id) - return types.ChatMember.de_json(result) - - async def send_message( - self, chat_id: Union[int, str], text: str, - disable_web_page_preview: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send text messages. - - Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error. - If you must send more than 4000 characters, - use the `split_string` or `smart_split` function in util.py. - - :param chat_id: - :param text: - :param disable_web_page_preview: - :param reply_to_message_id: - :param reply_markup: - :param parse_mode: - :param disable_notification: Boolean, Optional. Sends the message silently. - :param timeout: - :param entities: - :param allow_sending_without_reply: - :return: API reply. - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_message( - self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, - reply_markup, parse_mode, disable_notification, timeout, - entities, allow_sending_without_reply)) - - async def forward_message( - self, chat_id: Union[int, str], from_chat_id: Union[int, str], - message_id: int, disable_notification: Optional[bool]=None, - timeout: Optional[int]=None) -> types.Message: - """ - Use this method to forward messages of any kind. - :param disable_notification: - :param chat_id: which chat to forward - :param from_chat_id: which chat message from - :param message_id: message id - :param timeout: - :return: API reply. - """ - return types.Message.de_json( - await asyncio_helper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) - - async def copy_message( - self, chat_id: Union[int, str], - from_chat_id: Union[int, str], - message_id: int, - caption: Optional[str]=None, - parse_mode: Optional[str]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None) -> int: - """ - Use this method to copy messages of any kind. - :param chat_id: which chat to forward - :param from_chat_id: which chat message from - :param message_id: message id - :param caption: - :param parse_mode: - :param caption_entities: - :param disable_notification: - :param reply_to_message_id: - :param allow_sending_without_reply: - :param reply_markup: - :param timeout: - :return: API reply. - """ - return types.MessageID.de_json( - await asyncio_helper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, - disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, - timeout)) - - async def delete_message(self, chat_id: Union[int, str], message_id: int, - timeout: Optional[int]=None) -> bool: - """ - Use this method to delete message. Returns True on success. - :param chat_id: in which chat to delete - :param message_id: which message to delete - :param timeout: - :return: API reply. - """ - return await asyncio_helper.delete_message(self.token, chat_id, message_id, timeout) - - async def send_dice( - self, chat_id: Union[int, str], - emoji: Optional[str]=None, disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send dices. - :param chat_id: - :param emoji: - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param timeout: - :param allow_sending_without_reply: - :return: Message - """ - return types.Message.de_json( - await asyncio_helper.send_dice( - self.token, chat_id, emoji, disable_notification, reply_to_message_id, - reply_markup, timeout, allow_sending_without_reply) - ) - - async def send_photo( - self, chat_id: Union[int, str], photo: Union[Any, str], - caption: Optional[str]=None, reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send photos. - :param chat_id: - :param photo: - :param caption: - :param parse_mode: - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param timeout: - :param caption_entities: - :param allow_sending_without_reply: - :return: API reply. - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_photo( - self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, caption_entities, - allow_sending_without_reply)) - - async def send_audio( - self, chat_id: Union[int, str], audio: Union[Any, str], - caption: Optional[str]=None, duration: Optional[int]=None, - performer: Optional[str]=None, title: Optional[str]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - thumb: Optional[Union[Any, str]]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send audio files, if you want Telegram clients to display them in the music player. - Your audio must be in the .mp3 format. - :param chat_id:Unique identifier for the message recipient - :param audio:Audio file to send. - :param caption: - :param duration:Duration of the audio in seconds - :param performer:Performer - :param title:Track name - :param reply_to_message_id:If the message is a reply, ID of the original message - :param reply_markup: - :param parse_mode - :param disable_notification: - :param timeout: - :param thumb: - :param caption_entities: - :param allow_sending_without_reply: - :return: Message - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_audio( - self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, - reply_markup, parse_mode, disable_notification, timeout, thumb, - caption_entities, allow_sending_without_reply)) - - async def send_voice( - self, chat_id: Union[int, str], voice: Union[Any, str], - caption: Optional[str]=None, duration: Optional[int]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send audio files, if you want Telegram clients to display the file - as a playable voice message. - :param chat_id:Unique identifier for the message recipient. - :param voice: - :param caption: - :param duration:Duration of sent audio in seconds - :param reply_to_message_id: - :param reply_markup: - :param parse_mode - :param disable_notification: - :param timeout: - :param caption_entities: - :param allow_sending_without_reply: - :return: Message - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_voice( - self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, - parse_mode, disable_notification, timeout, caption_entities, - allow_sending_without_reply)) - - async def send_document( - self, chat_id: Union[int, str], data: Union[Any, str], - reply_to_message_id: Optional[int]=None, - caption: Optional[str]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - thumb: Optional[Union[Any, str]]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None, - visible_file_name: Optional[str]=None, - disable_content_type_detection: Optional[bool]=None) -> types.Message: - """ - Use this method to send general files. - :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) - :param data: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data - :param reply_to_message_id: If the message is a reply, ID of the original message - :param caption: Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing - :param reply_markup: - :param parse_mode: Mode for parsing entities in the document caption - :param disable_notification: Sends the message silently. Users will receive a notification with no sound. - :param timeout: - :param thumb: InputFile or String : Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under - :param caption_entities: - :param allow_sending_without_reply: - :param visible_file_name: allows to async define file name that will be visible in the Telegram instead of original file name - :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data - :return: API reply. - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_data( - self.token, chat_id, data, 'document', - reply_to_message_id = reply_to_message_id, reply_markup = reply_markup, parse_mode = parse_mode, - disable_notification = disable_notification, timeout = timeout, caption = caption, thumb = thumb, - caption_entities = caption_entities, allow_sending_without_reply = allow_sending_without_reply, - disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name)) - - async def send_sticker( - self, chat_id: Union[int, str], data: Union[Any, str], - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send .webp stickers. - :param chat_id: - :param data: - :param reply_to_message_id: - :param reply_markup: - :param disable_notification: to disable the notification - :param timeout: timeout - :param allow_sending_without_reply: - :return: API reply. - """ - return types.Message.de_json( - await asyncio_helper.send_data( - self.token, chat_id, data, 'sticker', - reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, - disable_notification=disable_notification, timeout=timeout, - allow_sending_without_reply=allow_sending_without_reply)) - - async def send_video( - self, chat_id: Union[int, str], data: Union[Any, str], - duration: Optional[int]=None, - caption: Optional[str]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, - supports_streaming: Optional[bool]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - thumb: Optional[Union[Any, str]]=None, - width: Optional[int]=None, - height: Optional[int]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send video files, Telegram clients support mp4 videos. - :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id - :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend - a video that is already on the Telegram server - :param duration: Integer : Duration of sent video in seconds - :param caption: String : Video caption (may also be used when resending videos by file_id). - :param parse_mode: - :param supports_streaming: - :param reply_to_message_id: - :param reply_markup: - :param disable_notification: - :param timeout: - :param thumb: InputFile or String : Thumbnail of the file sent - :param width: - :param height: - :param caption_entities: - :param allow_sending_without_reply: - :return: - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_video( - self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, - parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height, - caption_entities, allow_sending_without_reply)) - - async def send_animation( - self, chat_id: Union[int, str], animation: Union[Any, str], - duration: Optional[int]=None, - caption: Optional[str]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - parse_mode: Optional[str]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - thumb: Optional[Union[Any, str]]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). - :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id - :param animation: InputFile or String : Animation to send. You can either pass a file_id as String to resend an - animation that is already on the Telegram server - :param duration: Integer : Duration of sent video in seconds - :param caption: String : Animation caption (may also be used when resending animation by file_id). - :param parse_mode: - :param reply_to_message_id: - :param reply_markup: - :param disable_notification: - :param timeout: - :param thumb: InputFile or String : Thumbnail of the file sent - :param caption_entities: - :param allow_sending_without_reply: - :return: - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - return types.Message.de_json( - await asyncio_helper.send_animation( - self.token, chat_id, animation, duration, caption, reply_to_message_id, - reply_markup, parse_mode, disable_notification, timeout, thumb, - caption_entities, allow_sending_without_reply)) - - async def send_video_note( - self, chat_id: Union[int, str], data: Union[Any, str], - duration: Optional[int]=None, - length: Optional[int]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - thumb: Optional[Union[Any, str]]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send - video messages. - :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id - :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend - a video that is already on the Telegram server - :param duration: Integer : Duration of sent video in seconds - :param length: Integer : Video width and height, Can't be None and should be in range of (0, 640) - :param reply_to_message_id: - :param reply_markup: - :param disable_notification: - :param timeout: - :param thumb: InputFile or String : Thumbnail of the file sent - :param allow_sending_without_reply: - :return: - """ - return types.Message.de_json( - await asyncio_helper.send_video_note( - self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, - disable_notification, timeout, thumb, allow_sending_without_reply)) - - async def send_media_group( - self, chat_id: Union[int, str], - media: List[Union[ - types.InputMediaAudio, types.InputMediaDocument, - types.InputMediaPhoto, types.InputMediaVideo]], - disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> List[types.Message]: - """ - send a group of photos or videos as an album. On success, an array of the sent Messages is returned. - :param chat_id: - :param media: - :param disable_notification: - :param reply_to_message_id: - :param timeout: - :param allow_sending_without_reply: - :return: - """ - result = await asyncio_helper.send_media_group( - self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, - allow_sending_without_reply) - return [types.Message.de_json(msg) for msg in result] - - async def send_location( - self, chat_id: Union[int, str], - latitude: float, longitude: float, - live_period: Optional[int]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - disable_notification: Optional[bool]=None, - timeout: Optional[int]=None, - horizontal_accuracy: Optional[float]=None, - heading: Optional[int]=None, - proximity_alert_radius: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - - - """ - Use this method to send point on the map. - :param chat_id: - :param latitude: - :param longitude: - :param live_period: - :param reply_to_message_id: - :param reply_markup: - :param disable_notification: - :param timeout: - :param horizontal_accuracy: - :param heading: - :param proximity_alert_radius: - :param allow_sending_without_reply: - :return: API reply. - """ - return types.Message.de_json( - await asyncio_helper.send_location( - self.token, chat_id, latitude, longitude, live_period, - reply_to_message_id, reply_markup, disable_notification, timeout, - horizontal_accuracy, heading, proximity_alert_radius, - allow_sending_without_reply)) - - async def edit_message_live_location( - self, latitude: float, longitude: float, - chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None, - horizontal_accuracy: Optional[float]=None, - heading: Optional[int]=None, - proximity_alert_radius: Optional[int]=None) -> types.Message: - """ - Use this method to edit live location - :param latitude: - :param longitude: - :param chat_id: - :param message_id: - :param reply_markup: - :param timeout: - :param inline_message_id: - :param horizontal_accuracy: - :param heading: - :param proximity_alert_radius: - :return: - """ - return types.Message.de_json( - await asyncio_helper.edit_message_live_location( - self.token, latitude, longitude, chat_id, message_id, - inline_message_id, reply_markup, timeout, - horizontal_accuracy, heading, proximity_alert_radius)) - - async def stop_message_live_location( - self, chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None) -> types.Message: - """ - Use this method to stop updating a live location message sent by the bot - or via the bot (for inline bots) before live_period expires - :param chat_id: - :param message_id: - :param inline_message_id: - :param reply_markup: - :param timeout: - :return: - """ - return types.Message.de_json( - await asyncio_helper.stop_message_live_location( - self.token, chat_id, message_id, inline_message_id, reply_markup, timeout)) - - async def send_venue( - self, chat_id: Union[int, str], - latitude: float, longitude: float, - title: str, address: str, - foursquare_id: Optional[str]=None, - foursquare_type: Optional[str]=None, - disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None, - google_place_id: Optional[str]=None, - google_place_type: Optional[str]=None) -> types.Message: - """ - Use this method to send information about a venue. - :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel - :param latitude: Float : Latitude of the venue - :param longitude: Float : Longitude of the venue - :param title: String : Name of the venue - :param address: String : Address of the venue - :param foursquare_id: String : Foursquare identifier of the venue - :param foursquare_type: Foursquare type of the venue, if known. (For example, “arts_entertainment/async default”, - “arts_entertainment/aquarium” or “food/icecream”.) - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param timeout: - :param allow_sending_without_reply: - :param google_place_id: - :param google_place_type: - :return: - """ - return types.Message.de_json( - await asyncio_helper.send_venue( - self.token, chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, - disable_notification, reply_to_message_id, reply_markup, timeout, - allow_sending_without_reply, google_place_id, google_place_type) - ) - - async def send_contact( - self, chat_id: Union[int, str], phone_number: str, - first_name: str, last_name: Optional[str]=None, - vcard: Optional[str]=None, - disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - return types.Message.de_json( - await asyncio_helper.send_contact( - self.token, chat_id, phone_number, first_name, last_name, vcard, - disable_notification, reply_to_message_id, reply_markup, timeout, - allow_sending_without_reply) - ) - - async def send_chat_action( - self, chat_id: Union[int, str], action: str, timeout: Optional[int]=None) -> bool: - """ - Use this method when you need to tell the user that something is happening on the bot's side. - The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear - its typing status). - :param chat_id: - :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', - 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', - 'upload_video_note'. - :param timeout: - :return: API reply. :type: boolean - """ - return await asyncio_helper.send_chat_action(self.token, chat_id, action, timeout) - - async def kick_chat_member( - self, chat_id: Union[int, str], user_id: int, - until_date:Optional[Union[int, datetime]]=None, - revoke_messages: Optional[bool]=None) -> bool: - """ - This function is deprecated. Use `ban_chat_member` instead - """ - logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') - return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) - - async def ban_chat_member( - self, chat_id: Union[int, str], user_id: int, - until_date:Optional[Union[int, datetime]]=None, - revoke_messages: Optional[bool]=None) -> bool: - """ - Use this method to ban a user in a group, a supergroup or a channel. - In the case of supergroups and channels, the user will not be able to return to the chat on their - own using invite links, etc., unless unbanned first. - Returns True on success. - :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup - :param user_id: Int : Unique identifier of the target user - :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or - less than 30 seconds from the current time they are considered to be banned forever - :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. - If False, the user will be able to see messages in the group that were sent before the user was removed. - Always True for supergroups and channels. - :return: boolean - """ - return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) - - async def unban_chat_member( - self, chat_id: Union[int, str], user_id: int, - only_if_banned: Optional[bool]=False) -> bool: - """ - Use this method to unban a previously kicked user in a supergroup or channel. - The user will not return to the group or channel automatically, but will be able to join via link, etc. - The bot must be an administrator for this to work. By async default, this method guarantees that after the call - the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat - they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. - - :param chat_id: Unique identifier for the target group or username of the target supergroup or channel - (in the format @username) - :param user_id: Unique identifier of the target user - :param only_if_banned: Do nothing if the user is not banned - :return: True on success - """ - return await asyncio_helper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) - - async def restrict_chat_member( - self, chat_id: Union[int, str], user_id: int, - until_date: Optional[Union[int, datetime]]=None, - can_send_messages: Optional[bool]=None, - can_send_media_messages: Optional[bool]=None, - can_send_polls: Optional[bool]=None, - can_send_other_messages: Optional[bool]=None, - can_add_web_page_previews: Optional[bool]=None, - can_change_info: Optional[bool]=None, - can_invite_users: Optional[bool]=None, - can_pin_messages: Optional[bool]=None) -> bool: - """ - Use this method to restrict a user in a supergroup. - The bot must be an administrator in the supergroup for this to work and must have - the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. - - :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup - or channel (in the format @channelusername) - :param user_id: Int : Unique identifier of the target user - :param until_date: Date when restrictions will be lifted for the user, unix time. - If user is restricted for more than 366 days or less than 30 seconds from the current time, - they are considered to be restricted forever - :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues - :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes - and voice notes, implies can_send_messages - :param can_send_polls: Pass True, if the user is allowed to send polls, implies can_send_messages - :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and - use inline bots, implies can_send_media_messages - :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, - implies can_send_media_messages - :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. - Ignored in public supergroups - :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, - implies can_invite_users - :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups - :return: True on success - """ - return await asyncio_helper.restrict_chat_member( - self.token, chat_id, user_id, until_date, - can_send_messages, can_send_media_messages, - can_send_polls, can_send_other_messages, - can_add_web_page_previews, can_change_info, - can_invite_users, can_pin_messages) - - async def promote_chat_member( - self, chat_id: Union[int, str], user_id: int, - can_change_info: Optional[bool]=None, - can_post_messages: Optional[bool]=None, - can_edit_messages: Optional[bool]=None, - can_delete_messages: Optional[bool]=None, - can_invite_users: Optional[bool]=None, - can_restrict_members: Optional[bool]=None, - can_pin_messages: Optional[bool]=None, - can_promote_members: Optional[bool]=None, - is_anonymous: Optional[bool]=None, - can_manage_chat: Optional[bool]=None, - can_manage_voice_chats: Optional[bool]=None) -> bool: - """ - Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator - in the chat for this to work and must have the appropriate admin rights. - Pass False for all boolean parameters to demote a user. - - :param chat_id: Unique identifier for the target chat or username of the target channel ( - in the format @channelusername) - :param user_id: Int : Unique identifier of the target user - :param can_change_info: Bool: Pass True, if the administrator can change chat title, photo and other settings - :param can_post_messages: Bool : Pass True, if the administrator can create channel posts, channels only - :param can_edit_messages: Bool : Pass True, if the administrator can edit messages of other users, channels only - :param can_delete_messages: Bool : Pass True, if the administrator can delete messages of other users - :param can_invite_users: Bool : Pass True, if the administrator can invite new users to the chat - :param can_restrict_members: Bool: Pass True, if the administrator can restrict, ban or unban chat members - :param can_pin_messages: Bool: Pass True, if the administrator can pin messages, supergroups only - :param can_promote_members: Bool: Pass True, if the administrator can add new administrators with a subset - of his own privileges or demote administrators that he has promoted, directly or indirectly - (promoted by administrators that were appointed by him) - :param is_anonymous: Bool: Pass True, if the administrator's presence in the chat is hidden - :param can_manage_chat: Bool: Pass True, if the administrator can access the chat event log, chat statistics, - message statistics in channels, see channel members, - see anonymous administrators in supergroups and ignore slow mode. - Implied by any other administrator privilege - :param can_manage_voice_chats: Bool: Pass True, if the administrator can manage voice chats - For now, bots can use this privilege only for passing to other administrators. - :return: True on success. - """ - return await asyncio_helper.promote_chat_member( - self.token, chat_id, user_id, can_change_info, can_post_messages, - can_edit_messages, can_delete_messages, can_invite_users, - can_restrict_members, can_pin_messages, can_promote_members, - is_anonymous, can_manage_chat, can_manage_voice_chats) - - async def set_chat_administrator_custom_title( - self, chat_id: Union[int, str], user_id: int, custom_title: str) -> bool: - """ - Use this method to set a custom title for an administrator - in a supergroup promoted by the bot. - - :param chat_id: Unique identifier for the target chat or username of the target supergroup - (in the format @supergroupusername) - :param user_id: Unique identifier of the target user - :param custom_title: New custom title for the administrator; - 0-16 characters, emoji are not allowed - :return: True on success. - """ - return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) - - async def set_chat_permissions( - self, chat_id: Union[int, str], permissions: types.ChatPermissions) -> bool: - """ - Use this method to set async default chat permissions for all members. - The bot must be an administrator in the group or a supergroup for this to work - and must have the can_restrict_members admin rights. - - :param chat_id: Unique identifier for the target chat or username of the target supergroup - (in the format @supergroupusername) - :param permissions: New async default chat permissions - :return: True on success - """ - return await asyncio_helper.set_chat_permissions(self.token, chat_id, permissions) - - async def create_chat_invite_link( - self, chat_id: Union[int, str], - name: Optional[str]=None, - expire_date: Optional[Union[int, datetime]]=None, - member_limit: Optional[int]=None, - creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: - """ - Use this method to create an additional invite link for a chat. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - - :param chat_id: Id: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param name: Invite link name; 0-32 characters - :param expire_date: Point in time (Unix timestamp) when the link will expire - :param member_limit: Maximum number of users that can be members of the chat simultaneously - :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified - :return: - """ - return types.ChatInviteLink.de_json( - await asyncio_helper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request) - ) - - async def edit_chat_invite_link( - self, chat_id: Union[int, str], - invite_link: Optional[str] = None, - name: Optional[str]=None, - expire_date: Optional[Union[int, datetime]]=None, - member_limit: Optional[int]=None, - creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: - """ - Use this method to edit a non-primary invite link created by the bot. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - - :param chat_id: Id: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param name: Invite link name; 0-32 characters - :param invite_link: The invite link to edit - :param expire_date: Point in time (Unix timestamp) when the link will expire - :param member_limit: Maximum number of users that can be members of the chat simultaneously - :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified - :return: - """ - return types.ChatInviteLink.de_json( - await asyncio_helper.edit_chat_invite_link(self.token, chat_id, name, invite_link, expire_date, member_limit, creates_join_request) - ) - - async def revoke_chat_invite_link( - self, chat_id: Union[int, str], invite_link: str) -> types.ChatInviteLink: - """ - Use this method to revoke an invite link created by the bot. - Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator - in the chat for this to work and must have the appropriate admin rights. - - :param chat_id: Id: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param invite_link: The invite link to revoke - :return: - """ - return types.ChatInviteLink.de_json( - await asyncio_helper.revoke_chat_invite_link(self.token, chat_id, invite_link) - ) - - async def export_chat_invite_link(self, chat_id: Union[int, str]) -> str: - """ - Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator - in the chat for this to work and must have the appropriate admin rights. - - :param chat_id: Id: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :return: exported invite link as String on success. - """ - return await asyncio_helper.export_chat_invite_link(self.token, chat_id) - - - async def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: - """ - Use this method to approve a chat join request. - The bot must be an administrator in the chat for this to work and must have - the can_invite_users administrator right. Returns True on success. - - :param chat_id: Unique identifier for the target chat or username of the target supergroup - (in the format @supergroupusername) - :param user_id: Unique identifier of the target user - :return: True on success. - """ - return await asyncio_helper.approve_chat_join_request(self.token, chat_id, user_id) - - async def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: - """ - Use this method to decline a chat join request. - The bot must be an administrator in the chat for this to work and must have - the can_invite_users administrator right. Returns True on success. - - :param chat_id: Unique identifier for the target chat or username of the target supergroup - (in the format @supergroupusername) - :param user_id: Unique identifier of the target user - :return: True on success. - """ - return await asyncio_helper.decline_chat_join_request(self.token, chat_id, user_id) - - async def set_chat_photo(self, chat_id: Union[int, str], photo: Any) -> bool: - """ - Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. - Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ - setting is off in the target group. - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param photo: InputFile: New chat photo, uploaded using multipart/form-data - :return: - """ - return await asyncio_helper.set_chat_photo(self.token, chat_id, photo) - - async def delete_chat_photo(self, chat_id: Union[int, str]) -> bool: - """ - Use this method to delete a chat photo. Photos can't be changed for private chats. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. - Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ - setting is off in the target group. - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - """ - return await asyncio_helper.delete_chat_photo(self.token, chat_id) - - async def get_my_commands(self, scope: Optional[types.BotCommandScope], - language_code: Optional[str]) -> List[types.BotCommand]: - """ - Use this method to get the current list of the bot's commands. - Returns List of BotCommand on success. - :param scope: The scope of users for which the commands are relevant. - async defaults to BotCommandScopeasync default. - :param language_code: A two-letter ISO 639-1 language code. If empty, - commands will be applied to all users from the given scope, - for whose language there are no dedicated commands - """ - result = await asyncio_helper.get_my_commands(self.token, scope, language_code) - return [types.BotCommand.de_json(cmd) for cmd in result] - - async def set_my_commands(self, commands: List[types.BotCommand], - scope: Optional[types.BotCommandScope]=None, - language_code: Optional[str]=None) -> bool: - """ - Use this method to change the list of the bot's commands. - :param commands: List of BotCommand. At most 100 commands can be specified. - :param scope: The scope of users for which the commands are relevant. - async defaults to BotCommandScopeasync default. - :param language_code: A two-letter ISO 639-1 language code. If empty, - commands will be applied to all users from the given scope, - for whose language there are no dedicated commands - :return: - """ - return await asyncio_helper.set_my_commands(self.token, commands, scope, language_code) - - async def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None, - language_code: Optional[int]=None) -> bool: - """ - Use this method to delete the list of the bot's commands for the given scope and user language. - After deletion, higher level commands will be shown to affected users. - Returns True on success. - :param scope: The scope of users for which the commands are relevant. - async defaults to BotCommandScopeasync default. - :param language_code: A two-letter ISO 639-1 language code. If empty, - commands will be applied to all users from the given scope, - for whose language there are no dedicated commands - """ - return await asyncio_helper.delete_my_commands(self.token, scope, language_code) - - async def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: - """ - Use this method to change the title of a chat. Titles can't be changed for private chats. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. - Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ - setting is off in the target group. - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param title: New chat title, 1-255 characters - :return: - """ - return await asyncio_helper.set_chat_title(self.token, chat_id, title) - - async def set_chat_description(self, chat_id: Union[int, str], description: Optional[str]=None) -> bool: - """ - Use this method to change the description of a supergroup or a channel. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param description: Str: New chat description, 0-255 characters - :return: True on success. - """ - return await asyncio_helper.set_chat_description(self.token, chat_id, description) - - async def pin_chat_message( - self, chat_id: Union[int, str], message_id: int, - disable_notification: Optional[bool]=False) -> bool: - """ - Use this method to pin a message in a supergroup. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param message_id: Int: Identifier of a message to pin - :param disable_notification: Bool: Pass True, if it is not necessary to send a notification - to all group members about the new pinned message - :return: - """ - return await asyncio_helper.pin_chat_message(self.token, chat_id, message_id, disable_notification) - - async def unpin_chat_message(self, chat_id: Union[int, str], message_id: Optional[int]=None) -> bool: - """ - Use this method to unpin specific pinned message in a supergroup chat. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :param message_id: Int: Identifier of a message to unpin - :return: - """ - return await asyncio_helper.unpin_chat_message(self.token, chat_id, message_id) - - async def unpin_all_chat_messages(self, chat_id: Union[int, str]) -> bool: - """ - Use this method to unpin a all pinned messages in a supergroup chat. - The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - Returns True on success. - :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel - (in the format @channelusername) - :return: - """ - return await asyncio_helper.unpin_all_chat_messages(self.token, chat_id) - - async def edit_message_text( - self, text: str, - chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - parse_mode: Optional[str]=None, - entities: Optional[List[types.MessageEntity]]=None, - disable_web_page_preview: Optional[bool]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: - """ - Use this method to edit text and game messages. - :param text: - :param chat_id: - :param message_id: - :param inline_message_id: - :param parse_mode: - :param entities: - :param disable_web_page_preview: - :param reply_markup: - :return: - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - result = await asyncio_helper.edit_message_text(self.token, text, chat_id, message_id, inline_message_id, parse_mode, - entities, disable_web_page_preview, reply_markup) - if type(result) == bool: # if edit inline message return is bool not Message. - return result - return types.Message.de_json(result) - - async def edit_message_media( - self, media: Any, chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: - """ - Use this method to edit animation, audio, document, photo, or video messages. - If a message is a part of a message album, then it can be edited only to a photo or a video. - Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. - Use previously uploaded file via its file_id or specify a URL. - :param media: - :param chat_id: - :param message_id: - :param inline_message_id: - :param reply_markup: - :return: - """ - result = await asyncio_helper.edit_message_media(self.token, media, chat_id, message_id, inline_message_id, reply_markup) - if type(result) == bool: # if edit inline message return is bool not Message. - return result - return types.Message.de_json(result) - - async def edit_message_reply_markup( - self, chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: - """ - Use this method to edit only the reply markup of messages. - :param chat_id: - :param message_id: - :param inline_message_id: - :param reply_markup: - :return: - """ - result = await asyncio_helper.edit_message_reply_markup(self.token, chat_id, message_id, inline_message_id, reply_markup) - if type(result) == bool: - return result - return types.Message.de_json(result) - - async def send_game( - self, chat_id: Union[int, str], game_short_name: str, - disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None) -> types.Message: - """ - Used to send the game - :param chat_id: - :param game_short_name: - :param disable_notification: - :param reply_to_message_id: - :param reply_markup: - :param timeout: - :param allow_sending_without_reply: - :return: - """ - result = await asyncio_helper.send_game( - self.token, chat_id, game_short_name, disable_notification, - reply_to_message_id, reply_markup, timeout, - allow_sending_without_reply) - return types.Message.de_json(result) - - async def set_game_score( - self, user_id: Union[int, str], score: int, - force: Optional[bool]=None, - chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - disable_edit_message: Optional[bool]=None) -> Union[types.Message, bool]: - """ - Sets the value of points in the game to a specific user - :param user_id: - :param score: - :param force: - :param chat_id: - :param message_id: - :param inline_message_id: - :param disable_edit_message: - :return: - """ - result = await asyncio_helper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, - message_id, inline_message_id) - if type(result) == bool: - return result - return types.Message.de_json(result) - - async def get_game_high_scores( - self, user_id: int, chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: - """ - Gets top points and game play - :param user_id: - :param chat_id: - :param message_id: - :param inline_message_id: - :return: - """ - result = await asyncio_helper.get_game_high_scores(self.token, user_id, chat_id, message_id, inline_message_id) - return [types.GameHighScore.de_json(r) for r in result] - - async def send_invoice( - self, chat_id: Union[int, str], title: str, description: str, - invoice_payload: str, provider_token: str, currency: str, - prices: List[types.LabeledPrice], start_parameter: Optional[str]=None, - photo_url: Optional[str]=None, photo_size: Optional[int]=None, - photo_width: Optional[int]=None, photo_height: Optional[int]=None, - need_name: Optional[bool]=None, need_phone_number: Optional[bool]=None, - need_email: Optional[bool]=None, need_shipping_address: Optional[bool]=None, - send_phone_number_to_provider: Optional[bool]=None, - send_email_to_provider: Optional[bool]=None, - is_flexible: Optional[bool]=None, - disable_notification: Optional[bool]=None, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - provider_data: Optional[str]=None, - timeout: Optional[int]=None, - allow_sending_without_reply: Optional[bool]=None, - max_tip_amount: Optional[int] = None, - suggested_tip_amounts: Optional[List[int]]=None) -> types.Message: - """ - Sends invoice - :param chat_id: Unique identifier for the target private chat - :param title: Product name - :param description: Product description - :param invoice_payload: Bot-async defined invoice payload, 1-128 bytes. This will not be displayed to the user, - use for your internal processes. - :param provider_token: Payments provider token, obtained via @Botfather - :param currency: Three-letter ISO 4217 currency code, - see https://core.telegram.org/bots/payments#supported-currencies - :param prices: Price breakdown, a list of components - (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) - :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice - when used as a start parameter - :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods - or a marketing image for a service. People like it better when they see what they are paying for. - :param photo_size: Photo size - :param photo_width: Photo width - :param photo_height: Photo height - :param need_name: Pass True, if you require the user's full name to complete the order - :param need_phone_number: Pass True, if you require the user's phone number to complete the order - :param need_email: Pass True, if you require the user's email to complete the order - :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order - :param is_flexible: Pass True, if the final price depends on the shipping method - :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider - :param send_email_to_provider: Pass True, if user's email address should be sent to provider - :param disable_notification: Sends the message silently. Users will receive a notification with no sound. - :param reply_to_message_id: If the message is a reply, ID of the original message - :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, - one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button - :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. - A detailed description of required fields should be provided by the payment provider. - :param timeout: - :param allow_sending_without_reply: - :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency - :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest - units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip - amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. - :return: - """ - result = await asyncio_helper.send_invoice( - self.token, chat_id, title, description, invoice_payload, provider_token, - currency, prices, start_parameter, photo_url, photo_size, photo_width, - photo_height, need_name, need_phone_number, need_email, need_shipping_address, - send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, - reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply, - max_tip_amount, suggested_tip_amounts) - return types.Message.de_json(result) - - # noinspection PyShadowingBuiltins - async def send_poll( - self, chat_id: Union[int, str], question: str, options: List[str], - is_anonymous: Optional[bool]=None, type: Optional[str]=None, - allows_multiple_answers: Optional[bool]=None, - correct_option_id: Optional[int]=None, - explanation: Optional[str]=None, - explanation_parse_mode: Optional[str]=None, - open_period: Optional[int]=None, - close_date: Optional[Union[int, datetime]]=None, - is_closed: Optional[bool]=None, - disable_notification: Optional[bool]=False, - reply_to_message_id: Optional[int]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None, - allow_sending_without_reply: Optional[bool]=None, - timeout: Optional[int]=None, - explanation_entities: Optional[List[types.MessageEntity]]=None) -> types.Message: - """ - Send polls - :param chat_id: - :param question: - :param options: array of str with answers - :param is_anonymous: - :param type: - :param allows_multiple_answers: - :param correct_option_id: - :param explanation: - :param explanation_parse_mode: - :param open_period: - :param close_date: - :param is_closed: - :param disable_notification: - :param reply_to_message_id: - :param allow_sending_without_reply: - :param reply_markup: - :param timeout: - :param explanation_entities: - :return: - """ - - if isinstance(question, types.Poll): - raise RuntimeError("The send_poll signature was changed, please see send_poll function details.") - - return types.Message.de_json( - await asyncio_helper.send_poll( - self.token, chat_id, - question, options, - is_anonymous, type, allows_multiple_answers, correct_option_id, - explanation, explanation_parse_mode, open_period, close_date, is_closed, - disable_notification, reply_to_message_id, allow_sending_without_reply, - reply_markup, timeout, explanation_entities)) - - async def stop_poll( - self, chat_id: Union[int, str], message_id: int, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Poll: - """ - Stops poll - :param chat_id: - :param message_id: - :param reply_markup: - :return: - """ - return types.Poll.de_json(await asyncio_helper.stop_poll(self.token, chat_id, message_id, reply_markup)) - - async def answer_shipping_query( - self, shipping_query_id: str, ok: bool, - shipping_options: Optional[List[types.ShippingOption]]=None, - error_message: Optional[str]=None) -> bool: - """ - Asks for an answer to a shipping question - :param shipping_query_id: - :param ok: - :param shipping_options: - :param error_message: - :return: - """ - return await asyncio_helper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) - - async def answer_pre_checkout_query( - self, pre_checkout_query_id: int, ok: bool, - error_message: Optional[str]=None) -> bool: - """ - Response to a request for pre-inspection - :param pre_checkout_query_id: - :param ok: - :param error_message: - :return: - """ - return await asyncio_helper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) - - async def edit_message_caption( - self, caption: str, chat_id: Optional[Union[int, str]]=None, - message_id: Optional[int]=None, - inline_message_id: Optional[str]=None, - parse_mode: Optional[str]=None, - caption_entities: Optional[List[types.MessageEntity]]=None, - reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: - """ - Use this method to edit captions of messages - :param caption: - :param chat_id: - :param message_id: - :param inline_message_id: - :param parse_mode: - :param caption_entities: - :param reply_markup: - :return: - """ - parse_mode = self.parse_mode if (parse_mode is None) else parse_mode - - result = await asyncio_helper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, - parse_mode, caption_entities, reply_markup) - if type(result) == bool: - return result - return types.Message.de_json(result) - - async def reply_to(self, message: types.Message, text: str, **kwargs) -> types.Message: - """ - Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` - :param message: - :param text: - :param kwargs: - :return: - """ - return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) - - async def answer_inline_query( - self, inline_query_id: str, - results: List[Any], - cache_time: Optional[int]=None, - is_personal: Optional[bool]=None, - next_offset: Optional[str]=None, - switch_pm_text: Optional[str]=None, - switch_pm_parameter: Optional[str]=None) -> bool: - """ - Use this method to send answers to an inline query. On success, True is returned. - No more than 50 results per query are allowed. - :param inline_query_id: Unique identifier for the answered query - :param results: Array of results for the inline query - :param cache_time: The maximum amount of time in seconds that the result of the inline query - may be cached on the server. - :param is_personal: Pass True, if results may be cached on the server side only for - the user that sent the query. - :param next_offset: Pass the offset that a client should send in the next query with the same text - to receive more results. - :param switch_pm_parameter: If passed, clients will display a button with specified text that switches the user - to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter - :param switch_pm_text: Parameter for the start message sent to the bot when user presses the switch button - :return: True means success. - """ - return await asyncio_helper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset, - switch_pm_text, switch_pm_parameter) - - async def answer_callback_query( - self, callback_query_id: int, - text: Optional[str]=None, show_alert: Optional[bool]=None, - url: Optional[str]=None, cache_time: Optional[int]=None) -> bool: - """ - Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to - the user as a notification at the top of the chat screen or as an alert. - :param callback_query_id: - :param text: - :param show_alert: - :param url: - :param cache_time: - :return: - """ - return await asyncio_helper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) - - async def set_sticker_set_thumb( - self, name: str, user_id: int, thumb: Union[Any, str]=None): - """ - Use this method to set the thumbnail of a sticker set. - Animated thumbnails can be set for animated sticker sets only. Returns True on success. - """ - return await asyncio_helper.set_sticker_set_thumb(self.token, name, user_id, thumb) - - async def get_sticker_set(self, name: str) -> types.StickerSet: - """ - Use this method to get a sticker set. On success, a StickerSet object is returned. - :param name: - :return: - """ - result = await asyncio_helper.get_sticker_set(self.token, name) - return types.StickerSet.de_json(result) - - async def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: - """ - Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet - methods (can be used multiple times). Returns the uploaded File on success. - :param user_id: - :param png_sticker: - :return: - """ - result = await asyncio_helper.upload_sticker_file(self.token, user_id, png_sticker) - return types.File.de_json(result) - - async def create_new_sticker_set( - self, user_id: int, name: str, title: str, - emojis: str, - png_sticker: Union[Any, str], - tgs_sticker: Union[Any, str], - contains_masks: Optional[bool]=None, - mask_position: Optional[types.MaskPosition]=None) -> bool: - """ - Use this method to create new sticker set owned by a user. - The bot will be able to edit the created sticker set. - Returns True on success. - :param user_id: - :param name: - :param title: - :param emojis: - :param png_sticker: - :param tgs_sticker: - :param contains_masks: - :param mask_position: - :return: - """ - return await asyncio_helper.create_new_sticker_set( - self.token, user_id, name, title, emojis, png_sticker, tgs_sticker, - contains_masks, mask_position) - - - async def add_sticker_to_set( - self, user_id: int, name: str, emojis: str, - png_sticker: Optional[Union[Any, str]]=None, - tgs_sticker: Optional[Union[Any, str]]=None, - mask_position: Optional[types.MaskPosition]=None) -> bool: - """ - Use this method to add a new sticker to a set created by the bot. - It's required to pass `png_sticker` or `tgs_sticker`. - Returns True on success. - :param user_id: - :param name: - :param emojis: - :param png_sticker: Required if `tgs_sticker` is None - :param tgs_sticker: Required if `png_sticker` is None - :param mask_position: - :return: - """ - return await asyncio_helper.add_sticker_to_set( - self.token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position) - - - async def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: - """ - Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. - :param sticker: - :param position: - :return: - """ - return await asyncio_helper.set_sticker_position_in_set(self.token, sticker, position) - - async def delete_sticker_from_set(self, sticker: str) -> bool: - """ - Use this method to delete a sticker from a set created by the bot. Returns True on success. - :param sticker: - :return: - """ - return await asyncio_helper.delete_sticker_from_set(self.token, sticker) - - async def register_for_reply( - self, message: types.Message, callback: Callable, *args, **kwargs) -> None: - """ - Registers a callback function to be notified when a reply to `message` arrives. - - Warning: In case `callback` as lambda function, saving reply handlers will not work. - - :param message: The message for which we are awaiting a reply. - :param callback: The callback function to be called when a reply arrives. Must accept one `message` - parameter, which will contain the replied message. - """ - message_id = message.message_id - self.register_for_reply_by_message_id(message_id, callback, *args, **kwargs) - - async def register_for_reply_by_message_id( - self, message_id: int, callback: Callable, *args, **kwargs) -> None: - """ - Registers a callback function to be notified when a reply to `message` arrives. - - Warning: In case `callback` as lambda function, saving reply handlers will not work. - - :param message_id: The id of the message for which we are awaiting a reply. - :param callback: The callback function to be called when a reply arrives. Must accept one `message` - parameter, which will contain the replied message. - """ - self.reply_backend.register_handler(message_id, Handler(callback, *args, **kwargs)) - - async def _notify_reply_handlers(self, new_messages) -> None: - """ - Notify handlers of the answers - :param new_messages: - :return: - """ - for message in new_messages: - if hasattr(message, "reply_to_message") and message.reply_to_message is not None: - handlers = self.reply_backend.get_handlers(message.reply_to_message.message_id) - if handlers: - for handler in handlers: - self._exec_task(handler["callback"], message, *handler["args"], **handler["kwargs"]) - - async def register_next_step_handler( - self, message: types.Message, callback: Callable, *args, **kwargs) -> None: - """ - Registers a callback function to be notified when new message arrives after `message`. - - Warning: In case `callback` as lambda function, saving next step handlers will not work. - - :param message: The message for which we want to handle new message in the same chat. - :param callback: The callback function which next new message arrives. - :param args: Args to pass in callback func - :param kwargs: Args to pass in callback func - """ - chat_id = message.chat.id - self.register_next_step_handler_by_chat_id(chat_id, callback, *args, **kwargs) - - async def set_state(self, chat_id, state): - """ - Sets a new state of a user. - :param chat_id: - :param state: new state. can be string or integer. - """ - await self.current_states.add_state(chat_id, state) - - async def delete_state(self, chat_id): - """ - Delete the current state of a user. - :param chat_id: - :return: - """ - await self.current_states.delete_state(chat_id) - - def retrieve_data(self, chat_id): - return self.current_states.retrieve_data(chat_id) - - async def get_state(self, chat_id): - """ - Get current state of a user. - :param chat_id: - :return: state of a user - """ - return await self.current_states.current_state(chat_id) - - async def add_data(self, chat_id, **kwargs): - """ - Add data to states. - :param chat_id: - """ - for key, value in kwargs.items(): - await self.current_states._add_data(chat_id, key, value) \ No newline at end of file diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py new file mode 100644 index 0000000..eb2ac44 --- /dev/null +++ b/telebot/async_telebot.py @@ -0,0 +1,2869 @@ +# -*- coding: utf-8 -*- +from datetime import datetime + +import logging +import re +import sys +import time +import traceback +from typing import Any, Callable, List, Optional, Union + +# this imports are used to avoid circular import error +import telebot.util +import telebot.types + + +from inspect import signature + +from telebot import logger + +formatter = logging.Formatter( + '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"' +) + +console_output_handler = logging.StreamHandler(sys.stderr) +console_output_handler.setFormatter(formatter) +logger.addHandler(console_output_handler) + +logger.setLevel(logging.ERROR) + +from telebot import util, types, asyncio_helper +import asyncio +from telebot import asyncio_handler_backends +from telebot import asyncio_filters + + + +REPLY_MARKUP_TYPES = Union[ + types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, + types.ReplyKeyboardRemove, types.ForceReply] + + + +""" +Module : telebot +""" + + +class Handler: + """ + Class for (next step|reply) handlers + """ + + def __init__(self, callback, *args, **kwargs): + self.callback = callback + self.args = args + self.kwargs = kwargs + + def __getitem__(self, item): + return getattr(self, item) + + +class ExceptionHandler: + """ + Class for handling exceptions while Polling + """ + + # noinspection PyMethodMayBeStatic,PyUnusedLocal + def handle(self, exception): + return False + + +class SkipHandler: + """ + Class for skipping handlers. + Just return instance of this class + in middleware to skip handler. + Update will go to post_process, + but will skip execution of handler. + """ + + def __init__(self) -> None: + pass + +class CancelUpdate: + """ + Class for canceling updates. + Just return instance of this class + in middleware to skip update. + Update will skip handler and execution + of post_process in middlewares. + """ + + def __init__(self) -> None: + pass + + +class AsyncTeleBot: + + + def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, + exception_handler=None,suppress_middleware_excepions=False) -> None: # TODO: ADD TYPEHINTS + self.token = token + + self.offset = offset + self.token = token + self.parse_mode = parse_mode + self.update_listener = [] + self.suppress_middleware_excepions = suppress_middleware_excepions + + self.exc_info = None + + self.exception_handler = exception_handler + + self.message_handlers = [] + self.edited_message_handlers = [] + self.channel_post_handlers = [] + self.edited_channel_post_handlers = [] + self.inline_handlers = [] + self.chosen_inline_handlers = [] + self.callback_query_handlers = [] + self.shipping_query_handlers = [] + self.pre_checkout_query_handlers = [] + self.poll_handlers = [] + self.poll_answer_handlers = [] + self.my_chat_member_handlers = [] + self.chat_member_handlers = [] + self.chat_join_request_handlers = [] + self.custom_filters = {} + self.state_handlers = [] + + self.current_states = asyncio_handler_backends.StateMemory() + + + self.middlewares = [] + + + async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=None, + timeout: Optional[int]=None, allowed_updates: Optional[List]=None, request_timeout: Optional[int]=None) -> 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=20, allowed_updates: Optional[List[str]]=None, + none_stop: Optional[bool]=None): + """ + This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly. + + Warning: Do not call this function more than once! + + Always get updates. + :param interval: Delay between two update retrivals + :param non_stop: Do not stop polling when an ApiException occurs. + :param timeout: Request connection timeout + :param skip_pending: skip old updates + :param request_timeout: Timeout in seconds for a request. + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + :param none_stop: Deprecated, use non_stop. Old typo f***up compatibility + :return: + """ + if none_stop is not None: + non_stop = none_stop + + if skip_pending: + await self.skip_updates() + await self._process_polling(non_stop, interval, timeout, request_timeout, allowed_updates) + + async def infinity_polling(self, timeout: int=20, skip_pending: bool=False, request_timeout: int=20, logger_level=logging.ERROR, + allowed_updates: Optional[List[str]]=None, *args, **kwargs): + """ + Wrap polling with infinite loop and exception handling to avoid bot stops polling. + + :param timeout: Request connection timeout + :param long_polling_timeout: Timeout in seconds for long polling (see API docs) + :param skip_pending: skip old updates + :param logger_level: Custom logging level for infinity_polling logging. + Use logger levels from logging as a value. None/NOTSET = no error logging + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + """ + if skip_pending: + await self.skip_updates() + self._polling = True + while self._polling: + try: + await self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout, + allowed_updates=allowed_updates, *args, **kwargs) + except Exception as e: + if logger_level and logger_level >= logging.ERROR: + logger.error("Infinity polling exception: %s", str(e)) + if logger_level and logger_level >= logging.DEBUG: + logger.error("Exception traceback:\n%s", traceback.format_exc()) + time.sleep(3) + continue + if logger_level and logger_level >= logging.INFO: + logger.error("Infinity polling: polling exited") + if logger_level and logger_level >= logging.INFO: + logger.error("Break infinity polling") + + async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20, + request_timeout: int=20, allowed_updates: Optional[List[str]]=None): + """ + Function to process polling. + :param non_stop: Do not stop polling when an ApiException occurs. + :param interval: Delay between two update retrivals + :param timeout: Request connection timeout + :param request_timeout: Timeout in seconds for long polling (see API docs) + :param allowed_updates: A list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. + See util.update_types for a complete list of available update types. + Specify an empty list to receive all update types except chat_member (default). + If not specified, the previous setting will be used. + + Please note that this parameter doesn't affect updates created before the call to the get_updates, + so unwanted updates may be received for a short period of time. + :return: + + """ + self._polling = True + + try: + while self._polling: + try: + + updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout, request_timeout=request_timeout) + except asyncio.CancelledError: + return + + except asyncio_helper.ApiTelegramException as e: + logger.error(str(e)) + + continue + except Exception as e: + logger.error('Cause exception while getting updates.') + if non_stop: + logger.error(str(e)) + await asyncio.sleep(3) + continue + else: + raise e + if updates: + self.offset = updates[-1].update_id + 1 + self._loop_create_task(self.process_new_updates(updates)) # Seperate task for processing updates + if interval: await asyncio.sleep(interval) + + finally: + self._polling = False + logger.warning('Polling is stopped.') + + + def _loop_create_task(self, coro): + return asyncio.create_task(coro) + + async def _process_updates(self, handlers, messages, update_type): + """ + Process updates. + :param handlers: + :param messages: + :return: + """ + for message in messages: + middleware = await self.process_middlewares(message, update_type) + self._loop_create_task(self._run_middlewares_and_handlers(handlers, message, middleware)) + + + async def _run_middlewares_and_handlers(self, handlers, message, middleware): + handler_error = None + data = {} + for message_handler in handlers: + process_update = await self._test_message_handler(message_handler, message) + if not process_update: + continue + elif process_update: + if middleware: + middleware_result = await middleware.pre_process(message, data) + if isinstance(middleware_result, SkipHandler): + await middleware.post_process(message, data, handler_error) + break + if isinstance(middleware_result, CancelUpdate): + return + try: + if "data" in signature(message_handler['function']).parameters: + await message_handler['function'](message, data) + else: + await message_handler['function'](message) + break + except Exception as e: + handler_error = e + logger.info(str(e)) + + if middleware: + await middleware.post_process(message, data, handler_error) + # update handling + async def process_new_updates(self, updates): + upd_count = len(updates) + logger.info('Received {0} new updates'.format(upd_count)) + if upd_count == 0: return + + new_messages = None + new_edited_messages = None + new_channel_posts = None + new_edited_channel_posts = None + new_inline_queries = None + new_chosen_inline_results = None + new_callback_queries = None + new_shipping_queries = None + new_pre_checkout_queries = None + new_polls = None + new_poll_answers = None + new_my_chat_members = None + new_chat_members = None + chat_join_request = None + for update in updates: + logger.debug('Processing updates: {0}'.format(update)) + if update.message: + if new_messages is None: new_messages = [] + new_messages.append(update.message) + if update.edited_message: + if new_edited_messages is None: new_edited_messages = [] + new_edited_messages.append(update.edited_message) + if update.channel_post: + if new_channel_posts is None: new_channel_posts = [] + new_channel_posts.append(update.channel_post) + if update.edited_channel_post: + if new_edited_channel_posts is None: new_edited_channel_posts = [] + new_edited_channel_posts.append(update.edited_channel_post) + if update.inline_query: + if new_inline_queries is None: new_inline_queries = [] + new_inline_queries.append(update.inline_query) + if update.chosen_inline_result: + if new_chosen_inline_results is None: new_chosen_inline_results = [] + new_chosen_inline_results.append(update.chosen_inline_result) + if update.callback_query: + if new_callback_queries is None: new_callback_queries = [] + new_callback_queries.append(update.callback_query) + if update.shipping_query: + if new_shipping_queries is None: new_shipping_queries = [] + new_shipping_queries.append(update.shipping_query) + if update.pre_checkout_query: + if new_pre_checkout_queries is None: new_pre_checkout_queries = [] + new_pre_checkout_queries.append(update.pre_checkout_query) + if update.poll: + if new_polls is None: new_polls = [] + new_polls.append(update.poll) + if update.poll_answer: + if new_poll_answers is None: new_poll_answers = [] + new_poll_answers.append(update.poll_answer) + if update.my_chat_member: + if new_my_chat_members is None: new_my_chat_members = [] + new_my_chat_members.append(update.my_chat_member) + if update.chat_member: + if new_chat_members is None: new_chat_members = [] + new_chat_members.append(update.chat_member) + if update.chat_join_request: + if chat_join_request is None: chat_join_request = [] + chat_join_request.append(update.chat_join_request) + + if new_messages: + await self.process_new_messages(new_messages) + if new_edited_messages: + await self.process_new_edited_messages(new_edited_messages) + if new_channel_posts: + await self.process_new_channel_posts(new_channel_posts) + if new_edited_channel_posts: + await self.process_new_edited_channel_posts(new_edited_channel_posts) + if new_inline_queries: + await self.process_new_inline_query(new_inline_queries) + if new_chosen_inline_results: + await self.process_new_chosen_inline_query(new_chosen_inline_results) + if new_callback_queries: + await self.process_new_callback_query(new_callback_queries) + if new_shipping_queries: + await self.process_new_shipping_query(new_shipping_queries) + if new_pre_checkout_queries: + await self.process_new_pre_checkout_query(new_pre_checkout_queries) + if new_polls: + await self.process_new_poll(new_polls) + if new_poll_answers: + await self.process_new_poll_answer(new_poll_answers) + if new_my_chat_members: + await self.process_new_my_chat_member(new_my_chat_members) + if new_chat_members: + await self.process_new_chat_member(new_chat_members) + if chat_join_request: + await self.process_chat_join_request(chat_join_request) + + async def process_new_messages(self, new_messages): + await self.__notify_update(new_messages) + await self._process_updates(self.message_handlers, new_messages, 'message') + + async def process_new_edited_messages(self, edited_message): + await self._process_updates(self.edited_message_handlers, edited_message, 'edited_message') + + async def process_new_channel_posts(self, channel_post): + await self._process_updates(self.channel_post_handlers, channel_post , 'channel_post') + + async def process_new_edited_channel_posts(self, edited_channel_post): + await self._process_updates(self.edited_channel_post_handlers, edited_channel_post, 'edited_channel_post') + + async def process_new_inline_query(self, new_inline_querys): + await self._process_updates(self.inline_handlers, new_inline_querys, 'inline_query') + + async def process_new_chosen_inline_query(self, new_chosen_inline_querys): + 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): + await self._process_updates(self.callback_query_handlers, new_callback_querys, 'callback_query') + + async def process_new_shipping_query(self, new_shipping_querys): + await self._process_updates(self.shipping_query_handlers, new_shipping_querys, 'shipping_query') + + async def process_new_pre_checkout_query(self, pre_checkout_querys): + await self._process_updates(self.pre_checkout_query_handlers, pre_checkout_querys, 'pre_checkout_query') + + async def process_new_poll(self, polls): + await self._process_updates(self.poll_handlers, polls, 'poll') + + async def process_new_poll_answer(self, poll_answers): + await self._process_updates(self.poll_answer_handlers, poll_answers, 'poll_answer') + + async def process_new_my_chat_member(self, my_chat_members): + await self._process_updates(self.my_chat_member_handlers, my_chat_members, 'my_chat_member') + + async def process_new_chat_member(self, chat_members): + await self._process_updates(self.chat_member_handlers, chat_members, 'chat_member') + + async def process_chat_join_request(self, chat_join_request): + await self._process_updates(self.chat_join_request_handlers, chat_join_request, 'chat_join_request') + + async def process_middlewares(self, update, update_type): + for middleware in self.middlewares: + if update_type in middleware.update_types: + return middleware + return None + + async def __notify_update(self, new_messages): + if len(self.update_listener) == 0: + return + for listener in self.update_listener: + self._loop_create_task(listener, new_messages) + + async def _test_message_handler(self, message_handler, message): + """ + Test message handler + :param message_handler: + :param message: + :return: + """ + for message_filter, filter_value in message_handler['filters'].items(): + if filter_value is None: + continue + + if not await self._test_filter(message_filter, filter_value, message): + return False + + return True + + def add_custom_filter(self, custom_filter): + """ + Create custom filter. + custom_filter: Class with check(message) method. + """ + self.custom_filters[custom_filter.key] = custom_filter + + async def _test_filter(self, message_filter, filter_value, message): + """ + Test filters + :param message_filter: Filter type passed in handler + :param filter_value: Filter value passed in handler + :param message: Message to test + :return: True if filter conforms + """ + # test_cases = { + # 'content_types': lambda msg: msg.content_type in filter_value, + # 'regexp': lambda msg: msg.content_type == 'text' and re.search(filter_value, msg.text, re.IGNORECASE), + # 'commands': lambda msg: msg.content_type == 'text' and util.extract_command(msg.text) in filter_value, + # 'func': lambda msg: filter_value(msg) + # } + # return test_cases.get(message_filter, lambda msg: False)(message) + if message_filter == 'content_types': + return message.content_type in filter_value + elif message_filter == 'regexp': + return message.content_type == 'text' and re.search(filter_value, message.text, re.IGNORECASE) + elif message_filter == 'commands': + return message.content_type == 'text' and util.extract_command(message.text) in filter_value + elif message_filter == 'chat_types': + return message.chat.type in filter_value + elif message_filter == 'func': + return filter_value(message) + elif self.custom_filters and message_filter in self.custom_filters: + return await self._check_filter(message_filter,filter_value,message) + else: + return False + + async def _check_filter(self, message_filter, filter_value, message): + """ + Check up the filter + :param message_filter: + :param filter_value: + :param message: + :return: + """ + filter_check = self.custom_filters.get(message_filter) + if not filter_check: + return False + elif isinstance(filter_check, asyncio_filters.SimpleCustomFilter): + return filter_value == await filter_check.check(message) + elif isinstance(filter_check, asyncio_filters.AdvancedCustomFilter): + return await filter_check.check(message, filter_value) + else: + logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") + return False + + def setup_middleware(self, middleware): + """ + Setup middleware + :param middleware: + :return: + """ + self.middlewares.append(middleware) + + def message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + """ + Message handler decorator. + This decorator can be used to decorate functions that must handle certain types of messages. + All message handlers are tested in the order they were added. + + Example: + + 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?') + + # 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!') + + # Handle all sent documents of type 'text/plain'. + @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', + content_types=['document']) + async def command_handle_document(message): + bot.send_message(message.chat.id, 'Document received, sir!') + + # Handle all other messages. + @bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document', + 'text', 'location', 'contact', 'sticker']) + async def async default_command(message): + bot.send_message(message.chat.id, "This is the async default command handler.") + + :param commands: Optional list of strings (commands to handle). + :param regexp: Optional regular expression. + :param func: Optional lambda function. The lambda receives the message to test as the first parameter. + It must return True if the command should handle the message. + :param content_types: Supported message content types. Must be a list. async defaults to ['text']. + :param chat_types: list of chat types + """ + + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) + return handler + + return decorator + + def add_message_handler(self, handler_dict): + """ + Adds a message handler + :param handler_dict: + :return: + """ + self.message_handlers.append(handler_dict) + + def register_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + Registers message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :param chat_types: True for private chat + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_message_handler(handler_dict) + + def edited_message_handler(self, commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs): + """ + Edit message handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param chat_types: list of chat types + :param kwargs: + :return: + """ + + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) + return handler + + return decorator + + def add_edited_message_handler(self, handler_dict): + """ + Adds the edit message handler + :param handler_dict: + :return: + """ + self.edited_message_handlers.append(handler_dict) + + def register_edited_message_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, chat_types=None, **kwargs): + """ + Registers edited message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :param chat_types: True for private chat + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_edited_message_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_message_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + chat_types=chat_types, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_message_handler(handler_dict) + + + def channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + """ + Channel post handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param kwargs: + :return: + """ + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) + return handler + + return decorator + + def add_channel_post_handler(self, handler_dict): + """ + Adds channel post handler + :param handler_dict: + :return: + """ + self.channel_post_handlers.append(handler_dict) + + def register_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_channel_post_handler(handler_dict) + + def edited_channel_post_handler(self, commands=None, regexp=None, func=None, content_types=None, **kwargs): + """ + Edit channel post handler decorator + :param commands: + :param regexp: + :param func: + :param content_types: + :param kwargs: + :return: + """ + if content_types is None: + content_types = ["text"] + + if isinstance(commands, str): + logger.warning("edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + return handler + + return decorator + + def add_edited_channel_post_handler(self, handler_dict): + """ + Adds the edit channel post handler + :param handler_dict: + :return: + """ + self.edited_channel_post_handlers.append(handler_dict) + + def register_edited_channel_post_handler(self, callback, content_types=None, commands=None, regexp=None, func=None, **kwargs): + """ + Registers edited channel post message handler. + :param callback: function to be called + :param content_types: list of content_types + :param commands: list of commands + :param regexp: + :param func: + :return: decorated function + """ + if isinstance(commands, str): + logger.warning("register_edited_channel_post_handler: 'commands' filter should be List of strings (commands), not string.") + commands = [commands] + + if isinstance(content_types, str): + logger.warning("register_edited_channel_post_handler: 'content_types' filter should be List of strings (content types), not string.") + content_types = [content_types] + + handler_dict = self._build_handler_dict(callback, + content_types=content_types, + commands=commands, + regexp=regexp, + func=func, + **kwargs) + self.add_edited_channel_post_handler(handler_dict) + + def inline_handler(self, func, **kwargs): + """ + Inline call handler decorator + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_inline_handler(handler_dict) + return handler + + return decorator + + def add_inline_handler(self, handler_dict): + """ + Adds inline call handler + :param handler_dict: + :return: + """ + self.inline_handlers.append(handler_dict) + + def register_inline_handler(self, callback, func, **kwargs): + """ + Registers inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_inline_handler(handler_dict) + + def chosen_inline_handler(self, func, **kwargs): + """ + Description: TBD + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chosen_inline_handler(handler_dict) + return handler + + return decorator + + def add_chosen_inline_handler(self, handler_dict): + """ + Description: TBD + :param handler_dict: + :return: + """ + self.chosen_inline_handlers.append(handler_dict) + + def register_chosen_inline_handler(self, callback, func, **kwargs): + """ + Registers chosen inline handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chosen_inline_handler(handler_dict) + + def callback_query_handler(self, func, **kwargs): + """ + Callback request handler decorator + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_callback_query_handler(handler_dict) + return handler + + return decorator + + def add_callback_query_handler(self, handler_dict): + """ + Adds a callback request handler + :param handler_dict: + :return: + """ + self.callback_query_handlers.append(handler_dict) + + def register_callback_query_handler(self, callback, func, **kwargs): + """ + Registers callback query handler.. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_callback_query_handler(handler_dict) + + def shipping_query_handler(self, func, **kwargs): + """ + Shipping request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_shipping_query_handler(handler_dict) + return handler + + return decorator + + def add_shipping_query_handler(self, handler_dict): + """ + Adds a shipping request handler + :param handler_dict: + :return: + """ + self.shipping_query_handlers.append(handler_dict) + + def register_shipping_query_handler(self, callback, func, **kwargs): + """ + Registers shipping query handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_shipping_query_handler(handler_dict) + + def pre_checkout_query_handler(self, func, **kwargs): + """ + Pre-checkout request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_pre_checkout_query_handler(handler_dict) + return handler + + return decorator + + def add_pre_checkout_query_handler(self, handler_dict): + """ + Adds a pre-checkout request handler + :param handler_dict: + :return: + """ + self.pre_checkout_query_handlers.append(handler_dict) + + def register_pre_checkout_query_handler(self, callback, func, **kwargs): + """ + Registers pre-checkout request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_pre_checkout_query_handler(handler_dict) + + def poll_handler(self, func, **kwargs): + """ + Poll request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_poll_handler(handler_dict) + return handler + + return decorator + + def add_poll_handler(self, handler_dict): + """ + Adds a poll request handler + :param handler_dict: + :return: + """ + self.poll_handlers.append(handler_dict) + + def register_poll_handler(self, callback, func, **kwargs): + """ + Registers poll handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_poll_handler(handler_dict) + + def poll_answer_handler(self, func=None, **kwargs): + """ + Poll_answer request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_poll_answer_handler(handler_dict) + return handler + + return decorator + + def add_poll_answer_handler(self, handler_dict): + """ + Adds a poll_answer request handler + :param handler_dict: + :return: + """ + self.poll_answer_handlers.append(handler_dict) + + def register_poll_answer_handler(self, callback, func, **kwargs): + """ + Registers poll answer handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_poll_answer_handler(handler_dict) + + def my_chat_member_handler(self, func=None, **kwargs): + """ + my_chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_my_chat_member_handler(self, handler_dict): + """ + Adds a my_chat_member handler + :param handler_dict: + :return: + """ + self.my_chat_member_handlers.append(handler_dict) + + def register_my_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers my chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_my_chat_member_handler(handler_dict) + + def chat_member_handler(self, func=None, **kwargs): + """ + chat_member handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + return handler + + return decorator + + def add_chat_member_handler(self, handler_dict): + """ + Adds a chat_member handler + :param handler_dict: + :return: + """ + self.chat_member_handlers.append(handler_dict) + + def register_chat_member_handler(self, callback, func=None, **kwargs): + """ + Registers chat member handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_member_handler(handler_dict) + + def chat_join_request_handler(self, func=None, **kwargs): + """ + chat_join_request handler + :param func: + :param kwargs: + :return: + """ + + def decorator(handler): + handler_dict = self._build_handler_dict(handler, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + return handler + + return decorator + + def add_chat_join_request_handler(self, handler_dict): + """ + Adds a chat_join_request handler + :param handler_dict: + :return: + """ + self.chat_join_request_handlers.append(handler_dict) + + def register_chat_join_request_handler(self, callback, func=None, **kwargs): + """ + Registers chat join request handler. + :param callback: function to be called + :param func: + :return: decorated function + """ + handler_dict = self._build_handler_dict(callback, func=func, **kwargs) + self.add_chat_join_request_handler(handler_dict) + + @staticmethod + def _build_handler_dict(handler, **filters): + """ + Builds a dictionary for a handler + :param handler: + :param filters: + :return: + """ + return { + 'function': handler, + 'filters': {ftype: fvalue for ftype, fvalue in filters.items() if fvalue is not None} + # Remove None values, they are skipped in _test_filter anyway + #'filters': filters + } + + async def skip_updates(self): + await self.get_updates(-1) + return True + + # all methods begin here + + async def get_me(self) -> types.User: + """ + Returns basic information about the bot in form of a User object. + """ + result = await asyncio_helper.get_me(self.token) + return types.User.de_json(result) + + async def get_file(self, file_id: str) -> types.File: + """ + Use this method to get basic info about a file and prepare it for downloading. + For the moment, bots can download files of up to 20MB in size. + On success, a File object is returned. + It is guaranteed that the link will be valid for at least 1 hour. + When the link expires, a new one can be requested by calling get_file again. + """ + return types.File.de_json(await asyncio_helper.get_file(self.token, file_id)) + + async def get_file_url(self, file_id: str) -> str: + return await asyncio_helper.get_file_url(self.token, file_id) + + async def download_file(self, file_path: str) -> bytes: + return await asyncio_helper.download_file(self.token, file_path) + + async def log_out(self) -> bool: + """ + Use this method to log out from the cloud Bot API server before launching the bot locally. + You MUST log out the bot before running it locally, otherwise there is no guarantee + that the bot will receive updates. + After a successful call, you can immediately log in on a local server, + but will not be able to log in back to the cloud Bot API server for 10 minutes. + Returns True on success. + """ + return await asyncio_helper.log_out(self.token) + + async def close(self) -> bool: + """ + Use this method to close the bot instance before moving it from one local server to another. + You need to delete the webhook before calling this method to ensure that the bot isn't launched again + after server restart. + The method will return error 429 in the first 10 minutes after the bot is launched. + Returns True on success. + """ + return await asyncio_helper.close(self.token) + + def enable_saving_states(self, filename="./.state-save/states.pkl"): + """ + Enable saving states (by default saving disabled) + + :param filename: Filename of saving file + """ + + self.current_states = asyncio_handler_backends.StateFile(filename=filename) + self.current_states._create_dir() + + async def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, + drop_pending_updates = None, timeout=None): + """ + Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an + update for the bot, we will send an HTTPS POST request to the specified url, + containing a JSON-serialized Update. + In case of an unsuccessful request, we will give up after a reasonable amount of attempts. + Returns True on success. + + :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration + :param certificate: Upload your public key certificate so that the root certificate in use can be checked. + See our self-signed guide for details. + :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook + for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, + and higher values to increase your bot's throughput. + :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. + For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates + of these types. See Update for a complete list of available update types. + Specify an empty list to receive all updates regardless of type (default). + If not specified, the previous setting will be used. + :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address + resolved through DNS + :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout + :return: + """ + return await asyncio_helper.set_webhook(self.token, url, certificate, max_connections, allowed_updates, ip_address, + drop_pending_updates, timeout) + + async def delete_webhook(self, drop_pending_updates=None, timeout=None): + """ + Use this method to remove webhook integration if you decide to switch back to getUpdates. + + :param drop_pending_updates: Pass True to drop all pending updates + :param timeout: Integer. Request connection timeout + :return: bool + """ + return await asyncio_helper.delete_webhook(self.token, drop_pending_updates, timeout) + + async def get_webhook_info(self, timeout=None): + """ + Use this method to get current webhook status. Requires no parameters. + If the bot is using getUpdates, will return an object with the url field empty. + + :param timeout: Integer. Request connection timeout + :return: On success, returns a WebhookInfo object. + """ + result = await asyncio_helper.get_webhook_info(self.token, timeout) + return types.WebhookInfo.de_json(result) + + async def get_user_profile_photos(self, user_id: int, offset: Optional[int]=None, + limit: Optional[int]=None) -> types.UserProfilePhotos: + """ + Retrieves the user profile photos of the person with 'user_id' + See https://core.telegram.org/bots/api#getuserprofilephotos + :param user_id: + :param offset: + :param limit: + :return: API reply. + """ + result = await asyncio_helper.get_user_profile_photos(self.token, user_id, offset, limit) + return types.UserProfilePhotos.de_json(result) + + async def get_chat(self, chat_id: Union[int, str]) -> types.Chat: + """ + Use this method to get up to date information about the chat (current name of the user for one-on-one + conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.get_chat(self.token, chat_id) + return types.Chat.de_json(result) + + async def leave_chat(self, chat_id: Union[int, str]) -> bool: + """ + Use this method for your bot to leave a group, supergroup or channel. Returns True on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.leave_chat(self.token, chat_id) + return result + + async def get_chat_administrators(self, chat_id: Union[int, str]) -> List[types.ChatMember]: + """ + Use this method to get a list of administrators in a chat. + On success, returns an Array of ChatMember objects that contains + information about all chat administrators except other bots. + :param chat_id: Unique identifier for the target chat or username + of the target supergroup or channel (in the format @channelusername) + :return: + """ + result = await asyncio_helper.get_chat_administrators(self.token, chat_id) + return [types.ChatMember.de_json(r) for r in result] + + async def get_chat_members_count(self, chat_id: Union[int, str]) -> int: + """ + This function is deprecated. Use `get_chat_member_count` instead + """ + logger.info('get_chat_members_count is deprecated. Use get_chat_member_count instead.') + result = await asyncio_helper.get_chat_member_count(self.token, chat_id) + return result + + async def get_chat_member_count(self, chat_id: Union[int, str]) -> int: + """ + Use this method to get the number of members in a chat. Returns Int on success. + :param chat_id: + :return: + """ + result = await asyncio_helper.get_chat_member_count(self.token, chat_id) + return result + + async def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str) -> types.StickerSet: + """ + Use this method to set a new group sticker set for a supergroup. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + Use the field can_set_sticker_set optionally returned in getChat requests to check + if the bot can use this method. Returns True on success. + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param sticker_set_name: Name of the sticker set to be set as the group sticker set + :return: + """ + result = await asyncio_helper.set_chat_sticker_set(self.token, chat_id, sticker_set_name) + return result + + async def delete_chat_sticker_set(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat + for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set + optionally returned in getChat requests to check if the bot can use this method. Returns True on success. + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :return: + """ + result = await asyncio_helper.delete_chat_sticker_set(self.token, chat_id) + return result + + async def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatMember: + """ + Use this method to get information about a member of a chat. Returns a ChatMember object on success. + :param chat_id: + :param user_id: + :return: + """ + result = await asyncio_helper.get_chat_member(self.token, chat_id, user_id) + return types.ChatMember.de_json(result) + + async def send_message( + self, chat_id: Union[int, str], text: str, + disable_web_page_preview: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send text messages. + + Warning: Do not send more than about 4000 characters each message, otherwise you'll risk an HTTP 414 error. + If you must send more than 4000 characters, + use the `split_string` or `smart_split` function in util.py. + + :param chat_id: + :param text: + :param disable_web_page_preview: + :param reply_to_message_id: + :param reply_markup: + :param parse_mode: + :param disable_notification: Boolean, Optional. Sends the message silently. + :param timeout: + :param entities: + :param allow_sending_without_reply: + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_message( + self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, + entities, allow_sending_without_reply)) + + async def forward_message( + self, chat_id: Union[int, str], from_chat_id: Union[int, str], + message_id: int, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None) -> types.Message: + """ + Use this method to forward messages of any kind. + :param disable_notification: + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param timeout: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.forward_message(self.token, chat_id, from_chat_id, message_id, disable_notification, timeout)) + + async def copy_message( + self, chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + caption: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> int: + """ + Use this method to copy messages of any kind. + :param chat_id: which chat to forward + :param from_chat_id: which chat message from + :param message_id: message id + :param caption: + :param parse_mode: + :param caption_entities: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: + :param timeout: + :return: API reply. + """ + return types.MessageID.de_json( + await asyncio_helper.copy_message(self.token, chat_id, from_chat_id, message_id, caption, parse_mode, caption_entities, + disable_notification, reply_to_message_id, allow_sending_without_reply, reply_markup, + timeout)) + + async def delete_message(self, chat_id: Union[int, str], message_id: int, + timeout: Optional[int]=None) -> bool: + """ + Use this method to delete message. Returns True on success. + :param chat_id: in which chat to delete + :param message_id: which message to delete + :param timeout: + :return: API reply. + """ + return await asyncio_helper.delete_message(self.token, chat_id, message_id, timeout) + + async def send_dice( + self, chat_id: Union[int, str], + emoji: Optional[str]=None, disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send dices. + :param chat_id: + :param emoji: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :return: Message + """ + return types.Message.de_json( + await asyncio_helper.send_dice( + self.token, chat_id, emoji, disable_notification, reply_to_message_id, + reply_markup, timeout, allow_sending_without_reply) + ) + + async def send_photo( + self, chat_id: Union[int, str], photo: Union[Any, str], + caption: Optional[str]=None, reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send photos. + :param chat_id: + :param photo: + :param caption: + :param parse_mode: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param caption_entities: + :param allow_sending_without_reply: + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_photo( + self.token, chat_id, photo, caption, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) + + async def send_audio( + self, chat_id: Union[int, str], audio: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + performer: Optional[str]=None, title: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send audio files, if you want Telegram clients to display them in the music player. + Your audio must be in the .mp3 format. + :param chat_id:Unique identifier for the message recipient + :param audio:Audio file to send. + :param caption: + :param duration:Duration of the audio in seconds + :param performer:Performer + :param title:Track name + :param reply_to_message_id:If the message is a reply, ID of the original message + :param reply_markup: + :param parse_mode + :param disable_notification: + :param timeout: + :param thumb: + :param caption_entities: + :param allow_sending_without_reply: + :return: Message + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_audio( + self.token, chat_id, audio, caption, duration, performer, title, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) + + async def send_voice( + self, chat_id: Union[int, str], voice: Union[Any, str], + caption: Optional[str]=None, duration: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send audio files, if you want Telegram clients to display the file + as a playable voice message. + :param chat_id:Unique identifier for the message recipient. + :param voice: + :param caption: + :param duration:Duration of sent audio in seconds + :param reply_to_message_id: + :param reply_markup: + :param parse_mode + :param disable_notification: + :param timeout: + :param caption_entities: + :param allow_sending_without_reply: + :return: Message + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_voice( + self.token, chat_id, voice, caption, duration, reply_to_message_id, reply_markup, + parse_mode, disable_notification, timeout, caption_entities, + allow_sending_without_reply)) + + async def send_document( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + caption: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None, + visible_file_name: Optional[str]=None, + disable_content_type_detection: Optional[bool]=None) -> types.Message: + """ + Use this method to send general files. + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) + :param data: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data + :param reply_to_message_id: If the message is a reply, ID of the original message + :param caption: Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing + :param reply_markup: + :param parse_mode: Mode for parsing entities in the document caption + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under + :param caption_entities: + :param allow_sending_without_reply: + :param visible_file_name: allows to async define file name that will be visible in the Telegram instead of original file name + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :return: API reply. + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_data( + self.token, chat_id, data, 'document', + reply_to_message_id = reply_to_message_id, reply_markup = reply_markup, parse_mode = parse_mode, + disable_notification = disable_notification, timeout = timeout, caption = caption, thumb = thumb, + caption_entities = caption_entities, allow_sending_without_reply = allow_sending_without_reply, + disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name)) + + async def send_sticker( + self, chat_id: Union[int, str], data: Union[Any, str], + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send .webp stickers. + :param chat_id: + :param data: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: to disable the notification + :param timeout: timeout + :param allow_sending_without_reply: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.send_data( + self.token, chat_id, data, 'sticker', + reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, + disable_notification=disable_notification, timeout=timeout, + allow_sending_without_reply=allow_sending_without_reply)) + + async def send_video( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + supports_streaming: Optional[bool]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + width: Optional[int]=None, + height: Optional[int]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send video files, Telegram clients support mp4 videos. + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param caption: String : Video caption (may also be used when resending videos by file_id). + :param parse_mode: + :param supports_streaming: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param width: + :param height: + :param caption_entities: + :param allow_sending_without_reply: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_video( + self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup, + parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height, + caption_entities, allow_sending_without_reply)) + + async def send_animation( + self, chat_id: Union[int, str], animation: Union[Any, str], + duration: Optional[int]=None, + caption: Optional[str]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + parse_mode: Optional[str]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param animation: InputFile or String : Animation to send. You can either pass a file_id as String to resend an + animation that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param caption: String : Animation caption (may also be used when resending animation by file_id). + :param parse_mode: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param caption_entities: + :param allow_sending_without_reply: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + return types.Message.de_json( + await asyncio_helper.send_animation( + self.token, chat_id, animation, duration, caption, reply_to_message_id, + reply_markup, parse_mode, disable_notification, timeout, thumb, + caption_entities, allow_sending_without_reply)) + + async def send_video_note( + self, chat_id: Union[int, str], data: Union[Any, str], + duration: Optional[int]=None, + length: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + thumb: Optional[Union[Any, str]]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send + video messages. + :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id + :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend + a video that is already on the Telegram server + :param duration: Integer : Duration of sent video in seconds + :param length: Integer : Video width and height, Can't be None and should be in range of (0, 640) + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param thumb: InputFile or String : Thumbnail of the file sent + :param allow_sending_without_reply: + :return: + """ + return types.Message.de_json( + await asyncio_helper.send_video_note( + self.token, chat_id, data, duration, length, reply_to_message_id, reply_markup, + disable_notification, timeout, thumb, allow_sending_without_reply)) + + async def send_media_group( + self, chat_id: Union[int, str], + media: List[Union[ + types.InputMediaAudio, types.InputMediaDocument, + types.InputMediaPhoto, types.InputMediaVideo]], + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> List[types.Message]: + """ + send a group of photos or videos as an album. On success, an array of the sent Messages is returned. + :param chat_id: + :param media: + :param disable_notification: + :param reply_to_message_id: + :param timeout: + :param allow_sending_without_reply: + :return: + """ + result = await asyncio_helper.send_media_group( + self.token, chat_id, media, disable_notification, reply_to_message_id, timeout, + allow_sending_without_reply) + return [types.Message.de_json(msg) for msg in result] + + async def send_location( + self, chat_id: Union[int, str], + latitude: float, longitude: float, + live_period: Optional[int]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + disable_notification: Optional[bool]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + + + """ + Use this method to send point on the map. + :param chat_id: + :param latitude: + :param longitude: + :param live_period: + :param reply_to_message_id: + :param reply_markup: + :param disable_notification: + :param timeout: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :param allow_sending_without_reply: + :return: API reply. + """ + return types.Message.de_json( + await asyncio_helper.send_location( + self.token, chat_id, latitude, longitude, live_period, + reply_to_message_id, reply_markup, disable_notification, timeout, + horizontal_accuracy, heading, proximity_alert_radius, + allow_sending_without_reply)) + + async def edit_message_live_location( + self, latitude: float, longitude: float, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + horizontal_accuracy: Optional[float]=None, + heading: Optional[int]=None, + proximity_alert_radius: Optional[int]=None) -> types.Message: + """ + Use this method to edit live location + :param latitude: + :param longitude: + :param chat_id: + :param message_id: + :param reply_markup: + :param timeout: + :param inline_message_id: + :param horizontal_accuracy: + :param heading: + :param proximity_alert_radius: + :return: + """ + return types.Message.de_json( + await asyncio_helper.edit_message_live_location( + self.token, latitude, longitude, chat_id, message_id, + inline_message_id, reply_markup, timeout, + horizontal_accuracy, heading, proximity_alert_radius)) + + async def stop_message_live_location( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None) -> types.Message: + """ + Use this method to stop updating a live location message sent by the bot + or via the bot (for inline bots) before live_period expires + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :param timeout: + :return: + """ + return types.Message.de_json( + await asyncio_helper.stop_message_live_location( + self.token, chat_id, message_id, inline_message_id, reply_markup, timeout)) + + async def send_venue( + self, chat_id: Union[int, str], + latitude: float, longitude: float, + title: str, address: str, + foursquare_id: Optional[str]=None, + foursquare_type: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + google_place_id: Optional[str]=None, + google_place_type: Optional[str]=None) -> types.Message: + """ + Use this method to send information about a venue. + :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel + :param latitude: Float : Latitude of the venue + :param longitude: Float : Longitude of the venue + :param title: String : Name of the venue + :param address: String : Address of the venue + :param foursquare_id: String : Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, “arts_entertainment/async default”, + “arts_entertainment/aquarium” or “food/icecream”.) + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :param google_place_id: + :param google_place_type: + :return: + """ + return types.Message.de_json( + await asyncio_helper.send_venue( + self.token, chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply, google_place_id, google_place_type) + ) + + async def send_contact( + self, chat_id: Union[int, str], phone_number: str, + first_name: str, last_name: Optional[str]=None, + vcard: Optional[str]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + return types.Message.de_json( + await asyncio_helper.send_contact( + self.token, chat_id, phone_number, first_name, last_name, vcard, + disable_notification, reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) + ) + + async def send_chat_action( + self, chat_id: Union[int, str], action: str, timeout: Optional[int]=None) -> bool: + """ + Use this method when you need to tell the user that something is happening on the bot's side. + The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear + its typing status). + :param chat_id: + :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', + 'record_audio', 'upload_audio', 'upload_document', 'find_location', 'record_video_note', + 'upload_video_note'. + :param timeout: + :return: API reply. :type: boolean + """ + return await asyncio_helper.send_chat_action(self.token, chat_id, action, timeout) + + async def kick_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + This function is deprecated. Use `ban_chat_member` instead + """ + logger.info('kick_chat_member is deprecated. Use ban_chat_member instead.') + return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + + async def ban_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date:Optional[Union[int, datetime]]=None, + revoke_messages: Optional[bool]=None) -> bool: + """ + Use this method to ban a user in a group, a supergroup or a channel. + In the case of supergroups and channels, the user will not be able to return to the chat on their + own using invite links, etc., unless unbanned first. + Returns True on success. + :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when the user will be unbanned, unix time. If user is banned for more than 366 days or + less than 30 seconds from the current time they are considered to be banned forever + :param revoke_messages: Bool: Pass True to delete all messages from the chat for the user that is being removed. + If False, the user will be able to see messages in the group that were sent before the user was removed. + Always True for supergroups and channels. + :return: boolean + """ + return await asyncio_helper.ban_chat_member(self.token, chat_id, user_id, until_date, revoke_messages) + + async def unban_chat_member( + self, chat_id: Union[int, str], user_id: int, + only_if_banned: Optional[bool]=False) -> bool: + """ + Use this method to unban a previously kicked user in a supergroup or channel. + The user will not return to the group or channel automatically, but will be able to join via link, etc. + The bot must be an administrator for this to work. By async default, this method guarantees that after the call + the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat + they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. + + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel + (in the format @username) + :param user_id: Unique identifier of the target user + :param only_if_banned: Do nothing if the user is not banned + :return: True on success + """ + return await asyncio_helper.unban_chat_member(self.token, chat_id, user_id, only_if_banned) + + async def restrict_chat_member( + self, chat_id: Union[int, str], user_id: int, + until_date: Optional[Union[int, datetime]]=None, + can_send_messages: Optional[bool]=None, + can_send_media_messages: Optional[bool]=None, + can_send_polls: Optional[bool]=None, + can_send_other_messages: Optional[bool]=None, + can_add_web_page_previews: Optional[bool]=None, + can_change_info: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_pin_messages: Optional[bool]=None) -> bool: + """ + Use this method to restrict a user in a supergroup. + The bot must be an administrator in the supergroup for this to work and must have + the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. + + :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup + or channel (in the format @channelusername) + :param user_id: Int : Unique identifier of the target user + :param until_date: Date when restrictions will be lifted for the user, unix time. + If user is restricted for more than 366 days or less than 30 seconds from the current time, + they are considered to be restricted forever + :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues + :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes + and voice notes, implies can_send_messages + :param can_send_polls: Pass True, if the user is allowed to send polls, implies can_send_messages + :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and + use inline bots, implies can_send_media_messages + :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, + implies can_send_media_messages + :param can_change_info: Pass True, if the user is allowed to change the chat title, photo and other settings. + Ignored in public supergroups + :param can_invite_users: Pass True, if the user is allowed to invite new users to the chat, + implies can_invite_users + :param can_pin_messages: Pass True, if the user is allowed to pin messages. Ignored in public supergroups + :return: True on success + """ + return await asyncio_helper.restrict_chat_member( + self.token, chat_id, user_id, until_date, + can_send_messages, can_send_media_messages, + can_send_polls, can_send_other_messages, + can_add_web_page_previews, can_change_info, + can_invite_users, can_pin_messages) + + async def promote_chat_member( + self, chat_id: Union[int, str], user_id: int, + can_change_info: Optional[bool]=None, + can_post_messages: Optional[bool]=None, + can_edit_messages: Optional[bool]=None, + can_delete_messages: Optional[bool]=None, + can_invite_users: Optional[bool]=None, + can_restrict_members: Optional[bool]=None, + can_pin_messages: Optional[bool]=None, + can_promote_members: Optional[bool]=None, + is_anonymous: Optional[bool]=None, + can_manage_chat: Optional[bool]=None, + can_manage_voice_chats: Optional[bool]=None) -> bool: + """ + Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + Pass False for all boolean parameters to demote a user. + + :param chat_id: Unique identifier for the target chat or username of the target channel ( + in the format @channelusername) + :param user_id: Int : Unique identifier of the target user + :param can_change_info: Bool: Pass True, if the administrator can change chat title, photo and other settings + :param can_post_messages: Bool : Pass True, if the administrator can create channel posts, channels only + :param can_edit_messages: Bool : Pass True, if the administrator can edit messages of other users, channels only + :param can_delete_messages: Bool : Pass True, if the administrator can delete messages of other users + :param can_invite_users: Bool : Pass True, if the administrator can invite new users to the chat + :param can_restrict_members: Bool: Pass True, if the administrator can restrict, ban or unban chat members + :param can_pin_messages: Bool: Pass True, if the administrator can pin messages, supergroups only + :param can_promote_members: Bool: Pass True, if the administrator can add new administrators with a subset + of his own privileges or demote administrators that he has promoted, directly or indirectly + (promoted by administrators that were appointed by him) + :param is_anonymous: Bool: Pass True, if the administrator's presence in the chat is hidden + :param can_manage_chat: Bool: Pass True, if the administrator can access the chat event log, chat statistics, + message statistics in channels, see channel members, + see anonymous administrators in supergroups and ignore slow mode. + Implied by any other administrator privilege + :param can_manage_voice_chats: Bool: Pass True, if the administrator can manage voice chats + For now, bots can use this privilege only for passing to other administrators. + :return: True on success. + """ + return await asyncio_helper.promote_chat_member( + self.token, chat_id, user_id, can_change_info, can_post_messages, + can_edit_messages, can_delete_messages, can_invite_users, + can_restrict_members, can_pin_messages, can_promote_members, + is_anonymous, can_manage_chat, can_manage_voice_chats) + + async def set_chat_administrator_custom_title( + self, chat_id: Union[int, str], user_id: int, custom_title: str) -> bool: + """ + Use this method to set a custom title for an administrator + in a supergroup promoted by the bot. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :param custom_title: New custom title for the administrator; + 0-16 characters, emoji are not allowed + :return: True on success. + """ + return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) + + async def set_chat_permissions( + self, chat_id: Union[int, str], permissions: types.ChatPermissions) -> bool: + """ + Use this method to set async default chat permissions for all members. + The bot must be an administrator in the group or a supergroup for this to work + and must have the can_restrict_members admin rights. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param permissions: New async default chat permissions + :return: True on success + """ + return await asyncio_helper.set_chat_permissions(self.token, chat_id, permissions) + + async def create_chat_invite_link( + self, chat_id: Union[int, str], + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: + """ + Use this method to create an additional invite link for a chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request) + ) + + async def edit_chat_invite_link( + self, chat_id: Union[int, str], + invite_link: Optional[str] = None, + name: Optional[str]=None, + expire_date: Optional[Union[int, datetime]]=None, + member_limit: Optional[int]=None, + creates_join_request: Optional[bool]=None) -> types.ChatInviteLink: + """ + Use this method to edit a non-primary invite link created by the bot. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param name: Invite link name; 0-32 characters + :param invite_link: The invite link to edit + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: Maximum number of users that can be members of the chat simultaneously + :param creates_join_request: True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.edit_chat_invite_link(self.token, chat_id, name, invite_link, expire_date, member_limit, creates_join_request) + ) + + async def revoke_chat_invite_link( + self, chat_id: Union[int, str], invite_link: str) -> types.ChatInviteLink: + """ + Use this method to revoke an invite link created by the bot. + Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param invite_link: The invite link to revoke + :return: + """ + return types.ChatInviteLink.de_json( + await asyncio_helper.revoke_chat_invite_link(self.token, chat_id, invite_link) + ) + + async def export_chat_invite_link(self, chat_id: Union[int, str]) -> str: + """ + Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator + in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Id: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :return: exported invite link as String on success. + """ + return await asyncio_helper.export_chat_invite_link(self.token, chat_id) + + + async def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to approve a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return await asyncio_helper.approve_chat_join_request(self.token, chat_id, user_id) + + async def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool: + """ + Use this method to decline a chat join request. + The bot must be an administrator in the chat for this to work and must have + the can_invite_users administrator right. Returns True on success. + + :param chat_id: Unique identifier for the target chat or username of the target supergroup + (in the format @supergroupusername) + :param user_id: Unique identifier of the target user + :return: True on success. + """ + return await asyncio_helper.decline_chat_join_request(self.token, chat_id, user_id) + + async def set_chat_photo(self, chat_id: Union[int, str], photo: Any) -> bool: + """ + Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param photo: InputFile: New chat photo, uploaded using multipart/form-data + :return: + """ + return await asyncio_helper.set_chat_photo(self.token, chat_id, photo) + + async def delete_chat_photo(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to delete a chat photo. Photos can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + """ + return await asyncio_helper.delete_chat_photo(self.token, chat_id) + + async def get_my_commands(self, scope: Optional[types.BotCommandScope], + language_code: Optional[str]) -> List[types.BotCommand]: + """ + Use this method to get the current list of the bot's commands. + Returns List of BotCommand on success. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + """ + result = await asyncio_helper.get_my_commands(self.token, scope, language_code) + return [types.BotCommand.de_json(cmd) for cmd in result] + + async def set_my_commands(self, commands: List[types.BotCommand], + scope: Optional[types.BotCommandScope]=None, + language_code: Optional[str]=None) -> bool: + """ + Use this method to change the list of the bot's commands. + :param commands: List of BotCommand. At most 100 commands can be specified. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + :return: + """ + return await asyncio_helper.set_my_commands(self.token, commands, scope, language_code) + + async def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None, + language_code: Optional[int]=None) -> bool: + """ + Use this method to delete the list of the bot's commands for the given scope and user language. + After deletion, higher level commands will be shown to affected users. + Returns True on success. + :param scope: The scope of users for which the commands are relevant. + async defaults to BotCommandScopeasync default. + :param language_code: A two-letter ISO 639-1 language code. If empty, + commands will be applied to all users from the given scope, + for whose language there are no dedicated commands + """ + return await asyncio_helper.delete_my_commands(self.token, scope, language_code) + + async def set_chat_title(self, chat_id: Union[int, str], title: str) -> bool: + """ + Use this method to change the title of a chat. Titles can't be changed for private chats. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ + setting is off in the target group. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param title: New chat title, 1-255 characters + :return: + """ + return await asyncio_helper.set_chat_title(self.token, chat_id, title) + + async def set_chat_description(self, chat_id: Union[int, str], description: Optional[str]=None) -> bool: + """ + Use this method to change the description of a supergroup or a channel. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param description: Str: New chat description, 0-255 characters + :return: True on success. + """ + return await asyncio_helper.set_chat_description(self.token, chat_id, description) + + async def pin_chat_message( + self, chat_id: Union[int, str], message_id: int, + disable_notification: Optional[bool]=False) -> bool: + """ + Use this method to pin a message in a supergroup. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to pin + :param disable_notification: Bool: Pass True, if it is not necessary to send a notification + to all group members about the new pinned message + :return: + """ + return await asyncio_helper.pin_chat_message(self.token, chat_id, message_id, disable_notification) + + async def unpin_chat_message(self, chat_id: Union[int, str], message_id: Optional[int]=None) -> bool: + """ + Use this method to unpin specific pinned message in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :param message_id: Int: Identifier of a message to unpin + :return: + """ + return await asyncio_helper.unpin_chat_message(self.token, chat_id, message_id) + + async def unpin_all_chat_messages(self, chat_id: Union[int, str]) -> bool: + """ + Use this method to unpin a all pinned messages in a supergroup chat. + The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + Returns True on success. + :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + :return: + """ + return await asyncio_helper.unpin_all_chat_messages(self.token, chat_id) + + async def edit_message_text( + self, text: str, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + entities: Optional[List[types.MessageEntity]]=None, + disable_web_page_preview: Optional[bool]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit text and game messages. + :param text: + :param chat_id: + :param message_id: + :param inline_message_id: + :param parse_mode: + :param entities: + :param disable_web_page_preview: + :param reply_markup: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + result = await asyncio_helper.edit_message_text(self.token, text, chat_id, message_id, inline_message_id, parse_mode, + entities, disable_web_page_preview, reply_markup) + if type(result) == bool: # if edit inline message return is bool not Message. + return result + return types.Message.de_json(result) + + async def edit_message_media( + self, media: Any, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit animation, audio, document, photo, or video messages. + If a message is a part of a message album, then it can be edited only to a photo or a video. + Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. + Use previously uploaded file via its file_id or specify a URL. + :param media: + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :return: + """ + result = await asyncio_helper.edit_message_media(self.token, media, chat_id, message_id, inline_message_id, reply_markup) + if type(result) == bool: # if edit inline message return is bool not Message. + return result + return types.Message.de_json(result) + + async def edit_message_reply_markup( + self, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit only the reply markup of messages. + :param chat_id: + :param message_id: + :param inline_message_id: + :param reply_markup: + :return: + """ + result = await asyncio_helper.edit_message_reply_markup(self.token, chat_id, message_id, inline_message_id, reply_markup) + if type(result) == bool: + return result + return types.Message.de_json(result) + + async def send_game( + self, chat_id: Union[int, str], game_short_name: str, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None) -> types.Message: + """ + Used to send the game + :param chat_id: + :param game_short_name: + :param disable_notification: + :param reply_to_message_id: + :param reply_markup: + :param timeout: + :param allow_sending_without_reply: + :return: + """ + result = await asyncio_helper.send_game( + self.token, chat_id, game_short_name, disable_notification, + reply_to_message_id, reply_markup, timeout, + allow_sending_without_reply) + return types.Message.de_json(result) + + async def set_game_score( + self, user_id: Union[int, str], score: int, + force: Optional[bool]=None, + chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + disable_edit_message: Optional[bool]=None) -> Union[types.Message, bool]: + """ + Sets the value of points in the game to a specific user + :param user_id: + :param score: + :param force: + :param chat_id: + :param message_id: + :param inline_message_id: + :param disable_edit_message: + :return: + """ + result = await asyncio_helper.set_game_score(self.token, user_id, score, force, disable_edit_message, chat_id, + message_id, inline_message_id) + if type(result) == bool: + return result + return types.Message.de_json(result) + + async def get_game_high_scores( + self, user_id: int, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None) -> List[types.GameHighScore]: + """ + Gets top points and game play + :param user_id: + :param chat_id: + :param message_id: + :param inline_message_id: + :return: + """ + result = await asyncio_helper.get_game_high_scores(self.token, user_id, chat_id, message_id, inline_message_id) + return [types.GameHighScore.de_json(r) for r in result] + + async def send_invoice( + self, chat_id: Union[int, str], title: str, description: str, + invoice_payload: str, provider_token: str, currency: str, + prices: List[types.LabeledPrice], start_parameter: Optional[str]=None, + photo_url: Optional[str]=None, photo_size: Optional[int]=None, + photo_width: Optional[int]=None, photo_height: Optional[int]=None, + need_name: Optional[bool]=None, need_phone_number: Optional[bool]=None, + need_email: Optional[bool]=None, need_shipping_address: Optional[bool]=None, + send_phone_number_to_provider: Optional[bool]=None, + send_email_to_provider: Optional[bool]=None, + is_flexible: Optional[bool]=None, + disable_notification: Optional[bool]=None, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + provider_data: Optional[str]=None, + timeout: Optional[int]=None, + allow_sending_without_reply: Optional[bool]=None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]]=None) -> types.Message: + """ + Sends invoice + :param chat_id: Unique identifier for the target private chat + :param title: Product name + :param description: Product description + :param invoice_payload: Bot-async defined invoice payload, 1-128 bytes. This will not be displayed to the user, + use for your internal processes. + :param provider_token: Payments provider token, obtained via @Botfather + :param currency: Three-letter ISO 4217 currency code, + see https://core.telegram.org/bots/payments#supported-currencies + :param prices: Price breakdown, a list of components + (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + :param start_parameter: Unique deep-linking parameter that can be used to generate this invoice + when used as a start parameter + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods + or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass True, if you require the user's full name to complete the order + :param need_phone_number: Pass True, if you require the user's phone number to complete the order + :param need_email: Pass True, if you require the user's email to complete the order + :param need_shipping_address: Pass True, if you require the user's shipping address to complete the order + :param is_flexible: Pass True, if the final price depends on the shipping method + :param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider + :param send_email_to_provider: Pass True, if user's email address should be sent to provider + :param disable_notification: Sends the message silently. Users will receive a notification with no sound. + :param reply_to_message_id: If the message is a reply, ID of the original message + :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, + one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button + :param provider_data: A JSON-serialized data about the invoice, which will be shared with the payment provider. + A detailed description of required fields should be provided by the payment provider. + :param timeout: + :param allow_sending_without_reply: + :param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest + units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip + amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + :return: + """ + result = await asyncio_helper.send_invoice( + self.token, chat_id, title, description, invoice_payload, provider_token, + currency, prices, start_parameter, photo_url, photo_size, photo_width, + photo_height, need_name, need_phone_number, need_email, need_shipping_address, + send_phone_number_to_provider, send_email_to_provider, is_flexible, disable_notification, + reply_to_message_id, reply_markup, provider_data, timeout, allow_sending_without_reply, + max_tip_amount, suggested_tip_amounts) + return types.Message.de_json(result) + + # noinspection PyShadowingBuiltins + async def send_poll( + self, chat_id: Union[int, str], question: str, options: List[str], + is_anonymous: Optional[bool]=None, type: Optional[str]=None, + allows_multiple_answers: Optional[bool]=None, + correct_option_id: Optional[int]=None, + explanation: Optional[str]=None, + explanation_parse_mode: Optional[str]=None, + open_period: Optional[int]=None, + close_date: Optional[Union[int, datetime]]=None, + is_closed: Optional[bool]=None, + disable_notification: Optional[bool]=False, + reply_to_message_id: Optional[int]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None, + allow_sending_without_reply: Optional[bool]=None, + timeout: Optional[int]=None, + explanation_entities: Optional[List[types.MessageEntity]]=None) -> types.Message: + """ + Send polls + :param chat_id: + :param question: + :param options: array of str with answers + :param is_anonymous: + :param type: + :param allows_multiple_answers: + :param correct_option_id: + :param explanation: + :param explanation_parse_mode: + :param open_period: + :param close_date: + :param is_closed: + :param disable_notification: + :param reply_to_message_id: + :param allow_sending_without_reply: + :param reply_markup: + :param timeout: + :param explanation_entities: + :return: + """ + + if isinstance(question, types.Poll): + raise RuntimeError("The send_poll signature was changed, please see send_poll function details.") + + return types.Message.de_json( + await asyncio_helper.send_poll( + self.token, chat_id, + question, options, + is_anonymous, type, allows_multiple_answers, correct_option_id, + explanation, explanation_parse_mode, open_period, close_date, is_closed, + disable_notification, reply_to_message_id, allow_sending_without_reply, + reply_markup, timeout, explanation_entities)) + + async def stop_poll( + self, chat_id: Union[int, str], message_id: int, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Poll: + """ + Stops poll + :param chat_id: + :param message_id: + :param reply_markup: + :return: + """ + return types.Poll.de_json(await asyncio_helper.stop_poll(self.token, chat_id, message_id, reply_markup)) + + async def answer_shipping_query( + self, shipping_query_id: str, ok: bool, + shipping_options: Optional[List[types.ShippingOption]]=None, + error_message: Optional[str]=None) -> bool: + """ + Asks for an answer to a shipping question + :param shipping_query_id: + :param ok: + :param shipping_options: + :param error_message: + :return: + """ + return await asyncio_helper.answer_shipping_query(self.token, shipping_query_id, ok, shipping_options, error_message) + + async def answer_pre_checkout_query( + self, pre_checkout_query_id: int, ok: bool, + error_message: Optional[str]=None) -> bool: + """ + Response to a request for pre-inspection + :param pre_checkout_query_id: + :param ok: + :param error_message: + :return: + """ + return await asyncio_helper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) + + async def edit_message_caption( + self, caption: str, chat_id: Optional[Union[int, str]]=None, + message_id: Optional[int]=None, + inline_message_id: Optional[str]=None, + parse_mode: Optional[str]=None, + caption_entities: Optional[List[types.MessageEntity]]=None, + reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> Union[types.Message, bool]: + """ + Use this method to edit captions of messages + :param caption: + :param chat_id: + :param message_id: + :param inline_message_id: + :param parse_mode: + :param caption_entities: + :param reply_markup: + :return: + """ + parse_mode = self.parse_mode if (parse_mode is None) else parse_mode + + result = await asyncio_helper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, + parse_mode, caption_entities, reply_markup) + if type(result) == bool: + return result + return types.Message.de_json(result) + + async def reply_to(self, message: types.Message, text: str, **kwargs) -> types.Message: + """ + Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` + :param message: + :param text: + :param kwargs: + :return: + """ + return await self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) + + async def answer_inline_query( + self, inline_query_id: str, + results: List[Any], + cache_time: Optional[int]=None, + is_personal: Optional[bool]=None, + next_offset: Optional[str]=None, + switch_pm_text: Optional[str]=None, + switch_pm_parameter: Optional[str]=None) -> bool: + """ + Use this method to send answers to an inline query. On success, True is returned. + No more than 50 results per query are allowed. + :param inline_query_id: Unique identifier for the answered query + :param results: Array of results for the inline query + :param cache_time: The maximum amount of time in seconds that the result of the inline query + may be cached on the server. + :param is_personal: Pass True, if results may be cached on the server side only for + the user that sent the query. + :param next_offset: Pass the offset that a client should send in the next query with the same text + to receive more results. + :param switch_pm_parameter: If passed, clients will display a button with specified text that switches the user + to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter + :param switch_pm_text: Parameter for the start message sent to the bot when user presses the switch button + :return: True means success. + """ + return await asyncio_helper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset, + switch_pm_text, switch_pm_parameter) + + async def answer_callback_query( + self, callback_query_id: int, + text: Optional[str]=None, show_alert: Optional[bool]=None, + url: Optional[str]=None, cache_time: Optional[int]=None) -> bool: + """ + Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to + the user as a notification at the top of the chat screen or as an alert. + :param callback_query_id: + :param text: + :param show_alert: + :param url: + :param cache_time: + :return: + """ + return await asyncio_helper.answer_callback_query(self.token, callback_query_id, text, show_alert, url, cache_time) + + async def set_sticker_set_thumb( + self, name: str, user_id: int, thumb: Union[Any, str]=None): + """ + Use this method to set the thumbnail of a sticker set. + Animated thumbnails can be set for animated sticker sets only. Returns True on success. + """ + return await asyncio_helper.set_sticker_set_thumb(self.token, name, user_id, thumb) + + async def get_sticker_set(self, name: str) -> types.StickerSet: + """ + Use this method to get a sticker set. On success, a StickerSet object is returned. + :param name: + :return: + """ + result = await asyncio_helper.get_sticker_set(self.token, name) + return types.StickerSet.de_json(result) + + async def upload_sticker_file(self, user_id: int, png_sticker: Union[Any, str]) -> types.File: + """ + Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet + methods (can be used multiple times). Returns the uploaded File on success. + :param user_id: + :param png_sticker: + :return: + """ + result = await asyncio_helper.upload_sticker_file(self.token, user_id, png_sticker) + return types.File.de_json(result) + + async def create_new_sticker_set( + self, user_id: int, name: str, title: str, + emojis: str, + png_sticker: Union[Any, str], + tgs_sticker: Union[Any, str], + contains_masks: Optional[bool]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to create new sticker set owned by a user. + The bot will be able to edit the created sticker set. + Returns True on success. + :param user_id: + :param name: + :param title: + :param emojis: + :param png_sticker: + :param tgs_sticker: + :param contains_masks: + :param mask_position: + :return: + """ + return await asyncio_helper.create_new_sticker_set( + self.token, user_id, name, title, emojis, png_sticker, tgs_sticker, + contains_masks, mask_position) + + + async def add_sticker_to_set( + self, user_id: int, name: str, emojis: str, + png_sticker: Optional[Union[Any, str]]=None, + tgs_sticker: Optional[Union[Any, str]]=None, + mask_position: Optional[types.MaskPosition]=None) -> bool: + """ + Use this method to add a new sticker to a set created by the bot. + It's required to pass `png_sticker` or `tgs_sticker`. + Returns True on success. + :param user_id: + :param name: + :param emojis: + :param png_sticker: Required if `tgs_sticker` is None + :param tgs_sticker: Required if `png_sticker` is None + :param mask_position: + :return: + """ + return await asyncio_helper.add_sticker_to_set( + self.token, user_id, name, emojis, png_sticker, tgs_sticker, mask_position) + + + async def set_sticker_position_in_set(self, sticker: str, position: int) -> bool: + """ + Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. + :param sticker: + :param position: + :return: + """ + return await asyncio_helper.set_sticker_position_in_set(self.token, sticker, position) + + async def delete_sticker_from_set(self, sticker: str) -> bool: + """ + Use this method to delete a sticker from a set created by the bot. Returns True on success. + :param sticker: + :return: + """ + return await asyncio_helper.delete_sticker_from_set(self.token, sticker) + + + async def set_state(self, chat_id, state): + """ + Sets a new state of a user. + :param chat_id: + :param state: new state. can be string or integer. + """ + await self.current_states.add_state(chat_id, state) + + async def delete_state(self, chat_id): + """ + Delete the current state of a user. + :param chat_id: + :return: + """ + await self.current_states.delete_state(chat_id) + + def retrieve_data(self, chat_id): + return self.current_states.retrieve_data(chat_id) + + async def get_state(self, chat_id): + """ + Get current state of a user. + :param chat_id: + :return: state of a user + """ + return await self.current_states.current_state(chat_id) + + async def add_data(self, chat_id, **kwargs): + """ + Add data to states. + :param chat_id: + """ + for key, value in kwargs.items(): + await self.current_states._add_data(chat_id, key, value) \ No newline at end of file diff --git a/telebot/asyncio_filters.py b/telebot/asyncio_filters.py index c8242fe..cce7017 100644 --- a/telebot/asyncio_filters.py +++ b/telebot/asyncio_filters.py @@ -144,7 +144,8 @@ class IsAdminFilter(SimpleCustomFilter): self._bot = bot async def check(self, message): - return self._bot.get_chat_member(message.chat.id, message.from_user.id).status in ['creator', 'administrator'] + result = await self._bot.get_chat_member(message.chat.id, message.from_user.id) + return result.status in ['creator', 'administrator'] class StateFilter(AdvancedCustomFilter): """ @@ -158,10 +159,11 @@ class StateFilter(AdvancedCustomFilter): key = 'state' async def check(self, message, text): - if await self.bot.current_states.current_state(message.from_user.id) is False: return False + result = await self.bot.current_states.current_state(message.from_user.id) + if result is False: return False elif text == '*': return True - elif type(text) is list: return await self.bot.current_states.current_state(message.from_user.id) in text - return await self.bot.current_states.current_state(message.from_user.id) == text + elif type(text) is list: return result in text + return result == text class IsDigitFilter(SimpleCustomFilter): """ diff --git a/telebot/asyncio_handler_backends.py b/telebot/asyncio_handler_backends.py index b46c988..d3c452f 100644 --- a/telebot/asyncio_handler_backends.py +++ b/telebot/asyncio_handler_backends.py @@ -94,11 +94,11 @@ class StateFile: async def delete_state(self, chat_id): """Delete a state""" - states_data = await self._read_data() + states_data = self._read_data() states_data.pop(chat_id) await self._save_data(states_data) - async def _read_data(self): + def _read_data(self): """ Read the data from file. """ @@ -107,7 +107,7 @@ class StateFile: file.close() return states_data - async def _create_dir(self): + def _create_dir(self): """ Create directory .save-handlers. """ @@ -152,7 +152,7 @@ class StateFile: """ await self.delete_state(chat_id) - async def retrieve_data(self, chat_id): + def retrieve_data(self, chat_id): """ Save input text. @@ -195,7 +195,7 @@ class StateFileContext: return self.data async def __aexit__(self, exc_type, exc_val, exc_tb): - old_data = await self.obj._read_data() + old_data = self.obj._read_data() for i in self.data: old_data[self.chat_id]['data'][i] = self.data.get(i) await self.obj._save_data(old_data) From bfc0b8ecd540c8e9af118011be4087defa016808 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 28 Nov 2021 00:21:09 +0500 Subject: [PATCH 325/350] Update async_telebot.py --- telebot/async_telebot.py | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index eb2ac44..7ee990f 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -69,30 +69,6 @@ class ExceptionHandler: return False -class SkipHandler: - """ - Class for skipping handlers. - Just return instance of this class - in middleware to skip handler. - Update will go to post_process, - but will skip execution of handler. - """ - - def __init__(self) -> None: - pass - -class CancelUpdate: - """ - Class for canceling updates. - Just return instance of this class - in middleware to skip update. - Update will skip handler and execution - of post_process in middlewares. - """ - - def __init__(self) -> None: - pass - class AsyncTeleBot: From d58336adcb8bc5508a30285117d123276ffd2f47 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 28 Nov 2021 00:25:56 +0500 Subject: [PATCH 326/350] Fix --- telebot/__init__.py | 24 ------------------------ telebot/async_telebot.py | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 7983a26..6f29f86 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -68,30 +68,6 @@ class ExceptionHandler: return False -class SkipHandler: - """ - Class for skipping handlers. - Just return instance of this class - in middleware to skip handler. - Update will go to post_process, - but will skip execution of handler. - """ - - def __init__(self) -> None: - pass - -class CancelUpdate: - """ - Class for canceling updates. - Just return instance of this class - in middleware to skip update. - Update will skip handler and execution - of post_process in middlewares. - """ - - def __init__(self) -> None: - pass - class TeleBot: """ This is TeleBot Class Methods: diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 7ee990f..48b6487 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -69,6 +69,29 @@ class ExceptionHandler: return False +class SkipHandler: + """ + Class for skipping handlers. + Just return instance of this class + in middleware to skip handler. + Update will go to post_process, + but will skip execution of handler. + """ + + def __init__(self) -> None: + pass + +class CancelUpdate: + """ + Class for canceling updates. + Just return instance of this class + in middleware to skip update. + Update will skip handler and execution + of post_process in middlewares. + """ + + def __init__(self) -> None: + pass class AsyncTeleBot: From 7d9856dae3739565dc2ac9fbfd4d3a9fd9271f70 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 27 Nov 2021 22:29:57 +0300 Subject: [PATCH 327/350] Python 3.10 added --- .travis.yml | 1 + README.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2f6ddfb..36dbf89 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ python: - "3.7" - "3.8" - "3.9" + - "3.10" - "pypy3" install: "pip install -r requirements.txt" script: diff --git a/README.md b/README.md index 849a249..2e9607e 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ ## Getting started -This API is tested with Python 3.6-3.9 and Pypy 3. +This API is tested with Python 3.6-3.10 and Pypy 3. There are two ways to install the library: * Installation using pip (a Python package manager)*: From 411c7e915aa820c0fbae0ec28416466dfdfcab96 Mon Sep 17 00:00:00 2001 From: _run Date: Sun, 28 Nov 2021 01:04:49 +0500 Subject: [PATCH 328/350] No asyncio.run() --- examples/asynchronous_telebot/chat_join_request.py | 4 ++-- .../asynchronous_telebot/chat_member_example.py | 4 ++-- .../custom_filters/admin_filter_example.py | 3 +-- .../custom_filters/general_custom_filters.py | 3 +-- .../custom_filters/id_filter_example.py | 4 +--- .../custom_filters/is_filter_example.py | 4 ++-- .../custom_filters/text_filter_example.py | 3 +-- examples/asynchronous_telebot/custom_states.py | 3 +-- examples/asynchronous_telebot/echo_bot.py | 3 +-- examples/asynchronous_telebot/register_handler.py | 3 +-- .../asynchronous_telebot/skip_updates_example.py | 4 ++-- telebot/async_telebot.py | 14 +++++++------- 12 files changed, 22 insertions(+), 30 deletions(-) diff --git a/examples/asynchronous_telebot/chat_join_request.py b/examples/asynchronous_telebot/chat_join_request.py index 6b2bfb7..5262ebd 100644 --- a/examples/asynchronous_telebot/chat_join_request.py +++ b/examples/asynchronous_telebot/chat_join_request.py @@ -1,5 +1,5 @@ from telebot.async_telebot import AsyncTeleBot -import asyncio + import telebot bot = AsyncTeleBot('TOKEN') @@ -8,4 +8,4 @@ async def make_some(message: telebot.types.ChatJoinRequest): await bot.send_message(message.chat.id, 'I accepted a new user!') await bot.approve_chat_join_request(message.chat.id, message.from_user.id) -asyncio.run(bot.polling(skip_pending=True)) \ No newline at end of file +bot.polling(skip_pending=True) \ No newline at end of file diff --git a/examples/asynchronous_telebot/chat_member_example.py b/examples/asynchronous_telebot/chat_member_example.py index 7806cfd..4d90036 100644 --- a/examples/asynchronous_telebot/chat_member_example.py +++ b/examples/asynchronous_telebot/chat_member_example.py @@ -1,6 +1,6 @@ from telebot import types,util from telebot.async_telebot import AsyncTeleBot -import asyncio + bot = AsyncTeleBot('TOKEN') #chat_member_handler. When status changes, telegram gives update. check status from old_chat_member and new_chat_member. @@ -30,4 +30,4 @@ async def my_chat_m(message: types.ChatMemberUpdated): @bot.message_handler(content_types=util.content_type_service) async def delall(message: types.Message): await bot.delete_message(message.chat.id,message.message_id) -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/custom_filters/admin_filter_example.py b/examples/asynchronous_telebot/custom_filters/admin_filter_example.py index 3aee738..5a508c4 100644 --- a/examples/asynchronous_telebot/custom_filters/admin_filter_example.py +++ b/examples/asynchronous_telebot/custom_filters/admin_filter_example.py @@ -1,4 +1,3 @@ -import asyncio from telebot.async_telebot import AsyncTeleBot from telebot import asyncio_filters bot = AsyncTeleBot('TOKEN') @@ -10,4 +9,4 @@ async def answer_for_admin(message): # Register filter bot.add_custom_filter(asyncio_filters.IsAdminFilter(bot)) -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/custom_filters/general_custom_filters.py b/examples/asynchronous_telebot/custom_filters/general_custom_filters.py index dfeeb88..1b36beb 100644 --- a/examples/asynchronous_telebot/custom_filters/general_custom_filters.py +++ b/examples/asynchronous_telebot/custom_filters/general_custom_filters.py @@ -40,5 +40,4 @@ async def bye_user(message): bot.add_custom_filter(MainFilter()) bot.add_custom_filter(IsAdmin()) -import asyncio -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/custom_filters/id_filter_example.py b/examples/asynchronous_telebot/custom_filters/id_filter_example.py index 5878bc7..5a07963 100644 --- a/examples/asynchronous_telebot/custom_filters/id_filter_example.py +++ b/examples/asynchronous_telebot/custom_filters/id_filter_example.py @@ -1,6 +1,5 @@ from telebot.async_telebot import AsyncTeleBot import telebot -import asyncio bot = AsyncTeleBot('TOKEN') @@ -15,5 +14,4 @@ async def not_admin(message): # Do not forget to register bot.add_custom_filter(telebot.asyncio_filters.ChatFilter()) - -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/custom_filters/is_filter_example.py b/examples/asynchronous_telebot/custom_filters/is_filter_example.py index 20857be..961fd0f 100644 --- a/examples/asynchronous_telebot/custom_filters/is_filter_example.py +++ b/examples/asynchronous_telebot/custom_filters/is_filter_example.py @@ -1,6 +1,6 @@ from telebot.async_telebot import AsyncTeleBot import telebot -import asyncio + bot = AsyncTeleBot('TOKEN') @@ -19,4 +19,4 @@ async def text_filter(message): bot.add_custom_filter(telebot.asyncio_filters.IsReplyFilter()) bot.add_custom_filter(telebot.asyncio_filters.ForwardFilter()) -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/custom_filters/text_filter_example.py b/examples/asynchronous_telebot/custom_filters/text_filter_example.py index 57513ea..84aaee9 100644 --- a/examples/asynchronous_telebot/custom_filters/text_filter_example.py +++ b/examples/asynchronous_telebot/custom_filters/text_filter_example.py @@ -1,6 +1,5 @@ from telebot.async_telebot import AsyncTeleBot import telebot -import asyncio bot = AsyncTeleBot('TOKEN') @@ -18,4 +17,4 @@ async def text_filter(message): bot.add_custom_filter(telebot.asyncio_filters.TextMatchFilter()) bot.add_custom_filter(telebot.asyncio_filters.TextStartsFilter()) -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/custom_states.py b/examples/asynchronous_telebot/custom_states.py index 2f0257a..36132d8 100644 --- a/examples/asynchronous_telebot/custom_states.py +++ b/examples/asynchronous_telebot/custom_states.py @@ -1,7 +1,6 @@ import telebot from telebot import asyncio_filters from telebot.async_telebot import AsyncTeleBot -import asyncio bot = AsyncTeleBot('TOKEN') @@ -72,4 +71,4 @@ bot.add_custom_filter(asyncio_filters.IsDigitFilter()) # set saving states into file. bot.enable_saving_states() # you can delete this if you do not need to save states -asyncio.run(bot.polling()) \ No newline at end of file +bot.polling() \ No newline at end of file diff --git a/examples/asynchronous_telebot/echo_bot.py b/examples/asynchronous_telebot/echo_bot.py index 24cbe3f..940aecc 100644 --- a/examples/asynchronous_telebot/echo_bot.py +++ b/examples/asynchronous_telebot/echo_bot.py @@ -4,7 +4,6 @@ # It echoes any incoming text messages. from telebot.async_telebot import AsyncTeleBot -import asyncio bot = AsyncTeleBot('TOKEN') @@ -24,4 +23,4 @@ async def echo_message(message): await bot.reply_to(message, message.text) -asyncio.run(bot.polling()) +bot.polling() diff --git a/examples/asynchronous_telebot/register_handler.py b/examples/asynchronous_telebot/register_handler.py index 04dabd4..76d194d 100644 --- a/examples/asynchronous_telebot/register_handler.py +++ b/examples/asynchronous_telebot/register_handler.py @@ -1,5 +1,4 @@ from telebot.async_telebot import AsyncTeleBot -import asyncio bot = AsyncTeleBot('TOKEN') async def start_executor(message): @@ -16,4 +15,4 @@ bot.register_message_handler(start_executor, commands=['start']) # Start command # bot.register_edited_message_handler(*args, **kwargs) # And other functions.. -asyncio.run(bot.polling(skip_pending=True)) +bot.polling(skip_pending=True) diff --git a/examples/asynchronous_telebot/skip_updates_example.py b/examples/asynchronous_telebot/skip_updates_example.py index dc2c157..c149cb2 100644 --- a/examples/asynchronous_telebot/skip_updates_example.py +++ b/examples/asynchronous_telebot/skip_updates_example.py @@ -1,5 +1,5 @@ from telebot.async_telebot import AsyncTeleBot -import asyncio + bot = AsyncTeleBot('TOKEN') @bot.message_handler(commands=['start', 'help']) @@ -10,4 +10,4 @@ async def send_welcome(message): async def echo_all(message): await bot.reply_to(message, message.text) -asyncio.run(bot.polling(skip_pending=True))# Skip pending skips old updates +bot.polling(skip_pending=True)# Skip pending skips old updates diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 48b6487..9f24d90 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -138,7 +138,7 @@ class AsyncTeleBot: 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, + def polling(self, non_stop: bool=False, skip_pending=False, interval: int=0, timeout: int=20, request_timeout: int=20, allowed_updates: Optional[List[str]]=None, none_stop: Optional[bool]=None): """ @@ -167,10 +167,10 @@ class AsyncTeleBot: non_stop = none_stop if skip_pending: - await self.skip_updates() - await self._process_polling(non_stop, interval, timeout, request_timeout, allowed_updates) + asyncio.run(self.skip_updates()) + asyncio.run(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=20, logger_level=logging.ERROR, + def infinity_polling(self, timeout: int=20, skip_pending: bool=False, request_timeout: int=20, logger_level=logging.ERROR, allowed_updates: Optional[List[str]]=None, *args, **kwargs): """ Wrap polling with infinite loop and exception handling to avoid bot stops polling. @@ -190,12 +190,12 @@ class AsyncTeleBot: so unwanted updates may be received for a short period of time. """ if skip_pending: - await self.skip_updates() + asyncio.run(self.skip_updates()) self._polling = True while self._polling: try: - await self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout, - allowed_updates=allowed_updates, *args, **kwargs) + asyncio.run( self._process_polling(non_stop=True, timeout=timeout, request_timeout=request_timeout, + allowed_updates=allowed_updates, *args, **kwargs) ) except Exception as e: if logger_level and logger_level >= logging.ERROR: logger.error("Infinity polling exception: %s", str(e)) From a5305f551c50a0ff06e787fe856c41868eefb94b Mon Sep 17 00:00:00 2001 From: _run Date: Fri, 3 Dec 2021 21:13:02 +0500 Subject: [PATCH 329/350] Update README.md --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 1908e45..492a1bf 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ * [Reply markup](#reply-markup) * [Advanced use of the API](#advanced-use-of-the-api) * [Using local Bot API Server](#using-local-bot-api-sever) - * [Asynchronous delivery of messages](#asynchronous-delivery-of-messages) + * [Asynchronous TeleBot](#asynchronous-telebot) * [Sending large text messages](#sending-large-text-messages) * [Controlling the amount of Threads used by TeleBot](#controlling-the-amount-of-threads-used-by-telebot) * [The listener mechanism](#the-listener-mechanism) @@ -555,26 +555,26 @@ apihelper.API_URL = "http://localhost:4200/bot{0}/{1}" *Note: 4200 is an example port* -### Asynchronous delivery of messages -There exists an implementation of TeleBot which executes all `send_xyz` and the `get_me` functions asynchronously. This can speed up your bot __significantly__, but it has unwanted side effects if used without caution. +### Asynchronous TeleBot +New: There is an asynchronous implementation of telebot. It is more flexible. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot. ```python tb = telebot.AsyncTeleBot("TOKEN") ``` -Now, every function that calls the Telegram API is executed in a separate Thread. The functions are modified to return an AsyncTask instance (defined in util.py). Using AsyncTeleBot allows you to do the following: +Now, every function that calls the Telegram API is executed in a separate asynchronous task. +Using AsyncTeleBot allows you to do the following: ```python import telebot tb = telebot.AsyncTeleBot("TOKEN") -task = tb.get_me() # Execute an API call -# Do some other operations... -a = 0 -for a in range(100): - a += 10 -result = task.wait() # Get the result of the execution +@tb.message_handler(commands=['start']) +async def start_message(message): + await bot.send_message(message.chat.id, 'Hello'!) + ``` -*Note: if you execute send_xyz functions after eachother without calling wait(), the order in which messages are delivered might be wrong.* + +See more in [examples](https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) ### Sending large text messages Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API: From 51eabde320b99520f7ed64876fd9b01a799fd0c2 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:11:51 +0500 Subject: [PATCH 330/350] Update --- .../download_file_example.py | 20 ++++++++ .../asynchronous_telebot/exception_handler.py | 27 +++++++++++ .../middleware/flooding_middleware.py | 39 +++++++++++++++ .../asynchronous_telebot/middleware/i18n.py | 48 +++++++++++++++++++ .../asynchronous_telebot/send_file_example.py | 27 +++++++++++ 5 files changed, 161 insertions(+) create mode 100644 examples/asynchronous_telebot/download_file_example.py create mode 100644 examples/asynchronous_telebot/exception_handler.py create mode 100644 examples/asynchronous_telebot/middleware/flooding_middleware.py create mode 100644 examples/asynchronous_telebot/middleware/i18n.py create mode 100644 examples/asynchronous_telebot/send_file_example.py diff --git a/examples/asynchronous_telebot/download_file_example.py b/examples/asynchronous_telebot/download_file_example.py new file mode 100644 index 0000000..5105d9d --- /dev/null +++ b/examples/asynchronous_telebot/download_file_example.py @@ -0,0 +1,20 @@ + +import telebot +from telebot.async_telebot import AsyncTeleBot + + + +bot = AsyncTeleBot('TOKEN') + + +@bot.message_handler(content_types=['photo']) +async def new_message(message: telebot.types.Message): + result_message = await bot.send_message(message.chat.id, 'Downloading your photo...', parse_mode='HTML', disable_web_page_preview=True) + file_path = await bot.get_file(message.photo[-1].file_id) + downloaded_file = await bot.download_file(file_path.file_path) + with open('file.jpg', 'wb') as new_file: + new_file.write(downloaded_file) + await bot.edit_message_text(chat_id=message.chat.id, message_id=result_message.id, text='Done!', parse_mode='HTML') + + +bot.polling(skip_pending=True) diff --git a/examples/asynchronous_telebot/exception_handler.py b/examples/asynchronous_telebot/exception_handler.py new file mode 100644 index 0000000..f1da60f --- /dev/null +++ b/examples/asynchronous_telebot/exception_handler.py @@ -0,0 +1,27 @@ + +import telebot +from telebot.async_telebot import AsyncTeleBot + + +import logging + +logger = telebot.logger +telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console. + +class ExceptionHandler(telebot.ExceptionHandler): + def handle(self, exception): + logger.error(exception) + +bot = AsyncTeleBot('TOKEN',exception_handler=ExceptionHandler()) + + + + +@bot.message_handler(commands=['photo']) +async def photo_send(message: telebot.types.Message): + await bot.send_message(message.chat.id, 'Hi, this is an example of exception handlers.') + raise Exception('test') # Exception goes to ExceptionHandler if it is set + + + +bot.polling(skip_pending=True) diff --git a/examples/asynchronous_telebot/middleware/flooding_middleware.py b/examples/asynchronous_telebot/middleware/flooding_middleware.py new file mode 100644 index 0000000..de70702 --- /dev/null +++ b/examples/asynchronous_telebot/middleware/flooding_middleware.py @@ -0,0 +1,39 @@ +# Just a little example of middleware handlers + +import telebot +from telebot.asyncio_handler_backends import BaseMiddleware +from telebot.async_telebot import AsyncTeleBot +from telebot.async_telebot import CancelUpdate +bot = AsyncTeleBot('TOKEN') + + +class SimpleMiddleware(BaseMiddleware): + def __init__(self, limit) -> None: + self.last_time = {} + self.limit = limit + self.update_types = ['message'] + # Always specify update types, otherwise middlewares won't work + + + async def pre_process(self, message, data): + if not message.from_user.id in self.last_time: + # User is not in a dict, so lets add and cancel this function + self.last_time[message.from_user.id] = message.date + return + if message.date - self.last_time[message.from_user.id] < self.limit: + # User is flooding + await bot.send_message(message.chat.id, 'You are making request too often') + return CancelUpdate() + self.last_time[message.from_user.id] = message.date + + + async def post_process(self, message, data, exception): + pass + +bot.setup_middleware(SimpleMiddleware(2)) + +@bot.message_handler(commands=['start']) +async def start(message): + await bot.send_message(message.chat.id, 'Hello!') + +bot.polling() \ No newline at end of file diff --git a/examples/asynchronous_telebot/middleware/i18n.py b/examples/asynchronous_telebot/middleware/i18n.py new file mode 100644 index 0000000..3c3196e --- /dev/null +++ b/examples/asynchronous_telebot/middleware/i18n.py @@ -0,0 +1,48 @@ +#!/usr/bin/python + +# This example shows how to implement i18n (internationalization) l10n (localization) to create +# multi-language bots with middleware handler. +# +# Also, you could check language code in handler itself too. +# But this example just to show the work of middlewares. + +import telebot +from telebot.async_telebot import AsyncTeleBot +from telebot import asyncio_handler_backends +import logging + +logger = telebot.logger +telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console. + +TRANSLATIONS = { + 'hello': { + 'en': 'hello', + 'ru': 'привет', + 'uz': 'salom' + } +} + + + +bot = AsyncTeleBot('TOKEN') + + +class LanguageMiddleware(asyncio_handler_backends.BaseMiddleware): + def __init__(self): + self.update_types = ['message'] # Update types that will be handled by this middleware. + async def pre_process(self, message, data): + data['response'] = TRANSLATIONS['hello'][message.from_user.language_code] + async def post_process(self, message, data, exception): + if exception: # You can get exception occured in handler. + logger.exception(str(exception)) + +bot.setup_middleware(LanguageMiddleware()) # do not forget to setup + +@bot.message_handler(commands=['start']) +async def start(message, data: dict): + # you can get the data in handler too. + # Not necessary to create data parameter in handler function. + await bot.send_message(message.chat.id, data['response']) + + +bot.polling() diff --git a/examples/asynchronous_telebot/send_file_example.py b/examples/asynchronous_telebot/send_file_example.py new file mode 100644 index 0000000..64e3047 --- /dev/null +++ b/examples/asynchronous_telebot/send_file_example.py @@ -0,0 +1,27 @@ + +import telebot +from telebot.async_telebot import AsyncTeleBot + + + +bot = AsyncTeleBot('1297441208:AAH-Z-YbiK_pQ1jTuHXYa-hA_PLZQVQ6qsw') + + +@bot.message_handler(commands=['photo']) +async def photo_send(message: telebot.types.Message): + with open('test.png', 'rb') as new_file: + await bot.send_photo(message.chat.id, new_file) + +@bot.message_handler(commands=['document']) +async def document_send(message: telebot.types.Message): + with open('test.docx', 'rb') as new_file: + await bot.send_document(message.chat.id, new_file) + +@bot.message_handler(commands=['photos']) +async def photos_send(message: telebot.types.Message): + with open('test.png', 'rb') as new_file, open('test2.png', 'rb') as new_file2: + await bot.send_media_group(message.chat.id, [telebot.types.InputMediaPhoto(new_file), telebot.types.InputMediaPhoto(new_file2)]) + + + +bot.polling(skip_pending=True) From 3035763277f9729ec28ef0c41f217a847029afad Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:22:00 +0500 Subject: [PATCH 331/350] Update send_file_example.py --- examples/asynchronous_telebot/send_file_example.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/asynchronous_telebot/send_file_example.py b/examples/asynchronous_telebot/send_file_example.py index 64e3047..e67f8d8 100644 --- a/examples/asynchronous_telebot/send_file_example.py +++ b/examples/asynchronous_telebot/send_file_example.py @@ -4,7 +4,7 @@ from telebot.async_telebot import AsyncTeleBot -bot = AsyncTeleBot('1297441208:AAH-Z-YbiK_pQ1jTuHXYa-hA_PLZQVQ6qsw') +bot = AsyncTeleBot('TOKEN') @bot.message_handler(commands=['photo']) From 60294d0c4142273455cdb15c51bc4607a7f71634 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:22:44 +0500 Subject: [PATCH 332/350] Update README.md --- README.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/README.md b/README.md index 492a1bf..ebd37a7 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ * [Proxy](#proxy) * [Testing](#testing) * [API conformance](#api-conformance) + * [Asynchronous TeleBot](#asynctelebot) * [F.A.Q.](#faq) * [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat) * [How can I handle reocurring ConnectionResetErrors?](#how-can-i-handle-reocurring-connectionreseterrors) @@ -712,6 +713,52 @@ Result will be: * ✔ [Bot API 2.0](https://core.telegram.org/bots/api-changelog#april-9-2016) +## AsyncTeleBot +### Asynchronous version of telebot +We have a fully asynchronous version of TeleBot. +This class is not controlled by threads. Asyncio tasks are created to execute all the stuff. + +### EchoBot +Echo Bot example on AsyncTeleBot: + +```python +# This is a simple echo bot using the decorator mechanism. +# It echoes any incoming text messages. + +from telebot.async_telebot import AsyncTeleBot +bot = AsyncTeleBot('TOKEN') + + + +# Handle '/start' and '/help' +@bot.message_handler(commands=['help', 'start']) +async def send_welcome(message): + await bot.reply_to(message, """\ +Hi there, I am EchoBot. +I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\ +""") + + +# Handle all other messages with content_type 'text' (content_types defaults to ['text']) +@bot.message_handler(func=lambda message: True) +async def echo_message(message): + await bot.reply_to(message, message.text) + + +bot.polling() +``` +As you can see here, keywords are await and async. + +### Why should I use async? +Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other. + +### Differences in AsyncTeleBot +AsyncTeleBot has different middlewares. See example on [middlewares](https://github.com/coder2020official/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) + +### Examples +See more examples in our [examples](https://github.com/coder2020official/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) folder + + ## F.A.Q. ### How can I distinguish a User and a GroupChat in message.chat? From bbe4a96984dc173a74dec0c8484576e27c937c11 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:23:23 +0500 Subject: [PATCH 333/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ebd37a7..995abb6 100644 --- a/README.md +++ b/README.md @@ -753,7 +753,7 @@ As you can see here, keywords are await and async. Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other. ### Differences in AsyncTeleBot -AsyncTeleBot has different middlewares. See example on [middlewares](https://github.com/coder2020official/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) +AsyncTeleBot has different middlewares. See example on [middlewares](https://github.com/coder2020official/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot/middleware) ### Examples See more examples in our [examples](https://github.com/coder2020official/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) folder From 482589af4935d8425f32379106ec38ddae9123db Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:25:14 +0500 Subject: [PATCH 334/350] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 995abb6..7e1d499 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ #

pyTelegramBotAPI

A simple, but extensible Python implementation for the Telegram Bot API. +

Supports both sync and async ways.. ##

Supported Bot API version: 5.4! From f4b9480588ddc44bcc4e862423eb1fe993f9fc69 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:25:47 +0500 Subject: [PATCH 335/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7e1d499..d1b13d0 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ #

pyTelegramBotAPI

A simple, but extensible Python implementation for the Telegram Bot API. -

Supports both sync and async ways.. +

Supports both sync and async ways. ##

Supported Bot API version: 5.4! From a2822c74ed04375518eb15ec0ae40952d2f7e533 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:34:15 +0500 Subject: [PATCH 336/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d1b13d0..ce33584 100644 --- a/README.md +++ b/README.md @@ -558,7 +558,7 @@ apihelper.API_URL = "http://localhost:4200/bot{0}/{1}" *Note: 4200 is an example port* ### Asynchronous TeleBot -New: There is an asynchronous implementation of telebot. It is more flexible. +New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot. ```python tb = telebot.AsyncTeleBot("TOKEN") From e2dbb884596572cff2f08ef336cae1bff3f664a3 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 4 Dec 2021 19:41:25 +0300 Subject: [PATCH 337/350] Readme minor fixed --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index d1b13d0..7570e81 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ #

pyTelegramBotAPI

A simple, but extensible Python implementation for the Telegram Bot API. -

Supports both sync and async ways. +Supports both sync and async ways.

##

Supported Bot API version: 5.4! @@ -53,7 +53,7 @@ * [Proxy](#proxy) * [Testing](#testing) * [API conformance](#api-conformance) - * [Asynchronous TeleBot](#asynctelebot) + * [AsyncTeleBot](#asynctelebot) * [F.A.Q.](#faq) * [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat) * [How can I handle reocurring ConnectionResetErrors?](#how-can-i-handle-reocurring-connectionreseterrors) @@ -184,8 +184,8 @@ TeleBot supports the following filters: |content_types|list of strings (default `['text']`)|`True` if message.content_type is in the list of strings.| |regexp|a regular expression as a string|`True` if `re.search(regexp_arg)` returns `True` and `message.content_type == 'text'` (See [Python Regular Expressions](https://docs.python.org/2/library/re.html))| |commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.| -|chat_types|list of chat types|`True` if `message.chat.type` in your filter -|func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` +|chat_types|list of chat types|`True` if `message.chat.type` in your filter| +|func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True`| Here are some examples of using the filters and message handlers: @@ -376,8 +376,8 @@ bot.add_custom_filter(IsAdmin()) # Now, you can use it in handler. @bot.message_handler(is_admin=True) def admin_of_group(message): - bot.send_message(message.chat.id, 'You are admin of this group'!) - + bot.send_message(message.chat.id, 'You are admin of this group!') + ``` @@ -558,7 +558,7 @@ apihelper.API_URL = "http://localhost:4200/bot{0}/{1}" *Note: 4200 is an example port* ### Asynchronous TeleBot -New: There is an asynchronous implementation of telebot. It is more flexible. +New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot. ```python tb = telebot.AsyncTeleBot("TOKEN") @@ -572,8 +572,8 @@ tb = telebot.AsyncTeleBot("TOKEN") @tb.message_handler(commands=['start']) async def start_message(message): - await bot.send_message(message.chat.id, 'Hello'!) - + await bot.send_message(message.chat.id, 'Hello!') + ``` See more in [examples](https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) @@ -769,7 +769,7 @@ Telegram Bot API support new type Chat for message.chat. - ```python if message.chat.type == "private": - # private chat message + # private chat message if message.chat.type == "group": # group chat message From 6cca77f755dcb591801bb503a6cd9590255dfd73 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 4 Dec 2021 19:43:01 +0300 Subject: [PATCH 338/350] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7570e81..d393e3b 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ #

pyTelegramBotAPI -

A simple, but extensible Python implementation for the Telegram Bot API. -Supports both sync and async ways.

+

A simple, but extensible Python implementation for the Telegram Bot API

. +

Supports both sync and async ways.

-##

Supported Bot API version: 5.4! +##

Supporting Bot API version: 5.4! ## Contents From f224069a34025717eb7501a421941c8804eafd47 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 4 Dec 2021 19:43:33 +0300 Subject: [PATCH 339/350] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d393e3b..5d62908 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ #

pyTelegramBotAPI -

A simple, but extensible Python implementation for the Telegram Bot API

. +

A simple, but extensible Python implementation for the Telegram Bot API.

Supports both sync and async ways.

##

Supporting Bot API version: 5.4! From fb52137bff4e27bd398f05296a411020855c00be Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:54:26 +0500 Subject: [PATCH 340/350] 2 new examples --- .../CallbackData_example.py | 87 +++++++++++++++++++ .../asynchronous_telebot/update_listener.py | 14 +++ 2 files changed, 101 insertions(+) create mode 100644 examples/asynchronous_telebot/CallbackData_example.py create mode 100644 examples/asynchronous_telebot/update_listener.py diff --git a/examples/asynchronous_telebot/CallbackData_example.py b/examples/asynchronous_telebot/CallbackData_example.py new file mode 100644 index 0000000..0386bec --- /dev/null +++ b/examples/asynchronous_telebot/CallbackData_example.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +""" +This Example will show you how to use CallbackData +""" + +from telebot.callback_data import CallbackData, CallbackDataFilter +from telebot import types +from telebot.async_telebot import AsyncTeleBot +from telebot.asyncio_filters import AdvancedCustomFilter + +API_TOKEN = 'TOKEN' +PRODUCTS = [ + {'id': '0', 'name': 'xiaomi mi 10', 'price': 400}, + {'id': '1', 'name': 'samsung s20', 'price': 800}, + {'id': '2', 'name': 'iphone 13', 'price': 1300} +] + +bot = AsyncTeleBot(API_TOKEN) +products_factory = CallbackData('product_id', prefix='products') + + +def products_keyboard(): + return types.InlineKeyboardMarkup( + keyboard=[ + [ + types.InlineKeyboardButton( + text=product['name'], + callback_data=products_factory.new(product_id=product["id"]) + ) + ] + for product in PRODUCTS + ] + ) + + +def back_keyboard(): + return types.InlineKeyboardMarkup( + keyboard=[ + [ + types.InlineKeyboardButton( + text='⬅', + callback_data='back' + ) + ] + ] + ) + + +class ProductsCallbackFilter(AdvancedCustomFilter): + key = 'config' + + async def check(self, call: types.CallbackQuery, config: CallbackDataFilter): + return config.check(query=call) + + +@bot.message_handler(commands=['products']) +async def products_command_handler(message: types.Message): + await bot.send_message(message.chat.id, 'Products:', reply_markup=products_keyboard()) + + +# Only product with field - product_id = 2 +@bot.callback_query_handler(func=None, config=products_factory.filter(product_id='2')) +async def product_one_callback(call: types.CallbackQuery): + await bot.answer_callback_query(callback_query_id=call.id, text='Not available :(', show_alert=True) + + +# Any other products +@bot.callback_query_handler(func=None, config=products_factory.filter()) +async def products_callback(call: types.CallbackQuery): + callback_data: dict = products_factory.parse(callback_data=call.data) + product_id = int(callback_data['product_id']) + product = PRODUCTS[product_id] + + text = f"Product name: {product['name']}\n" \ + f"Product price: {product['price']}" + await bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, + text=text, reply_markup=back_keyboard()) + + +@bot.callback_query_handler(func=lambda c: c.data == 'back') +async def back_callback(call: types.CallbackQuery): + await bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, + text='Products:', reply_markup=products_keyboard()) + + +bot.add_custom_filter(ProductsCallbackFilter()) +bot.polling() diff --git a/examples/asynchronous_telebot/update_listener.py b/examples/asynchronous_telebot/update_listener.py new file mode 100644 index 0000000..75488cf --- /dev/null +++ b/examples/asynchronous_telebot/update_listener.py @@ -0,0 +1,14 @@ +from telebot.async_telebot import AsyncTeleBot + +# Update listeners are functions that are called when any update is received. + +bot = AsyncTeleBot(token='TOKEN') + +async def update_listener(messages): + for message in messages: + if message.text == '/start': + await bot.send_message(message.chat.id, 'Hello!') + +bot.set_update_listener(update_listener) + +bot.polling() \ No newline at end of file From a5ee5f816c7ac32872fc98b5db1af06f55c901aa Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 21:57:16 +0500 Subject: [PATCH 341/350] Update README.md --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index ce33584..5d62908 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ #

pyTelegramBotAPI -

A simple, but extensible Python implementation for the Telegram Bot API. -

Supports both sync and async ways. +

A simple, but extensible Python implementation for the Telegram Bot API.

+

Supports both sync and async ways.

-##

Supported Bot API version: 5.4! +##

Supporting Bot API version: 5.4! ## Contents @@ -53,7 +53,7 @@ * [Proxy](#proxy) * [Testing](#testing) * [API conformance](#api-conformance) - * [Asynchronous TeleBot](#asynctelebot) + * [AsyncTeleBot](#asynctelebot) * [F.A.Q.](#faq) * [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat) * [How can I handle reocurring ConnectionResetErrors?](#how-can-i-handle-reocurring-connectionreseterrors) @@ -184,8 +184,8 @@ TeleBot supports the following filters: |content_types|list of strings (default `['text']`)|`True` if message.content_type is in the list of strings.| |regexp|a regular expression as a string|`True` if `re.search(regexp_arg)` returns `True` and `message.content_type == 'text'` (See [Python Regular Expressions](https://docs.python.org/2/library/re.html))| |commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.| -|chat_types|list of chat types|`True` if `message.chat.type` in your filter -|func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True` +|chat_types|list of chat types|`True` if `message.chat.type` in your filter| +|func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True`| Here are some examples of using the filters and message handlers: @@ -376,8 +376,8 @@ bot.add_custom_filter(IsAdmin()) # Now, you can use it in handler. @bot.message_handler(is_admin=True) def admin_of_group(message): - bot.send_message(message.chat.id, 'You are admin of this group'!) - + bot.send_message(message.chat.id, 'You are admin of this group!') + ``` @@ -572,8 +572,8 @@ tb = telebot.AsyncTeleBot("TOKEN") @tb.message_handler(commands=['start']) async def start_message(message): - await bot.send_message(message.chat.id, 'Hello'!) - + await bot.send_message(message.chat.id, 'Hello!') + ``` See more in [examples](https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples/asynchronous_telebot) @@ -769,7 +769,7 @@ Telegram Bot API support new type Chat for message.chat. - ```python if message.chat.type == "private": - # private chat message + # private chat message if message.chat.type == "group": # group chat message From 4f198bc6f59c5545a1515e470eb343b004c26322 Mon Sep 17 00:00:00 2001 From: _run Date: Sat, 4 Dec 2021 22:03:14 +0500 Subject: [PATCH 342/350] Forgot to update file --- telebot/async_telebot.py | 33 ++++++++++++++++++--------- telebot/asyncio_helper.py | 47 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 67 insertions(+), 13 deletions(-) diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 9f24d90..e7221bc 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -97,16 +97,15 @@ class AsyncTeleBot: def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, - exception_handler=None,suppress_middleware_excepions=False) -> None: # TODO: ADD TYPEHINTS + exception_handler=None) -> None: # TODO: ADD TYPEHINTS self.token = token self.offset = offset self.token = token self.parse_mode = parse_mode self.update_listener = [] - self.suppress_middleware_excepions = suppress_middleware_excepions - self.exc_info = None + self.exception_handler = exception_handler @@ -234,13 +233,23 @@ class AsyncTeleBot: try: updates = await self.get_updates(offset=self.offset, allowed_updates=allowed_updates, timeout=timeout, request_timeout=request_timeout) + if updates: + self.offset = updates[-1].update_id + 1 + self._loop_create_task(self.process_new_updates(updates)) # Seperate task for processing updates + if interval: await asyncio.sleep(interval) + + except KeyboardInterrupt: + return except asyncio.CancelledError: return except asyncio_helper.ApiTelegramException as e: logger.error(str(e)) - continue + if non_stop: + continue + else: + break except Exception as e: logger.error('Cause exception while getting updates.') if non_stop: @@ -249,10 +258,6 @@ class AsyncTeleBot: continue else: raise e - if updates: - self.offset = updates[-1].update_id + 1 - self._loop_create_task(self.process_new_updates(updates)) # Seperate task for processing updates - if interval: await asyncio.sleep(interval) finally: self._polling = False @@ -297,7 +302,12 @@ class AsyncTeleBot: break except Exception as e: handler_error = e - logger.info(str(e)) + + if not middleware: + if self.exception_handler: + return self.exception_handler.handle(e) + logging.error(str(e)) + return if middleware: await middleware.post_process(message, data, handler_error) @@ -448,7 +458,7 @@ class AsyncTeleBot: if len(self.update_listener) == 0: return for listener in self.update_listener: - self._loop_create_task(listener, new_messages) + self._loop_create_task(listener(new_messages)) async def _test_message_handler(self, message_handler, message): """ @@ -466,6 +476,9 @@ class AsyncTeleBot: return True + def set_update_listener(self, func): + self.update_listener.append(func) + def add_custom_filter(self, custom_filter): """ Create custom filter. diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py index 3d1189d..3a765de 100644 --- a/telebot/asyncio_helper.py +++ b/telebot/asyncio_helper.py @@ -8,7 +8,7 @@ try: import ujson as json except ImportError: import json - +import os API_URL = 'https://api.telegram.org/bot{0}/{1}' from datetime import datetime @@ -42,14 +42,55 @@ RETRY_TIMEOUT = 2 MAX_RETRIES = 15 async def _process_request(token, url, method='get', params=None, files=None, request_timeout=None): + params = compose_data(params, files) async with await session_manager._get_new_session() as session: - async with session.get(API_URL.format(token, url), params=params, data=files, timeout=request_timeout) as response: + async with session.request(method=method, url=API_URL.format(token, url), data=params, timeout=request_timeout) as response: logger.debug("Request: method={0} url={1} params={2} files={3} request_timeout={4}".format(method, url, params, files, request_timeout).replace(token, token.split(':')[0] + ":{TOKEN}")) json_result = await _check_result(url, response) if json_result: return json_result['result'] +def guess_filename(obj): + """ + Get file name from object + + :param obj: + :return: + """ + name = getattr(obj, 'name', None) + if name and isinstance(name, str) and name[0] != '<' and name[-1] != '>': + return os.path.basename(name) + + +def compose_data(params=None, files=None): + """ + Prepare request data + + :param params: + :param files: + :return: + """ + data = aiohttp.formdata.FormData(quote_fields=False) + + if params: + for key, value in params.items(): + data.add_field(key, str(value)) + + if files: + for key, f in files.items(): + if isinstance(f, tuple): + if len(f) == 2: + filename, fileobj = f + else: + raise ValueError('Tuple must have exactly 2 elements: filename, fileobj') + else: + filename, fileobj = guess_filename(f) or key, f + + data.add_field(key, fileobj, filename=filename) + + return data + async def _convert_markup(markup): if isinstance(markup, types.JsonSerializable): return markup.to_json() @@ -731,7 +772,7 @@ async def send_audio(token, chat_id, audio, caption=None, duration=None, perform async def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None, allow_sending_without_reply=None, disable_content_type_detection=None, visible_file_name=None): - method_url = get_method_by_type(data_type) + method_url = await get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None if not util.is_string(data): From fbf34f59533fb2175c052718a6b4b0aa10e2b381 Mon Sep 17 00:00:00 2001 From: Badiboy Date: Sat, 4 Dec 2021 20:25:39 +0300 Subject: [PATCH 343/350] Bump version to 4.2.1 - AsyncTeleBot alpha --- telebot/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telebot/version.py b/telebot/version.py index 24f8550..9011d0c 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '4.2.0' +__version__ = '4.2.1' From 038be81db360357567c0718aad4294d5f9bf83c4 Mon Sep 17 00:00:00 2001 From: _run Date: Tue, 7 Dec 2021 22:17:51 +0500 Subject: [PATCH 344/350] 5.5 --- telebot/__init__.py | 35 +++++++++++++++++++++++++++++++++++ telebot/apihelper.py | 14 ++++++++++++++ telebot/async_telebot.py | 34 ++++++++++++++++++++++++++++++++++ telebot/asyncio_helper.py | 13 +++++++++++++ telebot/types.py | 17 +++++++++++++---- 5 files changed, 109 insertions(+), 4 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index 6f29f86..f30a9db 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1667,6 +1667,41 @@ class TeleBot: """ return apihelper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) + + def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str], + until_date:Optional[Union[int, datetime]]=None) -> bool: + """ + Use this method to ban a channel chat in a supergroup or a channel. + The owner of the chat will not be able to send messages and join live + streams on behalf of the chat, unless it is unbanned first. + The bot must be an administrator in the supergroup or channel + for this to work and must have the appropriate administrator rights. + Returns True on success. + + :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 + :param until_date: Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days + or less than 30 seconds from the current time they are considered to be banned forever. + :return: True on success. + """ + return apihelper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id, until_date) + + def unban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str]) -> bool: + """ + Use this method to unban a previously banned channel chat in a supergroup or channel. + The bot must be an administrator for this to work and must have the appropriate + administrator rights. + Returns True on success. + + :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 + :return: True on success. + """ + return apihelper.unban_chat_sender_chat(self.token, chat_id, sender_chat_id) + + def set_chat_permissions( self, chat_id: Union[int, str], permissions: types.ChatPermissions) -> bool: """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 0ca982e..6a38b67 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -969,6 +969,20 @@ def set_chat_administrator_custom_title(token, chat_id, user_id, custom_title): return _make_request(token, method_url, params=payload, method='post') +def ban_chat_sender_chat(token, chat_id, sender_chat_id, until_date=None): + method_url = 'banChatSenderChat' + payload = {'chat_id': chat_id, 'sender_chat_id': sender_chat_id} + if until_date: + payload['until_date'] = until_date + return _make_request(token, method_url, params=payload, method='post') + + +def unban_chat_sender_chat(token, chat_id, sender_chat_id): + method_url = 'unbanChatSenderChat' + payload = {'chat_id': chat_id, 'sender_chat_id': sender_chat_id} + return _make_request(token, method_url, params=payload, method='post') + + def set_chat_permissions(token, chat_id, permissions): method_url = 'setChatPermissions' payload = { diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index e7221bc..176d2b9 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -2135,6 +2135,40 @@ class AsyncTeleBot: """ return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) + + async def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str], + until_date:Optional[Union[int, datetime]]=None) -> bool: + """ + Use this method to ban a channel chat in a supergroup or a channel. + The owner of the chat will not be able to send messages and join live + streams on behalf of the chat, unless it is unbanned first. + The bot must be an administrator in the supergroup or channel + for this to work and must have the appropriate administrator rights. + Returns True on success. + + :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 + :param until_date: Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days + or less than 30 seconds from the current time they are considered to be banned forever. + :return: True on success. + """ + return await asyncio_helper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id, until_date) + + async def unban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str]) -> bool: + """ + Use this method to unban a previously banned channel chat in a supergroup or channel. + The bot must be an administrator for this to work and must have the appropriate + administrator rights. + Returns True on success. + + :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 + :return: True on success. + """ + 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: """ diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py index 3a765de..1fcf47f 100644 --- a/telebot/asyncio_helper.py +++ b/telebot/asyncio_helper.py @@ -912,6 +912,19 @@ async def set_chat_administrator_custom_title(token, chat_id, user_id, custom_ti return await _process_request(token, method_url, params=payload, method='post') +async def ban_chat_sender_chat(token, chat_id, sender_chat_id, until_date=None): + method_url = 'banChatSenderChat' + payload = {'chat_id': chat_id, 'sender_chat_id': sender_chat_id} + if until_date: + payload['until_date'] = until_date + return await _process_request(token, method_url, params=payload, method='post') + + +async def unban_chat_sender_chat(token, chat_id, sender_chat_id): + method_url = 'unbanChatSenderChat' + payload = {'chat_id': chat_id, 'sender_chat_id': sender_chat_id} + return await _process_request(token, method_url, params=payload, method='post') + async def set_chat_permissions(token, chat_id, permissions): method_url = 'setChatPermissions' payload = { diff --git a/telebot/types.py b/telebot/types.py index 263b327..eb3fabf 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -274,10 +274,11 @@ class Chat(JsonDeserializable): return cls(**obj) def __init__(self, id, type, title=None, username=None, first_name=None, - last_name=None, photo=None, bio=None, description=None, invite_link=None, - pinned_message=None, permissions=None, slow_mode_delay=None, - message_auto_delete_time=None, sticker_set_name=None, can_set_sticker_set=None, - linked_chat_id=None, location=None, **kwargs): + last_name=None, photo=None, bio=None, has_private_forwards=None, + description=None, invite_link=None, pinned_message=None, + permissions=None, slow_mode_delay=None, + message_auto_delete_time=None, has_protected_content=None, sticker_set_name=None, + can_set_sticker_set=None, linked_chat_id=None, location=None, **kwargs): self.id: int = id self.type: str = type self.title: str = title @@ -286,12 +287,14 @@ class Chat(JsonDeserializable): self.last_name: str = last_name self.photo: ChatPhoto = photo self.bio: str = bio + self.has_private_forwards: bool = has_private_forwards self.description: str = description self.invite_link: str = invite_link self.pinned_message: Message = pinned_message self.permissions: ChatPermissions = permissions self.slow_mode_delay: int = slow_mode_delay self.message_auto_delete_time: int = message_auto_delete_time + self.has_protected_content: bool = has_protected_content self.sticker_set_name: str = sticker_set_name self.can_set_sticker_set: bool = can_set_sticker_set self.linked_chat_id: int = linked_chat_id @@ -334,12 +337,16 @@ class Message(JsonDeserializable): opts['forward_sender_name'] = obj.get('forward_sender_name') if 'forward_date' in obj: opts['forward_date'] = obj.get('forward_date') + if 'is_automatic_forward' in obj: + opts['is_automatic_forward'] = obj.get('is_automatic_forward') if 'reply_to_message' in obj: opts['reply_to_message'] = Message.de_json(obj['reply_to_message']) if 'via_bot' in obj: opts['via_bot'] = User.de_json(obj['via_bot']) if 'edit_date' in obj: opts['edit_date'] = obj.get('edit_date') + if 'has_protected_content' in obj: + opts['has_protected_content'] = obj.get('has_protected_content') if 'media_group_id' in obj: opts['media_group_id'] = obj.get('media_group_id') if 'author_signature' in obj: @@ -503,9 +510,11 @@ class Message(JsonDeserializable): self.forward_signature: Optional[str] = None self.forward_sender_name: Optional[str] = None self.forward_date: Optional[int] = None + self.is_automatic_forward: Optional[bool] = None self.reply_to_message: Optional[Message] = None self.via_bot: Optional[User] = None self.edit_date: Optional[int] = None + self.has_protected_content: Optional[bool] = None self.media_group_id: Optional[str] = None self.author_signature: Optional[str] = None self.text: Optional[str] = None From 5a03ab62d069546e3a17726063d39d7f4278afb8 Mon Sep 17 00:00:00 2001 From: _run Date: Tue, 7 Dec 2021 22:27:19 +0500 Subject: [PATCH 345/350] Update test_types.py --- tests/test_types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_types.py b/tests/test_types.py index 7f9b32f..4a580eb 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -50,7 +50,7 @@ def test_json_message_with_dice(): def test_json_message_group(): - json_string = r'{"message_id":10,"from":{"id":12345,"first_name":"g","last_name":"G","username":"GG","is_bot":true},"chat":{"id":-866,"type":"private","title":"\u4ea4"},"date":1435303157,"text":"HIHI"}' + json_string = r'{"message_id":10,"from":{"id":12345,"first_name":"g","last_name":"G","username":"GG","is_bot":true},"chat":{"id":-866,"type":"private","title":"\u4ea4"},"date":1435303157,"text":"HIHI","has_protected_content":true}' msg = types.Message.de_json(json_string) assert msg.text == 'HIHI' assert len(msg.chat.title) != 0 From 555257a3fe3309fadb1508f4b91e6d9105ec0392 Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 8 Dec 2021 14:00:39 +0500 Subject: [PATCH 346/350] Documentation Bug fixed --- telebot/__init__.py | 5 ++--- telebot/apihelper.py | 4 +--- telebot/async_telebot.py | 5 ++--- telebot/asyncio_helper.py | 4 +--- 4 files changed, 6 insertions(+), 12 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index f30a9db..d1ff2c2 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1668,8 +1668,7 @@ class TeleBot: return apihelper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) - def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str], - until_date:Optional[Union[int, datetime]]=None) -> bool: + def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str]) -> bool: """ Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live @@ -1685,7 +1684,7 @@ class TeleBot: or less than 30 seconds from the current time they are considered to be banned forever. :return: True on success. """ - return apihelper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id, until_date) + return apihelper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id) def unban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str]) -> bool: """ diff --git a/telebot/apihelper.py b/telebot/apihelper.py index 6a38b67..229fa78 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -969,11 +969,9 @@ def set_chat_administrator_custom_title(token, chat_id, user_id, custom_title): return _make_request(token, method_url, params=payload, method='post') -def ban_chat_sender_chat(token, chat_id, sender_chat_id, until_date=None): +def ban_chat_sender_chat(token, chat_id, sender_chat_id): method_url = 'banChatSenderChat' payload = {'chat_id': chat_id, 'sender_chat_id': sender_chat_id} - if until_date: - payload['until_date'] = until_date return _make_request(token, method_url, params=payload, method='post') diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 176d2b9..782ba6d 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -2136,8 +2136,7 @@ class AsyncTeleBot: return await asyncio_helper.set_chat_administrator_custom_title(self.token, chat_id, user_id, custom_title) - async def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str], - until_date:Optional[Union[int, datetime]]=None) -> bool: + async def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str]) -> bool: """ Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live @@ -2153,7 +2152,7 @@ class AsyncTeleBot: or less than 30 seconds from the current time they are considered to be banned forever. :return: True on success. """ - return await asyncio_helper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id, until_date) + return await asyncio_helper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id) async def unban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: Union[int, str]) -> bool: """ diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py index 1fcf47f..0360b09 100644 --- a/telebot/asyncio_helper.py +++ b/telebot/asyncio_helper.py @@ -912,11 +912,9 @@ async def set_chat_administrator_custom_title(token, chat_id, user_id, custom_ti return await _process_request(token, method_url, params=payload, method='post') -async def ban_chat_sender_chat(token, chat_id, sender_chat_id, until_date=None): +async def ban_chat_sender_chat(token, chat_id, sender_chat_id): method_url = 'banChatSenderChat' payload = {'chat_id': chat_id, 'sender_chat_id': sender_chat_id} - if until_date: - payload['until_date'] = until_date return await _process_request(token, method_url, params=payload, method='post') From 08fc32b70a523e98aa93029cfe01700ec4906e92 Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 8 Dec 2021 14:13:39 +0500 Subject: [PATCH 347/350] Comment fix --- telebot/__init__.py | 53 +++++++++++++--------------------- telebot/async_telebot.py | 61 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 35 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index d1ff2c2..acea58b 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -75,74 +75,59 @@ class TeleBot: logOut close sendMessage + Formatting options forwardMessage copyMessage - deleteMessage sendPhoto sendAudio sendDocument - sendSticker sendVideo - sendVenue sendAnimation + sendVoice sendVideoNote - sendLocation - sendChatAction - sendDice - sendContact - sendInvoice sendMediaGroup - getUserProfilePhotos - getUpdates - getFile - sendPoll - stopPoll - sendGame - setGameScore - getGameHighScores - editMessageText - editMessageCaption - editMessageMedia - editMessageReplyMarkup + sendLocation editMessageLiveLocation stopMessageLiveLocation + sendVenue + sendContact + sendPoll + sendDice + sendChatAction + getUserProfilePhotos + getFile banChatMember unbanChatMember restrictChatMember promoteChatMember setChatAdministratorCustomTitle + banChatSenderChat + unbanChatSenderChat setChatPermissions + exportChatInviteLink createChatInviteLink editChatInviteLink revokeChatInviteLink - exportChatInviteLink - setChatStickerSet - deleteChatStickerSet - createNewStickerSet - addStickerToSet - deleteStickerFromSet - setStickerPositionInSet - uploadStickerFile - setStickerSetThumb - getStickerSet + approveChatJoinRequest + declineChatJoinRequest setChatPhoto deleteChatPhoto setChatTitle setChatDescription pinChatMessage unpinChatMessage + unpinAllChatMessages leaveChat getChat getChatAdministrators getChatMemberCount getChatMember + setChatStickerSet + deleteChatStickerSet answerCallbackQuery - getMyCommands setMyCommands deleteMyCommands - answerInlineQuery - answerShippingQuery - answerPreCheckoutQuery + getMyCommands """ def __init__( diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 782ba6d..a467bfd 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -94,7 +94,66 @@ class CancelUpdate: pass class AsyncTeleBot: - + """ This is AsyncTeleBot Class + Methods: + getMe + logOut + close + sendMessage + Formatting options + forwardMessage + copyMessage + sendPhoto + sendAudio + sendDocument + sendVideo + sendAnimation + sendVoice + sendVideoNote + sendMediaGroup + sendLocation + editMessageLiveLocation + stopMessageLiveLocation + sendVenue + sendContact + sendPoll + sendDice + sendChatAction + getUserProfilePhotos + getFile + banChatMember + unbanChatMember + restrictChatMember + promoteChatMember + setChatAdministratorCustomTitle + banChatSenderChat + unbanChatSenderChat + setChatPermissions + exportChatInviteLink + createChatInviteLink + editChatInviteLink + revokeChatInviteLink + approveChatJoinRequest + declineChatJoinRequest + setChatPhoto + deleteChatPhoto + setChatTitle + setChatDescription + pinChatMessage + unpinChatMessage + unpinAllChatMessages + leaveChat + getChat + getChatAdministrators + getChatMemberCount + getChatMember + setChatStickerSet + deleteChatStickerSet + answerCallbackQuery + setMyCommands + deleteMyCommands + getMyCommands + """ def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, exception_handler=None) -> None: # TODO: ADD TYPEHINTS From 311eec68880e7cbf1dc9288f027c6ae3a525da7f Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 8 Dec 2021 14:15:40 +0500 Subject: [PATCH 348/350] fix --- telebot/__init__.py | 53 ++++++++++++++++++++++++++-------------- telebot/async_telebot.py | 53 ++++++++++++++++++++++++++-------------- 2 files changed, 68 insertions(+), 38 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index acea58b..d1ff2c2 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -75,59 +75,74 @@ class TeleBot: logOut close sendMessage - Formatting options forwardMessage copyMessage + deleteMessage sendPhoto sendAudio sendDocument + sendSticker sendVideo + sendVenue sendAnimation - sendVoice sendVideoNote - sendMediaGroup sendLocation + sendChatAction + sendDice + sendContact + sendInvoice + sendMediaGroup + getUserProfilePhotos + getUpdates + getFile + sendPoll + stopPoll + sendGame + setGameScore + getGameHighScores + editMessageText + editMessageCaption + editMessageMedia + editMessageReplyMarkup editMessageLiveLocation stopMessageLiveLocation - sendVenue - sendContact - sendPoll - sendDice - sendChatAction - getUserProfilePhotos - getFile banChatMember unbanChatMember restrictChatMember promoteChatMember setChatAdministratorCustomTitle - banChatSenderChat - unbanChatSenderChat setChatPermissions - exportChatInviteLink createChatInviteLink editChatInviteLink revokeChatInviteLink - approveChatJoinRequest - declineChatJoinRequest + exportChatInviteLink + setChatStickerSet + deleteChatStickerSet + createNewStickerSet + addStickerToSet + deleteStickerFromSet + setStickerPositionInSet + uploadStickerFile + setStickerSetThumb + getStickerSet setChatPhoto deleteChatPhoto setChatTitle setChatDescription pinChatMessage unpinChatMessage - unpinAllChatMessages leaveChat getChat getChatAdministrators getChatMemberCount getChatMember - setChatStickerSet - deleteChatStickerSet answerCallbackQuery + getMyCommands setMyCommands deleteMyCommands - getMyCommands + answerInlineQuery + answerShippingQuery + answerPreCheckoutQuery """ def __init__( diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index a467bfd..4813f7c 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -100,59 +100,74 @@ class AsyncTeleBot: logOut close sendMessage - Formatting options forwardMessage copyMessage + deleteMessage sendPhoto sendAudio sendDocument + sendSticker sendVideo + sendVenue sendAnimation - sendVoice sendVideoNote - sendMediaGroup sendLocation + sendChatAction + sendDice + sendContact + sendInvoice + sendMediaGroup + getUserProfilePhotos + getUpdates + getFile + sendPoll + stopPoll + sendGame + setGameScore + getGameHighScores + editMessageText + editMessageCaption + editMessageMedia + editMessageReplyMarkup editMessageLiveLocation stopMessageLiveLocation - sendVenue - sendContact - sendPoll - sendDice - sendChatAction - getUserProfilePhotos - getFile banChatMember unbanChatMember restrictChatMember promoteChatMember setChatAdministratorCustomTitle - banChatSenderChat - unbanChatSenderChat setChatPermissions - exportChatInviteLink createChatInviteLink editChatInviteLink revokeChatInviteLink - approveChatJoinRequest - declineChatJoinRequest + exportChatInviteLink + setChatStickerSet + deleteChatStickerSet + createNewStickerSet + addStickerToSet + deleteStickerFromSet + setStickerPositionInSet + uploadStickerFile + setStickerSetThumb + getStickerSet setChatPhoto deleteChatPhoto setChatTitle setChatDescription pinChatMessage unpinChatMessage - unpinAllChatMessages leaveChat getChat getChatAdministrators getChatMemberCount getChatMember - setChatStickerSet - deleteChatStickerSet answerCallbackQuery + getMyCommands setMyCommands deleteMyCommands - getMyCommands + answerInlineQuery + answerShippingQuery + answerPreCheckoutQuery """ def __init__(self, token: str, parse_mode: Optional[str]=None, offset=None, From bb19687854c583c36a6fc0e067be65e93a47673f Mon Sep 17 00:00:00 2001 From: _run Date: Wed, 8 Dec 2021 15:15:57 +0500 Subject: [PATCH 349/350] fix --- telebot/__init__.py | 2 -- telebot/async_telebot.py | 2 -- 2 files changed, 4 deletions(-) diff --git a/telebot/__init__.py b/telebot/__init__.py index d1ff2c2..7104ebb 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -1680,8 +1680,6 @@ class TeleBot: :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 - :param until_date: Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days - or less than 30 seconds from the current time they are considered to be banned forever. :return: True on success. """ return apihelper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id) diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py index 4813f7c..3b8317d 100644 --- a/telebot/async_telebot.py +++ b/telebot/async_telebot.py @@ -2222,8 +2222,6 @@ class AsyncTeleBot: :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 - :param until_date: Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days - or less than 30 seconds from the current time they are considered to be banned forever. :return: True on success. """ return await asyncio_helper.ban_chat_sender_chat(self.token, chat_id, sender_chat_id) From 751deeafd716bf5dc4ad0f22fd5dc370cd4bfe3f Mon Sep 17 00:00:00 2001 From: Badiboy Date: Wed, 8 Dec 2021 23:44:57 +0300 Subject: [PATCH 350/350] Bump version to 4.2.2 --- .travis.yml | 1 - README.md | 17 +++-------------- telebot/version.py | 2 +- 3 files changed, 4 insertions(+), 16 deletions(-) diff --git a/.travis.yml b/.travis.yml index 36dbf89..c4bd8af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ language: python python: - - "3.6" - "3.7" - "3.8" - "3.9" diff --git a/README.md b/README.md index 5d62908..b751585 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

A simple, but extensible Python implementation for the Telegram Bot API.

Supports both sync and async ways.

-##

Supporting Bot API version: 5.4! +##

Supporting Bot API version: 5.5! ## Contents @@ -685,8 +685,9 @@ Result will be: ## API conformance +* ✔ [Bot API 5.5](https://core.telegram.org/bots/api#december-7-2021) * ✔ [Bot API 5.4](https://core.telegram.org/bots/api#november-5-2021) -* ➕ [Bot API 5.3](https://core.telegram.org/bots/api#june-25-2021) - ChatMemberXXX classes are full copies of ChatMember +* ➕ [Bot API 5.3](https://core.telegram.org/bots/api#june-25-2021) - ChatMember* classes are full copies of ChatMember * ✔ [Bot API 5.2](https://core.telegram.org/bots/api#april-26-2021) * ✔ [Bot API 5.1](https://core.telegram.org/bots/api#march-9-2021) * ✔ [Bot API 5.0](https://core.telegram.org/bots/api-changelog#november-4-2020) @@ -700,18 +701,6 @@ Result will be: * ✔ [Bot API 4.2](https://core.telegram.org/bots/api-changelog#april-14-2019) * ➕ [Bot API 4.1](https://core.telegram.org/bots/api-changelog#august-27-2018) - No Passport support * ➕ [Bot API 4.0](https://core.telegram.org/bots/api-changelog#july-26-2018) - No Passport support -* ✔ [Bot API 3.6](https://core.telegram.org/bots/api-changelog#february-13-2018) -* ✔ [Bot API 3.5](https://core.telegram.org/bots/api-changelog#november-17-2017) -* ✔ [Bot API 3.4](https://core.telegram.org/bots/api-changelog#october-11-2017) -* ✔ [Bot API 3.3](https://core.telegram.org/bots/api-changelog#august-23-2017) -* ✔ [Bot API 3.2](https://core.telegram.org/bots/api-changelog#july-21-2017) -* ✔ [Bot API 3.1](https://core.telegram.org/bots/api-changelog#june-30-2017) -* ✔ [Bot API 3.0](https://core.telegram.org/bots/api-changelog#may-18-2017) -* ✔ [Bot API 2.3.1](https://core.telegram.org/bots/api-changelog#december-4-2016) -* ✔ [Bot API 2.3](https://core.telegram.org/bots/api-changelog#november-21-2016) -* ✔ [Bot API 2.2](https://core.telegram.org/bots/api-changelog#october-3-2016) -* ✔ [Bot API 2.1](https://core.telegram.org/bots/api-changelog#may-22-2016) -* ✔ [Bot API 2.0](https://core.telegram.org/bots/api-changelog#april-9-2016) ## AsyncTeleBot diff --git a/telebot/version.py b/telebot/version.py index 9011d0c..468312f 100644 --- a/telebot/version.py +++ b/telebot/version.py @@ -1,3 +1,3 @@ # Versions should comply with PEP440. # This line is parsed in setup.py: -__version__ = '4.2.1' +__version__ = '4.2.2'