Как считать сообщение из чата телеграмм python

от admin

Работа с сообщениями¶

В этой главе мы разберёмся, как применять различные типы форматирования к сообщениям и работать с медиафайлами.

Текст¶

Обработка текстовых сообщений — это, пожалуй, одно из важнейших действий у большинства ботов. Текстом можно выразить практически что угодно и при этом подавать информацию хочется красиво. В распоряжении у разработчика имеется три способа разметки текста: HTML, Markdown и MarkdownV2. Наиболее продвинутыми из них считаются HTML и MarkdownV2, «классический» маркдаун оставлен для обеспечения обратной совместимости и поддерживает меньше возможностей.

За выбор форматирования при отправке сообщений отвечает аргумент parse_mode , например:

Если в боте повсеместно используется определённое форматирование, то каждый раз указывать аргумент parse_mode довольно накладно. К счастью, в aiogram можно передать необходимый тип прямо в объект Bot, а если в каком-то конкретном случае нужно обойтись без этих ваших разметок, то просто укажите parse_mode=»» (пустая строка):

Настройка типа разметки по умолчанию

Существует и более «программный» или даже «динамический» способ формирования сообщения. Для этого нужно импортировать модуль markdown из aiogram.utils, который, несмотря на название, поддерживает и HTML тоже. Далее вызовите функцию text() , в которую передайте произвольное число таких же вызовов функции text() . Тип форматирования определяется названием функции, а буква «h» в начале означает HTML, т.е. функция hbold() обрамляет переданный ей текст как жирный в HTML-разметке ( <b>текст</b> ). Аргумент sep определяет разделитель между кусками текста.
В общем, смотрите на код и скриншот ниже. Стоит ли использовать такой способ создания текста — решать вам:

Динамическое форматирование

Помимо отправки с форматированием, Aiogram позволяет извлекать входящий текст как простое содержимое (plain text), как HTML и как Markdown. Сравнить можно на скриншоте ниже. Это удобно использовать, например, если вы хотите вернуть отправителю его сообщение с небольшими изменениями:

Настройка типа разметки по умолчанию

Всё бы ничего, но с использованием форматирования есть проблема: не в меру хитрые пользователи могут использовать спец. символы в именах или сообщениях, ломая бота. Впрочем, в aiogram существуют методы экранирования таких символов: escape_md() и quote_html() . Либо можно использовать упомянутые выше методы (h)bold, (h)italic и прочие:

Экранирование ввода

Подробнее о различных способах форматирования и поддерживаемых тегах можно узнать в документации Bot API.

Медиафайлы¶

Помимо обычных текстовых сообщений Telegram позволяет обмениваться медиафайлами различных типов: фото, видео, гифки, геолокации, стикеры и т.д. У большинства медиафайлов есть свойства file_id и file_unique_id . Первый можно использовать для повторной отправки одного и того же медиафайла много раз, причём отправка будет мгновенной, т.к. сам файл уже лежит на серверах Telegram. Это самый предпочтительный способ.
К примеру, следующий код заставит бота моментально ответить пользователю той же гифкой, что была прислана:

file_id уникален для каждого бота, т.е. переиспользовать чужой идентификатор нельзя. Однако в Bot API есть ещё file_unique_id . Его нельзя использовать для повторной отправки или скачивания медиафайла, но зато он одинаковый у всех ботов. Нужен file_unique_id обычно тогда, когда нескольким ботам требуется знать, что их собственные file_id односятся к одному и тому же файлу.

Кстати, про скачивание: aiogram предлагает удобный вспомогательный метод download() для загрузки небольших файлов на сервер, где запущен бот:

Работа с изображениями

Обратите внимание на конструкцию message.photo[-1] . Когда пользователь присылает боту изображение, Telegram присылает не один объект, а целый массив с разными размерами одного и того же изображения, отсортированными по возрастанию. В общем случае нас будет интересовать изображение наибольшего размера, стоящее последним (индекс «минус один»).

Скачивание больших файлов

Боты, использующие Telegram Bot API, могут скачивать файлы размером не более 20 мегабайт. Если вы планируете скачивать/заливать большие файлы, лучше рассмотрите библиотеки, взаимодействующие с Telegram Client API, а не с Telegram Bot API, например, Telethon. Немногие знают, но Client API могут использовать не только обычные аккаунты, но ещё и боты.

А начиная с Bot API версии 5.0, можно использовать собственный сервер Bot API для работы с большими файлами.

Бонус¶

Бывают ситуации, когда хочется отправить длинное сообщение с картинкой, но лимит на подписи к медиафайлам составляет всего 1024 символа против 4096 у обычного текстового, а вставлять внизу ссылку на медиа — выглядит некрасиво. Более того, когда Telegram делает предпросмотр ссылок, он берёт первую из них и считывает метатеги, в результате сообщение может отправиться не с тем превью, которое хочется увидеть.
Для решения этой проблемы ещё много лет назад придумали подход со «скрытыми ссылками» в HTML-разметке. Суть в том, что можно поместить ссылку в пробел нулевой ширины и вставить всю эту конструкцию в начало сообщения. Для наблюдателя в сообщении никаких ссылок нет, а сервер Telegram всё видит и честно добавляет предпросмотр.
Разработчики aiogram для этого даже сделали специальный вспомогательный метод hide_link() :

Изображение со скрытой ссылкой

На этом всё. До следующих глав!
Ставьте лайки, подписывайтесь, прожимайте колокольчик

Telegram get chat messages /posts — python Telethon

Been able to retreive message from groups, no problem but when it comes to channels I am stuck.

I’ve searched the telethon documentation but most answers were in response to the old get_message_history .

When I’m trying with the following chat.id = 1097988869 (news.bitcoin.com) I’m getting an error below (for groups the chat.id works fine):

PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type

Пишем простой граббер для Telegram чатов на Python

Пишем простой граббер для Telegram чатов на Python

В данном туториале мы научимся собирать данные и сообщения участников чатов и каналов Telegram, а также сохранять эту информацию в виде JSON-файлов, которые далее легко анализировать или экспортировать в базы данных.

Для указанных задач будет использоваться Python не ниже версии 3.5, а также высокоуровневая библиотека для работы с Telegram API – Telethon. Установить библиотеку можно с помощью менеджера пакетов pip :

Регистрируем в Telegram новое приложение

Для подключения к Telegram API необходимы api_id и api_hash . Эти параметры выдаются при регистрации приложения в инструментах разработчика (при отсутствии доступа используйте VPN). Для авторизации указываем номер телефона, к которому привязан аккаунт Telegram.

Пишем простой граббер для Telegram чатов на Python

Вводим пришедший в Telegram численно-буквенный код и попадаем на страницу регистрации нового приложения. Заполняем форму, достаточно первых двух граф:

Пишем простой граббер для Telegram чатов на Python

В результате попадаем на страницу конфигурации приложения. Находим оба параметра, а также доступные MTProto-сервера и открытые (публичные) ключи.

Избегая проблем с безопасностью, сохраняем учетные данные в отдельном файле config.ini следующей структуры:

Поле username далее будет использоваться лишь для автоматического сохранения сессии под именем username.session . Одному клиенту соответствует одна сессия, учтите это в случае запуска нескольких клиентов.

Создаем клиент Telegram

Начнем с импорта библиотек.

Встроенные модули configparser и json применяем соответственно для чтения параметров и вывода данных. Из библиотеки Telethon импортируем класс клиента Telegram и класс исключений. Внутренний модуль connection необходим при использовании прокси-сервера. Остальные элементы модуля telethon.tl используются для запросов необходимых нам списков (участников канала/чата и их сообщений).

Теперь считаем учетные данные из config.ini :

Создадим объект клиента Telegram API:

При необходимости прописываем прокси. При использовании протокола MTProxy прокси задается в виде кортежа (сервер, порт, ключ) .

При первом запуске платформа запросит номер телефона, и вслед – код подтверждения. Так же, как если бы вы входили в учетную запись в приложении или браузере.

Для сбора, обработки и сохранения информации мы создадим две функции:

  1. dump_all_participants(сhannel) заберет данные о пользователях администрируемого нами сообщества channel ;
  2. dump_all_messages(сhannel) соберет все сообщения. Для этой функции достаточно, чтобы у вас был доступ к сообществу (необязательно быть администратором).

Обе функции будут вызываться в теле функции main , в которой пользователь передаст ссылку на интересующий источник:

Касательно написания вызова функций стоит оговориться, что Telethon является асинхронной библиотекой. Поэтому в коде используются операторы async и await. В связи с этим функция main полностью будет выглядеть так:

Заметим, что из-за асинхронности Telethon может некорректно работать в средах, использующих те же подходы (Anaconda, Spyder, Jupyter).

Рекомендуемым способом управления клиентом является менеджер контекстов with . Его мы запустим в конце скрипта после описания вложенных в main функций.

Собираем данные об участниках

Telegram не выводит все запрашиваемые данные за один раз, а выдает их в пакетном режиме, по 100 записей за каждый запрос.

Устанавливаем ограничение в 100, начинаем со смещения 0, создаем список всех участников канала all_participants . Внутри бесконечного цикла передаем запрос GetParticipantsRequest .

Проверяем, есть ли у объекта participants свойство users . Если нет, выходим из цикла. В обратном случае добавляем новых членов в список all_participants , а длину полученного списка добавляем к смещению offset_user . Следующий запрос забирает пользователей, начиная с этого смещения. Цикл продолжается до тех пор, пока не соберет всех фолловеров канала.

Самый простой способ сохранить собранные данные в структурированном виде – воспользоваться форматом JSON. Базы данных, такие как MySQL, MongoDB и т. д., стоит рассматривать лишь для очень популярных каналов и большого количества сохраняемой информации. Либо если вы планируете такое расширение в будущем.

В JSON-файле можно хранить и всю информацию о каждом пользователе, но обычно достаточно лишь нескольких параметров. Покажем на примере, как ограничиться набором определенных данных:

Итак, для каждого пользователя создается свой словарь данных и добавляется в общий список all_user_details , который записывается в JSON-файл.

Собираем сообщения

Ситуация со сбором сообщений идентична сбору сведений о пользователях. Отличия сводятся к трем пунктам:

  1. Вместо клиентского запроса GetParticipantsRequest необходимо отправить GetHistoryRequest со своим набором параметров. Так же, как и в случае со списком участников запрос ограничен сотней записей за один раз.
  2. Для списка сообщений важна их последовательность. Чтобы получать последние сообщения, нужно правильно задать смещение в GetHistoryRequest (с конца).
  3. Чтобы корректно сохранить данные о времени публикации сообщений в JSON-файле, нужно преобразовать формат времени.

Если для анализа сообщений потребуются не все записи, задайте их число в переменной total_count_limit . Если нужна только сборка сообщений канала, достаточно закомментировать вызов await dump_all_participants(channel) .

Таким образом, с помощью Python и 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 13.12: Since Bot API 6.0, voice chat was renamed to video chat.

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.

date ( datetime.datetime ) – Date the message was sent in Unix time. Converted to datetime.datetime .

chat ( telegram.Chat ) – Conversation the message belongs to.

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 .

is_automatic_forward ( bool , optional) –

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.

edit_date ( datetime.datetime , optional) – Date the message was last edited in Unix time. Converted to datetime.datetime .

has_protected_content ( bool , optional) –

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. Also found as telegram.constants.MAX_MESSAGE_LENGTH .

entities (List[ telegram.MessageEntity ], 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.

caption_entities (List[ telegram.MessageEntity ]) – 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.

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.

photo (List[ telegram.PhotoSize ], optional) – Message is a photo, available sizes of the photo.

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_chat_members (List[ telegram.User ], optional) – New members that were added to the group or supergroup and information about them (the bot itself may be one of these members).

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.

new_chat_photo (List[ telegram.PhotoSize ], optional) – A chat photo was changed to this value.

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.

message_auto_delete_timer_changed ( telegram.MessageAutoDeleteTimerChanged , optional) –

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. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.

migrate_from_chat_id ( int , optional) – The supergroup has been migrated from a group with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.

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.

passport_data ( telegram.PassportData , optional) – Telegram Passport data.

poll ( telegram.Poll , optional) – Message is a native poll, information about the poll.

dice ( telegram.Dice , optional) – Message is a dice with random value from 1 to 6.

via_bot ( telegram.User , optional) – Message was sent through an inline bot.

proximity_alert_triggered ( telegram.ProximityAlertTriggered , optional) – Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.

voice_chat_scheduled ( telegram.VoiceChatScheduled , optional) –

Service message: voice chat scheduled.

New in version 13.5.

Deprecated since version 13.12.

voice_chat_started ( telegram.VoiceChatStarted , optional) –

Service message: voice chat started.

New in version 13.4.

Deprecated since version 13.12.

voice_chat_ended ( telegram.VoiceChatEnded , optional) –

Service message: voice chat ended.

New in version 13.4.

Deprecated since version 13.12.

voice_chat_participants_invited ( telegram.VoiceChatParticipantsInvited optional) –

Service message: new participants invited to a voice chat.

New in version 13.4.

Deprecated since version 13.12.

video_chat_scheduled ( telegram.VideoChatScheduled , optional) –

Service message: video chat scheduled.

New in version 13.12.

video_chat_started ( telegram.VideaChatStarted , optional) –

Service message: video chat started.

New in version 13.12.

video_chat_ended ( telegram.VideaChatEnded , optional) –

Service message: video chat ended.

New in version 13.12.

video_chat_participants_invited ( telegram.VideoChatParticipantsInvited optional) –

Service message: new participants invited to a video chat.

New in version 13.12.

web_app_data ( telegram.WebAppData , optional) – Service message: data sent by a Web App. .. versionadded:: 13.12

reply_markup ( telegram.InlineKeyboardMarkup , optional) – Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.

bot ( telegram.Bot , optional) – The Bot to use for instance methods.

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 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.

Conversation the message belongs to.

Optional. Sender of the original message.

Optional. For messages forwarded from channels or from anonymous administrators, information about the original sender chat.

Optional. Identifier of the original message in the channel.

Optional. Date the original message was sent.

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.

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. The actual UTF-8 text of the message.

Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the text. See Message.parse_entity and parse_entities methods for how to use properly.

Optional. 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.

Optional. Information about the file.

Optional. Information about the file.

For backward compatibility, when this field is set, the document field will also be set.

Optional. Information about the game.

Optional. Available sizes of the photo.

Optional. Information about the sticker.

Optional. Information about the video.

Optional. Information about the file.

Optional. Information about the video message.

Optional. Information about new members to the chat. (the bot itself may be one of these members).

Optional. Caption for the document, photo or video, 0-1024 characters.

Optional. Information about the contact.

Optional. Information about the location.

Optional. Information about the venue.

Optional. Information about the user that left the group. (this member may be the bot itself).

Optional. A chat title was changed to this value.

Optional. A chat photo was changed to this value.

Optional. The chat photo was deleted.

Optional. The group has been created.

Optional. The supergroup has been created.

Optional. The channel has been created.

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.

Optional. Information about the invoice.

Optional. Information about the payment.

Optional. The domain name of the website on which the user has logged in.

Optional. Signature of the post author for messages forwarded from channels.

Optional. Sender’s name for messages forwarded from users who disallow adding a link to their account in forwarded messages.

Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator.

Optional. Telegram Passport data.

Optional. Message is a native poll, information about the poll.

Optional. Message is a dice.

Optional. Bot through which the message was sent.

Optional. Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.

Optional. Service message: voice chat scheduled.

New in version 13.5.

Deprecated since version 13.12: contains the same value as VideoChatScheduled for backwards compatibility.

Optional. Service message: voice chat started.

New in version 13.4.

Deprecated since version 13.12: contains the same value as VideoChatStarted for backwards compatibility.

Optional. Service message: voice chat ended.

New in version 13.4.

Deprecated since version 13.12: contains the same value as VideoChatEnded for backwards compatibility.

Optional. Service message: new participants invited to a voice chat.

New in version 13.4.

Deprecated since version 13.12: contains the same value as VideoChatParticipantsInvited for backwards compatibility.

Optional. Service message: video chat scheduled.

New in version 13.12.

Optional. Service message: video chat started.

New in version 13.12.

Optional. Service message: video chat ended.

New in version 13.12.

Optional. Service message: new participants invited to a video chat.

New in version 13.12.

Optional. Service message: data sent by a Web App.

New in version 13.12.

Optional. Inline keyboard attached to the message.

Optional. The Bot to use for instance methods.

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.

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.

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.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.

telegram.ParseMode.MARKDOWN is is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2() instead.

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.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.

telegram.ParseMode.MARKDOWN is is a legacy mode, retained by Telegram for backward compatibility. You should use caption_markdown_v2_urled() instead.

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.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.

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.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.

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Message caption with caption entities formatted as Markdown.

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 , timeout = None , api_kwargs = None , protect_content = None ) ¶

For the documentation of the arguments, please see telegram.Bot.copy_message() .

On success, returns the MessageId of the sent message.

delete ( timeout = None , api_kwargs = None ) ¶

For the documentation of the arguments, please see telegram.Bot.delete_message() .

On success, True is returned.

edit_caption ( caption = None , reply_markup = None , timeout = None , parse_mode = None , api_kwargs = None , caption_entities = None ) ¶

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.

edit_live_location ( latitude = None , longitude = None , location = None , reply_markup = None , timeout = None , api_kwargs = None , horizontal_accuracy = None , heading = None , proximity_alert_radius = None ) ¶

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.

edit_media ( media = None , reply_markup = None , timeout = None , api_kwargs = None ) ¶

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 sent by the bot, the edited Message is returned, otherwise True is returned.

edit_reply_markup ( reply_markup = None , timeout = None , api_kwargs = None ) ¶

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.

edit_text ( text , parse_mode = None , disable_web_page_preview = None , reply_markup = None , timeout = None , api_kwargs = None , entities = None ) ¶

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.

forward ( chat_id , disable_notification = None , timeout = None , api_kwargs = None , protect_content = None ) ¶

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.

get_game_high_scores ( user_id , timeout = None , api_kwargs = None ) ¶

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.

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 ) ¶

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.

