- Создание Telegram бота на PHP #3: примеры отправки сообщений с кнопками в Telegram
- Отправка простых сообщений
- Отправка ответа на сообщение
- Удаление сообщений из чата
- Отправка кнопок в чат
- Отправка клавиатуры в чат
- Bot API 5.6
- sendMessage
- Formatting options
- forwardMessage
- copyMessage
- sendPhoto
- sendAudio
- sendDocument
- sendVideo
- sendAnimation
- sendVoice
- sendVideoNote
- sendMediaGroup
- sendLocation
- sendVenue
- sendContact
- sendPoll
- sendDice
- sendSticker
- sendInvoice
- sendGame
Создание Telegram бота на PHP #3: примеры отправки сообщений с кнопками в Telegram
В новом уроке мы с вами рассмотрим отправку базовых запросов в Telegram. Я покажу вам как отправлять простые текстовые сообщения в Telegram, как отправлять кнопки и дополнительные клавиатуры.
Всю информацию по параметрам запросов мы будем брать из официальной документации Telegram.
Полный список всех записей курса находится на сайте или в публикациях на Хабр.
Все ответы от Telegram приходят в виде JSON строки. Для удобного отображения массива ответа в браузере, советую вам установить специальное расширение для браузера, которое называется JSON Viewer.
Отправка простых сообщений
Для отправки простых текстовых сообщений, нам необходимо воспользоваться методом sendMessage.
Ранее я показывал вам, как отправлять запросы с передачей параметров в URL, теперь для удобства я буду использовать запись параметров в массиве и с помощью функции http_build_query мы будем формировать строку с GET параметрами.
$token = "5340791844:AAEXXDduvInvQrlykV91USOQSevrPVU"; $getQuery = array( "chat_id" => 1424625511, "text" => "Новое сообщение из формы", "parse_mode" => "html" ); $ch = curl_init("https://api.telegram.org/bot". $token ."/sendMessage?" . http_build_query($getQuery)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $resultQuery = curl_exec($ch); curl_close($ch); echo $resultQuery;
Каждый запрос будет иметь переменную с записанным токеном, массив с параметрами запроса, код для создания запроса через Curl и вывод или запись полученной информации.
Отправка ответа на сообщение
Для отправки ответа на ранее созданное сообщения, вам необходимо в новом запросе sendMessage отправить дополнительный параметр reply_to_message_id, передав в него id сообщения, которое вы хотите прикрепить.
Полный запрос будет выглядеть так…
$token = "5340791844:AAEXXDduvInvQrlykV91USOQSevrPVU"; $getQuery = array( "chat_id" => 1424625511, "text" => "Новое сообщение из формы", "parse_mode" => "html", "reply_to_message_id" => 7 ); $ch = curl_init("https://api.telegram.org/bot". $token ."/sendMessage?" . http_build_query($getQuery)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $resultQuery = curl_exec($ch); curl_close($ch); echo $resultQuery;
Удаление сообщений из чата
Для удаления сообщений, вам нужно воспользоваться методом deleteMessage и знать id сообщения которое вы хотите удалить.
Пример кода для удаления сообщений выглядит так:
$token = "5340791844:AAEXXDduvInvQrlykV91USOQSevrPVU"; $getQuery = array( "chat_id" => 1424625511, "message_id" => 32456, ); $ch = curl_init("https://api.telegram.org/bot". $token ."/deleteMessage?" . http_build_query($getQuery)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $resultQuery = curl_exec($ch); curl_close($ch); echo $resultQuery;
Отправка кнопок в чат
На данный момент, существует 3 вида кнопок в чате, в Telegram.
- Кнопки которые прикреплены к сообщению (inline_keyboard).
- Кнопки которые располагаются под строкой ввода сообщения, они называются клавиатурой (keyboard).
- Кнопки меню команд, которые чаще всего располагаются слева от строки ввода сообщения.
Для начала давайте рассмотрим как нам добавить кнопки которые будут прикреплены к сообщению.
Для отправки таких кнопок, нам нужно воспользоваться методом sendMessage и передать ему в качестве параметра reply_markup — массив со свойствами клавиатуры.
Данный массив выглядит следующим образом…
. 'reply_markup' => json_encode(array( 'inline_keyboard' => array( array( array( 'text' => 'Button 1', 'callback_data' => 'test_2', ), array( 'text' => 'Button 2', 'callback_data' => 'test_2', ), ) ), )), .
Первое важное правило — reply_markup принимает json, поэтому для создания кнопок, вам нужно конвертировать массив в JSON с помощью функции json_encode.
В массиве с параметрами кнопок, есть особые параметры. Эти параметры, так же, указаны в документации.
- С помощью параметра text вы можете передать текст кнопки.
- параметр url указывает ссылку, если вам нужно сделать кнопку для перехода на внешний ресурс.
- параметр callback_data указывает строку которая будет возвращена после нажатия на кнопку. Данную строку используют как команду.
Массив для кнопок имеет сложную многоуровневую систему. Первый уровень отвечает за общую запись параметров, второй уровень отвечает за ряд кнопок, третий уровень отвечает за параметры кнопки.
Таким образом, для создания 2 кнопок в одном ряду, мы будем использовать следующий код
. 'reply_markup' => json_encode(array( 'inline_keyboard' => array( array( array( 'text' => 'Button 1', 'callback_data' => 'test_2', ), array( 'text' => 'Button 2', 'callback_data' => 'test_2', ), ) ), )), .
Для создания 2 рядов по 2 кнопки используйте код .
. 'reply_markup' => json_encode(array( 'inline_keyboard' => array( array( array( 'text' => 'Button 1', 'callback_data' => 'test_2', ), array( 'text' => 'Button 2', 'callback_data' => 'test_2', ), ), array( array( 'text' => 'Button 3', 'callback_data' => 'test_3', ), array( 'text' => 'Button 4', 'callback_data' => 'test_4', ), ) ), )), .
И для создания одной кнопки в первом ряду и 2 — во втором, используйте следующий код.
. 'reply_markup' => json_encode(array( 'inline_keyboard' => array( array( array( 'text' => 'Button 2', 'callback_data' => 'test_2', ), ), array( array( 'text' => 'Button 3', 'callback_data' => 'test_3', ), array( 'text' => 'Button 4', 'callback_data' => 'test_4', ), ) ), )), .
Надеюсь, я смог объяснить данную тему доступно, если у вас будут вопросы, пишите их в нашем Telegram канале.
Отправка клавиатуры в чат
Аналогичные параметры имеет и массив для отправки клавиатуры в чат. Для создания клавиатуры пропишем следующий код.
. 'reply_markup' => json_encode(array( 'keyboard' => array( array( array( 'text' => 'Тестовая кнопка 1', 'url' => 'YOUR BUTTON URL', ), array( 'text' => 'Тестовая кнопка 2', 'url' => 'YOUR BUTTON URL', ), ) ), 'one_time_keyboard' => TRUE, 'resize_keyboard' => TRUE, )), .
Структура массивом для кнопок та же, но только есть отличие в названиях и количестве параметров.
Ключ inline_keyboard заменяется на keyboard.
А так же для клавиатуры добавляются 2 дополнительных параметра:
- one_time_keyboard — скрыть клавиатуру, как только она была использована. Клавиатура по-прежнему будет доступна, но клиенты будут автоматически отображать обычную, буквенную клавиатуру в чате — пользователь может нажать специальную кнопку в поле ввода, чтобы снова увидеть пользовательскую клавиатуру. Значение по умолчанию равно false.
- resize_keyboard — изменяет размер клавиатуры по вертикали для оптимальной подгонки (например, уменьшить клавиатуру, если есть только два ряда кнопок). По умолчанию установлено значение false, и в этом случае пользовательская клавиатура всегда имеет ту же высоту, что и стандартная клавиатура приложения.
- В новом уроке мы с вами разобрали самый популярный метод для работы с Телеграм ботами — sendMessage. Данный метод позволяет отправлять текстовые сообщения с привязанными кнопками и клавиатурами.
- Научились удалять сообщения
- Разобрали какие бывают типы кнопок и научились создавать массивы для гибкой структуры вывода дополнительных клавиатур и кнопок.
В следующем уроке, я вам покажу как отправлять файлы и изображения в чат.
Bot API 5.6
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.
Field | Type | Description |
---|---|---|
type | String | Type of the entity. Currently, can be “mention” ( @username ), “hashtag” ( #hashtag ), “cashtag” ( $USD ), “bot_command” ( /start@jobs_bot ), “url” ( https://telegram.org ), “email” ( do-not-reply@telegram.org ), “phone_number” ( +1-212-555-0123 ), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames) |
sendMessage
Use this method to send text messages. On success, the sent Message is returned.
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of sent messages from forwarding and saving |
Formatting options
The Bot API supports basic formatting for messages. You can use bold, italic, underlined, strikethrough, and spoiler text, as well as inline links and pre-formatted code in your bots’ messages. Telegram clients will render them accordingly. You can use either markdown-style or HTML-style formatting.
Message entities can be nested, providing following restrictions are met:
— If two entities have common characters then one of them is fully contained inside another.
— bold, italic, underline, strikethrough, and spoiler entities can contain and can be part of any other entities, except pre and code.
— All other entities can’t contain each other.
MarkdownV2 style
To use this mode, pass MarkdownV2 in the parse_mode field. Use the following syntax in your message:
*bold \*text* _italic \*text_ __underline__ ~strikethrough~ ||spoiler|| *bold _italic bold ~italic bold strikethrough ||italic bold strikethrough spoiler||~ __underline italic bold___ bold*
HTML style
To use this mode, pass HTML in the parse_mode field. The following tags are currently supported:
bold, bold italic, italic underline, underline strikethrough, strikethrough, strikethrough italic bold italic bold strikethrough underline italic bold bold
forwardMessage
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the forwarded message from forwarding and saving |
copyMessage
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendPhoto
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendAudio
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendDocument
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendVideo
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendAnimation
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendVoice
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendVideoNote
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendMediaGroup
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent messages from forwarding and saving |
sendLocation
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendVenue
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendContact
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendPoll
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendDice
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding |
sendSticker
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendInvoice
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
sendGame
Parameter | Type | Required | Description |
---|---|---|---|
protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |