diff --git a/README.md b/README.md
index d3664d2c5..2b4b39935 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
-## Supported Bot API version:
+##
Supported Bot API version:
diff --git a/telebot/__init__.py b/telebot/__init__.py
index 40e4c37e6..93fc80320 100644
--- a/telebot/__init__.py
+++ b/telebot/__init__.py
@@ -252,6 +252,8 @@ def __init__(
self.guest_message_handlers = []
self.subscription_handlers = []
self.stopped_message_generation_handlers = []
+ self.widget_query_handlers = []
+ self.shared_widget_query_handlers = []
self.custom_filters = {}
self.state_handlers = []
@@ -287,6 +289,8 @@ def __init__(
'guest_message': [],
'subscription': [],
'stopped_message_generation': [],
+ 'widget_query': [],
+ 'shared_widget_query': [],
}
self.default_middleware_handlers = []
if apihelper.ENABLE_MIDDLEWARE and use_class_middlewares:
@@ -738,6 +742,8 @@ def process_new_updates(self, updates: List[types.Update]):
new_guest_messages = None
new_subscriptions = None
new_stopped_message_generations = None
+ new_widget_queries = None
+ new_shared_widget_queries = None
for update in updates:
if apihelper.ENABLE_MIDDLEWARE and not self.use_class_middlewares:
@@ -834,6 +840,12 @@ def process_new_updates(self, updates: List[types.Update]):
if update.stopped_message_generation:
if new_stopped_message_generations is None: new_stopped_message_generations = []
new_stopped_message_generations.append(update.stopped_message_generation)
+ if update.widget_query:
+ if new_widget_queries is None: new_widget_queries = []
+ new_widget_queries.append(update.widget_query)
+ if update.shared_widget_query:
+ if new_shared_widget_queries is None: new_shared_widget_queries = []
+ new_shared_widget_queries.append(update.shared_widget_query)
if new_messages:
self.process_new_messages(new_messages)
@@ -889,6 +901,10 @@ def process_new_updates(self, updates: List[types.Update]):
self.process_new_managed_bot(new_managed_bots)
if new_guest_messages:
self.process_new_guest_message(new_guest_messages)
+ if new_widget_queries:
+ self.process_new_widget_query(new_widget_queries)
+ if new_shared_widget_queries:
+ self.process_new_shared_widget_query(new_shared_widget_queries)
def process_new_messages(self, new_messages):
"""
@@ -1059,6 +1075,18 @@ def process_new_stopped_message_generation(self, new_stopped_message_generations
'stopped_message_generation',
)
+ def process_new_widget_query(self, new_widget_queries):
+ """
+ :meta private:
+ """
+ self._notify_command_handlers(self.widget_query_handlers, new_widget_queries, 'widget_query')
+
+ def process_new_shared_widget_query(self, new_shared_widget_queries):
+ """
+ :meta private:
+ """
+ self._notify_command_handlers(self.shared_widget_query_handlers, new_shared_widget_queries, 'shared_widget_query')
+
def process_middlewares(self, update):
"""
:meta private:
@@ -1783,7 +1811,7 @@ def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types.ChatM
def send_message(
- self, chat_id: Union[int, str], text: str,
+ self, chat_id: Optional[Union[int, str]], text: str,
parse_mode: Optional[str]=None,
entities: Optional[List[types.MessageEntity]]=None,
disable_web_page_preview: Optional[bool]=None, # deprecated, for backward compatibility
@@ -1813,7 +1841,7 @@ def send_message(
Telegram documentation: https://core.telegram.org/bots/api#sendmessage
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param text: Text of the message to be sent
@@ -2031,7 +2059,7 @@ def copy_message(
message_effect_id: Optional[str]=None) -> types.MessageId:
"""
Use this method to copy messages of any kind.
- Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied.
+ Service messages, paid media messages, giveaway messages, giveaway winners messages, invoice messages, and widget messages can't be copied.
A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method
forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
@@ -2331,7 +2359,7 @@ def copy_messages(self, chat_id: Union[str, int], from_chat_id: Union[str, int],
"""
Use this method to copy messages of any kind.
If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages,
- and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous
+ invoice messages, and widget messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous
to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array
of MessageId of the sent messages is returned.
@@ -2460,6 +2488,279 @@ def edit_message_checklist(
apihelper.edit_message_checklist(
self.token, business_connection_id, chat_id, message_id, checklist, reply_markup=reply_markup))
+ def send_widget(
+ self, chat_id: Union[int, str], html: str,
+ message_thread_id: Optional[int]=None,
+ width: Optional[int]=None,
+ height: Optional[int]=None,
+ public_data: Optional[str]=None,
+ chat_data: Optional[str]=None,
+ caption: Optional[str]=None,
+ parse_mode: Optional[str]=None,
+ caption_entities: Optional[List[types.MessageEntity]]=None,
+ show_caption_above_media: Optional[bool]=None,
+ allow_queries: Optional[bool]=None,
+ is_shared: Optional[bool]=None,
+ disable_notification: Optional[bool]=None,
+ protect_content: Optional[bool]=None,
+ allow_paid_broadcast: Optional[bool]=None,
+ message_effect_id: Optional[str]=None,
+ reply_parameters: Optional[types.ReplyParameters]=None,
+ reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Message:
+ """
+ Use this method to send a message with an HTML widget. Currently, in the production environment, widgets can be sent
+ only to private chats, and sent widgets automatically have protected content and therefore can't be forwarded.
+ On success, the sent Message is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#sendwidget
+
+ :param chat_id: Unique identifier for the target chat or username of the target supergroup in the format @username
+ :type chat_id: :obj:`int` or :obj:`str`
+
+ :param html: HTML code of the widget, 1-32768 bytes. The code must not exceed 4096 bytes when compressed by zlib
+ with the maximum compression level.
+ :type html: :obj:`str`
+
+ :param message_thread_id: Unique identifier for the target message thread (topic) of a forum; for forum supergroups
+ and private chats of bots with forum topic mode enabled only
+ :type message_thread_id: :obj:`int`
+
+ :param width: Width of the widget in logical pixels; omit if the widget must occupy the whole width of the message bubble.
+ The width is clamped by the app to the range from 200 to the maximum width of the message bubble.
+ :type width: :obj:`int`
+
+ :param height: Height of the widget in logical pixels; omit if the height of the widget isn't fixed.
+ The height is clamped by the app to the range 50-600.
+ :type height: :obj:`int`
+
+ :param public_data: Public data of the widget, 0-1024 bytes, which will be available wherever the widget is shown.
+ If the widget is shared, then all messages with it will have the same public data.
+ :type public_data: :obj:`str`
+
+ :param chat_data: Data of the widget, which is specific to the message, 0-1024 bytes
+ :type chat_data: :obj:`str`
+
+ :param caption: Widget caption, 0-1024 characters after entities parsing
+ :type caption: :obj:`str`
+
+ :param parse_mode: Mode for parsing entities in the widget caption
+ :type parse_mode: :obj:`str`
+
+ :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
+ :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
+ :param show_caption_above_media: Pass True if the caption must be shown above the widget
+ :type show_caption_above_media: :obj:`bool`
+
+ :param allow_queries: Pass True to allow the widget to send queries to the bot
+ :type allow_queries: :obj:`bool`
+
+ :param is_shared: Pass True to create a shared widget, which can be sent again using the method sendSharedWidget
+ :type is_shared: :obj:`bool`
+
+ :param disable_notification: Sends the message silently. Users will receive a notification with no sound.
+ :type disable_notification: :obj:`bool`
+
+ :param protect_content: Protects the contents of the sent message from forwarding and saving
+ :type protect_content: :obj:`bool`
+
+ :param allow_paid_broadcast: Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee
+ of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance
+ :type allow_paid_broadcast: :obj:`bool`
+
+ :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only
+ :type message_effect_id: :obj:`str`
+
+ :param reply_parameters: Description of the message to reply to
+ :type reply_parameters: :class:`telebot.types.ReplyParameters`
+
+ :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
+ to remove reply keyboard or to force a reply from the user.
+ :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove`
+ or :class:`telebot.types.ForceReply`
+
+ :return: On success, the sent Message is returned.
+ :rtype: :class:`telebot.types.Message`
+ """
+ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode
+ disable_notification = self.disable_notification if (disable_notification is None) else disable_notification
+ protect_content = self.protect_content if (protect_content is None) else protect_content
+
+ if reply_parameters and (reply_parameters.allow_sending_without_reply is None):
+ reply_parameters.allow_sending_without_reply = self.allow_sending_without_reply
+
+ return types.Message.de_json(
+ apihelper.send_widget(
+ self.token, chat_id, html, message_thread_id=message_thread_id, width=width, height=height,
+ public_data=public_data, chat_data=chat_data, caption=caption, parse_mode=parse_mode,
+ caption_entities=caption_entities, show_caption_above_media=show_caption_above_media,
+ allow_queries=allow_queries, is_shared=is_shared, disable_notification=disable_notification,
+ protect_content=protect_content, allow_paid_broadcast=allow_paid_broadcast,
+ message_effect_id=message_effect_id, reply_parameters=reply_parameters, reply_markup=reply_markup))
+
+ def send_shared_widget(
+ self, chat_id: Union[int, str], widget_id: str,
+ message_thread_id: Optional[int]=None,
+ chat_data: Optional[str]=None,
+ caption: Optional[str]=None,
+ parse_mode: Optional[str]=None,
+ caption_entities: Optional[List[types.MessageEntity]]=None,
+ show_caption_above_media: Optional[bool]=None,
+ disable_notification: Optional[bool]=None,
+ protect_content: Optional[bool]=None,
+ allow_paid_broadcast: Optional[bool]=None,
+ message_effect_id: Optional[str]=None,
+ reply_parameters: Optional[types.ReplyParameters]=None,
+ reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Message:
+ """
+ Use this method to send again a shared widget created by the bot. Currently, in the production environment, widgets can be sent
+ only to private chats, and sent widgets automatically have protected content and therefore can't be forwarded.
+ On success, the sent Message is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#sendsharedwidget
+
+ :param chat_id: Unique identifier for the target chat or username of the target supergroup in the format @username
+ :type chat_id: :obj:`int` or :obj:`str`
+
+ :param widget_id: Unique identifier of the shared widget
+ :type widget_id: :obj:`str`
+
+ :param message_thread_id: Unique identifier for the target message thread (topic) of a forum; for forum supergroups
+ and private chats of bots with forum topic mode enabled only
+ :type message_thread_id: :obj:`int`
+
+ :param chat_data: Data of the widget, which is specific to the message, 0-1024 bytes
+ :type chat_data: :obj:`str`
+
+ :param caption: Widget caption, 0-1024 characters after entities parsing
+ :type caption: :obj:`str`
+
+ :param parse_mode: Mode for parsing entities in the widget caption
+ :type parse_mode: :obj:`str`
+
+ :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
+ :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
+ :param show_caption_above_media: Pass True if the caption must be shown above the widget
+ :type show_caption_above_media: :obj:`bool`
+
+ :param disable_notification: Sends the message silently. Users will receive a notification with no sound.
+ :type disable_notification: :obj:`bool`
+
+ :param protect_content: Protects the contents of the sent message from forwarding and saving
+ :type protect_content: :obj:`bool`
+
+ :param allow_paid_broadcast: Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee
+ of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance
+ :type allow_paid_broadcast: :obj:`bool`
+
+ :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only
+ :type message_effect_id: :obj:`str`
+
+ :param reply_parameters: Description of the message to reply to
+ :type reply_parameters: :class:`telebot.types.ReplyParameters`
+
+ :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
+ to remove reply keyboard or to force a reply from the user.
+ :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove`
+ or :class:`telebot.types.ForceReply`
+
+ :return: On success, the sent Message is returned.
+ :rtype: :class:`telebot.types.Message`
+ """
+ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode
+ disable_notification = self.disable_notification if (disable_notification is None) else disable_notification
+ protect_content = self.protect_content if (protect_content is None) else protect_content
+
+ if reply_parameters and (reply_parameters.allow_sending_without_reply is None):
+ reply_parameters.allow_sending_without_reply = self.allow_sending_without_reply
+
+ return types.Message.de_json(
+ apihelper.send_shared_widget(
+ self.token, chat_id, widget_id, message_thread_id=message_thread_id, chat_data=chat_data,
+ caption=caption, parse_mode=parse_mode, caption_entities=caption_entities,
+ show_caption_above_media=show_caption_above_media, disable_notification=disable_notification,
+ protect_content=protect_content, allow_paid_broadcast=allow_paid_broadcast,
+ message_effect_id=message_effect_id, reply_parameters=reply_parameters, reply_markup=reply_markup))
+
+ def answer_widget_query(self, widget_query_id: str, data: Optional[str]=None) -> bool:
+ """
+ Use this method to send an answer to a query from a widget. The query must be answered within 15 seconds.
+ The answer is received only by the widget that sent the query and doesn't change data of the widget;
+ use editMessageWidgetData or editSharedWidgetData to change it. On success, True is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#answerwidgetquery
+
+ :param widget_query_id: Unique identifier for the query to be answered
+ :type widget_query_id: :obj:`str`
+
+ :param data: Data to be returned to the widget, 0-1024 bytes
+ :type data: :obj:`str`
+
+ :return: On success, True is returned.
+ :rtype: :obj:`bool`
+ """
+ return apihelper.answer_widget_query(self.token, widget_query_id, data=data)
+
+ def edit_message_widget_data(
+ self, chat_id: Optional[Union[int, str]]=None,
+ message_id: Optional[int]=None,
+ inline_message_id: Optional[str]=None,
+ public_data: Optional[str]=None,
+ chat_data: Optional[str]=None) -> bool:
+ """
+ Use this method to edit data of a widget in a message sent by the bot or via the bot (for inline bots).
+ Public data of a shared widget can be changed at most once per second. On success, True is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#editmessagewidgetdata
+
+ :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username
+ of the target supergroup in the format @username.
+ :type chat_id: :obj:`int` or :obj:`str`
+
+ :param message_id: Required if inline_message_id is not specified. Identifier of the message with the widget.
+ :type message_id: :obj:`int`
+
+ :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message.
+ :type inline_message_id: :obj:`str`
+
+ :param public_data: New public data of the widget, 0-1024 bytes; pass an empty string to remove the public data.
+ If omitted, then the public data isn't changed.
+ :type public_data: :obj:`str`
+
+ :param chat_data: New data of the widget, which is specific to the message, 0-1024 bytes; pass an empty string to remove the data.
+ If omitted, then the data isn't changed.
+ :type chat_data: :obj:`str`
+
+ :return: On success, True is returned.
+ :rtype: :obj:`bool`
+ """
+ return apihelper.edit_message_widget_data(
+ self.token, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id,
+ public_data=public_data, chat_data=chat_data)
+
+ def edit_shared_widget_data(self, widget_id: str, public_data: str, cache_time: Optional[int]=None) -> bool:
+ """
+ Use this method to edit public data of a shared widget created by the bot. A shared widget can be edited
+ at most once per second. On success, True is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#editsharedwidgetdata
+
+ :param widget_id: Unique identifier of the shared widget
+ :type widget_id: :obj:`str`
+
+ :param public_data: New public data of the widget, 0-1024 bytes; pass an empty string to remove the public data
+ :type public_data: :obj:`str`
+
+ :param cache_time: The maximum amount of time in seconds that the public data of the widget may be cached client-side; 5-3600.
+ If omitted, then the current value is kept, which is 30 by default.
+ :type cache_time: :obj:`int`
+
+ :return: On success, True is returned.
+ :rtype: :obj:`bool`
+ """
+ return apihelper.edit_shared_widget_data(self.token, widget_id, public_data, cache_time=cache_time)
+
def send_dice(
self, chat_id: Union[int, str],
emoji: Optional[str]=None, disable_notification: Optional[bool]=None,
@@ -2569,7 +2870,7 @@ def send_dice(
def send_photo(
- self, chat_id: Union[int, str], photo: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], photo: Union[Any, str],
caption: Optional[str]=None, parse_mode: Optional[str]=None,
caption_entities: Optional[List[types.MessageEntity]]=None,
disable_notification: Optional[bool]=None,
@@ -2595,7 +2896,7 @@ def send_photo(
Telegram documentation: https://core.telegram.org/bots/api#sendphoto
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended),
@@ -2714,7 +3015,7 @@ def send_photo(
)
def send_live_photo(
- self, chat_id: Union[int, str], live_photo: Union[Any, str], photo: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], live_photo: Union[Any, str], photo: Union[Any, str],
message_thread_id: Optional[int]=None, direct_messages_topic_id: Optional[int]=None,
business_connection_id: Optional[str]=None,
caption: Optional[str]=None, parse_mode: Optional[str]=None,
@@ -2738,7 +3039,7 @@ def send_live_photo(
:param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent
:type business_connection_id: :obj:`str`
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param live_photo: Live photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size.
@@ -2815,7 +3116,7 @@ def send_live_photo(
def send_audio(
- self, chat_id: Union[int, str], audio: Union[Any, str],
+ self, chat_id: Optional[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, # deprecated, for backward compatibility
@@ -2847,7 +3148,7 @@ def send_audio(
Telegram documentation: https://core.telegram.org/bots/api#sendaudio
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended),
@@ -2980,7 +3281,7 @@ def send_audio(
)
def send_voice(
- self, chat_id: Union[int, str], voice: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], voice: Union[Any, str],
caption: Optional[str]=None, duration: Optional[int]=None,
reply_to_message_id: Optional[int]=None, # deprecated, for backward compatibility
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
@@ -3005,7 +3306,7 @@ def send_voice(
Telegram documentation: https://core.telegram.org/bots/api#sendvoice
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended),
@@ -3118,7 +3419,7 @@ def send_voice(
def send_document(
- self, chat_id: Union[int, str], document: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], document: Union[Any, str],
reply_to_message_id: Optional[int]=None, # deprecated, for backward compatibility
caption: Optional[str]=None,
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
@@ -3147,7 +3448,7 @@ def send_document(
Telegram documentation: https://core.telegram.org/bots/api#senddocument
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param document: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a
@@ -3286,7 +3587,7 @@ def send_document(
def send_sticker(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
sticker: Union[Any, str],
reply_to_message_id: Optional[int]=None, # deprecated, for backward compatibility
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
@@ -3312,7 +3613,7 @@ def send_sticker(
Telegram documentation: https://core.telegram.org/bots/api#sendsticker
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL
@@ -3424,7 +3725,7 @@ def send_sticker(
def send_video(
- self, chat_id: Union[int, str], video: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], video: Union[Any, str],
duration: Optional[int]=None,
width: Optional[int]=None,
height: Optional[int]=None,
@@ -3460,7 +3761,7 @@ def send_video(
Telegram documentation: https://core.telegram.org/bots/api#sendvideo
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param video: Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file using multipart/form-data.
@@ -3617,7 +3918,7 @@ def send_video(
def send_animation(
- self, chat_id: Union[int, str], animation: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], animation: Union[Any, str],
duration: Optional[int]=None,
width: Optional[int]=None,
height: Optional[int]=None,
@@ -3650,7 +3951,7 @@ def send_animation(
Telegram documentation: https://core.telegram.org/bots/api#sendanimation
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended),
@@ -3790,7 +4091,7 @@ def send_animation(
def send_video_note(
- self, chat_id: Union[int, str], data: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], data: Union[Any, str],
duration: Optional[int]=None,
length: Optional[int]=None,
reply_to_message_id: Optional[int]=None, # deprecated, for backward compatibility
@@ -3817,7 +4118,7 @@ def send_video_note(
Telegram documentation: https://core.telegram.org/bots/api#sendvideonote
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param data: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended)
@@ -4118,7 +4419,7 @@ def send_media_group(
def send_location(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
latitude: float, longitude: float,
live_period: Optional[int]=None,
reply_to_message_id: Optional[int]=None, # deprecated, for backward compatibility
@@ -4145,7 +4446,7 @@ def send_location(
Telegram documentation: https://core.telegram.org/bots/api#sendlocation
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param latitude: Latitude of the location
@@ -4369,7 +4670,7 @@ def stop_message_live_location(
def send_venue(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
latitude: Optional[float], longitude: Optional[float],
title: str, address: str,
foursquare_id: Optional[str]=None,
@@ -4397,7 +4698,7 @@ def send_venue(
Telegram documentation: https://core.telegram.org/bots/api#sendvenue
- :param chat_id: Unique identifier for the target chat or username of the target channel
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param latitude: Latitude of the venue
@@ -4518,7 +4819,7 @@ def send_venue(
def send_contact(
- self, chat_id: Union[int, str], phone_number: str,
+ self, chat_id: Optional[Union[int, str]], phone_number: str,
first_name: str, last_name: Optional[str]=None,
vcard: Optional[str]=None,
disable_notification: Optional[bool]=None,
@@ -4541,7 +4842,7 @@ def send_contact(
Telegram documentation: https://core.telegram.org/bots/api#sendcontact
- :param chat_id: Unique identifier for the target chat or username of the target channel
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param phone_number: Contact's phone number
@@ -4694,7 +4995,7 @@ def send_message_draft(
def send_rich_message(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
rich_message: types.InputRichMessage,
business_connection_id: Optional[str]=None,
message_thread_id: Optional[int]=None,
@@ -4713,7 +5014,7 @@ def send_rich_message(
Telegram documentation: https://core.telegram.org/bots/api#sendrichmessage
- :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param rich_message: The message to be sent
@@ -7732,7 +8033,10 @@ def send_gift(self, user_id: Optional[Union[str, int]] = None, gift_id: str=None
return apihelper.send_gift(self.token, gift_id, text=text, text_parse_mode=text_parse_mode, text_entities=text_entities,
pay_for_upgrade=pay_for_upgrade, chat_id=chat_id, user_id=user_id)
- def verify_user(self, user_id: int, custom_description: Optional[str]=None) -> bool:
+ def verify_user(
+ self, user_id: int, custom_description: Optional[str]=None,
+ custom_description_parse_mode: Optional[str]=None,
+ custom_description_entities: Optional[List[types.MessageEntity]]=None) -> bool:
"""
Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.
@@ -7744,12 +8048,24 @@ def verify_user(self, user_id: int, custom_description: Optional[str]=None) -> b
:param custom_description: Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
:type custom_description: :obj:`str`
+ :param custom_description_parse_mode: Optional. Mode for parsing entities in the custom description. See formatting options for more details. Only “text_link” entities are supported.
+ :type custom_description_parse_mode: :obj:`str`
+
+ :param custom_description_entities: Optional. A JSON-serialized list of special entities that appear in the custom description, which can be specified instead of custom_description_parse_mode. Only “text_link” entities are supported.
+ :type custom_description_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
:return: Returns True on success.
:rtype: :obj:`bool`
"""
- return apihelper.verify_user(self.token, user_id, custom_description=custom_description)
+ return apihelper.verify_user(
+ self.token, user_id, custom_description=custom_description,
+ custom_description_parse_mode=custom_description_parse_mode,
+ custom_description_entities=custom_description_entities)
- def verify_chat(self, chat_id: Union[int, str], custom_description: Optional[str]=None) -> bool:
+ def verify_chat(
+ self, chat_id: Union[int, str], custom_description: Optional[str]=None,
+ custom_description_parse_mode: Optional[str]=None,
+ custom_description_entities: Optional[List[types.MessageEntity]]=None) -> bool:
"""
Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.
@@ -7761,10 +8077,19 @@ def verify_chat(self, chat_id: Union[int, str], custom_description: Optional[str
:param custom_description: Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
:type custom_description: :obj:`str`
+ :param custom_description_parse_mode: Optional. Mode for parsing entities in the custom description. See formatting options for more details. Only “text_link” entities are supported.
+ :type custom_description_parse_mode: :obj:`str`
+
+ :param custom_description_entities: Optional. A JSON-serialized list of special entities that appear in the custom description, which can be specified instead of custom_description_parse_mode. Only “text_link” entities are supported.
+ :type custom_description_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
:return: Returns True on success.
:rtype: :obj:`bool`
"""
- return apihelper.verify_chat(self.token, chat_id, custom_description=custom_description)
+ return apihelper.verify_chat(
+ self.token, chat_id, custom_description=custom_description,
+ custom_description_parse_mode=custom_description_parse_mode,
+ custom_description_entities=custom_description_entities)
def remove_user_verification(self, user_id: int) -> bool:
"""
@@ -8172,6 +8497,25 @@ def convert_gift_to_stars(self, business_connection_id: str, owned_gift_id: str)
"""
return apihelper.convert_gift_to_stars(self.token, business_connection_id, owned_gift_id)
+ def delete_business_account_gift(self, business_connection_id: str, owned_gift_id: str) -> bool:
+ """
+ Deletes a regular gift owned by a managed business account without receiving Telegram Stars for it.
+ Requires the can_convert_gifts_to_stars business bot right. The gift can be deleted only if it isn't limited
+ (the field total_count of the Gift is omitted) and wasn't refunded. Returns True on success.
+
+ Telegram documentation: https://core.telegram.org/bots/api#deletebusinessaccountgift
+
+ :param business_connection_id: Unique identifier of the business connection
+ :type business_connection_id: :obj:`str`
+
+ :param owned_gift_id: Unique identifier of the regular gift that should be deleted
+ :type owned_gift_id: :obj:`str`
+
+ :return: Returns True on success.
+ :rtype: :obj:`bool`
+ """
+ return apihelper.delete_business_account_gift(self.token, business_connection_id, owned_gift_id)
+
def upgrade_gift(
self, business_connection_id: str, owned_gift_id: str,
keep_original_details: Optional[bool]=None,
@@ -8491,6 +8835,36 @@ def get_available_gifts(self) -> types.Gifts:
apihelper.get_available_gifts(self.token)
)
+ def get_unique_gift(self, name: str) -> types.UniqueGift:
+ """
+ Use this method to get information about a unique gift by its name. Returns a UniqueGift object on success.
+
+ Telegram documentation: https://core.telegram.org/bots/api#getuniquegift
+
+ :param name: Unique name of the gift
+ :type name: :obj:`str`
+
+ :return: On success, a UniqueGift object is returned.
+ :rtype: :class:`telebot.types.UniqueGift`
+ """
+ return types.UniqueGift.de_json(
+ apihelper.get_unique_gift(self.token, name)
+ )
+
+ def get_chat_share_theme_backdrops(self) -> types.ChatShareThemeBackdrops:
+ """
+ Use this method to get the list of backdrops, which can be used as the background of a theme of the screen
+ for sharing a link to a user or a chat. Requires no parameters. Returns a ChatShareThemeBackdrops object.
+
+ Telegram documentation: https://core.telegram.org/bots/api#getchatsharethemebackdrops
+
+ :return: On success, a ChatShareThemeBackdrops object is returned.
+ :rtype: :class:`telebot.types.ChatShareThemeBackdrops`
+ """
+ return types.ChatShareThemeBackdrops.de_json(
+ apihelper.get_chat_share_theme_backdrops(self.token)
+ )
+
def replace_sticker_in_set(self, user_id: int, name: str, old_sticker: str, sticker: types.InputSticker) -> bool:
"""
Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet,
@@ -11476,6 +11850,104 @@ def register_stopped_message_generation_handler(
handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs)
self.add_stopped_message_generation_handler(handler_dict)
+ def widget_query_handler(self, func=None, **kwargs):
+ """
+ Handles new incoming queries from widgets in messages sent by the bot or via the bot.
+ As a parameter to the decorator function, it passes :class:`telebot.types.WidgetQuery` object.
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ def decorator(handler):
+ handler_dict = self._build_handler_dict(handler, func=func, **kwargs)
+ self.add_widget_query_handler(handler_dict)
+ return handler
+
+ return decorator
+
+ def add_widget_query_handler(self, handler_dict):
+ """
+ Adds a widget_query handler.
+ Note that you should use register_widget_query_handler to add widget_query_handler to the bot.
+
+ :meta private:
+
+ :param handler_dict:
+ :return:
+ """
+ self.widget_query_handlers.append(handler_dict)
+
+ def register_widget_query_handler(self, callback: Callable, func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs):
+ """
+ Registers widget_query handler.
+
+ :param callback: function to be called
+ :type callback: :obj:`function`
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)
+ :type pass_bot: :obj:`bool`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs)
+ self.add_widget_query_handler(handler_dict)
+
+ def shared_widget_query_handler(self, func=None, **kwargs):
+ """
+ Handles new incoming queries from forwarded messages with shared widgets.
+ As a parameter to the decorator function, it passes :class:`telebot.types.SharedWidgetQuery` object.
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ def decorator(handler):
+ handler_dict = self._build_handler_dict(handler, func=func, **kwargs)
+ self.add_shared_widget_query_handler(handler_dict)
+ return handler
+
+ return decorator
+
+ def add_shared_widget_query_handler(self, handler_dict):
+ """
+ Adds a shared_widget_query handler.
+ Note that you should use register_shared_widget_query_handler to add shared_widget_query_handler to the bot.
+
+ :meta private:
+
+ :param handler_dict:
+ :return:
+ """
+ self.shared_widget_query_handlers.append(handler_dict)
+
+ def register_shared_widget_query_handler(self, callback: Callable, func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs):
+ """
+ Registers shared_widget_query handler.
+
+ :param callback: function to be called
+ :type callback: :obj:`function`
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param pass_bot: True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)
+ :type pass_bot: :obj:`bool`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs)
+ self.add_shared_widget_query_handler(handler_dict)
+
def add_custom_filter(self, custom_filter: Union[SimpleCustomFilter, AdvancedCustomFilter]):
"""
diff --git a/telebot/apihelper.py b/telebot/apihelper.py
index e40e81027..e853f02cb 100644
--- a/telebot/apihelper.py
+++ b/telebot/apihelper.py
@@ -265,7 +265,9 @@ def send_message(
direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendMessage'
- payload = {'chat_id': str(chat_id), 'text': text}
+ payload = {'text': text}
+ if chat_id is not None:
+ payload['chat_id'] = str(chat_id)
if link_preview_options is not None:
payload['link_preview_options'] = link_preview_options.to_json()
if reply_markup:
@@ -307,7 +309,9 @@ def send_rich_message(
message_thread_id=None, ephemeral_message_parameters=None):
method_url = r'sendRichMessage'
rich_message_json, files = rich_message.convert_input_rich_message()
- payload = {'chat_id': chat_id, 'rich_message': rich_message_json}
+ payload = {'rich_message': rich_message_json}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if disable_notification is not None:
payload['disable_notification'] = disable_notification
if protect_content is not None:
@@ -600,6 +604,114 @@ def edit_message_checklist(
payload['reply_markup'] = _convert_markup(reply_markup)
return _make_request(token, method_url, params=payload)
+def send_widget(
+ token, chat_id, html, message_thread_id=None, width=None, height=None, public_data=None, chat_data=None,
+ caption=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, allow_queries=None,
+ is_shared=None, disable_notification=None, protect_content=None, allow_paid_broadcast=None,
+ message_effect_id=None, reply_parameters=None, reply_markup=None):
+ method_url = r'sendWidget'
+ payload = {'chat_id': chat_id, 'html': html}
+ if message_thread_id is not None:
+ payload['message_thread_id'] = message_thread_id
+ if width is not None:
+ payload['width'] = width
+ if height is not None:
+ payload['height'] = height
+ if public_data is not None:
+ payload['public_data'] = public_data
+ if chat_data is not None:
+ payload['chat_data'] = chat_data
+ if caption:
+ payload['caption'] = caption
+ 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 show_caption_above_media is not None:
+ payload['show_caption_above_media'] = show_caption_above_media
+ if allow_queries is not None:
+ payload['allow_queries'] = allow_queries
+ if is_shared is not None:
+ payload['is_shared'] = is_shared
+ if disable_notification is not None:
+ payload['disable_notification'] = disable_notification
+ if protect_content is not None:
+ payload['protect_content'] = protect_content
+ if allow_paid_broadcast is not None:
+ payload['allow_paid_broadcast'] = allow_paid_broadcast
+ if message_effect_id:
+ payload['message_effect_id'] = message_effect_id
+ if reply_parameters:
+ payload['reply_parameters'] = reply_parameters.to_json()
+ if reply_markup:
+ payload['reply_markup'] = _convert_markup(reply_markup)
+ return _make_request(token, method_url, params=payload, method='post')
+
+
+def send_shared_widget(
+ token, chat_id, widget_id, message_thread_id=None, chat_data=None, caption=None, parse_mode=None,
+ caption_entities=None, show_caption_above_media=None, disable_notification=None, protect_content=None,
+ allow_paid_broadcast=None, message_effect_id=None, reply_parameters=None, reply_markup=None):
+ method_url = r'sendSharedWidget'
+ payload = {'chat_id': chat_id, 'widget_id': widget_id}
+ if message_thread_id is not None:
+ payload['message_thread_id'] = message_thread_id
+ if chat_data is not None:
+ payload['chat_data'] = chat_data
+ if caption:
+ payload['caption'] = caption
+ 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 show_caption_above_media is not None:
+ payload['show_caption_above_media'] = show_caption_above_media
+ if disable_notification is not None:
+ payload['disable_notification'] = disable_notification
+ if protect_content is not None:
+ payload['protect_content'] = protect_content
+ if allow_paid_broadcast is not None:
+ payload['allow_paid_broadcast'] = allow_paid_broadcast
+ if message_effect_id:
+ payload['message_effect_id'] = message_effect_id
+ if reply_parameters:
+ payload['reply_parameters'] = reply_parameters.to_json()
+ if reply_markup:
+ payload['reply_markup'] = _convert_markup(reply_markup)
+ return _make_request(token, method_url, params=payload, method='post')
+
+
+def answer_widget_query(token, widget_query_id, data=None):
+ method_url = r'answerWidgetQuery'
+ payload = {'widget_query_id': widget_query_id}
+ if data is not None:
+ payload['data'] = data
+ return _make_request(token, method_url, params=payload, method='post')
+
+
+def edit_message_widget_data(token, chat_id=None, message_id=None, inline_message_id=None, public_data=None, chat_data=None):
+ method_url = r'editMessageWidgetData'
+ 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 public_data is not None:
+ payload['public_data'] = public_data
+ if chat_data is not None:
+ payload['chat_data'] = chat_data
+ return _make_request(token, method_url, params=payload, method='post')
+
+
+def edit_shared_widget_data(token, widget_id, public_data, cache_time=None):
+ method_url = r'editSharedWidgetData'
+ payload = {'widget_id': widget_id, 'public_data': public_data}
+ if cache_time is not None:
+ payload['cache_time'] = cache_time
+ return _make_request(token, method_url, params=payload, method='post')
+
def send_dice(
token, chat_id,
@@ -645,7 +757,9 @@ def send_photo(
message_effect_id=None, show_caption_above_media=None, allow_paid_broadcast=None,
direct_messages_topic_id=None, suggested_post_parameters=None,ephemeral_message_parameters=None):
method_url = r'sendPhoto'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if util.is_string(photo):
payload['photo'] = photo
@@ -697,7 +811,9 @@ def send_live_photo(
direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendLivePhoto'
files = {}
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if util.is_string(live_photo):
payload['live_photo'] = live_photo
else:
@@ -825,7 +941,9 @@ def send_location(
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None,
suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendLocation'
- payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude}
+ payload = {'latitude': latitude, 'longitude': longitude}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if live_period:
payload['live_period'] = live_period
if horizontal_accuracy:
@@ -917,7 +1035,9 @@ def send_venue(
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendVenue'
- payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address}
+ payload = {'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if foursquare_id:
payload['foursquare_id'] = foursquare_id
if foursquare_type:
@@ -960,7 +1080,9 @@ def send_contact(
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendContact'
- payload = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
+ payload = {'phone_number': phone_number, 'first_name': first_name}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if last_name:
payload['last_name'] = last_name
if vcard:
@@ -1031,7 +1153,9 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_markup=N
cover=None, start_timestamp=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendVideo'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
files = {'video': data}
@@ -1109,7 +1233,9 @@ def send_animation(
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendAnimation'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
files = {'animation': data}
@@ -1172,7 +1298,9 @@ def send_voice(token, chat_id, voice, caption=None, duration=None, reply_markup=
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendVoice'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(voice):
files = {'voice': voice}
@@ -1219,7 +1347,9 @@ def send_video_note(token, chat_id, data, duration=None, length=None, reply_mark
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendVideoNote'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
files = {'video_note': data}
@@ -1272,7 +1402,9 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendAudio'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(audio):
files = {'audio': audio}
@@ -1332,7 +1464,9 @@ def send_data(token, chat_id, data, data_type, reply_markup=None, parse_mode=Non
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = get_method_by_type(data_type)
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
file_data = data
@@ -2333,6 +2467,15 @@ def get_available_gifts(token):
method_url = 'getAvailableGifts'
return _make_request(token, method_url)
+def get_unique_gift(token, name):
+ method_url = 'getUniqueGift'
+ payload = {'name': name}
+ return _make_request(token, method_url, params=payload)
+
+def get_chat_share_theme_backdrops(token):
+ method_url = 'getChatShareThemeBackdrops'
+ return _make_request(token, method_url)
+
def send_gift(token, gift_id, text=None, text_parse_mode=None, text_entities=None, pay_for_upgrade=None,
chat_id=None, user_id=None):
@@ -2353,19 +2496,29 @@ def send_gift(token, gift_id, text=None, text_parse_mode=None, text_entities=Non
return _make_request(token, method_url, params=payload, method='post')
-def verify_user(token, user_id, custom_description=None):
+def verify_user(token, user_id, custom_description=None, custom_description_parse_mode=None,
+ custom_description_entities=None):
method_url = 'verifyUser'
payload = {'user_id': user_id}
if custom_description:
payload['custom_description'] = custom_description
+ if custom_description_parse_mode:
+ payload['custom_description_parse_mode'] = custom_description_parse_mode
+ if custom_description_entities:
+ payload['custom_description_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(custom_description_entities))
return _make_request(token, method_url, params=payload, method='post')
-def verify_chat(token, chat_id, custom_description=None):
+def verify_chat(token, chat_id, custom_description=None, custom_description_parse_mode=None,
+ custom_description_entities=None):
method_url = 'verifyChat'
payload = {'chat_id': chat_id}
if custom_description:
payload['custom_description'] = custom_description
+ if custom_description_parse_mode:
+ payload['custom_description_parse_mode'] = custom_description_parse_mode
+ if custom_description_entities:
+ payload['custom_description_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(custom_description_entities))
return _make_request(token, method_url, params=payload, method='post')
@@ -2529,6 +2682,11 @@ def convert_gift_to_stars(token, business_connection_id, owned_gift_id):
payload = {'business_connection_id': business_connection_id, 'owned_gift_id': owned_gift_id}
return _make_request(token, method_url, params=payload, method='post')
+def delete_business_account_gift(token, business_connection_id, owned_gift_id):
+ method_url = 'deleteBusinessAccountGift'
+ payload = {'business_connection_id': business_connection_id, 'owned_gift_id': owned_gift_id}
+ return _make_request(token, method_url, params=payload, method='post')
+
def upgrade_gift(token, business_connection_id, owned_gift_id, keep_original_details=None, star_count=None):
method_url = 'upgradeGift'
payload = {'business_connection_id': business_connection_id, 'owned_gift_id': owned_gift_id}
diff --git a/telebot/async_telebot.py b/telebot/async_telebot.py
index 676acb88d..85e507a24 100644
--- a/telebot/async_telebot.py
+++ b/telebot/async_telebot.py
@@ -189,6 +189,8 @@ def __init__(self, token: str, parse_mode: Optional[str]=None, offset: Optional[
self.guest_message_handlers = []
self.subscription_handlers = []
self.stopped_message_generation_handlers = []
+ self.widget_query_handlers = []
+ self.shared_widget_query_handlers = []
self.custom_filters = {}
self.state_handlers = []
@@ -656,6 +658,8 @@ async def process_new_updates(self, updates: List[types.Update]):
new_guest_messages = None
new_subscriptions = None
new_stopped_message_generations = None
+ new_widget_queries = None
+ new_shared_widget_queries = None
for update in updates:
@@ -741,6 +745,12 @@ async def process_new_updates(self, updates: List[types.Update]):
if update.stopped_message_generation:
if new_stopped_message_generations is None: new_stopped_message_generations = []
new_stopped_message_generations.append(update.stopped_message_generation)
+ if update.widget_query:
+ if new_widget_queries is None: new_widget_queries = []
+ new_widget_queries.append(update.widget_query)
+ if update.shared_widget_query:
+ if new_shared_widget_queries is None: new_shared_widget_queries = []
+ new_shared_widget_queries.append(update.shared_widget_query)
if new_messages:
@@ -797,6 +807,10 @@ async def process_new_updates(self, updates: List[types.Update]):
await self.process_new_subscriptions(new_subscriptions)
if new_stopped_message_generations:
await self.process_new_stopped_message_generation(new_stopped_message_generations)
+ if new_widget_queries:
+ await self.process_new_widget_query(new_widget_queries)
+ if new_shared_widget_queries:
+ await self.process_new_shared_widget_query(new_shared_widget_queries)
async def process_new_messages(self, new_messages):
"""
@@ -965,6 +979,18 @@ async def process_new_stopped_message_generation(self, new_stopped_message_gener
'stopped_message_generation',
)
+ async def process_new_widget_query(self, new_widget_queries):
+ """
+ :meta private:
+ """
+ await self._process_updates(self.widget_query_handlers, new_widget_queries, 'widget_query')
+
+ async def process_new_shared_widget_query(self, new_shared_widget_queries):
+ """
+ :meta private:
+ """
+ await self._process_updates(self.shared_widget_query_handlers, new_shared_widget_queries, 'shared_widget_query')
+
async def _get_middlewares(self, update_type):
"""
:meta private:
@@ -2904,6 +2930,104 @@ def register_stopped_message_generation_handler(
handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs)
self.add_stopped_message_generation_handler(handler_dict)
+ def widget_query_handler(self, func=None, **kwargs):
+ """
+ Handles new incoming queries from widgets in messages sent by the bot or via the bot.
+ As a parameter to the decorator function, it passes :class:`telebot.types.WidgetQuery` object.
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ def decorator(handler):
+ handler_dict = self._build_handler_dict(handler, func=func, **kwargs)
+ self.add_widget_query_handler(handler_dict)
+ return handler
+
+ return decorator
+
+ def add_widget_query_handler(self, handler_dict):
+ """
+ Adds a widget_query handler.
+ Note that you should use register_widget_query_handler to add widget_query_handler to the bot.
+
+ :meta private:
+
+ :param handler_dict:
+ :return:
+ """
+ self.widget_query_handlers.append(handler_dict)
+
+ def register_widget_query_handler(self, callback: Callable[[Any], Awaitable], func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs):
+ """
+ Registers widget_query handler.
+
+ :param callback: function to be called
+ :type callback: :obj:`function`
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param pass_bot: True if you need to pass AsyncTeleBot instance to handler(useful for separating handlers into different files)
+ :type pass_bot: :obj:`bool`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs)
+ self.add_widget_query_handler(handler_dict)
+
+ def shared_widget_query_handler(self, func=None, **kwargs):
+ """
+ Handles new incoming queries from forwarded messages with shared widgets.
+ As a parameter to the decorator function, it passes :class:`telebot.types.SharedWidgetQuery` object.
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ def decorator(handler):
+ handler_dict = self._build_handler_dict(handler, func=func, **kwargs)
+ self.add_shared_widget_query_handler(handler_dict)
+ return handler
+
+ return decorator
+
+ def add_shared_widget_query_handler(self, handler_dict):
+ """
+ Adds a shared_widget_query handler.
+ Note that you should use register_shared_widget_query_handler to add shared_widget_query_handler to the bot.
+
+ :meta private:
+
+ :param handler_dict:
+ :return:
+ """
+ self.shared_widget_query_handlers.append(handler_dict)
+
+ def register_shared_widget_query_handler(self, callback: Callable[[Any], Awaitable], func: Optional[Callable]=None, pass_bot: Optional[bool]=False, **kwargs):
+ """
+ Registers shared_widget_query handler.
+
+ :param callback: function to be called
+ :type callback: :obj:`function`
+
+ :param func: Function executed as a filter
+ :type func: :obj:`function`
+
+ :param pass_bot: True if you need to pass AsyncTeleBot instance to handler(useful for separating handlers into different files)
+ :type pass_bot: :obj:`bool`
+
+ :param kwargs: Optional keyword arguments(custom filters)
+ :return: None
+ """
+ handler_dict = self._build_handler_dict(callback, func=func, pass_bot=pass_bot, **kwargs)
+ self.add_shared_widget_query_handler(handler_dict)
+
@staticmethod
def _build_handler_dict(handler, pass_bot=False, **filters):
@@ -3521,7 +3645,7 @@ async def get_chat_member(self, chat_id: Union[int, str], user_id: int) -> types
return types.ChatMember.de_json(result)
async def send_message(
- self, chat_id: Union[int, str], text: str,
+ self, chat_id: Optional[Union[int, str]], text: str,
parse_mode: Optional[str]=None,
entities: Optional[List[types.MessageEntity]]=None,
disable_web_page_preview: Optional[bool]=None,
@@ -3551,7 +3675,7 @@ async def send_message(
Telegram documentation: https://core.telegram.org/bots/api#sendmessage
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param text: Text of the message to be sent
@@ -3776,7 +3900,7 @@ async def copy_message(
"""
Use this method to copy messages of any kind.
If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages,
- and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous
+ invoice messages, and widget messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous
to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array
of MessageId of the sent messages is returned.
@@ -4071,7 +4195,7 @@ async def copy_messages(self, chat_id: Union[str, int], from_chat_id: Union[str,
direct_messages_topic_id: Optional[int] = None) -> List[types.MessageId]:
"""
Use this method to copy messages of any kind.
- Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied.
+ Service messages, paid media messages, giveaway messages, giveaway winners messages, invoice messages, and widget messages can't be copied.
A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method
forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
@@ -4196,6 +4320,279 @@ async def edit_message_checklist(
await asyncio_helper.edit_message_checklist(
self.token, business_connection_id, chat_id, message_id, checklist, reply_markup=reply_markup))
+ async def send_widget(
+ self, chat_id: Union[int, str], html: str,
+ message_thread_id: Optional[int]=None,
+ width: Optional[int]=None,
+ height: Optional[int]=None,
+ public_data: Optional[str]=None,
+ chat_data: Optional[str]=None,
+ caption: Optional[str]=None,
+ parse_mode: Optional[str]=None,
+ caption_entities: Optional[List[types.MessageEntity]]=None,
+ show_caption_above_media: Optional[bool]=None,
+ allow_queries: Optional[bool]=None,
+ is_shared: Optional[bool]=None,
+ disable_notification: Optional[bool]=None,
+ protect_content: Optional[bool]=None,
+ allow_paid_broadcast: Optional[bool]=None,
+ message_effect_id: Optional[str]=None,
+ reply_parameters: Optional[types.ReplyParameters]=None,
+ reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Message:
+ """
+ Use this method to send a message with an HTML widget. Currently, in the production environment, widgets can be sent
+ only to private chats, and sent widgets automatically have protected content and therefore can't be forwarded.
+ On success, the sent Message is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#sendwidget
+
+ :param chat_id: Unique identifier for the target chat or username of the target supergroup in the format @username
+ :type chat_id: :obj:`int` or :obj:`str`
+
+ :param html: HTML code of the widget, 1-32768 bytes. The code must not exceed 4096 bytes when compressed by zlib
+ with the maximum compression level.
+ :type html: :obj:`str`
+
+ :param message_thread_id: Unique identifier for the target message thread (topic) of a forum; for forum supergroups
+ and private chats of bots with forum topic mode enabled only
+ :type message_thread_id: :obj:`int`
+
+ :param width: Width of the widget in logical pixels; omit if the widget must occupy the whole width of the message bubble.
+ The width is clamped by the app to the range from 200 to the maximum width of the message bubble.
+ :type width: :obj:`int`
+
+ :param height: Height of the widget in logical pixels; omit if the height of the widget isn't fixed.
+ The height is clamped by the app to the range 50-600.
+ :type height: :obj:`int`
+
+ :param public_data: Public data of the widget, 0-1024 bytes, which will be available wherever the widget is shown.
+ If the widget is shared, then all messages with it will have the same public data.
+ :type public_data: :obj:`str`
+
+ :param chat_data: Data of the widget, which is specific to the message, 0-1024 bytes
+ :type chat_data: :obj:`str`
+
+ :param caption: Widget caption, 0-1024 characters after entities parsing
+ :type caption: :obj:`str`
+
+ :param parse_mode: Mode for parsing entities in the widget caption
+ :type parse_mode: :obj:`str`
+
+ :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
+ :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
+ :param show_caption_above_media: Pass True if the caption must be shown above the widget
+ :type show_caption_above_media: :obj:`bool`
+
+ :param allow_queries: Pass True to allow the widget to send queries to the bot
+ :type allow_queries: :obj:`bool`
+
+ :param is_shared: Pass True to create a shared widget, which can be sent again using the method sendSharedWidget
+ :type is_shared: :obj:`bool`
+
+ :param disable_notification: Sends the message silently. Users will receive a notification with no sound.
+ :type disable_notification: :obj:`bool`
+
+ :param protect_content: Protects the contents of the sent message from forwarding and saving
+ :type protect_content: :obj:`bool`
+
+ :param allow_paid_broadcast: Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee
+ of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance
+ :type allow_paid_broadcast: :obj:`bool`
+
+ :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only
+ :type message_effect_id: :obj:`str`
+
+ :param reply_parameters: Description of the message to reply to
+ :type reply_parameters: :class:`telebot.types.ReplyParameters`
+
+ :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
+ to remove reply keyboard or to force a reply from the user.
+ :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove`
+ or :class:`telebot.types.ForceReply`
+
+ :return: On success, the sent Message is returned.
+ :rtype: :class:`telebot.types.Message`
+ """
+ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode
+ disable_notification = self.disable_notification if (disable_notification is None) else disable_notification
+ protect_content = self.protect_content if (protect_content is None) else protect_content
+
+ if reply_parameters and (reply_parameters.allow_sending_without_reply is None):
+ reply_parameters.allow_sending_without_reply = self.allow_sending_without_reply
+
+ return types.Message.de_json(
+ await asyncio_helper.send_widget(
+ self.token, chat_id, html, message_thread_id=message_thread_id, width=width, height=height,
+ public_data=public_data, chat_data=chat_data, caption=caption, parse_mode=parse_mode,
+ caption_entities=caption_entities, show_caption_above_media=show_caption_above_media,
+ allow_queries=allow_queries, is_shared=is_shared, disable_notification=disable_notification,
+ protect_content=protect_content, allow_paid_broadcast=allow_paid_broadcast,
+ message_effect_id=message_effect_id, reply_parameters=reply_parameters, reply_markup=reply_markup))
+
+ async def send_shared_widget(
+ self, chat_id: Union[int, str], widget_id: str,
+ message_thread_id: Optional[int]=None,
+ chat_data: Optional[str]=None,
+ caption: Optional[str]=None,
+ parse_mode: Optional[str]=None,
+ caption_entities: Optional[List[types.MessageEntity]]=None,
+ show_caption_above_media: Optional[bool]=None,
+ disable_notification: Optional[bool]=None,
+ protect_content: Optional[bool]=None,
+ allow_paid_broadcast: Optional[bool]=None,
+ message_effect_id: Optional[str]=None,
+ reply_parameters: Optional[types.ReplyParameters]=None,
+ reply_markup: Optional[REPLY_MARKUP_TYPES]=None) -> types.Message:
+ """
+ Use this method to send again a shared widget created by the bot. Currently, in the production environment, widgets can be sent
+ only to private chats, and sent widgets automatically have protected content and therefore can't be forwarded.
+ On success, the sent Message is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#sendsharedwidget
+
+ :param chat_id: Unique identifier for the target chat or username of the target supergroup in the format @username
+ :type chat_id: :obj:`int` or :obj:`str`
+
+ :param widget_id: Unique identifier of the shared widget
+ :type widget_id: :obj:`str`
+
+ :param message_thread_id: Unique identifier for the target message thread (topic) of a forum; for forum supergroups
+ and private chats of bots with forum topic mode enabled only
+ :type message_thread_id: :obj:`int`
+
+ :param chat_data: Data of the widget, which is specific to the message, 0-1024 bytes
+ :type chat_data: :obj:`str`
+
+ :param caption: Widget caption, 0-1024 characters after entities parsing
+ :type caption: :obj:`str`
+
+ :param parse_mode: Mode for parsing entities in the widget caption
+ :type parse_mode: :obj:`str`
+
+ :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
+ :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
+ :param show_caption_above_media: Pass True if the caption must be shown above the widget
+ :type show_caption_above_media: :obj:`bool`
+
+ :param disable_notification: Sends the message silently. Users will receive a notification with no sound.
+ :type disable_notification: :obj:`bool`
+
+ :param protect_content: Protects the contents of the sent message from forwarding and saving
+ :type protect_content: :obj:`bool`
+
+ :param allow_paid_broadcast: Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee
+ of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance
+ :type allow_paid_broadcast: :obj:`bool`
+
+ :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only
+ :type message_effect_id: :obj:`str`
+
+ :param reply_parameters: Description of the message to reply to
+ :type reply_parameters: :class:`telebot.types.ReplyParameters`
+
+ :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
+ to remove reply keyboard or to force a reply from the user.
+ :type reply_markup: :class:`telebot.types.InlineKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardMarkup` or :class:`telebot.types.ReplyKeyboardRemove`
+ or :class:`telebot.types.ForceReply`
+
+ :return: On success, the sent Message is returned.
+ :rtype: :class:`telebot.types.Message`
+ """
+ parse_mode = self.parse_mode if (parse_mode is None) else parse_mode
+ disable_notification = self.disable_notification if (disable_notification is None) else disable_notification
+ protect_content = self.protect_content if (protect_content is None) else protect_content
+
+ if reply_parameters and (reply_parameters.allow_sending_without_reply is None):
+ reply_parameters.allow_sending_without_reply = self.allow_sending_without_reply
+
+ return types.Message.de_json(
+ await asyncio_helper.send_shared_widget(
+ self.token, chat_id, widget_id, message_thread_id=message_thread_id, chat_data=chat_data,
+ caption=caption, parse_mode=parse_mode, caption_entities=caption_entities,
+ show_caption_above_media=show_caption_above_media, disable_notification=disable_notification,
+ protect_content=protect_content, allow_paid_broadcast=allow_paid_broadcast,
+ message_effect_id=message_effect_id, reply_parameters=reply_parameters, reply_markup=reply_markup))
+
+ async def answer_widget_query(self, widget_query_id: str, data: Optional[str]=None) -> bool:
+ """
+ Use this method to send an answer to a query from a widget. The query must be answered within 15 seconds.
+ The answer is received only by the widget that sent the query and doesn't change data of the widget;
+ use editMessageWidgetData or editSharedWidgetData to change it. On success, True is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#answerwidgetquery
+
+ :param widget_query_id: Unique identifier for the query to be answered
+ :type widget_query_id: :obj:`str`
+
+ :param data: Data to be returned to the widget, 0-1024 bytes
+ :type data: :obj:`str`
+
+ :return: On success, True is returned.
+ :rtype: :obj:`bool`
+ """
+ return await asyncio_helper.answer_widget_query(self.token, widget_query_id, data=data)
+
+ async def edit_message_widget_data(
+ self, chat_id: Optional[Union[int, str]]=None,
+ message_id: Optional[int]=None,
+ inline_message_id: Optional[str]=None,
+ public_data: Optional[str]=None,
+ chat_data: Optional[str]=None) -> bool:
+ """
+ Use this method to edit data of a widget in a message sent by the bot or via the bot (for inline bots).
+ Public data of a shared widget can be changed at most once per second. On success, True is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#editmessagewidgetdata
+
+ :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username
+ of the target supergroup in the format @username.
+ :type chat_id: :obj:`int` or :obj:`str`
+
+ :param message_id: Required if inline_message_id is not specified. Identifier of the message with the widget.
+ :type message_id: :obj:`int`
+
+ :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message.
+ :type inline_message_id: :obj:`str`
+
+ :param public_data: New public data of the widget, 0-1024 bytes; pass an empty string to remove the public data.
+ If omitted, then the public data isn't changed.
+ :type public_data: :obj:`str`
+
+ :param chat_data: New data of the widget, which is specific to the message, 0-1024 bytes; pass an empty string to remove the data.
+ If omitted, then the data isn't changed.
+ :type chat_data: :obj:`str`
+
+ :return: On success, True is returned.
+ :rtype: :obj:`bool`
+ """
+ return await asyncio_helper.edit_message_widget_data(
+ self.token, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id,
+ public_data=public_data, chat_data=chat_data)
+
+ async def edit_shared_widget_data(self, widget_id: str, public_data: str, cache_time: Optional[int]=None) -> bool:
+ """
+ Use this method to edit public data of a shared widget created by the bot. A shared widget can be edited
+ at most once per second. On success, True is returned.
+
+ Telegram documentation: https://core.telegram.org/bots/api#editsharedwidgetdata
+
+ :param widget_id: Unique identifier of the shared widget
+ :type widget_id: :obj:`str`
+
+ :param public_data: New public data of the widget, 0-1024 bytes; pass an empty string to remove the public data
+ :type public_data: :obj:`str`
+
+ :param cache_time: The maximum amount of time in seconds that the public data of the widget may be cached client-side; 5-3600.
+ If omitted, then the current value is kept, which is 30 by default.
+ :type cache_time: :obj:`int`
+
+ :return: On success, True is returned.
+ :rtype: :obj:`bool`
+ """
+ return await asyncio_helper.edit_shared_widget_data(self.token, widget_id, public_data, cache_time=cache_time)
+
async def send_dice(
self, chat_id: Union[int, str],
emoji: Optional[str]=None, disable_notification: Optional[bool]=None,
@@ -4304,7 +4701,7 @@ async def send_dice(
)
async def send_photo(
- self, chat_id: Union[int, str], photo: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], photo: Union[Any, str],
caption: Optional[str]=None, parse_mode: Optional[str]=None,
caption_entities: Optional[List[types.MessageEntity]]=None,
disable_notification: Optional[bool]=None,
@@ -4330,7 +4727,7 @@ async def send_photo(
Telegram documentation: https://core.telegram.org/bots/api#sendphoto
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended),
@@ -4451,7 +4848,7 @@ async def send_photo(
)
async def send_live_photo(
- self, chat_id: Union[int, str], live_photo: Union[Any, str], photo: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], live_photo: Union[Any, str], photo: Union[Any, str],
message_thread_id: Optional[int] = None, direct_messages_topic_id: Optional[int]=None,
business_connection_id: Optional[str]=None,
caption: Optional[str]=None, parse_mode: Optional[str]=None,
@@ -4476,7 +4873,7 @@ async def send_live_photo(
:param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent
:type business_connection_id: :obj:`str`
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param live_photo: Live photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size.
@@ -4554,7 +4951,7 @@ async def send_live_photo(
)
async def send_audio(
- self, chat_id: Union[int, str], audio: Union[Any, str],
+ self, chat_id: Optional[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,
@@ -4586,7 +4983,7 @@ async def send_audio(
Telegram documentation: https://core.telegram.org/bots/api#sendaudio
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended),
@@ -4721,7 +5118,7 @@ async def send_audio(
)
async def send_voice(
- self, chat_id: Union[int, str], voice: Union[Any, str],
+ self, chat_id: Optional[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,
@@ -4746,7 +5143,7 @@ async def send_voice(
Telegram documentation: https://core.telegram.org/bots/api#sendvoice
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended),
@@ -4862,7 +5259,7 @@ async def send_voice(
)
async def send_document(
- self, chat_id: Union[int, str], document: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], document: Union[Any, str],
reply_to_message_id: Optional[int]=None,
caption: Optional[str]=None,
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
@@ -4892,7 +5289,7 @@ async def send_document(
Telegram documentation: https://core.telegram.org/bots/api#senddocument
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param document: (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a
@@ -5036,7 +5433,7 @@ async def send_document(
)
async def send_sticker(
- self, chat_id: Union[int, str], sticker: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], sticker: Union[Any, str],
reply_to_message_id: Optional[int]=None,
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
disable_notification: Optional[bool]=None,
@@ -5061,7 +5458,7 @@ async def send_sticker(
Telegram documentation: https://core.telegram.org/bots/api#sendsticker
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL
@@ -5176,7 +5573,7 @@ async def send_sticker(
)
async def send_video(
- self, chat_id: Union[int, str], video: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], video: Union[Any, str],
duration: Optional[int]=None,
width: Optional[int]=None,
height: Optional[int]=None,
@@ -5212,7 +5609,7 @@ async def send_video(
Telegram documentation: https://core.telegram.org/bots/api#sendvideo
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param video: Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file using multipart/form-data.
@@ -5366,7 +5763,7 @@ async def send_video(
ephemeral_message_parameters=ephemeral_message_parameters))
async def send_animation(
- self, chat_id: Union[int, str], animation: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], animation: Union[Any, str],
duration: Optional[int]=None,
width: Optional[int]=None,
height: Optional[int]=None,
@@ -5399,7 +5796,7 @@ async def send_animation(
Telegram documentation: https://core.telegram.org/bots/api#sendanimation
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended),
@@ -5541,7 +5938,7 @@ async def send_animation(
)
async def send_video_note(
- self, chat_id: Union[int, str], data: Union[Any, str],
+ self, chat_id: Optional[Union[int, str]], data: Union[Any, str],
duration: Optional[int]=None,
length: Optional[int]=None,
reply_to_message_id: Optional[int]=None,
@@ -5568,7 +5965,7 @@ async def send_video_note(
Telegram documentation: https://core.telegram.org/bots/api#sendvideonote
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param data: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended)
@@ -5870,7 +6267,7 @@ async def send_media_group(
return [types.Message.de_json(msg) for msg in result]
async def send_location(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
latitude: float, longitude: float,
live_period: Optional[int]=None,
reply_to_message_id: Optional[int]=None,
@@ -5897,7 +6294,7 @@ async def send_location(
Telegram documentation: https://core.telegram.org/bots/api#sendlocation
- :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param latitude: Latitude of the location
@@ -6120,7 +6517,7 @@ async def stop_message_live_location(
self.token, chat_id, message_id, inline_message_id, reply_markup, timeout, business_connection_id))
async def send_venue(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
latitude: float, longitude: float,
title: str, address: str,
foursquare_id: Optional[str]=None,
@@ -6148,7 +6545,7 @@ async def send_venue(
Telegram documentation: https://core.telegram.org/bots/api#sendvenue
- :param chat_id: Unique identifier for the target chat or username of the target channel
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param latitude: Latitude of the venue
@@ -6273,7 +6670,7 @@ async def send_venue(
)
async def send_contact(
- self, chat_id: Union[int, str], phone_number: str,
+ self, chat_id: Optional[Union[int, str]], phone_number: str,
first_name: str, last_name: Optional[str]=None,
vcard: Optional[str]=None,
disable_notification: Optional[bool]=None,
@@ -6297,7 +6694,7 @@ async def send_contact(
Telegram documentation: https://core.telegram.org/bots/api#sendcontact
- :param chat_id: Unique identifier for the target chat or username of the target channel
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param phone_number: Contact's phone number
@@ -6410,7 +6807,7 @@ async def send_contact(
)
async def send_rich_message(
- self, chat_id: Union[int, str],
+ self, chat_id: Optional[Union[int, str]],
rich_message: types.InputRichMessage,
business_connection_id: Optional[str]=None,
message_thread_id: Optional[int]=None,
@@ -6429,7 +6826,7 @@ async def send_rich_message(
Telegram documentation: https://core.telegram.org/bots/api#sendrichmessage
- :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
+ :param chat_id: Unique identifier for the target chat or username of the target bot, supergroup, or channel in the format @username; required unless the message is sent as an ephemeral reply to a callback query
:type chat_id: :obj:`int` or :obj:`str`
:param rich_message: The message to be sent
@@ -9436,7 +9833,10 @@ async def send_gift(self, user_id: Optional[Union[str, int]] = None, gift_id: st
return await asyncio_helper.send_gift(self.token, gift_id, text, text_parse_mode, text_entities, pay_for_upgrade=pay_for_upgrade,
chat_id=chat_id, user_id=user_id)
- async def verify_user(self, user_id: int, custom_description: Optional[str]=None) -> bool:
+ async def verify_user(
+ self, user_id: int, custom_description: Optional[str]=None,
+ custom_description_parse_mode: Optional[str]=None,
+ custom_description_entities: Optional[List[types.MessageEntity]]=None) -> bool:
"""
Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.
@@ -9448,12 +9848,24 @@ async def verify_user(self, user_id: int, custom_description: Optional[str]=None
:param custom_description: Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
:type custom_description: :obj:`str`
+ :param custom_description_parse_mode: Optional. Mode for parsing entities in the custom description. See formatting options for more details. Only “text_link” entities are supported.
+ :type custom_description_parse_mode: :obj:`str`
+
+ :param custom_description_entities: Optional. A JSON-serialized list of special entities that appear in the custom description, which can be specified instead of custom_description_parse_mode. Only “text_link” entities are supported.
+ :type custom_description_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
:return: Returns True on success.
:rtype: :obj:`bool`
"""
- return await asyncio_helper.verify_user(self.token, user_id, custom_description=custom_description)
+ return await asyncio_helper.verify_user(
+ self.token, user_id, custom_description=custom_description,
+ custom_description_parse_mode=custom_description_parse_mode,
+ custom_description_entities=custom_description_entities)
- async def verify_chat(self, chat_id: Union[int, str], custom_description: Optional[str]=None) -> bool:
+ async def verify_chat(
+ self, chat_id: Union[int, str], custom_description: Optional[str]=None,
+ custom_description_parse_mode: Optional[str]=None,
+ custom_description_entities: Optional[List[types.MessageEntity]]=None) -> bool:
"""
Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.
@@ -9465,11 +9877,20 @@ async def verify_chat(self, chat_id: Union[int, str], custom_description: Option
:param custom_description: Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
:type custom_description: :obj:`str`
+ :param custom_description_parse_mode: Optional. Mode for parsing entities in the custom description. See formatting options for more details. Only “text_link” entities are supported.
+ :type custom_description_parse_mode: :obj:`str`
+
+ :param custom_description_entities: Optional. A JSON-serialized list of special entities that appear in the custom description, which can be specified instead of custom_description_parse_mode. Only “text_link” entities are supported.
+ :type custom_description_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
:return: Returns True on success.
:rtype: :obj:`bool`
"""
- return await asyncio_helper.verify_chat(self.token, chat_id, custom_description=custom_description)
+ return await asyncio_helper.verify_chat(
+ self.token, chat_id, custom_description=custom_description,
+ custom_description_parse_mode=custom_description_parse_mode,
+ custom_description_entities=custom_description_entities)
async def remove_user_verification(self, user_id: int) -> bool:
"""
@@ -9876,6 +10297,25 @@ async def convert_gift_to_stars(self, business_connection_id: str, owned_gift_id
"""
return await asyncio_helper.convert_gift_to_stars(self.token, business_connection_id, owned_gift_id)
+ async def delete_business_account_gift(self, business_connection_id: str, owned_gift_id: str) -> bool:
+ """
+ Deletes a regular gift owned by a managed business account without receiving Telegram Stars for it.
+ Requires the can_convert_gifts_to_stars business bot right. The gift can be deleted only if it isn't limited
+ (the field total_count of the Gift is omitted) and wasn't refunded. Returns True on success.
+
+ Telegram documentation: https://core.telegram.org/bots/api#deletebusinessaccountgift
+
+ :param business_connection_id: Unique identifier of the business connection
+ :type business_connection_id: :obj:`str`
+
+ :param owned_gift_id: Unique identifier of the regular gift that should be deleted
+ :type owned_gift_id: :obj:`str`
+
+ :return: Returns True on success.
+ :rtype: :obj:`bool`
+ """
+ return await asyncio_helper.delete_business_account_gift(self.token, business_connection_id, owned_gift_id)
+
async def upgrade_gift(
self, business_connection_id: str, owned_gift_id: str,
keep_original_details: Optional[bool]=None,
@@ -10194,6 +10634,32 @@ async def get_available_gifts(self) -> types.Gifts:
return types.Gifts.de_json(await asyncio_helper.get_available_gifts(self.token))
+ async def get_unique_gift(self, name: str) -> types.UniqueGift:
+ """
+ Use this method to get information about a unique gift by its name. Returns a UniqueGift object on success.
+
+ Telegram documentation: https://core.telegram.org/bots/api#getuniquegift
+
+ :param name: Unique name of the gift
+ :type name: :obj:`str`
+
+ :return: On success, a UniqueGift object is returned.
+ :rtype: :class:`telebot.types.UniqueGift`
+ """
+ return types.UniqueGift.de_json(await asyncio_helper.get_unique_gift(self.token, name))
+
+ async def get_chat_share_theme_backdrops(self) -> types.ChatShareThemeBackdrops:
+ """
+ Use this method to get the list of backdrops, which can be used as the background of a theme of the screen
+ for sharing a link to a user or a chat. Requires no parameters. Returns a ChatShareThemeBackdrops object.
+
+ Telegram documentation: https://core.telegram.org/bots/api#getchatsharethemebackdrops
+
+ :return: On success, a ChatShareThemeBackdrops object is returned.
+ :rtype: :class:`telebot.types.ChatShareThemeBackdrops`
+ """
+ return types.ChatShareThemeBackdrops.de_json(await asyncio_helper.get_chat_share_theme_backdrops(self.token))
+
async def replace_sticker_in_set(self, user_id: int, name: str, old_sticker: str, sticker: types.InputSticker) -> bool:
"""
diff --git a/telebot/asyncio_helper.py b/telebot/asyncio_helper.py
index 287e3f7bc..b0d3b7ef3 100644
--- a/telebot/asyncio_helper.py
+++ b/telebot/asyncio_helper.py
@@ -298,7 +298,9 @@ async def send_message(
message_thread_id=None, reply_parameters=None, link_preview_options=None, business_connection_id=None, message_effect_id=None,
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_name = 'sendMessage'
- params = {'chat_id': str(chat_id), 'text': text}
+ params = {'text': text}
+ if chat_id is not None:
+ params['chat_id'] = str(chat_id)
if link_preview_options is not None:
params['link_preview_options'] = json.dumps(link_preview_options.to_dict())
if reply_markup:
@@ -339,7 +341,9 @@ async def send_rich_message(
suggested_post_parameters=None, message_thread_id=None, ephemeral_message_parameters=None):
method_url = r'sendRichMessage'
rich_message_json, files = rich_message.convert_input_rich_message()
- payload = {'chat_id': str(chat_id), 'rich_message': rich_message_json}
+ payload = {'rich_message': rich_message_json}
+ if chat_id is not None:
+ payload['chat_id'] = str(chat_id)
if disable_notification is not None:
payload['disable_notification'] = disable_notification
if protect_content is not None:
@@ -603,6 +607,114 @@ async def edit_message_checklist(
payload['reply_markup'] = await _convert_markup(reply_markup)
return await _process_request(token, method_url, params=payload)
+async def send_widget(
+ token, chat_id, html, message_thread_id=None, width=None, height=None, public_data=None, chat_data=None,
+ caption=None, parse_mode=None, caption_entities=None, show_caption_above_media=None, allow_queries=None,
+ is_shared=None, disable_notification=None, protect_content=None, allow_paid_broadcast=None,
+ message_effect_id=None, reply_parameters=None, reply_markup=None):
+ method_url = r'sendWidget'
+ payload = {'chat_id': chat_id, 'html': html}
+ if message_thread_id is not None:
+ payload['message_thread_id'] = message_thread_id
+ if width is not None:
+ payload['width'] = width
+ if height is not None:
+ payload['height'] = height
+ if public_data is not None:
+ payload['public_data'] = public_data
+ if chat_data is not None:
+ payload['chat_data'] = chat_data
+ if caption:
+ payload['caption'] = caption
+ 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 show_caption_above_media is not None:
+ payload['show_caption_above_media'] = show_caption_above_media
+ if allow_queries is not None:
+ payload['allow_queries'] = allow_queries
+ if is_shared is not None:
+ payload['is_shared'] = is_shared
+ if disable_notification is not None:
+ payload['disable_notification'] = disable_notification
+ if protect_content is not None:
+ payload['protect_content'] = protect_content
+ if allow_paid_broadcast is not None:
+ payload['allow_paid_broadcast'] = allow_paid_broadcast
+ if message_effect_id:
+ payload['message_effect_id'] = message_effect_id
+ if reply_parameters:
+ payload['reply_parameters'] = reply_parameters.to_json()
+ if reply_markup:
+ payload['reply_markup'] = await _convert_markup(reply_markup)
+ return await _process_request(token, method_url, params=payload, method='post')
+
+
+async def send_shared_widget(
+ token, chat_id, widget_id, message_thread_id=None, chat_data=None, caption=None, parse_mode=None,
+ caption_entities=None, show_caption_above_media=None, disable_notification=None, protect_content=None,
+ allow_paid_broadcast=None, message_effect_id=None, reply_parameters=None, reply_markup=None):
+ method_url = r'sendSharedWidget'
+ payload = {'chat_id': chat_id, 'widget_id': widget_id}
+ if message_thread_id is not None:
+ payload['message_thread_id'] = message_thread_id
+ if chat_data is not None:
+ payload['chat_data'] = chat_data
+ if caption:
+ payload['caption'] = caption
+ 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 show_caption_above_media is not None:
+ payload['show_caption_above_media'] = show_caption_above_media
+ if disable_notification is not None:
+ payload['disable_notification'] = disable_notification
+ if protect_content is not None:
+ payload['protect_content'] = protect_content
+ if allow_paid_broadcast is not None:
+ payload['allow_paid_broadcast'] = allow_paid_broadcast
+ if message_effect_id:
+ payload['message_effect_id'] = message_effect_id
+ if reply_parameters:
+ payload['reply_parameters'] = reply_parameters.to_json()
+ if reply_markup:
+ payload['reply_markup'] = await _convert_markup(reply_markup)
+ return await _process_request(token, method_url, params=payload, method='post')
+
+
+async def answer_widget_query(token, widget_query_id, data=None):
+ method_url = r'answerWidgetQuery'
+ payload = {'widget_query_id': widget_query_id}
+ if data is not None:
+ payload['data'] = data
+ return await _process_request(token, method_url, params=payload, method='post')
+
+
+async def edit_message_widget_data(token, chat_id=None, message_id=None, inline_message_id=None, public_data=None, chat_data=None):
+ method_url = r'editMessageWidgetData'
+ 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 public_data is not None:
+ payload['public_data'] = public_data
+ if chat_data is not None:
+ payload['chat_data'] = chat_data
+ return await _process_request(token, method_url, params=payload, method='post')
+
+
+async def edit_shared_widget_data(token, widget_id, public_data, cache_time=None):
+ method_url = r'editSharedWidgetData'
+ payload = {'widget_id': widget_id, 'public_data': public_data}
+ if cache_time is not None:
+ payload['cache_time'] = cache_time
+ return await _process_request(token, method_url, params=payload, method='post')
+
async def send_dice(
token, chat_id,
emoji=None, disable_notification=None,
@@ -647,7 +759,9 @@ async def send_photo(
business_connection_id=None, message_effect_id=None, show_caption_above_media=None, allow_paid_broadcast=None,
direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendPhoto'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if util.is_string(photo):
payload['photo'] = photo
@@ -700,7 +814,9 @@ async def send_live_photo(
business_connection_id=None, message_effect_id=None, show_caption_above_media=None, allow_paid_broadcast=None,
direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendLivePhoto'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = {}
if util.is_string(live_photo):
payload['live_photo'] = live_photo
@@ -832,7 +948,9 @@ async def send_location(
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendLocation'
- payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude}
+ payload = {'latitude': latitude, 'longitude': longitude}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if live_period:
payload['live_period'] = live_period
if horizontal_accuracy:
@@ -925,7 +1043,9 @@ async def send_venue(
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None,
ephemeral_message_parameters=None):
method_url = r'sendVenue'
- payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address}
+ payload = {'latitude': latitude, 'longitude': longitude, 'title': title, 'address': address}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if foursquare_id:
payload['foursquare_id'] = foursquare_id
if foursquare_type:
@@ -967,7 +1087,9 @@ async def send_contact(
protect_content=None, message_thread_id=None,reply_parameters=None, business_connection_id=None, message_effect_id=None,
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendContact'
- payload = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
+ payload = {'phone_number': phone_number, 'first_name': first_name}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
if last_name:
payload['last_name'] = last_name
if vcard:
@@ -1036,7 +1158,9 @@ async def send_video(token, chat_id, data, duration=None, caption=None, reply_m
message_effect_id=None, show_caption_above_media=None, allow_paid_broadcast=None, cover=None, start_timestamp=None,
direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendVideo'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
files = {'video': data}
@@ -1112,7 +1236,9 @@ async def send_animation(
has_spoiler=None,reply_parameters=None, business_connection_id=None, message_effect_id=None, show_caption_above_media=None,
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendAnimation'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
files = {'animation': data}
@@ -1174,7 +1300,9 @@ async def send_voice(token, chat_id, voice, caption=None, duration=None, reply_
protect_content=None, message_thread_id=None,reply_parameters=None,business_connection_id=None, message_effect_id=None,
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendVoice'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(voice):
files = {'voice': voice}
@@ -1220,7 +1348,9 @@ async def send_video_note(token, chat_id, data, duration=None, length=None, rep
message_thread_id=None,reply_parameters=None, business_connection_id=None, message_effect_id=None, allow_paid_broadcast=None,
direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendVideoNote'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
files = {'video_note': data}
@@ -1272,7 +1402,9 @@ async def send_audio(token, chat_id, audio, caption=None, duration=None, perform
caption_entities=None, protect_content=None, message_thread_id=None,reply_parameters=None, business_connection_id=None,
message_effect_id=None, allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = r'sendAudio'
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(audio):
files = {'audio': audio}
@@ -1331,7 +1463,9 @@ async def send_data(token, chat_id, data, data_type, reply_markup=None, parse_m
message_thread_id=None, emoji=None,reply_parameters=None, business_connection_id=None, message_effect_id=None,
allow_paid_broadcast=None, direct_messages_topic_id=None, suggested_post_parameters=None, ephemeral_message_parameters=None):
method_url = await get_method_by_type(data_type)
- payload = {'chat_id': chat_id}
+ payload = {}
+ if chat_id is not None:
+ payload['chat_id'] = chat_id
files = None
if not util.is_string(data):
file_data = data
@@ -2339,18 +2473,28 @@ async def send_gift(token, gift_id, text=None, text_parse_mode=None, text_entiti
payload['user_id'] = user_id
return await _process_request(token, method_url, params=payload, method='post')
-async def verify_user(token, user_id, custom_description=None):
+async def verify_user(token, user_id, custom_description=None, custom_description_parse_mode=None,
+ custom_description_entities=None):
method_url = 'verifyUser'
payload = {'user_id': user_id}
if custom_description:
payload['custom_description'] = custom_description
+ if custom_description_parse_mode:
+ payload['custom_description_parse_mode'] = custom_description_parse_mode
+ if custom_description_entities:
+ payload['custom_description_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(custom_description_entities))
return await _process_request(token, method_url, params=payload, method='post')
-async def verify_chat(token, chat_id, custom_description=None):
+async def verify_chat(token, chat_id, custom_description=None, custom_description_parse_mode=None,
+ custom_description_entities=None):
method_url = 'verifyChat'
payload = {'chat_id': chat_id}
if custom_description:
payload['custom_description'] = custom_description
+ if custom_description_parse_mode:
+ payload['custom_description_parse_mode'] = custom_description_parse_mode
+ if custom_description_entities:
+ payload['custom_description_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(custom_description_entities))
return await _process_request(token, method_url, params=payload, method='post')
async def remove_user_verification(token, user_id):
@@ -2502,6 +2646,11 @@ async def convert_gift_to_stars(token, business_connection_id, owned_gift_id):
payload = {'business_connection_id': business_connection_id, 'owned_gift_id': owned_gift_id}
return await _process_request(token, method_url, params=payload, method='post')
+async def delete_business_account_gift(token, business_connection_id, owned_gift_id):
+ method_url = 'deleteBusinessAccountGift'
+ payload = {'business_connection_id': business_connection_id, 'owned_gift_id': owned_gift_id}
+ return await _process_request(token, method_url, params=payload, method='post')
+
async def upgrade_gift(token, business_connection_id, owned_gift_id, keep_original_details=None, star_count=None):
method_url = 'upgradeGift'
payload = {'business_connection_id': business_connection_id, 'owned_gift_id': owned_gift_id}
@@ -2608,6 +2757,15 @@ async def get_available_gifts(token):
method_url = 'getAvailableGifts'
return await _process_request(token, method_url)
+async def get_unique_gift(token, name):
+ method_url = 'getUniqueGift'
+ payload = {'name': name}
+ return await _process_request(token, method_url, params=payload)
+
+async def get_chat_share_theme_backdrops(token):
+ method_url = 'getChatShareThemeBackdrops'
+ return await _process_request(token, method_url)
+
async def set_custom_emoji_sticker_set_thumbnail(token, name, custom_emoji_id=None):
method_url = 'setCustomEmojiStickerSetThumbnail'
payload = {'name': name}
diff --git a/telebot/types.py b/telebot/types.py
index 27c19ec5d..559fa1fa0 100644
--- a/telebot/types.py
+++ b/telebot/types.py
@@ -152,6 +152,12 @@ class Update(JsonDeserializable):
:param callback_query: Optional. New incoming callback query
:type callback_query: :class:`telebot.types.CallbackQuery`
+ :param widget_query: Optional. New incoming query from a widget in a message sent by the bot or via the bot
+ :type widget_query: :class:`telebot.types.WidgetQuery`
+
+ :param shared_widget_query: Optional. New incoming query from a forwarded message with a shared widget
+ :type shared_widget_query: :class:`telebot.types.SharedWidgetQuery`
+
:param shipping_query: Optional. New incoming shipping query. Only for invoices with flexible price
:type shipping_query: :class:`telebot.types.ShippingQuery`
@@ -242,20 +248,22 @@ def de_json(cls, json_string):
guest_message = Message.de_json(obj.get('guest_message'))
subscription = BotSubscriptionUpdated.de_json(obj.get('subscription'))
stopped_message_generation = MessageGenerationStopped.de_json(obj.get('stopped_message_generation'))
+ widget_query = WidgetQuery.de_json(obj.get('widget_query'))
+ shared_widget_query = SharedWidgetQuery.de_json(obj.get('shared_widget_query'))
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, chat_join_request, message_reaction, message_reaction_count,
removed_chat_boost, chat_boost, business_connection, business_message, edited_business_message,
deleted_business_messages, purchased_paid_media, managed_bot, guest_message, subscription,
- stopped_message_generation)
+ stopped_message_generation, widget_query, shared_widget_query)
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, chat_join_request, message_reaction, message_reaction_count,
removed_chat_boost, chat_boost, business_connection, business_message, edited_business_message,
deleted_business_messages, purchased_paid_media, managed_bot, guest_message, subscription,
- stopped_message_generation):
+ stopped_message_generation, widget_query, shared_widget_query):
self.update_id: int = update_id
self.message: Optional[Message] = message
self.edited_message: Optional[Message] = edited_message
@@ -284,6 +292,8 @@ def __init__(self, update_id, message, edited_message, channel_post, edited_chan
self.guest_message: Optional[Message] = guest_message
self.subscription: Optional[BotSubscriptionUpdated] = subscription
self.stopped_message_generation: Optional[MessageGenerationStopped] = stopped_message_generation
+ self.widget_query: Optional[WidgetQuery] = widget_query
+ self.shared_widget_query: Optional[SharedWidgetQuery] = shared_widget_query
class ChatMemberUpdated(JsonDeserializable):
"""
@@ -795,6 +805,12 @@ class ChatFullInfo(JsonDeserializable):
:param community: Optional. The Community to which the chat belongs
:type community: :class:`telebot.types.Community`
+ :param ton_wallet_card: Optional. For private chats, the TON wallet card of the user, which is shown on their profile page
+ :type ton_wallet_card: :class:`telebot.types.TonWalletCard`
+
+ :param share_theme: Optional. For private chats, supergroups and channels, the theme of the screen for sharing a link to the user or the chat; omitted if the default theme is used
+ :type share_theme: :class:`telebot.types.ChatShareTheme`
+
:return: Instance of the class
:rtype: :class:`telebot.types.ChatFullInfo`
"""
@@ -836,6 +852,10 @@ def de_json(cls, json_string):
obj['guard_bot'] = User.de_json(obj['guard_bot'])
if 'community' in obj:
obj['community'] = Community.de_json(obj['community'])
+ if 'ton_wallet_card' in obj:
+ obj['ton_wallet_card'] = TonWalletCard.de_json(obj['ton_wallet_card'])
+ if 'share_theme' in obj:
+ obj['share_theme'] = ChatShareTheme.de_json(obj['share_theme'])
return cls(**obj)
def __init__(self, id: int, type: str,
@@ -882,6 +902,7 @@ def __init__(self, id: int, type: str,
unique_gift_colors: Optional[UniqueGiftColors] = None,
first_profile_audio: Optional[Audio] = None,
guard_bot: Optional[User] = None, community: Optional[Community] = None,
+ ton_wallet_card: Optional[TonWalletCard] = None, share_theme: Optional[ChatShareTheme] = None,
**kwargs):
self.id: int = id
self.type: str = type
@@ -936,6 +957,8 @@ def __init__(self, id: int, type: str,
self.first_profile_audio: Optional[Audio] = first_profile_audio
self.guard_bot: Optional[User] = guard_bot
self.community: Optional[Community] = community
+ self.ton_wallet_card: Optional[TonWalletCard] = ton_wallet_card
+ self.share_theme: Optional[ChatShareTheme] = share_theme
@property
@@ -1210,13 +1233,16 @@ class Message(JsonDeserializable):
:param voice: Optional. Message is a voice message, information about the file
:type voice: :class:`telebot.types.Voice`
- :param caption: Optional. Caption for the animation, audio, document, paid media, photo, video or voice
+ :param widget: Optional. Message is an HTML widget, information about the widget
+ :type widget: :class:`telebot.types.Widget`
+
+ :param caption: Optional. Caption for the animation, audio, document, live photo, paid media, photo, video, voice, or widget
:type caption: :obj:`str`
:param caption_entities: Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
:type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
- :param show_caption_above_media: Optional. True, if the caption must be shown above the message media
+ :param show_caption_above_media: Optional. True, if the caption must be shown above the message media or the widget
:type show_caption_above_media: :obj:`bool`
:param has_media_spoiler: Optional. True, if the message media is covered by a spoiler animation
@@ -1381,6 +1407,9 @@ class Message(JsonDeserializable):
:param paid_message_price_changed: Optional. Service message: the price for paid messages has changed in the chat
:type paid_message_price_changed: :class:`telebot.types.PaidMessagePriceChanged`
+ :param paid_messages_waived: Optional. Service message: the sender of the message used a link of the other user, which allows sending messages to the user without paying Telegram Stars
+ :type paid_messages_waived: :class:`telebot.types.PaidMessagesWaived`
+
:param poll_option_added: Optional. Service message: answer option was added to a poll
:type poll_option_added: :class:`telebot.types.PollOptionAdded`
@@ -1402,6 +1431,9 @@ class Message(JsonDeserializable):
:param suggested_post_refunded: Optional. Service message: payment for a suggested post was refunded
:type suggested_post_refunded: :class:`telebot.types.SuggestedPostRefunded`
+ :param ton_wallet_transfer: Optional. Service message: a transfer with a TON wallet
+ :type ton_wallet_transfer: :class:`telebot.types.TonWalletTransfer`
+
:param video_chat_scheduled: Optional. Service message: video chat scheduled
:type video_chat_scheduled: :class:`telebot.types.VideoChatScheduled`
@@ -1751,6 +1783,15 @@ def de_json(cls, json_string):
if 'community_chat_joined' in obj:
opts['community_chat_joined'] = CommunityChatJoined.de_json(obj['community_chat_joined'])
content_type = 'community_chat_joined'
+ if 'widget' in obj:
+ opts['widget'] = Widget.de_json(obj['widget'])
+ content_type = 'widget'
+ if 'ton_wallet_transfer' in obj:
+ opts['ton_wallet_transfer'] = TonWalletTransfer.de_json(obj['ton_wallet_transfer'])
+ content_type = 'ton_wallet_transfer'
+ if 'paid_messages_waived' in obj:
+ opts['paid_messages_waived'] = PaidMessagesWaived.de_json(obj['paid_messages_waived'])
+ content_type = 'paid_messages_waived'
return cls(message_id, from_user, date, chat, content_type, opts, json_string)
@classmethod
@@ -1903,6 +1944,9 @@ def __init__(self, message_id, from_user, date, chat, content_type, options, jso
self.community_chat_added: Optional[CommunityChatAdded] = None
self.community_chat_removed: Optional[CommunityChatRemoved] = None
self.community_chat_joined: Optional[CommunityChatJoined] = None
+ self.widget: Optional[Widget] = None
+ self.ton_wallet_transfer: Optional[TonWalletTransfer] = None
+ self.paid_messages_waived: Optional[PaidMessagesWaived] = None
self.game: Optional[Game] = None
self.passport_data: Optional[PassportData] = None
@@ -2020,7 +2064,7 @@ class MessageEntity(Dictionaryable, JsonSerializable, JsonDeserializable):
Telegram documentation: https://core.telegram.org/bots/api#messageentity
- :param type: Type of the entity. Currently, can be “mention” ( @username ), "hashtag" ( #hashtag or #hashtag@chatusername ), "cashtag" ( $USD or $USD@chatusername ), “bot_command” ( /start@jobs_bot ), "url" ( https://telegram.org ), "email" ( do-not-reply@telegram.org ), “phone_number” ( +1-212-555-0123 ), "bold" ( bold text ), "italic" ( italic text ), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames ), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time).
+ :param type: Type of the entity. Currently, can be “mention” ( @username ), "hashtag" ( #hashtag or #hashtag@chatusername ), "cashtag" ( $USD or $USD@chatusername ), “bot_command” ( /start@jobs_bot ), "url" ( https://telegram.org ), "email" ( do-not-reply@telegram.org ), “phone_number” ( +1-212-555-0123 ), “bank_card_number” (bank card number), “ton_address” (address in the TON blockchain), "bold" ( bold text ), "italic" ( italic text ), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames ), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time).
:type type: :obj:`str`
:param offset: Offset in UTF-16 code units to the start of the entity
@@ -3832,7 +3876,7 @@ class ChatMemberRestricted(ChatMember):
:param can_send_polls: True, if the user is allowed to send polls and checklists
:type can_send_polls: :obj:`bool`
- :param can_send_other_messages: True, if the user is allowed to send animations, games, stickers and use inline bots
+ :param can_send_other_messages: True, if the user is allowed to send animations, games, stickers, widgets and use inline bots
:type can_send_other_messages: :obj:`bool`
:param can_add_web_page_previews: True, if the user is allowed to add web page previews to their messages
@@ -3969,7 +4013,7 @@ class ChatPermissions(JsonDeserializable, JsonSerializable, Dictionaryable):
:param can_send_polls: Optional. True, if the user is allowed to send polls and checklists
:type can_send_polls: :obj:`bool`
- :param can_send_other_messages: Optional. True, if the user is allowed to send animations, games, stickers and use inline bots
+ :param can_send_other_messages: Optional. True, if the user is allowed to send animations, games, stickers, widgets and use inline bots
:type can_send_other_messages: :obj:`bool`
:param can_add_web_page_previews: Optional. True, if the user is allowed to add web page previews to their messages
@@ -4740,6 +4784,144 @@ def to_json(self) -> str:
return json.dumps(self.to_dict())
+class InputWidgetMessageContent(Dictionaryable):
+ """
+ Represents the content of a message with an HTML widget to be sent as the result of an inline query.
+ Currently, widgets can't be sent in response to inline queries in the production environment.
+
+ Telegram documentation: https://core.telegram.org/bots/api#inputwidgetmessagecontent
+
+ :param html: HTML code of the widget, 1-32768 bytes. The code must not exceed 4096 bytes when compressed by zlib with the maximum compression level.
+ :type html: :obj:`str`
+
+ :param width: Optional. Width of the widget in logical pixels; omit if the widget must occupy the whole width of the message bubble. The width is clamped by the app to the range from 200 to the maximum width of the message bubble.
+ :type width: :obj:`int`
+
+ :param height: Optional. Height of the widget in logical pixels; omit if the height of the widget isn't fixed. The height is clamped by the app to the range 50-600.
+ :type height: :obj:`int`
+
+ :param public_data: Optional. Public data of the widget, 0-1024 bytes, which will be available wherever the widget is shown. If the widget is shared, then all messages with it will have the same public data.
+ :type public_data: :obj:`str`
+
+ :param chat_data: Optional. Data of the widget, which is specific to the message, 0-1024 bytes
+ :type chat_data: :obj:`str`
+
+ :param caption: Optional. Widget caption, 0-1024 characters after entities parsing
+ :type caption: :obj:`str`
+
+ :param parse_mode: Optional. Mode for parsing entities in the widget caption. See formatting options for more details.
+ :type parse_mode: :obj:`str`
+
+ :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
+ :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
+ :param show_caption_above_media: Optional. Pass True if the caption must be shown above the widget
+ :type show_caption_above_media: :obj:`bool`
+
+ :param allow_queries: Optional. Pass True to allow the widget to send queries to the bot
+ :type allow_queries: :obj:`bool`
+
+ :param is_shared: Optional. Pass True to create a shared widget. Each message sent from the result creates a separate shared widget, whose identifier is received by the bot only in the field widget_id of queries from the widget. To send an existing shared widget in response to an inline query, use InputSharedWidgetMessageContent instead.
+ :type is_shared: :obj:`bool`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.InputWidgetMessageContent`
+ """
+ def __init__(self, html: str, width: Optional[int] = None, height: Optional[int] = None,
+ public_data: Optional[str] = None, chat_data: Optional[str] = None, caption: Optional[str] = None,
+ parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None,
+ show_caption_above_media: Optional[bool] = None, allow_queries: Optional[bool] = None,
+ is_shared: Optional[bool] = None):
+ self.html: str = html
+ self.width: Optional[int] = width
+ self.height: Optional[int] = height
+ self.public_data: Optional[str] = public_data
+ self.chat_data: Optional[str] = chat_data
+ self.caption: Optional[str] = caption
+ self.parse_mode: Optional[str] = parse_mode
+ self.caption_entities: Optional[List[MessageEntity]] = caption_entities
+ self.show_caption_above_media: Optional[bool] = show_caption_above_media
+ self.allow_queries: Optional[bool] = allow_queries
+ self.is_shared: Optional[bool] = is_shared
+
+ def to_dict(self):
+ json_dict = {'html': self.html}
+ if self.width is not None:
+ json_dict['width'] = self.width
+ if self.height is not None:
+ json_dict['height'] = self.height
+ if self.public_data is not None:
+ json_dict['public_data'] = self.public_data
+ if self.chat_data is not None:
+ json_dict['chat_data'] = self.chat_data
+ if self.caption is not None:
+ 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_list_of_dicts(self.caption_entities)
+ if self.show_caption_above_media is not None:
+ json_dict['show_caption_above_media'] = self.show_caption_above_media
+ if self.allow_queries is not None:
+ json_dict['allow_queries'] = self.allow_queries
+ if self.is_shared is not None:
+ json_dict['is_shared'] = self.is_shared
+ return json_dict
+
+
+class InputSharedWidgetMessageContent(Dictionaryable):
+ """
+ Represents the content of a message with a shared widget to be sent as the result of an inline query.
+ Currently, widgets can't be sent in response to inline queries in the production environment.
+
+ Telegram documentation: https://core.telegram.org/bots/api#inputsharedwidgetmessagecontent
+
+ :param widget_id: Unique identifier of the shared widget created by the bot
+ :type widget_id: :obj:`str`
+
+ :param chat_data: Optional. Data of the widget, which is specific to the message, 0-1024 bytes
+ :type chat_data: :obj:`str`
+
+ :param caption: Optional. Widget caption, 0-1024 characters after entities parsing
+ :type caption: :obj:`str`
+
+ :param parse_mode: Optional. Mode for parsing entities in the widget caption. See formatting options for more details.
+ :type parse_mode: :obj:`str`
+
+ :param caption_entities: Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
+ :type caption_entities: :obj:`list` of :class:`telebot.types.MessageEntity`
+
+ :param show_caption_above_media: Optional. Pass True if the caption must be shown above the widget
+ :type show_caption_above_media: :obj:`bool`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.InputSharedWidgetMessageContent`
+ """
+ def __init__(self, widget_id: str, chat_data: Optional[str] = None, caption: Optional[str] = None,
+ parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None,
+ show_caption_above_media: Optional[bool] = None):
+ self.widget_id: str = widget_id
+ self.chat_data: Optional[str] = chat_data
+ self.caption: Optional[str] = caption
+ self.parse_mode: Optional[str] = parse_mode
+ self.caption_entities: Optional[List[MessageEntity]] = caption_entities
+ self.show_caption_above_media: Optional[bool] = show_caption_above_media
+
+ def to_dict(self):
+ json_dict = {'widget_id': self.widget_id}
+ if self.chat_data is not None:
+ json_dict['chat_data'] = self.chat_data
+ if self.caption is not None:
+ 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_list_of_dicts(self.caption_entities)
+ if self.show_caption_above_media is not None:
+ json_dict['show_caption_above_media'] = self.show_caption_above_media
+ return json_dict
+
+
class ChosenInlineResult(JsonDeserializable):
"""
Represents a result of an inline query that was chosen by the user and sent to their chat partner.
@@ -9333,6 +9515,9 @@ class ExternalReplyInfo(JsonDeserializable):
:param voice: Optional. Message is a voice message, information about the file
:type voice: :class:`Voice`
+ :param widget: Optional. Message is an HTML widget, information about the widget
+ :type widget: :class:`Widget`
+
:param has_media_spoiler: Optional. True, if the message media is covered by a spoiler animation
:type has_media_spoiler: :obj:`bool`
@@ -9420,6 +9605,8 @@ def de_json(cls, json_string):
obj['checklist'] = Checklist.de_json(obj['checklist'])
if 'live_photo' in obj:
obj['live_photo'] = LivePhoto.de_json(obj['live_photo'])
+ if 'widget' in obj:
+ obj['widget'] = Widget.de_json(obj['widget'])
return cls(**obj)
def __init__(
@@ -9433,7 +9620,8 @@ def __init__(
giveaway_winners: Optional[GiveawayWinners]=None, invoice: Optional[Invoice]=None,
location: Optional[Location]=None, poll: Optional[Poll]=None,
venue: Optional[Venue]=None, paid_media: Optional[PaidMediaInfo]=None,
- live_photo: Optional[LivePhoto]=None, checklist: Optional[Checklist]=None, **kwargs) -> None:
+ live_photo: Optional[LivePhoto]=None, checklist: Optional[Checklist]=None,
+ widget: Optional[Widget]=None, **kwargs) -> None:
self.origin: MessageOrigin = origin
self.chat: Optional[Chat] = chat
self.message_id: Optional[int] = message_id
@@ -9460,6 +9648,7 @@ def __init__(
self.paid_media: Optional[PaidMediaInfo] = paid_media
self.live_photo: Optional[LivePhoto] = live_photo
self.checklist: Optional[Checklist] = checklist
+ self.widget: Optional[Widget] = widget
# noinspection PyUnresolvedReferences,PyShadowingBuiltins
@@ -9886,13 +10075,16 @@ class TextQuote(JsonDeserializable):
Telegram documentation: https://core.telegram.org/bots/api#textquote
- :param text: Text of the quoted part of a message that is replied to by the given message
+ :param text: Text of the quoted part of a message that is replied to by the given message; may be empty if the quote was chosen from a rich message
:type text: :obj:`str`
:param entities: Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are kept in quotes.
:type entities: :obj:`list` of :class:`MessageEntity`
- :param position: Approximate quote position in the original message in UTF-16 code units as specified by the sender
+ :param rich_texts: Optional. Rich text of the quote if it was chosen from a rich message. May contain only plain text, RichTextBold, RichTextItalic, RichTextUnderline, RichTextStrikethrough, RichTextSpoiler, RichTextSubscript, RichTextSuperscript, RichTextDateTime, RichTextCustomEmoji, RichTextMathematicalExpression, and arrays of them.
+ :type rich_texts: :obj:`list` of :class:`RichText`
+
+ :param position: Approximate quote position in the original message in UTF-16 code units as specified by the sender. For quotes from rich messages, it is the position in the text formed by joining plain texts of all quotable texts of the message, separated by line feeds.
:type position: :obj:`int`
:param is_manual: Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server.
@@ -9908,13 +10100,17 @@ def de_json(cls, json_string):
obj = cls.check_json(json_string)
if 'entities' in obj:
obj['entities'] = [MessageEntity.de_json(entity) for entity in obj['entities']]
+ if 'rich_texts' in obj:
+ obj['rich_texts'] = RichText.de_json(obj['rich_texts'])
return cls(**obj)
def __init__(self, text: str, position: int,
entities: Optional[List[MessageEntity]] = None,
- is_manual: Optional[bool] = None, **kwargs) -> None:
+ is_manual: Optional[bool] = None,
+ rich_texts: Optional[List[RichText]] = None, **kwargs) -> None:
self.text: str = text
self.entities: Optional[List[MessageEntity]] = entities
+ self.rich_texts: Optional[List[RichText]] = rich_texts
self.position: int = position
self.is_manual: Optional[bool] = is_manual
@@ -9955,7 +10151,10 @@ class ReplyParameters(JsonDeserializable, Dictionaryable, JsonSerializable):
:param quote_entities: Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode.
:type quote_entities: :obj:`list` of :class:`MessageEntity`
- :param quote_position: Optional. Position of the quote in the original message in UTF-16 code units
+ :param quote_rich_texts: Optional. A JSON-serialized list of quoted parts of the rich message to be replied to. Must contain one element for each quoted text of the message in the order of their appearance. Each of the following is a separate quoted text: the text of a paragraph, a heading, a preformatted block, a footer, or a mathematical expression; the text and the credit of a block quotation or a pull quotation; the summary of a details block; the caption and each cell of a table; the text and the credit of a caption of a media block, a collage, a slideshow, or a map. Texts of blocks nested in lists, block quotations, details, collages, and slideshows are separate quoted texts too. The first and the last elements can contain only a part of the corresponding text; all other elements must contain the whole text. Formatting of the quoted parts must be kept, and rich texts must be nested in the same way as in the message received from the server. Mathematical expressions must be quoted entirely. Buttons in RichBlockButtons, anchors and dividers can't be quoted. Up to 32 quoted texts with total length up to 1024 characters can be specified. Only plain text, RichTextBold, RichTextItalic, RichTextUnderline, RichTextStrikethrough, RichTextSpoiler, RichTextSubscript, RichTextSuperscript, RichTextDateTime, RichTextCustomEmoji, RichTextMathematicalExpression, and arrays of them are kept in the quote; other rich text types are replaced with their text. If non-empty, then quote, quote_parse_mode and quote_entities are ignored.
+ :type quote_rich_texts: :obj:`list` of :class:`RichText`
+
+ :param quote_position: Optional. Position of the quote in the original message in UTF-16 code units. For quotes from rich messages, it is the position in the text formed by joining plain texts of all quotable texts of the message, separated by line feeds.
:type quote_position: :obj:`int`
:param checklist_task_id: Optional. Identifier of the specific checklist task to be replied to
@@ -9974,13 +10173,16 @@ def de_json(cls, json_string):
obj = cls.check_json(json_string)
if 'quote_entities' in obj:
obj['quote_entities'] = [MessageEntity.de_json(entity) for entity in obj['quote_entities']]
+ if 'quote_rich_texts' in obj:
+ obj['quote_rich_texts'] = RichText.de_json(obj['quote_rich_texts'])
return cls(**obj)
def __init__(self, message_id: Optional[int] = None, chat_id: Optional[Union[int, str]] = None,
allow_sending_without_reply: Optional[bool] = None, quote: Optional[str] = None,
quote_parse_mode: Optional[str] = None, quote_entities: Optional[List[MessageEntity]] = None,
quote_position: Optional[int] = None, checklist_task_id: Optional[int] = None,
- poll_option_id: Optional[str] = None, ephemeral_message_id: Optional[int] = None, **kwargs) -> None:
+ poll_option_id: Optional[str] = None, ephemeral_message_id: Optional[int] = None,
+ quote_rich_texts: Optional[List[RichText]] = None, **kwargs) -> None:
self.message_id: Optional[int] = message_id
self.chat_id: Optional[Union[int, str]] = chat_id
self.allow_sending_without_reply: Optional[bool] = allow_sending_without_reply
@@ -9991,6 +10193,7 @@ def __init__(self, message_id: Optional[int] = None, chat_id: Optional[Union[int
self.checklist_task_id: Optional[int] = checklist_task_id
self.poll_option_id: Optional[str] = poll_option_id
self.ephemeral_message_id: Optional[int] = ephemeral_message_id
+ self.quote_rich_texts: Optional[List[RichText]] = quote_rich_texts
if self.message_id is None and self.ephemeral_message_id is None:
raise ValueError("Either 'message_id' or 'ephemeral_message_id' must be provided.")
@@ -10009,6 +10212,8 @@ def to_dict(self) -> dict:
json_dict['quote_parse_mode'] = self.quote_parse_mode
if self.quote_entities is not None:
json_dict['quote_entities'] = [entity.to_dict() for entity in self.quote_entities]
+ if self.quote_rich_texts is not None:
+ json_dict['quote_rich_texts'] = RichText.richtext_to_dict(self.quote_rich_texts)
if self.quote_position is not None:
json_dict['quote_position'] = self.quote_position
if self.checklist_task_id is not None:
@@ -12817,32 +13022,32 @@ def convert_input_story(self):
return self.to_json(), {self._video_name: self.video}
-class StoryAreaPosition(JsonSerializable):
+class AreaPosition(JsonSerializable, JsonDeserializable):
"""
- Describes the position of a clickable area within a story.
+ Describes the position of a rectangle area on a story media or a TON wallet card.
- Telegram documentation: https://core.telegram.org/bots/api#storyareaposition
+ Telegram documentation: https://core.telegram.org/bots/api#areaposition
- :param x_percentage: The abscissa of the area's center, as a percentage of the media width
+ :param x_percentage: The abscissa of the area's center, as a percentage of the media or the card width
:type x_percentage: :obj:`float`
- :param y_percentage: The ordinate of the area's center, as a percentage of the media height
+ :param y_percentage: The ordinate of the area's center, as a percentage of the media or the card height
:type y_percentage: :obj:`float`
- :param width_percentage: The width of the area's rectangle, as a percentage of the media width
+ :param width_percentage: The width of the area's rectangle, as a percentage of the media or the card width
:type width_percentage: :obj:`float`
- :param height_percentage: The height of the area's rectangle, as a percentage of the media height
+ :param height_percentage: The height of the area's rectangle, as a percentage of the media or the card height
:type height_percentage: :obj:`float`
:param rotation_angle: The clockwise rotation angle of the rectangle, in degrees; 0-360
:type rotation_angle: :obj:`float`
- :param corner_radius_percentage: The radius of the rectangle corner rounding, as a percentage of the media width
+ :param corner_radius_percentage: The radius of the rectangle corner rounding, as a percentage of the media or the card width
:type corner_radius_percentage: :obj:`float`
:return: Instance of the class
- :rtype: :class:`StoryAreaPosition`
+ :rtype: :class:`AreaPosition`
"""
def __init__(self, x_percentage: float, y_percentage: float, width_percentage: float,
height_percentage: float, rotation_angle: float, corner_radius_percentage: float, **kwargs):
@@ -12853,6 +13058,12 @@ def __init__(self, x_percentage: float, y_percentage: float, width_percentage: f
self.rotation_angle: float = rotation_angle
self.corner_radius_percentage: float = corner_radius_percentage
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
def to_json(self):
return json.dumps(self.to_dict())
@@ -12868,6 +13079,15 @@ def to_dict(self):
return data
+class StoryAreaPosition(AreaPosition):
+ """Deprecated. Use AreaPosition instead."""
+ def __init__(self, x_percentage: float, y_percentage: float, width_percentage: float,
+ height_percentage: float, rotation_angle: float, corner_radius_percentage: float, **kwargs):
+ log_deprecation_warning('The class "StoryAreaPosition" is deprecated, use "AreaPosition" instead')
+ super().__init__(x_percentage, y_percentage, width_percentage, height_percentage,
+ rotation_angle, corner_radius_percentage)
+
+
class LocationAddress(JsonSerializable):
"""
Describes the physical address of a location.
@@ -13125,7 +13345,7 @@ class StoryArea(JsonSerializable):
Telegram documentation: https://core.telegram.org/bots/api#storyarea
:param position: Position of the area
- :type position: :class:`StoryAreaPosition`
+ :type position: :class:`AreaPosition`
:param type: Type of the area
:type type: :class:`StoryAreaType`
@@ -13133,8 +13353,8 @@ class StoryArea(JsonSerializable):
:return: Instance of the class
:rtype: :class:`StoryArea`
"""
- def __init__(self, position: StoryAreaPosition, type: StoryAreaType, **kwargs):
- self.position: StoryAreaPosition = position
+ def __init__(self, position: AreaPosition, type: StoryAreaType, **kwargs):
+ self.position: AreaPosition = position
self.type: StoryAreaType = type
def to_json(self):
@@ -14217,7 +14437,7 @@ class KeyboardButtonRequestManagedBot(JsonSerializable):
:param suggested_name: Optional. Suggested name for the bot
:type suggested_name: :obj:`str`
- :param suggested_username: Optional. Suggested username for the bot
+ :param suggested_username: Optional. Suggested username for the bot. The username must end with “bot”. If the user creating the bot has a Telegram Premium subscription, then the username can also end with “agent”, “ai”, “app”, “game”, or “gay”; in this case, the username will be assigned to the bot as a secondary username, and a regular username ending with “bot” will be assigned to the bot automatically.
:type suggested_username: :obj:`str`
:return: Instance of the class
@@ -14552,7 +14772,8 @@ def to_dict(self):
# why not..
MaybeInaccessibleMessage = Union[InaccessibleMessage, Message]
-InputMessageContent = Union[InputTextMessageContent, InputLocationMessageContent, InputVenueMessageContent, InputContactMessageContent, InputInvoiceMessageContent, InputRichMessageContent]
+InputMessageContent = Union[InputTextMessageContent, InputLocationMessageContent, InputVenueMessageContent, InputContactMessageContent, InputInvoiceMessageContent, InputRichMessageContent,
+ InputWidgetMessageContent, InputSharedWidgetMessageContent]
InputPollMedia = Union[InputMediaAnimation, InputMediaAudio, InputMediaDocument, InputMediaLivePhoto, InputMediaLocation, InputMediaPhoto, InputMediaVenue, InputMediaVideo]
@@ -14666,6 +14887,7 @@ class RichText(JsonDeserializable, Dictionaryable, ABC):
- :class:`RichTextEmailAddress`
- :class:`RichTextPhoneNumber`
- :class:`RichTextBankCardNumber`
+ - :class:`RichTextTonAddress`
- :class:`RichTextMention`
- :class:`RichTextHashtag`
- :class:`RichTextCashtag`
@@ -14752,6 +14974,8 @@ def _from_dict(cls, json_string):
return RichTextPhoneNumber.de_json(obj)
elif type == 'bank_card_number':
return RichTextBankCardNumber.de_json(obj)
+ elif type == 'ton_address':
+ return RichTextTonAddress.de_json(obj)
elif type == 'mention':
return RichTextMention.de_json(obj)
elif type == 'hashtag':
@@ -15372,6 +15596,43 @@ def to_dict(self):
return data
+class RichTextTonAddress(RichText):
+ """
+ An address in the TON blockchain.
+
+ Telegram documentation: https://core.telegram.org/bots/api#richtexttonaddress
+
+ :param type: Type of the rich text, always “ton_address”
+ :type type: :obj:`str`
+
+ :param text: Text of the address
+ :type text: :class:`RichText`
+
+ :param address: The address
+ :type address: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`RichTextTonAddress`
+ """
+ def __init__(self, text: RichText, address: str, **kwargs):
+ super().__init__(type='ton_address', **kwargs)
+ self.text: RichText = text
+ self.address: str = address
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['text'] = RichText.de_json(obj['text'])
+ return cls(**obj)
+
+ def to_dict(self):
+ data = super().to_dict()
+ data['text'] = RichText.richtext_to_dict(self.text)
+ data['address'] = self.address
+ return data
+
+
class RichTextMention(RichText):
"""
A mention by a username.
@@ -17554,10 +17815,10 @@ class EphemeralMessageParameters(Dictionaryable, JsonSerializable):
Telegram documentation: https://core.telegram.org/bots/api#ephemeralmessageparameters
- :param receiver_user_id: Identifier of the user who will receive the message. It is not guaranteed that the user will receive the message, especially if they are offline. See here for more details.
+ :param receiver_user_id: Optional. Identifier of the user who will receive the message; required unless the message is sent as an ephemeral reply to a callback query. If omitted, then the parameter chat_id of the method is ignored. If specified together with callback_query_id, then it must be the identifier of the user who pressed the button. Must be omitted for messages sent in chats where the bot isn't a member, unless the message is a reply to an ephemeral message. It is not guaranteed that the user will receive the message, especially if they are offline. See here for more details.
:type receiver_user_id: :obj:`int`
- :param callback_query_id: Optional. Identifier of the callback query which triggered the message, if any
+ :param callback_query_id: Optional. Identifier of the callback query which triggered the message, if any. If specified and receiver_user_id is omitted, then the message is sent as an ephemeral reply to the callback query and will be shown only to the user who pressed the button. Ephemeral replies can't be sent to callback queries from messages in channel direct messages chats. The bot must still answer the callback query using answerCallbackQuery.
:type callback_query_id: :obj:`str`
:param replace_callback_query_message: Optional. Pass True if the ephemeral message must be shown in place of the original message. Must be False for callback queries from ephemeral messages, which must be edited using regular editEphemeralMessage… methods.
@@ -17566,14 +17827,16 @@ class EphemeralMessageParameters(Dictionaryable, JsonSerializable):
:return: Instance of the class
:rtype: :class:`telebot.types.EphemeralMessageParameters`
"""
- def __init__(self, receiver_user_id: int, callback_query_id: Optional[str] = None,
+ def __init__(self, receiver_user_id: Optional[int] = None, callback_query_id: Optional[str] = None,
replace_callback_query_message: Optional[bool] = None):
- self.receiver_user_id: int = receiver_user_id
+ self.receiver_user_id: Optional[int] = receiver_user_id
self.callback_query_id: Optional[str] = callback_query_id
self.replace_callback_query_message: Optional[bool] = replace_callback_query_message
def to_dict(self):
- data = {'receiver_user_id': self.receiver_user_id}
+ data = {}
+ if self.receiver_user_id is not None:
+ data['receiver_user_id'] = self.receiver_user_id
if self.callback_query_id is not None:
data['callback_query_id'] = self.callback_query_id
if self.replace_callback_query_message is not None:
@@ -18063,3 +18326,716 @@ def de_json(cls, json_string):
obj = cls.check_json(json_string)
obj['user'] = User.de_json(obj.get('user'))
return cls(**obj)
+
+
+class Widget(JsonDeserializable):
+ """
+ This object describes an HTML widget.
+
+ Telegram documentation: https://core.telegram.org/bots/api#widget
+
+ :param id: Optional. Unique identifier of the shared widget, which can be used to send the widget again using the method sendSharedWidget; omitted if the widget isn't shared
+ :type id: :obj:`str`
+
+ :param width: Optional. Width of the widget in logical pixels; omitted if the widget must occupy the whole width of the message bubble
+ :type width: :obj:`int`
+
+ :param height: Optional. Height of the widget in logical pixels; omitted if the height of the widget isn't fixed
+ :type height: :obj:`int`
+
+ :param html: HTML code of the widget
+ :type html: :obj:`str`
+
+ :param public_data: Optional. Public data of the widget, which is available wherever the widget is shown. All messages with a shared widget have the same public data.
+ :type public_data: :obj:`str`
+
+ :param chat_data: Optional. Data of the widget, which is specific to the message
+ :type chat_data: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.Widget`
+ """
+ def __init__(self, html: str, id: Optional[str] = None, width: Optional[int] = None, height: Optional[int] = None,
+ public_data: Optional[str] = None, chat_data: Optional[str] = None, **kwargs):
+ self.id: Optional[str] = id
+ self.width: Optional[int] = width
+ self.height: Optional[int] = height
+ self.html: str = html
+ self.public_data: Optional[str] = public_data
+ self.chat_data: Optional[str] = chat_data
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+class WidgetQuery(JsonDeserializable):
+ """
+ This object represents an incoming query from a widget in a message sent by the bot or via the bot.
+ Use answerWidgetQuery to answer the query. Each user can send at most 5 queries per 5 seconds to the bot from all its widgets.
+
+ Telegram documentation: https://core.telegram.org/bots/api#widgetquery
+
+ :param id: Unique identifier for this query
+ :type id: :obj:`str`
+
+ :param from_user: Sender
+ :type from_user: :class:`telebot.types.User`
+
+ :param chat: Optional. Chat with the message containing the widget; omitted if the widget is in an inline message
+ :type chat: :class:`telebot.types.Chat`
+
+ :param message_id: Optional. Identifier of the message containing the widget; omitted if the widget is in an inline message
+ :type message_id: :obj:`int`
+
+ :param inline_message_id: Optional. Identifier of the inline message containing the widget
+ :type inline_message_id: :obj:`str`
+
+ :param chat_instance: Global identifier, uniquely corresponding to the chat to which the message with the widget was sent
+ :type chat_instance: :obj:`str`
+
+ :param chat_type: Optional. For widgets in inline messages, type of the chat to which the message was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”.
+ :type chat_type: :obj:`str`
+
+ :param type: Type of the query
+ :type type: :class:`telebot.types.WidgetQueryType`
+
+ :param data: Data of the query, 1-64 bytes
+ :type data: :obj:`str`
+
+ :param widget_id: Optional. Unique identifier of the shared widget, which sent the query; omitted if the widget isn't shared
+ :type widget_id: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.WidgetQuery`
+ """
+ def __init__(self, id: str, from_user: User, chat_instance: str, type: WidgetQueryType, data: str,
+ chat: Optional[Chat] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None,
+ chat_type: Optional[str] = None, widget_id: Optional[str] = None, **kwargs):
+ self.id: str = id
+ self.from_user: User = from_user
+ self.chat: Optional[Chat] = chat
+ self.message_id: Optional[int] = message_id
+ self.inline_message_id: Optional[str] = inline_message_id
+ self.chat_instance: str = chat_instance
+ self.chat_type: Optional[str] = chat_type
+ self.type: WidgetQueryType = type
+ self.data: str = data
+ self.widget_id: Optional[str] = widget_id
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['from_user'] = User.de_json(obj.pop('from'))
+ if 'chat' in obj:
+ obj['chat'] = Chat.de_json(obj['chat'])
+ obj['type'] = WidgetQueryType.de_json(obj['type'])
+ return cls(**obj)
+
+
+class SharedWidgetQuery(JsonDeserializable):
+ """
+ This object represents an incoming query from a forwarded message with a shared widget created by the bot.
+ Use answerWidgetQuery to answer the query. Each user can send at most 5 queries per 5 seconds to the bot from all its widgets.
+
+ Telegram documentation: https://core.telegram.org/bots/api#sharedwidgetquery
+
+ :param id: Unique identifier for this query
+ :type id: :obj:`str`
+
+ :param from_user: Sender
+ :type from_user: :class:`telebot.types.User`
+
+ :param type: Type of the query
+ :type type: :class:`telebot.types.WidgetQueryType`
+
+ :param data: Data of the query, 1-64 bytes
+ :type data: :obj:`str`
+
+ :param widget_id: Unique identifier of the shared widget, which sent the query
+ :type widget_id: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.SharedWidgetQuery`
+ """
+ def __init__(self, id: str, from_user: User, type: WidgetQueryType, data: str, widget_id: str, **kwargs):
+ self.id: str = id
+ self.from_user: User = from_user
+ self.type: WidgetQueryType = type
+ self.data: str = data
+ self.widget_id: str = widget_id
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['from_user'] = User.de_json(obj.pop('from'))
+ obj['type'] = WidgetQueryType.de_json(obj['type'])
+ return cls(**obj)
+
+
+class WidgetQueryType(JsonDeserializable, ABC):
+ """
+ This object describes the type of a query from a widget. Currently, it can be one of
+ WidgetQueryTypeData
+ WidgetQueryTypeSignData
+ WidgetQueryTypeSentTransaction
+
+ Telegram documentation: https://core.telegram.org/bots/api#widgetquerytype
+
+ :return: Instance of the class
+ :rtype: :class:`WidgetQueryTypeData` or :class:`WidgetQueryTypeSignData` or :class:`WidgetQueryTypeSentTransaction`
+ """
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ if obj['type'] == 'data':
+ return WidgetQueryTypeData.de_json(obj)
+ elif obj['type'] == 'sign_data':
+ return WidgetQueryTypeSignData.de_json(obj)
+ elif obj['type'] == 'sent_transaction':
+ return WidgetQueryTypeSentTransaction.de_json(obj)
+ else:
+ raise ValueError(f"Unknown widget query type: {obj['type']}.")
+
+
+# noinspection PyShadowingBuiltins
+class WidgetQueryTypeData(WidgetQueryType):
+ """
+ The query contains data for the bot.
+
+ Telegram documentation: https://core.telegram.org/bots/api#widgetquerytypedata
+
+ :param type: Type of the query, always “data”
+ :type type: :obj:`str`
+
+ :param wallet_card: Optional. TON wallet card of the user who sent the query, if it was sent to the bot along with the query
+ :type wallet_card: :class:`telebot.types.TonWalletCard`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.WidgetQueryTypeData`
+ """
+ def __init__(self, type: str, wallet_card: Optional[TonWalletCard] = None, **kwargs):
+ self.type: str = type
+ self.wallet_card: Optional[TonWalletCard] = wallet_card
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ if 'wallet_card' in obj:
+ obj['wallet_card'] = TonWalletCard.de_json(obj['wallet_card'])
+ return cls(**obj)
+
+
+# noinspection PyShadowingBuiltins
+class WidgetQueryTypeSignData(WidgetQueryType):
+ """
+ The query contains data signed by a TON wallet of the user who sent the query.
+ The data is signed for the domain bot, where is the identifier of the bot.
+
+ Telegram documentation: https://core.telegram.org/bots/api#widgetquerytypesigndata
+
+ :param type: Type of the query, always “sign_data”
+ :type type: :obj:`str`
+
+ :param wallet: The wallet that signed the data
+ :type wallet: :class:`telebot.types.WidgetQueryWallet`
+
+ :param sign_data: JSON-serialized signed data
+ :type sign_data: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.WidgetQueryTypeSignData`
+ """
+ def __init__(self, type: str, wallet: WidgetQueryWallet, sign_data: str, **kwargs):
+ self.type: str = type
+ self.wallet: WidgetQueryWallet = wallet
+ self.sign_data: str = sign_data
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['wallet'] = WidgetQueryWallet.de_json(obj['wallet'])
+ return cls(**obj)
+
+
+# noinspection PyShadowingBuiltins
+class WidgetQueryTypeSentTransaction(WidgetQueryType):
+ """
+ The query notifies the bot about a transaction sent from a TON wallet of the user who sent the query.
+
+ Telegram documentation: https://core.telegram.org/bots/api#widgetquerytypesenttransaction
+
+ :param type: Type of the query, always “sent_transaction”
+ :type type: :obj:`str`
+
+ :param wallet: The wallet from which the transaction was sent
+ :type wallet: :class:`telebot.types.WidgetQueryWallet`
+
+ :param msg_hash: Value of msg_hash of the transaction
+ :type msg_hash: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.WidgetQueryTypeSentTransaction`
+ """
+ def __init__(self, type: str, wallet: WidgetQueryWallet, msg_hash: str, **kwargs):
+ self.type: str = type
+ self.wallet: WidgetQueryWallet = wallet
+ self.msg_hash: str = msg_hash
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['wallet'] = WidgetQueryWallet.de_json(obj['wallet'])
+ return cls(**obj)
+
+
+class WidgetQueryWallet(JsonDeserializable):
+ """
+ This object describes a TON wallet of the user, which is used in a query from a widget.
+
+ Telegram documentation: https://core.telegram.org/bots/api#widgetquerywallet
+
+ :param address: Address of the wallet
+ :type address: :obj:`str`
+
+ :param amount: Balance of the wallet, in the smallest units of the cryptocurrency, as a decimal number
+ :type amount: :obj:`str`
+
+ :param public_key: Optional. Hex-encoded public key of the wallet; omitted if unknown
+ :type public_key: :obj:`str`
+
+ :param state_init: Optional. Base64-encoded serialized StateInit of the wallet contract; omitted if and only if public_key is omitted
+ :type state_init: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.WidgetQueryWallet`
+ """
+ def __init__(self, address: str, amount: str, public_key: Optional[str] = None, state_init: Optional[str] = None, **kwargs):
+ self.address: str = address
+ self.amount: str = amount
+ self.public_key: Optional[str] = public_key
+ self.state_init: Optional[str] = state_init
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+class TonWalletCard(JsonDeserializable):
+ """
+ This object describes a TON wallet card, which is shown on the profile page of a user to everyone.
+
+ Telegram documentation: https://core.telegram.org/bots/api#tonwalletcard
+
+ :param address: Address of the wallet
+ :type address: :obj:`str`
+
+ :param amount: Balance of the wallet, in the smallest units of the cryptocurrency, as a decimal number
+ :type amount: :obj:`str`
+
+ :param stickers: Stickers placed on the card
+ :type stickers: :obj:`list` of :class:`telebot.types.TonWalletCardSticker`
+
+ :param background_nft_address: Optional. Address of the NFT of one of the stickers, whose colors must be used for the card background; omitted if the default background must be used
+ :type background_nft_address: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.TonWalletCard`
+ """
+ def __init__(self, address: str, amount: str, stickers: List[TonWalletCardSticker],
+ background_nft_address: Optional[str] = None, **kwargs):
+ self.address: str = address
+ self.amount: str = amount
+ self.stickers: List[TonWalletCardSticker] = stickers
+ self.background_nft_address: Optional[str] = background_nft_address
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['stickers'] = [TonWalletCardSticker.de_json(sticker) for sticker in obj['stickers']]
+ return cls(**obj)
+
+
+class TonWalletCardSticker(JsonDeserializable):
+ """
+ This object describes a sticker on a TON wallet card.
+
+ Telegram documentation: https://core.telegram.org/bots/api#tonwalletcardsticker
+
+ :param position: Position of the sticker on the card
+ :type position: :class:`telebot.types.AreaPosition`
+
+ :param nft: The NFT shown as the sticker
+ :type nft: :class:`telebot.types.TonNft`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.TonWalletCardSticker`
+ """
+ def __init__(self, position: AreaPosition, nft: TonNft, **kwargs):
+ self.position: AreaPosition = position
+ self.nft: TonNft = nft
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['position'] = AreaPosition.de_json(obj['position'])
+ obj['nft'] = TonNft.de_json(obj['nft'])
+ return cls(**obj)
+
+
+class TonNft(JsonDeserializable):
+ """
+ This object represents an NFT in the TON blockchain.
+
+ Telegram documentation: https://core.telegram.org/bots/api#tonnft
+
+ :param address: Address of the NFT
+ :type address: :obj:`str`
+
+ :param collection_address: Optional. Address of the collection to which the NFT belongs; omitted if unknown
+ :type collection_address: :obj:`str`
+
+ :param index: Index of the NFT among all NFTs from the collection as a decimal number
+ :type index: :obj:`str`
+
+ :param name: Name of the NFT
+ :type name: :obj:`str`
+
+ :param description: Description of the NFT
+ :type description: :obj:`str`
+
+ :param attributes: Optional. Attributes of the NFT
+ :type attributes: :obj:`list` of :class:`telebot.types.TonNftAttribute`
+
+ :param gift: Optional. The unique gift corresponding to the NFT
+ :type gift: :class:`telebot.types.UniqueGift`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.TonNft`
+ """
+ def __init__(self, address: str, index: str, name: str, description: str, collection_address: Optional[str] = None,
+ attributes: Optional[List[TonNftAttribute]] = None, gift: Optional[UniqueGift] = None, **kwargs):
+ self.address: str = address
+ self.collection_address: Optional[str] = collection_address
+ self.index: str = index
+ self.name: str = name
+ self.description: str = description
+ self.attributes: Optional[List[TonNftAttribute]] = attributes
+ self.gift: Optional[UniqueGift] = gift
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ if 'attributes' in obj:
+ obj['attributes'] = [TonNftAttribute.de_json(attribute) for attribute in obj['attributes']]
+ if 'gift' in obj:
+ obj['gift'] = UniqueGift.de_json(obj['gift'])
+ return cls(**obj)
+
+
+class TonNftAttribute(JsonDeserializable):
+ """
+ This object represents an attribute of an NFT in the TON blockchain.
+
+ Telegram documentation: https://core.telegram.org/bots/api#tonnftattribute
+
+ :param trait_type: Trait type of the attribute
+ :type trait_type: :obj:`str`
+
+ :param value: Value of the attribute
+ :type value: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.TonNftAttribute`
+ """
+ def __init__(self, trait_type: str, value: str, **kwargs):
+ self.trait_type: str = trait_type
+ self.value: str = value
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+class TonWalletTransfer(JsonDeserializable):
+ """
+ Describes a service message about a transfer with a TON wallet.
+
+ Telegram documentation: https://core.telegram.org/bots/api#tonwallettransfer
+
+ :param transaction_id: Unique identifier of the transaction; may be empty if the transfer hasn't been sent yet
+ :type transaction_id: :obj:`str`
+
+ :param peer_address: Address of the transfer peer in the TON blockchain
+ :type peer_address: :obj:`str`
+
+ :param amount: The amount of transferred cryptocurrency, in the smallest units of the cryptocurrency, as a decimal number; negative for outgoing transfers
+ :type amount: :obj:`str`
+
+ :param comment: Optional. Comment added to the transfer; omitted if the comment is encrypted
+ :type comment: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.TonWalletTransfer`
+ """
+ def __init__(self, transaction_id: str, peer_address: str, amount: str, comment: Optional[str] = None, **kwargs):
+ self.transaction_id: str = transaction_id
+ self.peer_address: str = peer_address
+ self.amount: str = amount
+ self.comment: Optional[str] = comment
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+class PaidMessagesWaived(JsonDeserializable):
+ """
+ Describes a service message about the sender of the message using a link of the other user, which allows sending messages
+ to the user without paying Telegram Stars. Currently holds no information.
+
+ Telegram documentation: https://core.telegram.org/bots/api#paidmessageswaived
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.PaidMessagesWaived`
+ """
+ def __init__(self, **kwargs):
+ pass
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+class EmojiType(JsonDeserializable, ABC):
+ """
+ This object describes an emoji. Currently, it can be one of
+ EmojiTypeEmoji
+ EmojiTypeCustomEmoji
+
+ Telegram documentation: https://core.telegram.org/bots/api#emojitype
+
+ :return: Instance of the class
+ :rtype: :class:`EmojiTypeEmoji` or :class:`EmojiTypeCustomEmoji`
+ """
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ if obj['type'] == 'emoji':
+ return EmojiTypeEmoji.de_json(obj)
+ elif obj['type'] == 'custom_emoji':
+ return EmojiTypeCustomEmoji.de_json(obj)
+ else:
+ raise ValueError(f"Unknown emoji type: {obj['type']}.")
+
+
+# noinspection PyShadowingBuiltins
+class EmojiTypeEmoji(EmojiType):
+ """
+ A regular emoji.
+
+ Telegram documentation: https://core.telegram.org/bots/api#emojitypeemoji
+
+ :param type: Type of the emoji, always “emoji”
+ :type type: :obj:`str`
+
+ :param emoji: The emoji
+ :type emoji: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.EmojiTypeEmoji`
+ """
+ def __init__(self, type: str, emoji: str, **kwargs):
+ self.type: str = type
+ self.emoji: str = emoji
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+# noinspection PyShadowingBuiltins
+class EmojiTypeCustomEmoji(EmojiType):
+ """
+ A custom emoji.
+
+ Telegram documentation: https://core.telegram.org/bots/api#emojitypecustomemoji
+
+ :param type: Type of the emoji, always “custom_emoji”
+ :type type: :obj:`str`
+
+ :param custom_emoji_id: Identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker.
+ :type custom_emoji_id: :obj:`str`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.EmojiTypeCustomEmoji`
+ """
+ def __init__(self, type: str, custom_emoji_id: str, **kwargs):
+ self.type: str = type
+ self.custom_emoji_id: str = custom_emoji_id
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ return cls(**obj)
+
+
+class ChatShareTheme(JsonDeserializable, ABC):
+ """
+ This object describes the theme of the screen for sharing a link to a user or a chat. Currently, it can be one of
+ ChatShareThemeEmoji
+ ChatShareThemeUniqueGift
+
+ Telegram documentation: https://core.telegram.org/bots/api#chatsharetheme
+
+ :return: Instance of the class
+ :rtype: :class:`ChatShareThemeEmoji` or :class:`ChatShareThemeUniqueGift`
+ """
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ if obj['type'] == 'emoji':
+ return ChatShareThemeEmoji.de_json(obj)
+ elif obj['type'] == 'unique_gift':
+ return ChatShareThemeUniqueGift.de_json(obj)
+ else:
+ raise ValueError(f"Unknown chat share theme type: {obj['type']}.")
+
+
+# noinspection PyShadowingBuiltins
+class ChatShareThemeEmoji(ChatShareTheme):
+ """
+ The theme with emoji placed on a background.
+
+ Telegram documentation: https://core.telegram.org/bots/api#chatsharethemeemoji
+
+ :param type: Type of the theme, always “emoji”
+ :type type: :obj:`str`
+
+ :param emojis: The emoji; 0-6 regular or custom emoji
+ :type emojis: :obj:`list` of :class:`telebot.types.EmojiType`
+
+ :param background_backdrop_id: Optional. Identifier of the backdrop used as the background; omitted if the default background is used. Use getChatShareThemeBackdrops to get details about the backdrop.
+ :type background_backdrop_id: :obj:`int`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.ChatShareThemeEmoji`
+ """
+ def __init__(self, type: str, emojis: List[EmojiType], background_backdrop_id: Optional[int] = None, **kwargs):
+ self.type: str = type
+ self.emojis: List[EmojiType] = emojis
+ self.background_backdrop_id: Optional[int] = background_backdrop_id
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['emojis'] = [EmojiType.de_json(emoji) for emoji in obj['emojis']]
+ return cls(**obj)
+
+
+# noinspection PyShadowingBuiltins
+class ChatShareThemeUniqueGift(ChatShareTheme):
+ """
+ The theme based on a unique gift owned by the user or the chat.
+
+ Telegram documentation: https://core.telegram.org/bots/api#chatsharethemeuniquegift
+
+ :param type: Type of the theme, always “unique_gift”
+ :type type: :obj:`str`
+
+ :param gift: The gift
+ :type gift: :class:`telebot.types.UniqueGift`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.ChatShareThemeUniqueGift`
+ """
+ def __init__(self, type: str, gift: UniqueGift, **kwargs):
+ self.type: str = type
+ self.gift: UniqueGift = gift
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['gift'] = UniqueGift.de_json(obj['gift'])
+ return cls(**obj)
+
+
+# noinspection PyShadowingBuiltins
+class ChatShareThemeBackdrop(JsonDeserializable):
+ """
+ This object describes a backdrop, which can be used as the background of a theme of the screen for sharing a link to a user or a chat.
+
+ Telegram documentation: https://core.telegram.org/bots/api#chatsharethemebackdrop
+
+ :param id: Unique identifier of the backdrop
+ :type id: :obj:`int`
+
+ :param name: Name of the backdrop
+ :type name: :obj:`str`
+
+ :param colors: Colors of the backdrop
+ :type colors: :class:`telebot.types.UniqueGiftBackdropColors`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.ChatShareThemeBackdrop`
+ """
+ def __init__(self, id: int, name: str, colors: UniqueGiftBackdropColors, **kwargs):
+ self.id: int = id
+ self.name: str = name
+ self.colors: UniqueGiftBackdropColors = colors
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['colors'] = UniqueGiftBackdropColors.de_json(obj['colors'])
+ return cls(**obj)
+
+
+class ChatShareThemeBackdrops(JsonDeserializable):
+ """
+ This object contains a list of backdrops, which can be used as the background of a theme of the screen for sharing a link to a user or a chat.
+
+ Telegram documentation: https://core.telegram.org/bots/api#chatsharethemebackdrops
+
+ :param backdrops: The list of backdrops
+ :type backdrops: :obj:`list` of :class:`telebot.types.ChatShareThemeBackdrop`
+
+ :return: Instance of the class
+ :rtype: :class:`telebot.types.ChatShareThemeBackdrops`
+ """
+ def __init__(self, backdrops: List[ChatShareThemeBackdrop], **kwargs):
+ self.backdrops: List[ChatShareThemeBackdrop] = backdrops
+
+ @classmethod
+ def de_json(cls, json_string):
+ if json_string is None: return None
+ obj = cls.check_json(json_string)
+ obj['backdrops'] = [ChatShareThemeBackdrop.de_json(backdrop) for backdrop in obj['backdrops']]
+ return cls(**obj)
diff --git a/telebot/util.py b/telebot/util.py
index 7400f18e1..a2a33b3a4 100644
--- a/telebot/util.py
+++ b/telebot/util.py
@@ -29,7 +29,7 @@
content_type_media = [
'text', 'audio', 'document', 'animation', 'game', 'photo', 'sticker', 'video', 'video_note', 'voice', 'contact',
'location', 'venue', 'dice', 'invoice', 'successful_payment', 'connected_website', 'poll', 'passport_data',
- 'web_app_data', 'story', 'giveaway', 'gift', 'unique_gift',
+ 'web_app_data', 'story', 'giveaway', 'gift', 'unique_gift', 'widget',
]
#: Contains all service content types such as `User joined the group`.
@@ -45,7 +45,7 @@
'suggested_post_info', 'suggested_post_approved', 'suggested_post_approval_failed', 'suggested_post_declined',
'suggested_post_paid', 'gift_upgrade_sent', 'chat_owner_left', 'chat_owner_changed', 'managed_bot_created',
'poll_option_added', 'poll_option_deleted', 'community_chat_added', 'community_chat_removed',
- 'community_chat_joined'
+ 'community_chat_joined', 'ton_wallet_transfer', 'paid_messages_waived'
]
#: All update types, should be used for allowed_updates parameter in polling.
@@ -54,7 +54,8 @@
"callback_query", "shipping_query", "pre_checkout_query", "poll", "poll_answer", "my_chat_member", "chat_member",
"chat_join_request", "message_reaction", "message_reaction_count", "removed_chat_boost", "chat_boost",
"business_connection", "business_message", "edited_business_message", "deleted_business_messages",
- "purchased_paid_media", "managed_bot", "guest_message", "subscription", "stopped_message_generation"
+ "purchased_paid_media", "managed_bot", "guest_message", "subscription", "stopped_message_generation",
+ "widget_query", "shared_widget_query"
]
diff --git a/tests/test_apihelper_95.py b/tests/test_apihelper_95.py
index ea26d057d..80bce8d88 100644
--- a/tests/test_apihelper_95.py
+++ b/tests/test_apihelper_95.py
@@ -121,6 +121,22 @@ def test_send_and_edit_checklist_send_checklist_as_json(monkeypatch):
assert json.loads(captured['params']['checklist'])['tasks'][0]['text'] == 'Milk'
+def test_widget_methods_send_empty_data(monkeypatch):
+ captured = {}
+ monkeypatch.setattr(apihelper, '_make_request', _capture(captured))
+
+ apihelper.send_widget('token', 1, 'hi', public_data='', allow_queries=True)
+ assert captured['method_url'] == 'sendWidget'
+ assert captured['params'] == {'chat_id': 1, 'html': 'hi', 'public_data': '', 'allow_queries': True}
+
+ apihelper.edit_message_widget_data('token', chat_id=1, message_id=2, chat_data='')
+ assert captured['method_url'] == 'editMessageWidgetData'
+ assert captured['params'] == {'chat_id': 1, 'message_id': 2, 'chat_data': ''}
+
+ apihelper.edit_shared_widget_data('token', 'w1', '')
+ assert captured['params'] == {'widget_id': 'w1', 'public_data': ''}
+
+
def test_replace_sticker_in_set_uploads_the_sticker_file(monkeypatch):
captured = {}
monkeypatch.setattr(apihelper, '_make_request', _capture(captured))
@@ -156,3 +172,88 @@ async def fake_process_request(token, url, method='get', params=None, files=None
attach = json.loads(captured['params']['sticker'])['sticker']
assert captured['files'] == {attach[len('attach://'):]: sticker_file}
assert captured['method'] == 'post'
+
+
+def test_async_widget_methods(monkeypatch):
+ captured = {}
+
+ async def fake_process_request(token, url, method='get', params=None, files=None, **kwargs):
+ captured.update(url=url, params=params, method=method)
+ return True
+
+ monkeypatch.setattr(asyncio_helper, '_process_request', fake_process_request)
+
+ asyncio.run(asyncio_helper.send_shared_widget('token', 1, 'w1', chat_data=''))
+ assert captured['url'] == 'sendSharedWidget'
+ assert captured['params'] == {'chat_id': 1, 'widget_id': 'w1', 'chat_data': ''}
+
+ asyncio.run(asyncio_helper.answer_widget_query('token', 'q1', data='ok'))
+ assert captured['url'] == 'answerWidgetQuery'
+ assert captured['params'] == {'widget_query_id': 'q1', 'data': 'ok'}
+ assert captured['method'] == 'post'
+
+
+def test_ephemeral_reply_without_chat_id(monkeypatch):
+ captured = {}
+ monkeypatch.setattr(apihelper, '_make_request', _capture(captured))
+ parameters = types.EphemeralMessageParameters(callback_query_id='q1')
+
+ apihelper.send_message('token', None, 'hi', ephemeral_message_parameters=parameters)
+ assert captured['params'] == {'text': 'hi', 'ephemeral_message_parameters': '{"callback_query_id": "q1"}'}
+
+ apihelper.send_data('token', None, 'file-id', 'document', ephemeral_message_parameters=parameters)
+ assert 'chat_id' not in captured['params']
+
+ apihelper.send_message('token', 1, 'hi')
+ assert captured['params']['chat_id'] == '1'
+
+
+def test_api_104_methods(monkeypatch):
+ captured = {}
+ monkeypatch.setattr(apihelper, '_make_request', _capture(captured))
+
+ apihelper.get_unique_gift('token', 'Cake-1')
+ assert captured['method_url'] == 'getUniqueGift'
+ assert captured['params'] == {'name': 'Cake-1'}
+
+ apihelper.get_chat_share_theme_backdrops('token')
+ assert captured['method_url'] == 'getChatShareThemeBackdrops'
+
+ apihelper.delete_business_account_gift('token', 'bc', 'g1')
+ assert captured['method_url'] == 'deleteBusinessAccountGift'
+ assert captured['params'] == {'business_connection_id': 'bc', 'owned_gift_id': 'g1'}
+
+ entity = types.MessageEntity('text_link', 0, 4, url='https://example.com')
+ apihelper.verify_user('token', 1, 'Team', custom_description_entities=[entity])
+ assert json.loads(captured['params']['custom_description_entities'])[0]['url'] == 'https://example.com'
+
+ apihelper.verify_chat('token', 1, 'Team', custom_description_parse_mode='HTML')
+ assert captured['params']['custom_description_parse_mode'] == 'HTML'
+
+
+def test_async_api_104_methods(monkeypatch):
+ captured = {}
+
+ async def fake_process_request(token, url, method='get', params=None, files=None, **kwargs):
+ captured.update(url=url, params=params, method=method)
+ return True
+
+ monkeypatch.setattr(asyncio_helper, '_process_request', fake_process_request)
+ parameters = types.EphemeralMessageParameters(callback_query_id='q1')
+
+ asyncio.run(asyncio_helper.send_message('token', None, 'hi', ephemeral_message_parameters=parameters))
+ assert 'chat_id' not in captured['params']
+
+ asyncio.run(asyncio_helper.send_photo('token', None, 'file-id', ephemeral_message_parameters=parameters))
+ assert 'chat_id' not in captured['params']
+
+ asyncio.run(asyncio_helper.get_unique_gift('token', 'Cake-1'))
+ assert captured['url'] == 'getUniqueGift'
+ assert captured['params'] == {'name': 'Cake-1'}
+
+ asyncio.run(asyncio_helper.delete_business_account_gift('token', 'bc', 'g1'))
+ assert captured['url'] == 'deleteBusinessAccountGift'
+ assert captured['method'] == 'post'
+
+ asyncio.run(asyncio_helper.verify_chat('token', 1, custom_description_parse_mode='HTML'))
+ assert captured['params'] == {'chat_id': 1, 'custom_description_parse_mode': 'HTML'}
diff --git a/tests/test_async_telebot.py b/tests/test_async_telebot.py
index 2b72da6c0..66dbd41db 100644
--- a/tests/test_async_telebot.py
+++ b/tests/test_async_telebot.py
@@ -120,6 +120,32 @@ async def driver():
)
+def test_widget_query_handlers():
+ bot = AsyncTeleBot('1:fake', validate_token=False)
+ received = []
+
+ @bot.widget_query_handler()
+ async def widget_query(query):
+ received.append(query.id)
+
+ @bot.shared_widget_query_handler(func=lambda query: query.widget_id == 'w1')
+ async def shared_widget_query(query):
+ received.append(query.id)
+
+ query_type = {'type': 'data'}
+ user = {'id': 2, 'is_bot': False, 'first_name': 'User'}
+ asyncio.run(bot.process_new_updates([
+ types.Update.de_json({'update_id': 1, 'widget_query': {
+ 'id': 'q1', 'from': user, 'chat_instance': '1', 'type': query_type, 'data': 'a'}}),
+ types.Update.de_json({'update_id': 2, 'shared_widget_query': {
+ 'id': 'q2', 'from': user, 'type': query_type, 'data': 'b', 'widget_id': 'w1'}}),
+ types.Update.de_json({'update_id': 3, 'shared_widget_query': {
+ 'id': 'q3', 'from': user, 'type': query_type, 'data': 'c', 'widget_id': 'w2'}}),
+ ]))
+
+ assert received == ['q1', 'q2']
+
+
def _fake_429(retry_after: int):
from telebot.asyncio_helper import ApiTelegramException
diff --git a/tests/test_handler_backends.py b/tests/test_handler_backends.py
index 9a980ab1b..cb7a01936 100644
--- a/tests/test_handler_backends.py
+++ b/tests/test_handler_backends.py
@@ -72,7 +72,7 @@ def update_type(message):
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, chat_join_request, message_reaction, message_reaction_count, chat_boost, chat_boost_removed, None,
- None, None, None, None, None, None, None, None)
+ None, None, None, None, None, None, None, None, None, None)
@pytest.fixture()
@@ -97,7 +97,7 @@ def reply_to_message_update_type(reply_to_message):
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, chat_join_request, message_reaction, message_reaction_count, chat_boost, chat_boost_removed, None, None, None, None, None, None, None,
- None, None)
+ None, None, None, None)
def next_handler(message):
diff --git a/tests/test_telebot.py b/tests/test_telebot.py
index 0a3cf0e0b..3eef6e26a 100644
--- a/tests/test_telebot.py
+++ b/tests/test_telebot.py
@@ -73,6 +73,32 @@ def fail_polling(*args, **kwargs):
assert any('Exception traceback:' in message for message in logger.messages) is includes_traceback
+def test_widget_query_handlers():
+ bot = telebot.TeleBot('1:fake', validate_token=False, threaded=False)
+ received = []
+
+ @bot.widget_query_handler()
+ def widget_query(query):
+ received.append(query.id)
+
+ @bot.shared_widget_query_handler(func=lambda query: query.widget_id == 'w1')
+ def shared_widget_query(query):
+ received.append(query.id)
+
+ query_type = {'type': 'data'}
+ user = {'id': 2, 'is_bot': False, 'first_name': 'User'}
+ bot.process_new_updates([
+ types.Update.de_json({'update_id': 1, 'widget_query': {
+ 'id': 'q1', 'from': user, 'chat_instance': '1', 'type': query_type, 'data': 'a'}}),
+ types.Update.de_json({'update_id': 2, 'shared_widget_query': {
+ 'id': 'q2', 'from': user, 'type': query_type, 'data': 'b', 'widget_id': 'w1'}}),
+ types.Update.de_json({'update_id': 3, 'shared_widget_query': {
+ 'id': 'q3', 'from': user, 'type': query_type, 'data': 'c', 'widget_id': 'w2'}}),
+ ])
+
+ assert received == ['q1', 'q2']
+
+
@pytest.mark.skipif(should_skip, reason="No environment variables configured")
class TestTeleBot:
def test_message_listener(self):
@@ -597,7 +623,9 @@ def create_message_update(text):
managed_bot=None,
guest_message=None,
subscription=None,
- stopped_message_generation=None)
+ stopped_message_generation=None,
+ widget_query=None,
+ shared_widget_query=None)
def test_is_string_unicode(self):
s1 = u'string'
diff --git a/tests/test_types.py b/tests/test_types.py
index ca830ecb8..53efffad7 100644
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -82,6 +82,227 @@ def test_api_103_new_service_objects():
assert isinstance(message.community_chat_joined, types.CommunityChatJoined)
+def test_api_104_message_widget():
+ message = types.Message.de_json({
+ 'message_id': 1,
+ 'date': 1,
+ 'chat': {'id': 1, 'type': 'private'},
+ 'widget': {'id': 'w1', 'width': 300, 'height': 200, 'html': 'hi', 'public_data': 'p', 'chat_data': 'c'},
+ 'caption': 'Counter',
+ 'external_reply': {
+ 'origin': {'type': 'hidden_user', 'date': 1, 'sender_user_name': 'User'},
+ 'widget': {'html': 'quoted'},
+ },
+ })
+
+ assert message.content_type == 'widget'
+ assert message.widget.id == 'w1'
+ assert message.widget.width == 300
+ assert message.widget.height == 200
+ assert message.widget.html == 'hi'
+ assert message.widget.public_data == 'p'
+ assert message.widget.chat_data == 'c'
+ assert message.external_reply.widget.html == 'quoted'
+ assert message.external_reply.widget.id is None
+
+
+def test_api_104_widget_query():
+ update = types.Update.de_json({
+ 'update_id': 1,
+ 'widget_query': {
+ 'id': 'q1',
+ 'from': {'id': 2, 'is_bot': False, 'first_name': 'User'},
+ 'chat': {'id': 2, 'type': 'private'},
+ 'message_id': 10,
+ 'chat_instance': '-123',
+ 'type': {
+ 'type': 'data',
+ 'wallet_card': {
+ 'address': 'UQA',
+ 'amount': '1000000000',
+ 'stickers': [{
+ 'position': {
+ 'x_percentage': 50.0, 'y_percentage': 50.0, 'width_percentage': 20.0,
+ 'height_percentage': 20.0, 'rotation_angle': 0.0, 'corner_radius_percentage': 0.0,
+ },
+ 'nft': {
+ 'address': 'EQB', 'index': '7', 'name': 'NFT', 'description': 'An NFT',
+ 'attributes': [{'trait_type': 'Color', 'value': 'Blue'}],
+ },
+ }],
+ },
+ },
+ 'data': 'click',
+ },
+ })
+
+ query = update.widget_query
+ assert isinstance(query, types.WidgetQuery)
+ assert query.id == 'q1'
+ assert query.from_user.id == 2
+ assert query.chat.id == 2
+ assert query.message_id == 10
+ assert query.chat_instance == '-123'
+ assert query.data == 'click'
+ assert query.inline_message_id is None
+ assert query.widget_id is None
+ assert isinstance(query.type, types.WidgetQueryTypeData)
+ sticker = query.type.wallet_card.stickers[0]
+ assert sticker.position.x_percentage == 50.0
+ assert sticker.nft.attributes[0].value == 'Blue'
+ assert sticker.nft.gift is None
+
+
+def test_api_104_shared_widget_query():
+ update = types.Update.de_json({
+ 'update_id': 1,
+ 'shared_widget_query': {
+ 'id': 'q2',
+ 'from': {'id': 2, 'is_bot': False, 'first_name': 'User'},
+ 'type': {
+ 'type': 'sign_data',
+ 'wallet': {'address': 'UQA', 'amount': '5', 'public_key': 'abcd', 'state_init': 'te6c'},
+ 'sign_data': '{"type": "text", "text": "hi"}',
+ },
+ 'data': 'sign',
+ 'widget_id': 'w1',
+ },
+ })
+ sent_transaction = types.WidgetQueryType.de_json({
+ 'type': 'sent_transaction',
+ 'wallet': {'address': 'UQA', 'amount': '5'},
+ 'msg_hash': 'hash',
+ })
+
+ query = update.shared_widget_query
+ assert isinstance(query, types.SharedWidgetQuery)
+ assert query.widget_id == 'w1'
+ assert query.from_user.id == 2
+ assert isinstance(query.type, types.WidgetQueryTypeSignData)
+ assert query.type.wallet.public_key == 'abcd'
+ assert query.type.sign_data == '{"type": "text", "text": "hi"}'
+ assert isinstance(sent_transaction, types.WidgetQueryTypeSentTransaction)
+ assert sent_transaction.msg_hash == 'hash'
+ assert sent_transaction.wallet.public_key is None
+
+
+def test_api_104_input_widget_message_contents():
+ widget = types.InputWidgetMessageContent('hi', width=300, public_data='', allow_queries=True)
+ shared_widget = types.InputSharedWidgetMessageContent('w1', chat_data='c', caption='Counter')
+
+ assert widget.to_dict() == {'html': 'hi', 'width': 300, 'public_data': '', 'allow_queries': True}
+ assert shared_widget.to_dict() == {'widget_id': 'w1', 'chat_data': 'c', 'caption': 'Counter'}
+
+
+def test_api_104_ephemeral_reply_without_receiver():
+ parameters = types.EphemeralMessageParameters(callback_query_id='query')
+
+ assert parameters.to_dict() == {'callback_query_id': 'query'}
+
+
+def test_api_104_quotes_from_rich_messages():
+ quote = types.TextQuote.de_json({
+ 'text': '',
+ 'position': 6,
+ 'rich_texts': ['Hello ', {'type': 'bold', 'text': 'world'}],
+ })
+ reply_parameters = types.ReplyParameters(1, quote_rich_texts=['Hello ', types.RichTextBold('world')])
+
+ assert quote.text == ''
+ assert quote.rich_texts[0] == 'Hello '
+ assert isinstance(quote.rich_texts[1], types.RichTextBold)
+ assert reply_parameters.to_dict() == {
+ 'message_id': 1,
+ 'quote_rich_texts': ['Hello ', {'type': 'bold', 'text': 'world'}],
+ }
+ assert types.ReplyParameters.de_json(reply_parameters.to_json()).quote_rich_texts[1].text == 'world'
+
+
+def test_api_104_area_position():
+ position = {
+ 'x_percentage': 50.0, 'y_percentage': 50.0, 'width_percentage': 20.0,
+ 'height_percentage': 20.0, 'rotation_angle': 0.0, 'corner_radius_percentage': 0.0,
+ }
+ old_position = types.StoryAreaPosition(**position)
+
+ assert types.AreaPosition.de_json(position).to_dict() == position
+ assert isinstance(old_position, types.AreaPosition)
+ assert old_position.to_dict() == position
+
+
+def test_api_104_ton_wallet():
+ chat = types.ChatFullInfo.de_json({
+ 'id': 1,
+ 'type': 'private',
+ 'ton_wallet_card': {'address': 'UQA', 'amount': '1000000000', 'stickers': []},
+ })
+ message = types.Message.de_json({
+ 'message_id': 1,
+ 'date': 1,
+ 'chat': {'id': 1, 'type': 'private'},
+ 'ton_wallet_transfer': {'transaction_id': 'tx', 'peer_address': 'UQB', 'amount': '-5', 'comment': 'Thanks'},
+ })
+
+ assert isinstance(chat.ton_wallet_card, types.TonWalletCard)
+ assert chat.ton_wallet_card.amount == '1000000000'
+ assert message.content_type == 'ton_wallet_transfer'
+ assert message.ton_wallet_transfer.peer_address == 'UQB'
+ assert message.ton_wallet_transfer.amount == '-5'
+ assert message.ton_wallet_transfer.comment == 'Thanks'
+
+
+def test_api_104_chat_share_themes():
+ chat = types.ChatFullInfo.de_json({
+ 'id': 1,
+ 'type': 'supergroup',
+ 'share_theme': {
+ 'type': 'emoji',
+ 'emojis': [{'type': 'emoji', 'emoji': '🎉'}, {'type': 'custom_emoji', 'custom_emoji_id': '123'}],
+ 'background_backdrop_id': 7,
+ },
+ })
+ gift_theme = types.ChatShareTheme.de_json({
+ 'type': 'unique_gift',
+ 'gift': {
+ 'base_name': 'Cake', 'name': 'Cake-1', 'number': 1, 'gift_id': 'g1',
+ 'model': {'name': 'm', 'sticker': None, 'rarity_per_mille': 1},
+ 'symbol': {'name': 's', 'sticker': None, 'rarity_per_mille': 1},
+ 'backdrop': {'name': 'b', 'colors': {
+ 'center_color': 1, 'edge_color': 2, 'symbol_color': 3, 'text_color': 4}, 'rarity_per_mille': 1},
+ },
+ })
+ backdrops = types.ChatShareThemeBackdrops.de_json({'backdrops': [{
+ 'id': 7, 'name': 'Sky', 'colors': {'center_color': 1, 'edge_color': 2, 'symbol_color': 3, 'text_color': 4},
+ }]})
+
+ theme = chat.share_theme
+ assert isinstance(theme, types.ChatShareThemeEmoji)
+ assert isinstance(theme.emojis[0], types.EmojiTypeEmoji)
+ assert theme.emojis[0].emoji == '🎉'
+ assert isinstance(theme.emojis[1], types.EmojiTypeCustomEmoji)
+ assert theme.emojis[1].custom_emoji_id == '123'
+ assert theme.background_backdrop_id == 7
+ assert isinstance(gift_theme, types.ChatShareThemeUniqueGift)
+ assert gift_theme.gift.name == 'Cake-1'
+ assert backdrops.backdrops[0].id == 7
+ assert backdrops.backdrops[0].colors.text_color == 4
+
+
+def test_api_104_general():
+ address = types.RichText.de_json({'type': 'ton_address', 'text': 'UQA...', 'address': 'UQA'})
+ message = types.Message.de_json({
+ 'message_id': 1,
+ 'date': 1,
+ 'chat': {'id': 1, 'type': 'private'},
+ 'paid_messages_waived': {},
+ })
+
+ assert isinstance(address, types.RichTextTonAddress)
+ assert address.to_dict() == {'type': 'ton_address', 'text': 'UQA...', 'address': 'UQA'}
+ assert message.content_type == 'paid_messages_waived'
+ assert isinstance(message.paid_messages_waived, types.PaidMessagesWaived)
+
+
def test_json_user():
json_str = r'{"id": 123456789, "is_bot": false, "first_name": "John", "last_name": "Doe", "username": "@johndoe", "language_code": "en", "can_join_groups": true, "can_read_all_group_messages": false, "supports_inline_queries": true, "is_premium": true, "added_to_attachment_menu": false, "can_connect_to_business": true, "has_main_web_app": false, "has_topics_enabled": true, "allows_users_to_create_topics": true, "can_manage_bots": true, "supports_guest_queries": true, "supports_join_request_queries": true}'
result = types.User.de_json(json_str)