RuntimeError – If the message has no caption.

parse_entities ( types = None ) ¶

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.

RuntimeError – If the message has no text.

pin ( disable_notification = None , timeout = None , api_kwargs = None ) ¶

For the documentation of the arguments, please see telegram.Bot.pin_chat_message() .

On success, True is returned.

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 , timeout = 20 , api_kwargs = None , allow_sending_without_reply = None , caption_entities = None , filename = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_audio ( audio , duration = None , performer = None , title = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , parse_mode = None , thumb = None , api_kwargs = None , allow_sending_without_reply = None , caption_entities = None , filename = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_chat_action ( action , timeout = None , api_kwargs = None ) ¶

For the documentation of the arguments, please see telegram.Bot.send_chat_action() .

New in version 13.2.

On success, True is returned.

reply_contact ( phone_number = None , first_name = None , last_name = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , contact = None , vcard = None , api_kwargs = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

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 , timeout = None , api_kwargs = None , quote = None , protect_content = None ) ¶

For the documentation of the arguments, please see telegram.Bot.copy_message() .

quote ( bool , optional) –

If set to True , the copy is sent as an actual reply to this message. If reply_to_message_id is passed in kwargs , 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.

reply_dice ( disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , emoji = None , api_kwargs = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_document ( document , filename = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , parse_mode = None , thumb = None , api_kwargs = None , disable_content_type_detection = None , allow_sending_without_reply = None , caption_entities = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_game ( game_short_name , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , api_kwargs = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , 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.

reply_html ( text , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , api_kwargs = None , allow_sending_without_reply = None , entities = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

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 , timeout = None , api_kwargs = None , allow_sending_without_reply = None , quote = None , max_tip_amount = None , suggested_tip_amounts = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_location ( latitude = None , longitude = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , location = None , live_period = None , api_kwargs = None , horizontal_accuracy = None , heading = None , proximity_alert_radius = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_markdown ( text , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , api_kwargs = None , allow_sending_without_reply = None , entities = None , quote = None , protect_content = None ) ¶

Sends a message with Markdown version 1 formatting.

For the documentation of the arguments, please see telegram.Bot.send_message() .

telegram.ParseMode.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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_markdown_v2 ( text , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , api_kwargs = None , allow_sending_without_reply = None , entities = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_media_group ( media , disable_notification = None , reply_to_message_id = None , timeout = 20 , api_kwargs = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

An array of the sent Messages.

reply_photo ( photo , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , parse_mode = None , api_kwargs = None , allow_sending_without_reply = None , caption_entities = None , filename = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_poll ( question , options , is_anonymous = True , type = ‘regular’ , allows_multiple_answers = False , correct_option_id = None , is_closed = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , explanation = None , explanation_parse_mode = None , open_period = None , close_date = None , api_kwargs = None , allow_sending_without_reply = None , explanation_entities = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_sticker ( sticker , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , api_kwargs = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_text ( text , parse_mode = None , disable_web_page_preview = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , api_kwargs = None , allow_sending_without_reply = None , entities = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_venue ( latitude = None , longitude = None , title = None , address = None , foursquare_id = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = None , venue = None , foursquare_type = None , api_kwargs = None , google_place_id = None , google_place_type = None , allow_sending_without_reply = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_video ( video , duration = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , width = None , height = None , parse_mode = None , supports_streaming = None , thumb = None , api_kwargs = None , allow_sending_without_reply = None , caption_entities = None , filename = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_video_note ( video_note , duration = None , length = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , thumb = None , api_kwargs = None , allow_sending_without_reply = None , filename = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

reply_voice ( voice , duration = None , caption = None , disable_notification = None , reply_to_message_id = None , reply_markup = None , timeout = 20 , parse_mode = None , api_kwargs = None , allow_sending_without_reply = None , caption_entities = None , filename = None , quote = None , protect_content = None ) ¶

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 in kwargs , this parameter will be ignored. Default: True in group chats and False in private chats.

On success, instance representing the message posted.

set_game_score ( user_id , score , force = None , disable_edit_message = None , timeout = None , api_kwargs = None ) ¶

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.

stop_live_location ( reply_markup = None , timeout = None , api_kwargs = None ) ¶

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.

stop_poll ( reply_markup = None , timeout = None , api_kwargs = None ) ¶

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.

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.

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.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.

telegram.ParseMode.MARKDOWN is is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2() instead.

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.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.

telegram.ParseMode.MARKDOWN is is a legacy mode, retained by Telegram for backward compatibility. You should use text_markdown_v2_urled() instead.

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.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.

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.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.

Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.

Похожие статьи