Как читать сообщения из канала telegram программно?
Для таких целей придётся использовать клиентский API (Core API). Что это такое и базовое описание, можно прочитать на официальном сайте Telegram. А вот что касается документации, то, к сожалению, на оф.сайте она сильно устаревшая, благо нашлись добрые люди, которые создали и поддерживают актуальную неофициальную документацию.
Для работы с Core API есть готовые библиотеки, например, Telethon для Python 3. В Readme на гитхабе есть примеры с авторизацией и получением файла сессии, я же покажу пример, как прочитать самое свежее сообщение в канале:
Как считать сообщение из чата телеграмм python
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
Supported Bot API version: 6.0!
This API is tested with Python 3.6-3.10 and Pypy 3. There are two ways to install the library:
- Installation using pip (a Python package manager):
- Installation from source (requires git):
It is generally recommended to use the first option.
While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling
Writing your first bot
It is presumed that you have obtained an API token with @BotFather. We will call this token TOKEN . Furthermore, you have basic knowledge of the Python programming language and more importantly the Telegram Bot API.
A simple echo bot
The TeleBot class (defined in _init_.py) encapsulates all API calls in a single class. It provides functions such as send_xyz ( send_message , send_document etc.) and several ways to listen for incoming messages.
Create a file called echo_bot.py . Then, open the file and create an instance of the TeleBot class.
Note: Make sure to actually replace TOKEN with your own API token.
After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.
Let’s define a message handler which handles incoming /start and /help commands.
A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).
Let’s add another handler:
This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.
Note: all handlers are tested in the order in which they were declared
We now have a basic bot which replies a static message to «/start» and «/help» commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:
Alright, that’s it! Our source file now looks like this:
To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands (‘/start’ and ‘/help’) and arbitrary text messages.
General API Documentation
All types are defined in types.py. They are all completely in line with the Telegram API’s definition of the types, except for the Message’s from field, which is renamed to from_user (because from is a Python reserved token). Thus, attributes such as message_id can be accessed directly with message.message_id . Note that message.chat can be either an instance of User or GroupChat (see How can I distinguish a User and a GroupChat in message.chat?).
The Message object also has a content_type attribute, which defines the type of the Message. content_type can be one of the following strings: text , audio , document , photo , sticker , video , video_note , voice , location , contact , new_chat_members , left_chat_member , new_chat_title , new_chat_photo , delete_chat_photo , group_chat_created , supergroup_chat_created , channel_chat_created , migrate_to_chat_id , migrate_from_chat_id , pinned_message .
You can use some types in one function. Example:
All API methods are located in the TeleBot class. They are renamed to follow common Python naming conventions. E.g. getMe is renamed to get_me and sendMessage to send_message .
General use of the API
Outlined below are some general use cases of the API.
A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):
function_name is not bound to any restrictions. Any function name is permitted with message handlers. The function must accept at most one argument, which will be the message that the function must handle. filters is a list of keyword arguments. A filter is declared in the following manner: name=argument . One handler may have multiple filters. TeleBot supports the following filters:
| name | argument(s) | Condition |
|---|---|---|
| content_types | list of strings (default [‘text’] ) | True if message.content_type is in the list of strings. |
| regexp | a regular expression as a string | True if re.search(regexp_arg) returns True and message.content_type == ‘text’ (See Python Regular Expressions) |
| commands | list of strings | True if message.content_type == ‘text’ and message.text starts with a command that is in the list of strings. |
| chat_types | list of chat types | True if message.chat.type in your filter |
| func | a function (lambda or function reference) | True if the lambda or function reference returns True |
Here are some examples of using the filters and message handlers:
Important: all handlers are tested in the order in which they were declared
Edited Message handler
Handle edited messages @bot.edited_message_handler(filters) # <- passes a Message type object to your function
Channel Post handler
Handle channel post messages @bot.channel_post_handler(filters) # <- passes a Message type object to your function
Edited Channel Post handler
Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function
Callback Query Handler
Handle callback queries
Shipping Query Handler
Handle shipping queries @bot.shipping_query_handeler() # <- passes a ShippingQuery type object to your function
Pre Checkout Query Handler
Handle pre checkoupt queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function
Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function
Poll Answer Handler
Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function
My Chat Member Handler
Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function
Chat Member Handler
Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function Note: «chat_member» updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types
Chat Join Request Handler
Handle chat join requests using: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function
More information about Inline mode.
Now, you can use inline_handler to get inline queries in telebot.
Chosen Inline handler
Use chosen_inline_handler to get chosen_inline_result in telebot. Don’t forgot add the /setinlinefeedback command for @Botfather.
Answer Inline Query
Additional API features
A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are executed. Middleware processing is disabled by default, enable it by setting apihelper.ENABLE_MIDDLEWARE = True .
There are other examples using middleware handler in the examples/middleware directory.
There are class-based middlewares. Basic class-based middleware looks like this:
Class-based middleware should have to functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples
Also, you can use built-in custom filters. Or, you can create your own filter.
Also, we have examples on them. Check this links:
You can check some built-in filters in source code
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
All send_xyz functions of TeleBot take an optional reply_markup argument. This argument must be an instance of ReplyKeyboardMarkup , ReplyKeyboardRemove or ForceReply , which are defined in types.py.
The last example yields this result:


Working with entities
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:
- type
- url
- offset
- length
- user
Here’s an Example: message.entities[num].<attribute>
Here num is the entity number or order of entity in a reply, for if incase there are multiple entities in the reply/message.
message.entities returns a list of entities object.
message.entities[0].type would give the type of the first entity
Refer Bot Api for extra details
Advanced use of the API
Using local Bot API Sever
Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.
Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()
Note: 4200 is an example port
New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:
Sending large text messages
Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:
Or you can use the new smart_split function to get more meaningful substrings:
Controlling the amount of Threads used by TeleBot
The TeleBot constructor takes the following optional arguments:
- threaded: True/False (default True). A flag to indicate whether TeleBot should execute message handlers on it’s polling Thread.
The listener mechanism
As an alternative to the message handlers, one can also register a function as a listener to TeleBot.
NOTICE: handlers won’t disappear! Your message will be processed both by handlers and listeners. Also, it’s impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:
Using web hooks
When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.
There are some examples using webhooks in the examples/webhook_examples directory.
You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.
You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.
If you want to use socket5 proxy you need install dependency pip install requests[socks] and make sure, that you have the latest version of gunicorn , PySocks , pyTelegramBotAPI , requests and urllib3 .
You can disable or change the interaction with real Telegram server by using
parameter. You can pass there your own function that will be called instead of requests.request.
Then you can use API and proceed requests in your handler code.
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params:
- ✔ Bot API 6.0
- ✔ Bot API 5.7
- ✔ Bot API 5.6
- ✔ Bot API 5.5
- ✔ Bot API 5.4
- ➕ Bot API 5.3 — ChatMember* classes are full copies of ChatMember
- ✔ Bot API 5.2
- ✔ Bot API 5.1
- ✔ Bot API 5.0
- ✔ Bot API 4.9
- ✔ Bot API 4.8
- ✔ Bot API 4.7
- ✔ Bot API 4.6
- ➕ Bot API 4.5 — No nested MessageEntities and Markdown2 support
- ✔ Bot API 4.4
- ✔ Bot API 4.3
- ✔ Bot API 4.2
- ➕ Bot API 4.1 — No Passport support
- ➕ Bot API 4.0 — No Passport support
Asynchronous version of telebot
We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.
Echo Bot example on AsyncTeleBot:
As you can see here, keywords are await and async.
Why should I use async?
Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.
Differences in AsyncTeleBot
AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.
See more examples in our examples folder
How can I distinguish a User and a GroupChat in message.chat?
Telegram Bot API support new type Chat for message.chat.
- Check the type attribute in Chat object:
How can I handle reocurring ConnectionResetErrors?
Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.
The Telegram Chat Group
Get help. Discuss. Chat.
- Join the pyTelegramBotAPI Telegram Chat Group
Join the News channel. Here we will post releases and updates.
Template is a ready folder that contains architecture of basic project. Here are some examples of template:
Bots using this library
-
(source) by ilteoood — Monitors websites and sends a notification on changes by aRandomStranger by GabrielRF — Let me Google that for you. by mrgigabyte by Tronikart — Multifunctional Telegram Bot RadRetroRobot. (source) by i32ropie by @NeoRanger (source) — Share code snippets as beautifully syntax-highlighted HTML and/or images. (source) by alejandrocq — Telegram bot to check the menu of Universidad de Granada dining hall. — Simple Proxy Bot for Telegram. by p-hash — DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. It also records the date of the last donation so that it helps the donors to know when they can donate again. — by vfranch by Dmytryi Striletskyi — Timetable for one university in Kiev. by rmed — Send and receive messages to/from WhatsApp through Telegram (source) by jcolladosp — Telegram bot using the Python API that gets films rating from IMDb and metacritic (source) by GabrielRF — Send to Kindle service. (source) by GabrielRF — Bot used to track packages on the Brazilian Mail Service. (link) by EeOneDown — Bot with timetables for SPbU students. (link) by 0xVK — Telegram timetable bot, for Zhytomyr Ivan Franko State University students. (link) — A Telegram Bot created to help people to memorize other languages’ vocabulary. by rubenleon (GitHub) — Bot that provides buses coming to a certain stop and their remaining time for the city of Vigo (Galicia — Spain) (source) by airatk — bot which shows all the necessary information to KNTRU-KAI students. (source) by @FacuM — Support Telegram bot for developers and maintainers. (source) by @DesExcile — Сatalog of poems by Eduard Asadov. (source) by @LeoSvalov — words and synonyms from dictionary.com and thesaurus.com in the telegram. (source) by @irevenko — An all-round bot that displays some statistics (weather, time, crypto etc. ) (source) by @Fliego — a simple bot for food ordering (source) by @0xnu — Telegram bot for displaying the latest news, sports schedules and injury updates. (source) by @zeph1997 — A Telegram Bot to remove «join group» and «removed from group» notifications. (source) by @Pablo-Davila — A (tasks) lists manager bot for Telegram. (source) by @Pablo-Davila — An implementation of the famous Eliza psychologist chatbot. (source) by Mrsqd. A Telegram bot that will always be happy to show you the weather forecast. by ModischFabrications. This bot can start, stop and monitor a minecraft server. by dexpiper. This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. by Anvaari. This Bot make «Add to google calendar» link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. Source code by Areeg Fahad. This bot can be used to translate texts. by Areeg Fahad. With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. by Leon Heess (source). Send any link, and the bot tries its best to remove all tracking from the link you sent. by Vishal Singh(source code) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) by Aadithya & Amol Soans This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) (source) by TrevorWinstral — Gets live COVID Country data, plots it, and briefs the user (source) by TrevorWinstral — Notifies ETH students when their lectures have been uploaded by Resinprotein2333. This bot can help you to find The information of CVE vulnerabilities. (Source by DevAdvik — Get Live Ethereum Gas Fees in GWEI by JoachimStanislaus. This bot can help you to track your expenses by uploading your bot entries to your google sheet. by Carlosma7. This bot is a trivia game that allows you to play with people from different ages. This project addresses the use of a system through chatbots to carry out a social and intergenerational game as an alternative to traditional game development. (source) This bot lets you find difinitions of words in Spanish using RAE’s dictionary. It features direct message and inline search. by EnriqueMoran. Control your LinuxOS computer through Telegram. Query wolframalpha.com and make use of its API through Telegram. This Bot can understand spoken text in videos and translate it to English (source) Zyprexa can solve, help you solve any mathematical problem you encounter and convert your regular mathematical expressions into beautiful imagery using LaTeX. by tusharhero — Makes bincodes from text provides and also converts them back to text. Toolset for Hydrophilia tabletop game (game cards, rules, structure. ).
Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.
Телеграм. Как собрать информацию из чатов. Часть 1
В этой серии статей мы с Вами рассмотрим как написать свой отдельный клиент Телеграм, который будет собирать данные из интересных нам чатов, а также посмотрим, как сохранять эти сведения в свою базу данных.
Регистрация аккаунта разработчика и настройка клиента
Всем привет! Парсинг сайтов — дело веселое, можно использовать эти данные для своего ресурса или же делать это на заказ. А что если скачать, к примеру, все сообщения из телеграм-чата или список его участников, а затем использовать эти данные для аналитики или еще лучше, для формирования своей базы данных пользователей, которым интересна та или иная тема.
В этой серии статей мы с Вами рассмотрим как написать свой отдельный клиент Telegram, который будет собирать данные из интересных нам чатов, а также посмотрим, как сохранять эти сведения в свою базу данных.
Для создания отдельного клиента хорошо подойдет асинхронная библиотека «Telethon» (Вот репозиторий библиотеки). Сама библиотека может использоваться как для создания телеграм-ботов, так и для создания отдельных приложений работающих с API Telegram. Главным преимуществом является понятная документация в которой можно найти ответы на все вопросы (необходимо знание английского языка).
Создание нашего проекта начнем с регистрации аккаунта разработчика здесь
Регистрация разработчика
Вводим пришедший в Telegram численно-буквенный код и попадаем на страницу регистрации нового приложения. Заполняем форму, достаточно первых двух граф:

Если все введено верно вы увидите следующие сведения.

Сразу оговорюсь, данных будет немного больше, но нам важны параметры App api_id и App api_hash.
Поздравляю! Вы зарегистрировали ваше приложение в API Telegram. Закрывать страничку пока не стоит. Мы будем брать оттуда значения App api_id, App api_hash, Short_name для нашего приложения.
Переходим в PyCharm
Хорошим тоном будет не хранить в коде наш хэш и app_id, поэтому давайте сделаем красиво =) Используем библиотеку configparser для создания файла настроек. Создайте в корне проекта файл с расширением .ini (пример config.ini) и давайте поместим туда наши данные из аккаунта разработчика который мы зарегистрировали.
Файл config.ini
И да, я знаю про venv и переменные окружения. Вы можете использовать удобный вам метод.
Далее нас ждет самое интересное. Давайте установим в наш проект саму библиотеку Telethon командой «pip install telethon» и импортируем в проект класс TelegramClient из нашей установленной библиотеки.
Далее давайте настроим передачу наших данных в подключение из файла настроек
Обратите внимание что в файле «config.ini» первой строкой мы указали [Telegram]. С помощью этих тэгов мы просто не будем путаться в переменных настроек и разделять их в одном файле.
Создадим нашу главную функцию и запросим у сервера телеграм сведения о нас.
Наша библиотека Telethon асинхронная а значит функции и методы мы будем использовать с добавлением ключевых слов async и await (кстати можно и без них но не рекомендую)
Для того, что бы наш клиент не закрывался после запуска мы добавим в конце нашего файла такую запись
Первый запуск
При первом запуске в консоли PyCharm вас попросит ввести ваш номер телефона или токен бота

Это нужно, что бы создать файл сессии он будет хранится в корне проекта с расширением .session ( удалять их не стоит о них поговорим позднее)
Вводите ваш номер телефона в международном формате без «+»
Вам снова пришел код в аккаунт телеграмм только теперь из 5 цифр. Введите их.
Поздравляю вы запустили ваш клиент Телеграм.
Так что же вернула нам наша функция main
наша переменная about_me теперь содержит объект User с специфическим типом данных библиотеки telethon.
Внутри объекта вы можете увидеть данные о вашем аккаунте.

Для того, что бы посмотреть отдельные сведения давайте сделаем вот такой код
Ну в вашем случае звездочек не будет.
Только что сервер Телеграм рассказал вам о вас чуть больше чем вы видите в своем аккаунте. В следующей статье мы немного обнаглеем и соберем с серверов Телеграм сведения об участниках какого-нибудь чата.
Утечка данных из Telegram — проблема Telegram.
прим. автора
Все сведения которые мы будем получать являются общедоступными. И эти же сведения мы можем увидеть и через официальное приложение. Но я все-таки призываю Вас не использовать полученные знания в плохих целях. Вся изложенная информация подается с целью образования и популяризации языка программирования, его библиотек и возможностей.
Message¶
Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their message_id and chat are equal.
In Python from is a reserved word. Use from_user instead.
Changed in version 20.0:
The arguments and attributes voice_chat_scheduled , voice_chat_started and voice_chat_ended , voice_chat_participants_invited were renamed to video_chat_scheduled / video_chat_scheduled , video_chat_started / video_chat_started , video_chat_ended / video_chat_ended and video_chat_participants_invited / video_chat_participants_invited , respectively, in accordance to Bot API 6.0.
The following are now keyword-only arguments in Bot methods:
message_id ( int ) – Unique message identifier inside this chat.
from_user ( telegram.User , optional) – Sender of the message; empty for messages sent to channels. For backward compatibility, this will contain a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
sender_chat ( telegram.Chat , optional) – Sender of the message, sent on behalf of a chat. For example, the channel itself for channel posts, the supergroup itself for messages from anonymous group administrators, the linked channel for messages automatically forwarded to the discussion group. For backward compatibility, from_user contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
forward_from ( telegram.User , optional) – For forwarded messages, sender of the original message.
forward_from_chat ( telegram.Chat , optional) – For messages forwarded from channels or from anonymous administrators, information about the original sender chat.
forward_from_message_id ( int , optional) – For forwarded channel posts, identifier of the original message in the channel.
forward_sender_name ( str , optional) – Sender’s name for messages forwarded from users who disallow adding a link to their account in forwarded messages.
forward_date ( datetime.datetime , optional) – For forwarded messages, date the original message was sent in Unix time. Converted to datetime.datetime .
True , if the message is a channel post that was automatically forwarded to the connected discussion group.
New in version 13.9.
reply_to_message ( telegram.Message , optional) – For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
edit_date ( datetime.datetime , optional) – Date the message was last edited in Unix time. Converted to datetime.datetime .
True , if the message can’t be forwarded.
New in version 13.9.
media_group_id ( str , optional) – The unique identifier of a media message group this message belongs to.
text ( str , optional) – For text messages, the actual UTF-8 text of the message, 0- 4096 characters.
For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text. See parse_entity and parse_entities methods for how to use properly. This list is empty if the message does not contain entities.
Changed in version 20.0: Accepts any collections.abc.Sequence as input instead of just a list. The input is converted to a tuple.
For messages with a Caption. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See Message.parse_caption_entity and parse_caption_entities methods for how to use properly. This list is empty if the message does not contain caption entities.
Changed in version 20.0: Accepts any collections.abc.Sequence as input instead of just a list. The input is converted to a tuple.
audio ( telegram.Audio , optional) – Message is an audio file, information about the file.
document ( telegram.Document , optional) – Message is a general file, information about the file.
animation ( telegram.Animation , optional) – Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.
game ( telegram.Game , optional) – Message is a game, information about the game.
Message is a photo, available sizes of the photo. This list is empty if the message does not contain a photo.
Changed in version 20.0: Accepts any collections.abc.Sequence as input instead of just a list. The input is converted to a tuple.
sticker ( telegram.Sticker , optional) – Message is a sticker, information about the sticker.
video ( telegram.Video , optional) – Message is a video, information about the video.
voice ( telegram.Voice , optional) – Message is a voice message, information about the file.
video_note ( telegram.VideoNote , optional) – Message is a video note, information about the video message.
New members that were added to the group or supergroup and information about them (the bot itself may be one of these members). This list is empty if the message does not contain new chat members.
Changed in version 20.0: Accepts any collections.abc.Sequence as input instead of just a list. The input is converted to a tuple.
caption ( str , optional) – Caption for the animation, audio, document, photo, video or voice, 0- 1024 characters.
contact ( telegram.Contact , optional) – Message is a shared contact, information about the contact.
location ( telegram.Location , optional) – Message is a shared location, information about the location.
venue ( telegram.Venue , optional) – Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.
left_chat_member ( telegram.User , optional) – A member was removed from the group, information about them (this member may be the bot itself).
new_chat_title ( str , optional) – A chat title was changed to this value.
A chat photo was changed to this value. This list is empty if the message does not contain a new chat photo.
Changed in version 20.0: Accepts any collections.abc.Sequence as input instead of just a list. The input is converted to a tuple.
delete_chat_photo ( bool , optional) – Service message: The chat photo was deleted.
group_chat_created ( bool , optional) – Service message: The group has been created.
supergroup_chat_created ( bool , optional) – Service message: The supergroup has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
channel_chat_created ( bool , optional) – Service message: The channel has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.
Service message: auto-delete timer settings changed in the chat.
New in version 13.4.
migrate_to_chat_id ( int , optional) – The group has been migrated to a supergroup with the specified identifier.
migrate_from_chat_id ( int , optional) – The supergroup has been migrated from a group with the specified identifier.
pinned_message ( telegram.Message , optional) – Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
invoice ( telegram.Invoice , optional) – Message is an invoice for a payment, information about the invoice.
successful_payment ( telegram.SuccessfulPayment , optional) – Message is a service message about a successful payment, information about the payment.
connected_website ( str , optional) – The domain name of the website on which the user has logged in.
forward_signature ( str , optional) – For messages forwarded from channels, signature of the post author if present.
author_signature ( str , optional) – Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.
poll ( telegram.Poll , optional) – Message is a native poll, information about the poll.
dice ( telegram.Dice , optional) – Message is a dice with random value.
via_bot ( telegram.User , optional) – Bot through which message was sent.
proximity_alert_triggered ( telegram.ProximityAlertTriggered , optional) – Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.
Service message: video chat scheduled.
New in version 20.0.
Service message: video chat started.
New in version 20.0.
Service message: video chat ended.
New in version 20.0.
Service message: new participants invited to a video chat.
New in version 20.0.
Service message: data sent by a Web App.
New in version 20.0.
reply_markup ( telegram.InlineKeyboardMarkup , optional) – Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
True , if the message is sent to a forum topic.
New in version 20.0.
Unique identifier of a message thread to which the message belongs; for supergroups only.
New in version 20.0.
Service message: forum topic created.
New in version 20.0.
Service message: forum topic closed.
New in version 20.0.
Service message: forum topic reopened.
New in version 20.0.
Service message: forum topic edited.
New in version 20.0.
Service message: General forum topic hidden.
New in version 20.0.
Service message: General forum topic unhidden.
New in version 20.0.
Service message: the user allowed the bot added to the attachment menu to write messages.
New in version 20.0.
True , if the message media is covered by a spoiler animation.
New in version 20.0.
Service message: a user was shared with the bot.
New in version 20.1.
Service message: a chat was shared with the bot.
New in version 20.1.
Unique message identifier inside this chat.
Optional. Sender of the message; empty for messages sent to channels. For backward compatibility, this will contain a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
Optional. Sender of the message, sent on behalf of a chat. For example, the channel itself for channel posts, the supergroup itself for messages from anonymous group administrators, the linked channel for messages automatically forwarded to the discussion group. For backward compatibility, from_user contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
Date the message was sent in Unix time. Converted to datetime.datetime .
Conversation the message belongs to.
Optional. For forwarded messages, sender of the original message.
Optional. For messages forwarded from channels or from anonymous administrators, information about the original sender chat.
Optional. For forwarded channel posts, identifier of the original message in the channel.
Optional. For forwarded messages, date the original message was sent in Unix time. Converted to datetime.datetime .
Optional. True , if the message is a channel post that was automatically forwarded to the connected discussion group.
New in version 13.9.
Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
Optional. Date the message was last edited in Unix time. Converted to datetime.datetime .
Optional. True , if the message can’t be forwarded.
New in version 13.9.
Optional. The unique identifier of a media message group this message belongs to.
Optional. For text messages, the actual UTF-8 text of the message, 0- 4096 characters.
Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text. See parse_entity and parse_entities methods for how to use properly. This list is empty if the message does not contain entities.
Changed in version 20.0: This attribute is now an immutable tuple.
Optional. For messages with a Caption. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See Message.parse_caption_entity and parse_caption_entities methods for how to use properly. This list is empty if the message does not contain caption entities.
Changed in version 20.0: This attribute is now an immutable tuple.
Optional. Message is an audio file, information about the file.
Optional. Message is a general file, information about the file.
Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.
Optional. Message is a game, information about the game.
Optional. Message is a photo, available sizes of the photo. This list is empty if the message does not contain a photo.
Changed in version 20.0: This attribute is now an immutable tuple.
Optional. Message is a sticker, information about the sticker.
Optional. Message is a video, information about the video.
Optional. Message is a voice message, information about the file.
Optional. Message is a video note, information about the video message.
Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members). This list is empty if the message does not contain new chat members.
Changed in version 20.0: This attribute is now an immutable tuple.
Optional. Caption for the animation, audio, document, photo, video or voice, 0- 1024 characters.
Optional. Message is a shared contact, information about the contact.
Optional. Message is a shared location, information about the location.
Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.
Optional. A member was removed from the group, information about them (this member may be the bot itself).
Optional. A chat title was changed to this value.
A chat photo was changed to this value. This list is empty if the message does not contain a new chat photo.
Changed in version 20.0: This attribute is now an immutable tuple.
Optional. Service message: The chat photo was deleted.
Optional. Service message: The group has been created.
Optional. Service message: The supergroup has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
Optional. Service message: The channel has been created. This field can’t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.
Optional. Service message: auto-delete timer settings changed in the chat.
New in version 13.4.
Optional. The group has been migrated to a supergroup with the specified identifier.
Optional. The supergroup has been migrated from a group with the specified identifier.
Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
Optional. Message is an invoice for a payment, information about the invoice.
Optional. Message is a service message about a successful payment, information about the payment.
Optional. The domain name of the website on which the user has logged in.
Optional. For messages forwarded from channels, signature of the post author if present.
Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.
Optional. Sender’s name for messages forwarded from users who disallow adding a link to their account in forwarded messages.
Optional. Telegram Passport data.
Optional. Message is a native poll, information about the poll.
Optional. Message is a dice with random value.
Optional. Bot through which message was sent.
Optional. Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.
Optional. Service message: video chat scheduled.
New in version 20.0.
Optional. Service message: video chat started.
New in version 20.0.
Optional. Service message: video chat ended.
New in version 20.0.
Optional. Service message: new participants invited to a video chat.
New in version 20.0.
Optional. Service message: data sent by a Web App.
New in version 20.0.
Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
Optional. True , if the message is sent to a forum topic.
New in version 20.0.
Optional. Unique identifier of a message thread to which the message belongs; for supergroups only.
New in version 20.0.
Optional. Service message: forum topic created.
New in version 20.0.
Optional. Service message: forum topic closed.
New in version 20.0.
Optional. Service message: forum topic reopened.
New in version 20.0.
Optional. Service message: forum topic edited.
New in version 20.0.
Optional. Service message: General forum topic hidden.
New in version 20.0.
Optional. Service message: General forum topic unhidden.
New in version 20.0.
Optional. Service message: the user allowed the bot added to the attachment menu to write messages.
New in version 20.0.
Optional. True , if the message media is covered by a spoiler animation.
New in version 20.0.
Optional. Service message: a user was shared with the bot.
New in version 20.1.
Optional. Service message: a chat was shared with the bot.
New in version 20.1.
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML in the same way the original message was formatted.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as HTML.
Message caption with caption entities formatted as HTML.
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML. This also formats telegram.MessageEntity.URL as a hyperlink.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as HTML.
Message caption with caption entities formatted as HTML.
Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN .
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown in the same way the original message was formatted.
‘Markdown’ is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Message caption with caption entities formatted as Markdown.
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN .
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.
‘Markdown’ is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2_urled() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Message caption with caption entities formatted as Markdown.
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN_V2 .
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown in the same way the original message was formatted.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Message caption with caption entities formatted as Markdown.
Creates an Markdown-formatted string from the markup entities found in the message’s caption using telegram.constants.ParseMode.MARKDOWN_V2 .
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Message caption with caption entities formatted as Markdown.
async close_forum_topic ( * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.close_forum_topic() .
New in version 20.0.
On success, True is returned.
async copy ( chat_id , caption = None , parse_mode = None , caption_entities = None , disable_notification = None , reply_to_message_id = None , allow_sending_without_reply = None , reply_markup = None , protect_content = None , message_thread_id = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.copy_message() .
On success, returns the MessageId of the sent message.
async delete ( * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.delete_message() .
On success, True is returned.
async delete_forum_topic ( * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.delete_forum_topic() .
New in version 20.0.
On success, True is returned.
async edit_caption ( caption = None , reply_markup = None , parse_mode = None , caption_entities = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.edit_message_caption() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
async edit_forum_topic ( name = None , icon_custom_emoji_id = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.edit_forum_topic() .
New in version 20.0.
On success, True is returned.
async edit_live_location ( latitude = None , longitude = None , reply_markup = None , horizontal_accuracy = None , heading = None , proximity_alert_radius = None , * , location = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.edit_message_live_location() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
async edit_media ( media , reply_markup = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.edit_message_media() .
You can only edit messages that the bot sent itself(i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is not an inline message, the edited Message is returned, otherwise True is returned.
async edit_reply_markup ( reply_markup = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.edit_message_reply_markup() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
async edit_text ( text , parse_mode = None , disable_web_page_preview = None , reply_markup = None , entities = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.edit_message_text() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
If this message is neither a plain text message nor a status update, this gives the attachment that this message was sent with. This may be one of
Otherwise None is returned.
Changed in version 20.0: dice , passport_data and poll are now also considered to be an attachment.
For the documentation of the arguments, please see telegram.Bot.forward_message() .
Since the release of Bot API 5.5 it can be impossible to forward messages from some chats. Use the attributes telegram.Message.has_protected_content and telegram.Chat.has_protected_content to check this.
As a workaround, it is still possible to use copy() . However, this behaviour is undocumented and might be changed by Telegram.
On success, instance representing the message forwarded.
async get_game_high_scores ( user_id , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.get_game_high_scores() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
New in version 20.0.
Convenience property. If the chat of the message is not a private chat or normal group, returns a t.me link of the message.
parse_caption_entities ( types = None ) [source] ¶
Returns a dict that maps telegram.MessageEntity to str . It contains entities from this message’s caption filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity belongs to as the value of the dict .
This method should always be used instead of the caption_entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints. See parse_entity for more info.
types (List[ str ], optional) – List of telegram.MessageEntity types as strings. If the type attribute of an entity is contained in this list, it will be returned. Defaults to a list of all types. All types can be found as constants in telegram.MessageEntity .
A dictionary of entities mapped to the text that belongs to them, calculated based on UTF-16 codepoints.
Returns the text from a given telegram.MessageEntity .
This method is present because Telegram calculates the offset and length in UTF-16 codepoint pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.caption with the offset and length.)
entity ( telegram.MessageEntity ) – The entity to extract the text from. It must be an entity that belongs to this message.
The text of the given entity.
parse_entities ( types = None ) [source] ¶
Returns a dict that maps telegram.MessageEntity to str . It contains entities from this message filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity belongs to as the value of the dict .
This method should always be used instead of the entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints. See parse_entity for more info.
types (List[ str ], optional) – List of telegram.MessageEntity types as strings. If the type attribute of an entity is contained in this list, it will be returned. Defaults to a list of all types. All types can be found as constants in telegram.MessageEntity .
A dictionary of entities mapped to the text that belongs to them, calculated based on UTF-16 codepoints.
Returns the text from a given telegram.MessageEntity .
This method is present because Telegram calculates the offset and length in UTF-16 codepoint pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.text with the offset and length.)
entity ( telegram.MessageEntity ) – The entity to extract the text from. It must be an entity that belongs to this message.
The text of the given entity.
async pin ( disable_notification = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.pin_chat_message() .
On success, True is returned.
async reopen_forum_topic ( * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.reopen_forum_topic() .
New in version 20.0.
On success, True is returned.
async reply_animation ( animation , duration = None , width = None , height = None , thumb = None , caption = None , parse_mode = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , caption_entities = None , protect_content = None , message_thread_id = None , has_spoiler = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_animation() .
quote ( bool , optional) – If set to True , the animation is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_audio ( audio , duration = None , performer = None , title = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , parse_mode = None , thumb = None , allow_sending_without_reply = None , caption_entities = None , protect_content = None , message_thread_id = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_audio() .
quote ( bool , optional) – If set to True , the audio is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_chat_action ( action , message_thread_id = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_chat_action() .
New in version 13.2.
On success, True is returned.
async reply_contact ( phone_number = None , first_name = None , last_name = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , vcard = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , contact = None , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_contact() .
quote ( bool , optional) – If set to True , the contact is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_copy ( from_chat_id , message_id , caption = None , parse_mode = None , caption_entities = None , disable_notification = None , reply_to_message_id = None , allow_sending_without_reply = None , reply_markup = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.copy_message() .
If set to True , the copy is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
New in version 13.1.
On success, returns the MessageId of the sent message.
async reply_dice ( disable_notification = None , reply_to_message_id = None , reply_markup = None , emoji = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_dice() .
quote ( bool , optional) – If set to True , the dice is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_document ( document , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , parse_mode = None , thumb = None , disable_content_type_detection = None , allow_sending_without_reply = None , caption_entities = None , protect_content = None , message_thread_id = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_document() .
quote ( bool , optional) – If set to True , the document is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_game ( game_short_name , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_game() .
quote ( bool , optional) – If set to True , the game is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
New in version 13.2.
On success, instance representing the message posted.
async reply_html ( text , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , entities = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
Sends a message with HTML formatting.
For the documentation of the arguments, please see telegram.Bot.send_message() .
quote ( bool , optional) – If set to True , the message is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_invoice ( title , description , payload , provider_token , currency , prices , start_parameter = None , photo_url = None , photo_size = None , photo_width = None , photo_height = None , need_name = None , need_phone_number = None , need_email = None , need_shipping_address = None , is_flexible = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , provider_data = None , send_phone_number_to_provider = None , send_email_to_provider = None , allow_sending_without_reply = None , max_tip_amount = None , suggested_tip_amounts = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_invoice() .
As of API 5.2 start_parameter is an optional argument and therefore the order of the arguments had to be changed. Use keyword arguments to make sure that the arguments are passed correctly.
New in version 13.2.
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
quote ( bool , optional) – If set to True , the invoice is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_location ( latitude = None , longitude = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , live_period = None , horizontal_accuracy = None , heading = None , proximity_alert_radius = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , location = None , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_location() .
quote ( bool , optional) – If set to True , the location is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_markdown ( text , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , entities = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
Sends a message with Markdown version 1 formatting.
For the documentation of the arguments, please see telegram.Bot.send_message() .
‘Markdown’ is a legacy mode, retained by Telegram for backward compatibility. You should use reply_markdown_v2() instead.
quote ( bool , optional) – If set to True , the message is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_markdown_v2 ( text , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , entities = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
Sends a message with markdown version 2 formatting.
For the documentation of the arguments, please see telegram.Bot.send_message() .
quote ( bool , optional) – If set to True , the message is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_media_group ( media , disable_notification = None , reply_to_message_id = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None , caption = None , parse_mode = None , caption_entities = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_media_group() .
quote ( bool , optional) – If set to True , the media group is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
An array of the sent Messages.
async reply_photo ( photo , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , parse_mode = None , allow_sending_without_reply = None , caption_entities = None , protect_content = None , message_thread_id = None , has_spoiler = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_photo() .
quote ( bool , optional) – If set to True , the photo is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_poll ( question , options , is_anonymous = None , type = None , allows_multiple_answers = None , correct_option_id = None , is_closed = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , explanation = None , explanation_parse_mode = None , open_period = None , close_date = None , allow_sending_without_reply = None , explanation_entities = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_poll() .
quote ( bool , optional) – If set to True , the poll is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_sticker ( sticker , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_sticker() .
quote ( bool , optional) – If set to True , the sticker is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_text ( text , parse_mode = None , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , allow_sending_without_reply = None , entities = None , protect_content = None , message_thread_id = None , * , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_message() .
quote ( bool , optional) – If set to True , the message is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_venue ( latitude = None , longitude = None , title = None , address = None , foursquare_id = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , foursquare_type = None , google_place_id = None , google_place_type = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , venue = None , quote = None , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_venue() .
quote ( bool , optional) – If set to True , the venue is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_video ( video , duration = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , width = None , height = None , parse_mode = None , supports_streaming = None , thumb = None , allow_sending_without_reply = None , caption_entities = None , protect_content = None , message_thread_id = None , has_spoiler = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_video() .
quote ( bool , optional) – If set to True , the video is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_video_note ( video_note , duration = None , length = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , thumb = None , allow_sending_without_reply = None , protect_content = None , message_thread_id = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_video_note() .
quote ( bool , optional) – If set to True , the video note is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async reply_voice ( voice , duration = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , parse_mode = None , allow_sending_without_reply = None , caption_entities = None , protect_content = None , message_thread_id = None , * , filename = None , quote = None , read_timeout = None , write_timeout = 20 , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.send_voice() .
quote ( bool , optional) – If set to True , the voice note is sent as an actual reply to this message. If reply_to_message_id is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
On success, instance representing the message posted.
async set_game_score ( user_id , score , force = None , disable_edit_message = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.set_game_score() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
async stop_live_location ( reply_markup = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.stop_message_live_location() .
You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods) or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and might be changed by Telegram.
On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
async stop_poll ( reply_markup = None , * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.stop_poll() .
On success, the stopped Poll with the final results is returned.
Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML in the same way the original message was formatted.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as HTML.
Message text with entities formatted as HTML.
Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML. This also formats telegram.MessageEntity.URL as a hyperlink.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as HTML.
Message text with entities formatted as HTML.
Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN .
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted.
‘Markdown’ is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Message text with entities formatted as Markdown.
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN .
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.
‘Markdown’ is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2_urled() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Message text with entities formatted as Markdown.
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN_V2 .
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Message text with entities formatted as Markdown.
Creates an Markdown-formatted string from the markup entities found in the message using telegram.constants.ParseMode.MARKDOWN_V2 .
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats telegram.MessageEntity.URL as a hyperlink.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Message text with entities formatted as Markdown.
async unpin ( * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶
For the documentation of the arguments, please see telegram.Bot.unpin_chat_message() .
On success, True is returned.
async unpin_all_forum_topic_messages ( * , read_timeout = None , write_timeout = None , connect_timeout = None , pool_timeout = None , api_kwargs = None ) [source] ¶