Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot

БОТ В ТЕЛЕГРАМ

Наша интеграция с Telegram позволяет вам добавить Telegram bot в ваш аккаунт WhatsHelp. Обратите внимание, что вы должны быть авторизованы в Телеграмме для создания нового бота.

Создание нового бота

Создание нового бота происходит при помощи официального бота Телеграм @BotFather.

Начните диалог с этим ботом и при помощи команды ‘/newbot’ создайте собственного.

После указания всех необходимых параметров, вы получите Токен (секретный ключ) для доступа к боту через API. Данный ключ понадобится для подключения бота к WhatsHelp.

Подключение Telegram

Новый канал должен отобразиться в списке подключенных. Если этого не произошло, напишите нам в чат поддержки.

Установка приветственного сообщения

КАК ПОЛУЧИТЬ ТОКЕН?

BotFather

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Creating a new bot

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

Generating an authorization token

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Botfather commands

The remaining commands are pretty self-explanatory:

Please note, that it may take a few minutes for changes to take effect.

Пишем Telegram-бота на Rust, который будет запускать код на… Rust?

Доброй ночи! Сегодня хотелось бы кратко рассказать о том, как написать Telegram-бота на Rust, который будет запускать код на Rust. У статьи нет цели произвести полное погружение в API telegram_bot, Serde, Telegram или в нюансы разработки на Rust. Она скорее носит ознакомительный характер. Числа Пеано с помощью системы типов складывать не будем.
Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Создание бота в Telegram

Для начала создадим бота и получим HTTP API токен.

Заходим к этому парню и пишем следующее:

Alright, a new bot. How are we going to call it? Please choose a name for your bot.

Done! Congratulations on your new bot. You will find it at t.me/rustlanguage_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this. Use this token to access the HTTP. API: %TOKEN% For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Отлично. Бот создан. %TOKEN% — это, собственно, и есть токен.

Rust Playground

Теперь немного о том, как и где запускать код, который пользователь будет передавать боту в виде сообщения.

Перейдя по ссылке, введём простую hello-world программу:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Вроде бы всё прозрачно и понятно. Попробуем воспроизвести из консоли:

Отлично, поехали дальше.

Пишем бота

Добавим следующие зависимости в Cargo.toml :

Кратко опишу, зачем они нужны:

Serde предназначена для сериализации/десериализации данных в различных форматах. В данном случае нам необходима работа с JSON (serde_json) и щепотка кодогенерации (serde_derive);

Hyper для работы с сетью будем использовать HTTP-клиент, который она предоставляет для взаимодействия с Rust Playground. Так как взаимодействие производится по протоколу HTTPS, ещё необходима батарейка в виде hyper-rustls ;

В src/main.rs подключим все необходимые библиотеки и модули:

Примечание: #[macro_use] используется для включения в область видимости текущей программы макросов из библиотеки, к которой был применён данный атрибут.

В данной строке импортируем модули из корня библиотеки для определения типа сообщения, метода «прослушки», структуры представляющей API Telegram:

Опишем с помощью enum возможные виды ответов от сервера, а их в данном случае 2, когда программа была скомпилирована успешно, и когда произошла ошибка компиляции:

Определим структуру для нашего запроса в Rust Playground:

В главной функции программы main создадим инстанс Telegram API и заставим его печатать всё, что пришло боту в сообщении:

Чтобы проверить работоспособность данного кода, запустите программу, не забыв передать в качестве переменной окружения реальный токен, полученный ранее:

Немного разберём, что мы написали выше.

Под конец создаём цикл обработки сообщений при помощи функции listen и сопоставления по шаблону типа сообщения:

Условимся, что код мы будем передавать только в текстовом виде. Файлы и прочее исключим. Для этого, как вы могли заметить, все остальные варианты перечисления MessageType просто игнорируются.

Мы обрабатываем запрос только лишь в случае, если сообщение начинается с определённой команды ( /rust ):

А так же вытаскиваем код программы, которую необходимо скомпилировать:

Обрабатываем пришедший ответ:

Отправка результатов компиляции в чат:

В конце мы проверяем длину сообщения, чтобы исключить результаты компиляции с большим количеством вывода, и обрезаем это дело. После производим отправку сообщения, указывая идентификатор чата, из которого пришел запрос на компиляцию, и передаём итоговый результат компиляции. Так же передаём id сообщения, на которое необходимо ответить. Остальные передаваемые параметры необязательны и отвечают за вывод превью, вид ответа и тому подобное.

Проверяем работоспособность

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Вывод в консоль:

Заключение

Любая конструктивная критика приветствуется.
Репозиторий с полным кодом данного бота располагается здесь.

Sorry the username must end in bot e g tetris bot or tetrisbot

This project its to create an echo bot for Telegram

##The BotFather is the manager of the BotSystem

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Create a new bot Use the /newbot command to create a new bot. The BotFather will ask you for a «name» and «username», then generate an authorization token for your new bot.

it’s a little tricky that you need two names. The important name it´s username. It’s the way the people will call your bot.

The name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

Generate an authorization token for your bot If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Bot generation example:

BotFather Alright, a new bot. How are we going to call it? Please choose a name for your bot.

BotFather Sorry, this username is already taken. Think of something different.

BotFather Done! Congratulations on your new bot. You will find it at telegram.me/zyx_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands.

Use this token to access the HTTP API: 116169643:AAGHoOYKNAjvCH1YtTaKGzUYn1tXQLA6rx8

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

BotFather Choose a bot to generate a new token.

BotFather You can use this token to access HTTP API: 9999999999:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Comunicating with your bot

You should call the telegram yourBot API to get info about the messages it receives:

All queries to the Telegram Bot API must be served over HTTPS and need to be presented in this form: https://api.telegram.org/bot/METHOD_NAME. Like this for example:

*Important: bot its bot, not the name of your bot.

With this call, remembert to put your own bot access key

We support GET and POST HTTP methods. Use either URL query string or application/x-www-form-urlencoded or multipart/form-data for passing parameters in Bot API requests.

The response contains a JSON object, which always has a Boolean field ‘ok’ and may have an optional String field ‘description’ with a human-readable description of the result. If ‘ok’ equals true, the request was successful and the result of the query can be found in the ‘result’ field. In case of an unsuccessful request, ‘ok’ equals false and the error is explained in the ‘description’. An Integer ‘error_code’ field is also returned, but its contents are subject to change in the future.

In this case you will get something like this.

All methods in the Bot API are case-insensitive. All queries must be made using UTF-8.

Getting chat input

There are two mutually exclusive ways to get chat input. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

GetUpdates: it’s an active option. You need to call Telegram to get info SetWebhook: it’s a pasive option. telegram will make a post call ehenever he receives a message.

Update This object represents an incoming update.

|update_id|Integer|The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.| |message|Message|Optional. New incoming message of any kind — text, photo, sticker, etc.|

With getUpdates you can setup a pooling mechanism to pool data from the bot and process it, we will use this method in our examples (only to obtain a chat_id).

getUpdates Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.

|offset|Integer|Optional|Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.| |limit|Integer|Optional|Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100| |timeout|Integer|Optional|Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling|

If there are not mesaages, you receive this

If there are mesaages, you receive something like this

In thes case, two messages, the beggining of the conversation and the message «hola».

With setWebhook we can setup a «callback» url where the bot will push everything received into a conversation.

Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts.

If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. www.example.com/. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.

|url|String|Optional|HTTPS url to send updates to. Use an empty string to remove webhook integration| Notes

To send a message:

The remaining commands are pretty self-explanatory:

/setname – change your bot’s name. /setdescription — changes the bot’s description, a short text of up to 512 characters, describing your bot. Users will see this text at the beginning of the conversation with the bot, titled ‘What can this bot do?’. /setabouttext — changes the bot’s about info, an even shorter text of up to 120 characters. Users will see this text on the bot’s profile page. When they share your bot with someone, this text will be sent together with the link. /setuserpic — changes the bot‘s profile pictures. It’s always nice to put a face to a name. /setcommands — changes the list of commands supported by your bot. Each command has a name (must start with a slash ‘/’, alphanumeric plus underscores, no more than 32 characters, case-insensitive), parameters, and a text description. Users will see the list of commands whenever they type ‘/’ in a conversation with your bot. /setjoingroups — determines whether your bot can be added to groups or not. Any bot must be able to process private messages, but if your bot was not designed to work in groups, you can disable this. /setprivacy — determines which messages your bot will receive when added to a group. With privacy mode disabled, the bot will receive all messages. We recommend leaving privacy mode enabled. /deletebot — deletes your bot and frees its username. Please note, that it may take a few minutes for changes to take effect.

How to create a bot?

There’s a… bot for that. Just talk add BotFather to your Telegram and continue as follows. Once you’ve created a bot and received your authorization token, head down to the Installation page to see what you can do to get it up and running

Create a new bot: use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot will be displayed in contact details and elsewhere. The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’. The Bot Token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

Generate an authorization token for your bot If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Edit settings: the remaining commands are pretty self-explanatory:

Sorry the username must end in bot e g tetris bot or tetrisbot

Copy raw contents

Copy raw contents

Create a Telegram Bot with Botfather

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones. Commands known by Botfather

Creating a new Bot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

@botfather replies with Alright, a new bot. How are we going to call it? Please choose a name for your bot.

Type whatever name you want for your bot.

@botfather replies with Good. Now let’s choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.

@botfather replies with:

Done! Congratulations on your new bot. You will find it at telegram.me/telesample_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands.

Use this token to access the HTTP API: 123456789:AAG90e14-0f8-40183D-18491dDE

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Note down the ‘token’ mentioned above.

Type /setprivacy to @botfather.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

@botfather replies with Choose a bot to change group messages settings.

Type @telesample_bot (change to the username you set at step 5 above, but start it with @ )

@botfather replies with

Type Disable to let your bot receive all messages sent to a group. This step is up to you actually.

@botfather replies with Success! The new status is: DISABLED. /help

Bots: An introduction for developers

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s Bot API.

Telegram keeps evolving and adding new features, so this document may contain outdated information.
We expect to finish updating the FAQ, Bot Manuals, and other documents by the end of Summer 2022.

To name just a few things, you could use bots to:

Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.

Accept payments from Telegram users. A bot can offer paid services or work as a virtual storefront. Read more »
Demo Shop Bot, Demo Store

Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services.
Markdown bot, Sticker bot, Vote bot, Like bot

Build single- and multiplayer games. A bot can offer rich HTML5 experiences, from simple arcades and puzzles to 3D-shooters and real-time strategy games.
GameBot, Gamee

Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.

Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

Messages, commands and requests sent by users are passed to the software running on your servers. Our intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. We call that interface our Bot API.

A detailed description of the Bot API is available on this page »

There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authentication token, head down to the Bot API manual to see what you can teach your bot to do.

You may also like to check out some code examples here »

Telegram bots are unique in many ways — we offer two kinds of keyboards, additional interfaces for default commands and deep linking as well as text formatting, integrated payments and more.

Users can interact with your bot via inline queries straight from the text input field in any chat. All they need to do is start a message with your bot’s username and then type a query.

Having received the query, your bot can return some results. As soon as the user taps one of them, it is sent to the user’s currently opened chat. This way, people can request content from your bot in any of their chats, groups or channels.

Check out this blog to see a sample inline bot in action. You can also try the @sticker and @music bots to see for yourself.

We’ve also implemented an easy way for your bot to switch between inline and PM modes.

You can use bots to accept payments from Telegram users around the world.

Bots can offer their users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. The platform allows your bot to keep track of high scores for every game played in every chat. Whenever there’s a new leader in the game, other playing members in the chat are notified that they need to step it up.

Since the underlying technology is HTML5, the games can be anything from simple arcades and puzzles to multiplayer 3D-shooters and real-time strategy games. Our team has created a couple of simple demos for you to try out:

You can also check out the @gamee bot that has more than 20 games.

Traditional chat bots can of course be taught to understand human language. But sometimes you want some more formal input from the user — and this is where custom keyboards can become extremely useful.

Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options (see ReplyKeyboardMarkup). Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

We currently support text and emoji for your buttons. Here are some custom keyboard examples:

For more technical information on custom keyboards, please consult the Bot API manual (see sendMessage).

There are times when you’d prefer to do things without sending any messages to the chat. For example, when your user is changing settings or flipping through search results. In such cases you can use Inline Keyboards that are integrated directly into the messages they belong to.

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn’t result in messages sent to the chat. Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

When callback buttons are used, your bot can update its existing messages (or just their keyboards) so that the chat remains tidy. Check out these sample bots to see inline keyboards in action: @music, @vote, @like.

Commands present a more flexible way to communicate with your bot. The following syntax may be used:

A command must always start with the ‘/’ symbol and may not be longer than 32 characters. Commands can use latin letters, numbers and underscores. Here are a few examples:

Messages that start with a slash are always passed to the bot (along with replies to its messages and messages that @mention the bot by username). Telegram apps will:

If multiple bots are in a group, it is possible to add bot usernames to commands in order to avoid confusion:

This is done automatically when commands are selected via the list of suggestions. Please remember that your bot needs to be able to process commands that are followed by its username.

In order to make it easier for users to navigate the bot multiverse, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

Users will see a Start button when they first open a conversation with your bot. Help and Settings links will be available in the menu on the bot’s profile page.

You can use bold, italic or fixed-width text, as well as inline links in your bots’ messages. Telegram clients will render them accordingly.

Bots are frequently added to groups in order to augment communication between human users, e.g. by providing news, notifications from external services or additional search functionality. This is especially true for work-related groups. Now, when you share a group with a bot, you tend to ask yourself “How can I be sure that the little rascal isn’t selling my chat history to my competitors?” The answer is — privacy mode.

A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:

On one hand, this helps some of us sleep better at night (in our tinfoil nightcaps), on the other — it allows the bot developer to save a lot of resources, since they won’t need to process tens of thousands irrelevant messages each day.

Privacy mode is enabled by default for all bots, except bots that were added to the group as admins (bot admins always receive all messages). It can be disabled, so that the bot receives all messages like an ordinary user (the bot will need to be re-added to the group for this change to take effect). We only recommend doing this in cases where it is absolutely necessary for your bot to work — users can always see a bot’s current privacy setting in the group members list. In most cases, using the force reply option for the bot’s messages should be more than enough.

Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an authentication token to connect the user’s Telegram account to their account on some external service.

Following a link with the start parameter will open a one-on-one conversation with the bot, showing a START button in the place of the input field. If the startgroup parameter is used, the user is prompted to select a group to add the bot to. As soon as a user confirms the action (presses the START button in their app or selects a group to add the bot to), your bot will receive a message from that user in this format:

PAYLOAD stands for the value of the start or startgroup parameter that was passed in the link.

Some bots need extra data from the user to work properly. For example, knowing the user’s location helps provide more relevant geo-specific results. The user’s phone number can be very useful for integrations with other services, like banks, etc.

Bots can ask a user for their location and phone number using special buttons. Note that both phone number and location request buttons will only work in private chats.

When these buttons are pressed, Telegram clients will display a confirmation alert that tells the user what’s about to happen.

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authentication token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and t.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

The remaining commands are pretty self-explanatory:

Edit bots

Edit settings

Manage games

Please note, that it may take a few minutes for changes to take effect.

Millions choose Telegram for its speed. To stay competitive in this environment, your bot also needs to be responsive. In order to help developers keep their bots in shape, Botfather will send status alerts if it sees something is wrong.

We will be checking the number of replies and the request/response conversion rate for popular bots (

300 requests per minute: but don’t write this down as the value may change in the future). If we get abnormally low readings, you will receive a notification from Botfather.

By default, you will only get one alert per bot per hour. Each alert has the following buttons:

We will currently notify you about the following issues:

1.

Your bot is sending much fewer messages than it did in the previous weeks. This is useful for newsletter-style bots that send out messages without prompts from the users. The larger the value, the more significant the difference.

2.

Your bot is not replying to all messages that are being sent to it (the request/response conversion rate for your bot was too low for at least two of the last three 5-minute periods). To provide a good user experience, please respond to all messages that are sent to your bot. Respond to message updates by calling send… methods (e.g. sendMessage).

3.

Your bot is not replying to all inline queries that are being sent to it, calculated in the same way as above. Respond to inline_query updates by calling answerInlineQuery.

4.

Your bot is not replying to all callback queries that are being sent to it (with or without games), calculated in the same way as above. Respond to callback_query updates by calling answerCallbackQuery.

Please note that the status alerts feature is still being tested and will be improved in the future.

That’s it for the introduction. You are now definitely ready to proceed to the BOT API MANUAL.

If you’ve got any questions, please check out our Bot FAQ »

Telegram бот на PHP пошаговая инструкция

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Предисловие

У меня появилась необходимость создать telegram бота на php, так как это один из основных языков, который я использую в своих разработках. Безусловно, для этого есть большие библиотеки, например на github, среди них есть достаточно хорошие, но часть из них либо плохо, либо вообще не документированы. Также сложности возникают, когда нужно немного поменять или добавить функционал, необходимо изучить десятки файлов, устранять возникающие ошибки, когда нужно просто добавить кнопку. Для простых действий можно вполне обойтись библиотекой Guzzle, для удобства построения запросов, вместо стандартного CURL, так как telegram API просто обрабатывает запросы в формате JSON и возвращает результат, как и многие другие API.

Скачать исходники, описанные ниже, можно в конце статьи.

Все запросы к telegram API обрабатываются следующим образом, это всего лишь запрос на адрес: https://api.telegram.org/bot /METHOD_NAME. Где после bot подставляется полученный от @BotFather токен, затем /название_метода. Ссылка на оф. сайт, с описанием всех методов telegram API https://core.telegram.org/bots/api#available-methods

Вариант описанный в данной статье подойдет для тех, кто знает как устанавливать пакеты при помощи composer, имеет хотя бы небольшой опыт использования php. А также для тех, кто желает разобраться с самого начала, как происходит процесс создания telegram ботов, от получения токена, до обработки и отправки сообщений.

Шаг 1 — Подготовка среды

Для работы нам потребуется:

Шаг 2 — Получение токена

Токен бота — это как его идентификатор в системе, он необходим для формирования запросов к api. Процесс его получения достаточно простой, в строке поиска telegram вводим @BotFather и находим аккаунт.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Переходим в чат с @BotFather и пишем команду /newbot

В ответ получаем:

Alright, a new bot. How are we going to call it? Please choose a name for your bot. — Что означает: Хорошо, новый бот. Как мы собираемся это назвать? Пожалуйста, выберите имя для вашего бота.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Отправляем следующим сообщением название бота, в примере: testingbot, получаем ответ: Good. Now let’s choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot. — Что означает: Хорошо. Теперь давайте выберем имя пользователя для вашего бота. Оно должно заканчиваться на `бот`. Вот так, например: Tetris Bot или tetris_bot.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Следующим сообщением я отправил testing99_bot, но получил ответ, что такое имя пользователя занято : Sorry, this username is already taken. Please try something different. Такое сообщение свидетельствует о том, что такое имя пользователя занято. Значит необходимо выбрать другое, в итоге вот такое было свободно botfortest99_bot. И мы получаем такое сообщение, содержащее токен токен.

Done! Congratulations on your new bot. You will find it at t.me/botfortest99_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:

Keep your token secure and store it safely, it can be used by anyone to control your bot.

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

На момент публикации статьи этот бот и токен будет удален, поэтому я не переживаю за его размещение здесь.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Шаг 3 — Регистрация хука

Регистрация вебхука — это явное указание, по какому https адресу должен вызываться наш php-файл обработчик. Для начала его нужно создать, например index.php или любой другой.

Для установки вебхука(скрипта), который будет обрабатывать команды и отвечать на сообщения, необходимо открыть в браузере такую строку:

https://api.telegram.org/bot5236473451:AAEAjVbZY0kbxOLwBFYTV4j1YXRs77HmJEI/setWebhook?url=https://ae-nekrasov.ru/devbot/index.php

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

В результате открытия этой строки в браузере и нажатии кнопки enter, мы получаем такое сообщение : <«ok»:true,»result»:true,»description»:»Webhook was set»>— это означает, что вебхук установлен и теперь отправленные боту сообщения будут приходить на этот адрес.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Шаг 4 — Прием и обработка сообщений от пользователей

Чтобы принимать и обрабатывать сообщения нужно понять модель взаимодействия с telegram API и куда и в каком формате нам будут приходить сообщения.

Отправляем нашему боту несколько сообщений и посмотрим, что будет в файле apidata.txt.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Содержимое файла apidata.txt

Просмотрев содержимое файла, мы видим, что достаточно много данных нам отправляет telegram API. Исходя из этого, можно перейти к построению обработчика. Дальнейшие действия предполагают, что подготовка среды(см. Шаг1) Вы прошли и Вам будет понятно, что происходит дальше.

В директорию, где находится файл index.php размещаем файл composer.json, со следующим содержимым :

И выполняем в терминале команду composer require, в результате мы увидим что-то вроде:

Это означает, что необходимые пакеты с зависимостями установились, появилась папка vendor. Для своих классов создаем директорию src, в корне проекта. Там разместим первый класс Api и файл соответственно называется Api.php, со следующим содержимым:

В коде выше, был создан класс Api и внутри него метод sendMessage, на основе данных описанных в официальной документации telegram API по отправке сообщений https://core.telegram.org/bots/api#sendmessage

Теперь модифицируем файл index.php, чтобы он был такого содержимого:

Если Вы все сделали по инструкции описанной выше, то теперь на любые сообщения бот будет отвечать «Привет». Небольшая gif-ка с результатом работы.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Работает, естественно отвечать на все сообщения «Привет» — это не окончательная функциональность. Теперь нужно как-то обработать входящие сообщения и исходя из содержимого уже отправлять ответ.

Немного модифицируем класс Api, добавим новый метод, который будет возвращать отправленное сообщение боту, добавляемый код:

Также модифицируем файл index.php, новый код:

Теперь бот просто будет повторюшкой, он будет отправлять нам то, что мы ему, ниже gif-ка с примером работы:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Модифицируем index.php, добавим if else ветвления, чтобы отвечать уже в зависимости от того, что нам отправит пользователь, новый код:

Теперь бот отвечает специальным ответом, в зависимости от вопроса, ниже gif-ка с примером работы:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

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

Шаг 5 — Обработка команд

Команды можно обрабатывать как и текст сообщений, но чтобы при вводе / выпадал список команд с описанием, нужно через @BotFather их настроить, для этого:

Команды нужно вводить в одном сообщении, иначе новые затрат старые, а также важно понимать, что это не обработка команд, а всего лишь визуальное оформление.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Шаг 6 — Добавление кнопок в чат и обработка нажатий

В рамках данной статьи рассмотрим два варианта кнопок:

Вариант 1. Кнопки в зоне основной клавиатуры

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Вариант 2. Кнопки под сообщением

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Эти два варианта по разному обрабатываются. Первый вариант обрабатывается как обычное сообщение, но имеет несколько вариантов отображения, точнее что будет после нажатия, удаление совсем или же кнопки всегда можно будет вызвать, пока бот не отправит другую клавиатуру.

Второй вариант обрабатывается немного иначе, я для этого использую даже другой метод отправки сообщения, после нажатия на такую клавиатуру, это обусловлено тем, что при нажатии кнопок в режиме callback query, к нам придет немного другой формат массива с данными, точнее данные([from],[message],[chat]) будут вложены в массив [‘callback_query’]

Для экспериментов с кнопками, необходимо добавить в файл Api.php несколько методов, фрагмент добавляемого кода:

В комментариях к методам описано, для чего каждый из них необходим. Первый метод необходим, чтобы в файле index.php попасть в ветвление, где происходит обработка нажатия кнопок под сообщением. Второй метод немного отличается от стандартного, где происходит отправка сообщений, он необходим для отправки сообщения, когда нажаты кнопки выведенные под сообщением. Третий метод выводит кнопки под сообщением. Четвертый выводит кнопки в зоне стандартной клавиатуры и смайлов.

Также необходимо обновить файл index.php, его новый код:

Если Вы все делали по инструкции, то должен быть такой результат, как на gif-ке ниже:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Естественно, в этой статье описаны самые азы, в реальности на кнопки можно подвесить загрузку какой-либо информации из внешних источников, например crm-систем, отправку данных куда-то и многое другое.

Статья в ближайшее время будет дописана, в планах описать процесс взаимодействия с изображениями и файлами, пишите свои вопросы в комментариях, это поможет дополнить статью и выявить возможные баги.

Блог Lazarus-программиста

Блог о программировании

Telegram Bot API. Часть 1

Добрый день дорогие читатели. Сегодня я начал экспериментировать с созданием бота для Telegram на Lazarus. Ниже я буду описывать процесс создания бота от А до Я.

Прежде чем начать создавать бота, нужно почитать немного о таких вещах как формат данных JSON, как его парсить, ну и по хорошему документацию Telegram API Bot

Лично Я для облегчения своей работы использовал открытую библиотеку Superobject, которая легко позволяет парсить JSON

Нам интересны следующие файлы:

Данную библиотеку бросаем в папку с проектом и подключаем в Uses.

2. Для работы с https нам так же потребуется 2 библиотеки: libeay32.dll и ssleay32.dll — Скачать, их тоже бросаем в папку с проектом.

3. А для отправки запросов http нам понадобится библиотека Indy, как ее установить читайте здесь: http://www.freepascal.ru/article/lazarus/20100812185950/

Теперь для начала нам нужно создать бота в чате с @BotFather и получить уникальный Token, выглядит он примерно так: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

Через любое доступное приложение Telegram, пишет в личку @BotFather следующие команды:

/newbot

Вводим название бота

Если получаем в ответ «Good. Now let’s choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.» значит имя свободно, теперь требуется создать имя бота по которому мы сможем к нему обращаться @имябота. Обязательно нужно чтобы имя вашего бота заканчивалось на bot или _bot

Подобрав имя вы должны получить следующий ответ:

«Done! Congratulations on your new bot. You will find it at telegram.me/имябота. You can now add a description, about section and profile picture for your bot, see /help for a list of commands.

Use this token to access the HTTP API:
123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

For a description of the Bot API, see this page: https://core.telegram.org/bots/api«

Поздравляю! Пол дела сделано. И последние что мы сделаем в первой статье, это проверим работу нашего токена. Для начала просто в браузере введите: https://api.telegram.org/botВашТокен/GetMe (Например: https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/GetMe)

В ответ мы должны получить:

Если при запуске программы мы получили ответ об успешном старте бота, значит все получилось.

Для начала этого достаточно. В следующий раз расскажу как отсылать, и принимать сообщения с помощью long polling. Спасибо за внимание.

Bots: An introduction for developers

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s Bot API.

Telegram keeps evolving and adding new features, so this document may contain outdated information.
We expect to finish updating the FAQ, Bot Manuals, and other documents by the end of Summer 2022.

To name just a few things, you could use bots to:

Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.

Accept payments from Telegram users. A bot can offer paid services or work as a virtual storefront. Read more »
Demo Shop Bot, Demo Store

Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services.
Markdown bot, Sticker bot, Vote bot, Like bot

Build single- and multiplayer games. A bot can offer rich HTML5 experiences, from simple arcades and puzzles to 3D-shooters and real-time strategy games.
GameBot, Gamee

Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.

Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

Messages, commands and requests sent by users are passed to the software running on your servers. Our intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. We call that interface our Bot API.

A detailed description of the Bot API is available on this page »

There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authentication token, head down to the Bot API manual to see what you can teach your bot to do.

You may also like to check out some code examples here »

Telegram bots are unique in many ways — we offer two kinds of keyboards, additional interfaces for default commands and deep linking as well as text formatting, integrated payments and more.

Users can interact with your bot via inline queries straight from the text input field in any chat. All they need to do is start a message with your bot’s username and then type a query.

Having received the query, your bot can return some results. As soon as the user taps one of them, it is sent to the user’s currently opened chat. This way, people can request content from your bot in any of their chats, groups or channels.

Check out this blog to see a sample inline bot in action. You can also try the @sticker and @music bots to see for yourself.

We’ve also implemented an easy way for your bot to switch between inline and PM modes.

You can use bots to accept payments from Telegram users around the world.

Bots can offer their users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. The platform allows your bot to keep track of high scores for every game played in every chat. Whenever there’s a new leader in the game, other playing members in the chat are notified that they need to step it up.

Since the underlying technology is HTML5, the games can be anything from simple arcades and puzzles to multiplayer 3D-shooters and real-time strategy games. Our team has created a couple of simple demos for you to try out:

You can also check out the @gamee bot that has more than 20 games.

Traditional chat bots can of course be taught to understand human language. But sometimes you want some more formal input from the user — and this is where custom keyboards can become extremely useful.

Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options (see ReplyKeyboardMarkup). Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

We currently support text and emoji for your buttons. Here are some custom keyboard examples:

For more technical information on custom keyboards, please consult the Bot API manual (see sendMessage).

There are times when you’d prefer to do things without sending any messages to the chat. For example, when your user is changing settings or flipping through search results. In such cases you can use Inline Keyboards that are integrated directly into the messages they belong to.

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn’t result in messages sent to the chat. Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

When callback buttons are used, your bot can update its existing messages (or just their keyboards) so that the chat remains tidy. Check out these sample bots to see inline keyboards in action: @music, @vote, @like.

Commands present a more flexible way to communicate with your bot. The following syntax may be used:

A command must always start with the ‘/’ symbol and may not be longer than 32 characters. Commands can use latin letters, numbers and underscores. Here are a few examples:

Messages that start with a slash are always passed to the bot (along with replies to its messages and messages that @mention the bot by username). Telegram apps will:

If multiple bots are in a group, it is possible to add bot usernames to commands in order to avoid confusion:

This is done automatically when commands are selected via the list of suggestions. Please remember that your bot needs to be able to process commands that are followed by its username.

In order to make it easier for users to navigate the bot multiverse, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

Users will see a Start button when they first open a conversation with your bot. Help and Settings links will be available in the menu on the bot’s profile page.

You can use bold, italic or fixed-width text, as well as inline links in your bots’ messages. Telegram clients will render them accordingly.

Bots are frequently added to groups in order to augment communication between human users, e.g. by providing news, notifications from external services or additional search functionality. This is especially true for work-related groups. Now, when you share a group with a bot, you tend to ask yourself “How can I be sure that the little rascal isn’t selling my chat history to my competitors?” The answer is — privacy mode.

A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:

On one hand, this helps some of us sleep better at night (in our tinfoil nightcaps), on the other — it allows the bot developer to save a lot of resources, since they won’t need to process tens of thousands irrelevant messages each day.

Privacy mode is enabled by default for all bots, except bots that were added to the group as admins (bot admins always receive all messages). It can be disabled, so that the bot receives all messages like an ordinary user (the bot will need to be re-added to the group for this change to take effect). We only recommend doing this in cases where it is absolutely necessary for your bot to work — users can always see a bot’s current privacy setting in the group members list. In most cases, using the force reply option for the bot’s messages should be more than enough.

Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an authentication token to connect the user’s Telegram account to their account on some external service.

Following a link with the start parameter will open a one-on-one conversation with the bot, showing a START button in the place of the input field. If the startgroup parameter is used, the user is prompted to select a group to add the bot to. As soon as a user confirms the action (presses the START button in their app or selects a group to add the bot to), your bot will receive a message from that user in this format:

PAYLOAD stands for the value of the start or startgroup parameter that was passed in the link.

Some bots need extra data from the user to work properly. For example, knowing the user’s location helps provide more relevant geo-specific results. The user’s phone number can be very useful for integrations with other services, like banks, etc.

Bots can ask a user for their location and phone number using special buttons. Note that both phone number and location request buttons will only work in private chats.

When these buttons are pressed, Telegram clients will display a confirmation alert that tells the user what’s about to happen.

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authentication token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and t.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

The remaining commands are pretty self-explanatory:

Edit bots

Edit settings

Manage games

Please note, that it may take a few minutes for changes to take effect.

Millions choose Telegram for its speed. To stay competitive in this environment, your bot also needs to be responsive. In order to help developers keep their bots in shape, Botfather will send status alerts if it sees something is wrong.

We will be checking the number of replies and the request/response conversion rate for popular bots (

300 requests per minute: but don’t write this down as the value may change in the future). If we get abnormally low readings, you will receive a notification from Botfather.

By default, you will only get one alert per bot per hour. Each alert has the following buttons:

We will currently notify you about the following issues:

1.

Your bot is sending much fewer messages than it did in the previous weeks. This is useful for newsletter-style bots that send out messages without prompts from the users. The larger the value, the more significant the difference.

2.

Your bot is not replying to all messages that are being sent to it (the request/response conversion rate for your bot was too low for at least two of the last three 5-minute periods). To provide a good user experience, please respond to all messages that are sent to your bot. Respond to message updates by calling send… methods (e.g. sendMessage).

3.

Your bot is not replying to all inline queries that are being sent to it, calculated in the same way as above. Respond to inline_query updates by calling answerInlineQuery.

4.

Your bot is not replying to all callback queries that are being sent to it (with or without games), calculated in the same way as above. Respond to callback_query updates by calling answerCallbackQuery.

Please note that the status alerts feature is still being tested and will be improved in the future.

That’s it for the introduction. You are now definitely ready to proceed to the BOT API MANUAL.

If you’ve got any questions, please check out our Bot FAQ »

ebaste/TelegramBot

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This project its to create an echo bot for Telegram

##The BotFather is the manager of the BotSystem

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Create a new bot Use the /newbot command to create a new bot. The BotFather will ask you for a «name» and «username», then generate an authorization token for your new bot.

it’s a little tricky that you need two names. The important name it´s username. It’s the way the people will call your bot.

The name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

Generate an authorization token for your bot If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Bot generation example:

BotFather Alright, a new bot. How are we going to call it? Please choose a name for your bot.

BotFather Sorry, this username is already taken. Think of something different.

BotFather Done! Congratulations on your new bot. You will find it at telegram.me/zyx_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands.

Use this token to access the HTTP API: 116169643:AAGHoOYKNAjvCH1YtTaKGzUYn1tXQLA6rx8

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

BotFather Choose a bot to generate a new token.

BotFather You can use this token to access HTTP API: 9999999999:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Comunicating with your bot

You should call the telegram yourBot API to get info about the messages it receives:

All queries to the Telegram Bot API must be served over HTTPS and need to be presented in this form: https://api.telegram.org/bot/METHOD_NAME. Like this for example:

*Important: bot its bot, not the name of your bot.

With this call, remembert to put your own bot access key

We support GET and POST HTTP methods. Use either URL query string or application/x-www-form-urlencoded or multipart/form-data for passing parameters in Bot API requests.

The response contains a JSON object, which always has a Boolean field ‘ok’ and may have an optional String field ‘description’ with a human-readable description of the result. If ‘ok’ equals true, the request was successful and the result of the query can be found in the ‘result’ field. In case of an unsuccessful request, ‘ok’ equals false and the error is explained in the ‘description’. An Integer ‘error_code’ field is also returned, but its contents are subject to change in the future.

In this case you will get something like this.

All methods in the Bot API are case-insensitive. All queries must be made using UTF-8.

Getting chat input

There are two mutually exclusive ways to get chat input. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

GetUpdates: it’s an active option. You need to call Telegram to get info SetWebhook: it’s a pasive option. telegram will make a post call ehenever he receives a message.

Update This object represents an incoming update.

|update_id|Integer|The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.| |message|Message|Optional. New incoming message of any kind — text, photo, sticker, etc.|

With getUpdates you can setup a pooling mechanism to pool data from the bot and process it, we will use this method in our examples (only to obtain a chat_id).

getUpdates Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.

|offset|Integer|Optional|Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.| |limit|Integer|Optional|Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100| |timeout|Integer|Optional|Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling|

If there are not mesaages, you receive this

If there are mesaages, you receive something like this

In thes case, two messages, the beggining of the conversation and the message «hola».

With setWebhook we can setup a «callback» url where the bot will push everything received into a conversation.

Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts.

If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. www.example.com/. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.

|url|String|Optional|HTTPS url to send updates to. Use an empty string to remove webhook integration| Notes

To send a message:

The remaining commands are pretty self-explanatory:

/setname – change your bot’s name. /setdescription — changes the bot’s description, a short text of up to 512 characters, describing your bot. Users will see this text at the beginning of the conversation with the bot, titled ‘What can this bot do?’. /setabouttext — changes the bot’s about info, an even shorter text of up to 120 characters. Users will see this text on the bot’s profile page. When they share your bot with someone, this text will be sent together with the link. /setuserpic — changes the bot‘s profile pictures. It’s always nice to put a face to a name. /setcommands — changes the list of commands supported by your bot. Each command has a name (must start with a slash ‘/’, alphanumeric plus underscores, no more than 32 characters, case-insensitive), parameters, and a text description. Users will see the list of commands whenever they type ‘/’ in a conversation with your bot. /setjoingroups — determines whether your bot can be added to groups or not. Any bot must be able to process private messages, but if your bot was not designed to work in groups, you can disable this. /setprivacy — determines which messages your bot will receive when added to a group. With privacy mode disabled, the bot will receive all messages. We recommend leaving privacy mode enabled. /deletebot — deletes your bot and frees its username. Please note, that it may take a few minutes for changes to take effect.

Creating Telegram Bot on RaspberryPi [closed]

This question does not appear to be specific to the Raspberry Pi within the scope defined in the help center.

I am trying to create Telegram Bot on my raspberry pi 3

After this i am getting telepot.exception.UnauthorizedError with error code 401. Is it saying token is not correct?

1 Answer 1

Did you follow all of the steps in How do I Create a Bot?

From the website:

The website goes on to describe BotFather

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Create a new bot
Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

Generate an authorization token for your bot
If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Edit settings
The remaining commands are pretty self-explanatory:

It then goes on to explain the remaining commands.

Create Telegram Bot Using Python Tutorial with Examples

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Introduction

For engaging conversations, the automated chatbot is really beneficial. On platforms such as Facebook, Google, and others, we can develop chatbots. In this tutorial, we will learn about how we can create a Telegram chatbot and use it to prepare text messages with rich responses.

Here we learn how we can get different types of responses from the bot such as:

Steps to create a Telegram Bot

Follow the below instructions to make a Telegram chatbot.

Step 1: Open your telegram account and in the search bar type “BotFather”.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 2: Click on the “BotFather” and Click on the “Start” button.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 3: Type “/newbot”.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 4: Type your unique bot name.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 5: Now type a unique username for your bot.

Remember: username must end in ‘bot’. E.g. ‘Tetris_bot’ or ‘Tetrisbot’.

Step 6: After giving a unique username you will get a message like the below. it contains a token to access the HTTP API. Keep your token secure and store it safely.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 7: Creating a flask app for the webhook response.

First of all, you will need to install python and flask on your computer.

Run this code to check whether the flask app is running correctly or not. When you run the code you will get the link for the server like “http://127.0.0.1:5000/” click on that link you will be redirected to the webpage where you will see the response “Welcome!”

Step 8: NGROK setup.

Go to the Ngrok and type the command “ngrok http 5000” after running this command you will get the links.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

From that Ngrok links copy the HTTPS link and paste it to your browser. You will see the response “Welcome!” same as the previous step.

Step 9: Setup webhook.

Now you will need to set the webhook for the telegram bot.

You can do it by running the link in your browser.

After running the link in your web browser you will get the response shown in the bellow image.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 10: Get JSON response.

Now we will need to get the JSON response from the telegram bot for any text that we write to the bot.

Now open VS Code and add the following code and run it on the same Ngrok link on which you had run the previous code.

In BotFather where you get the token for your Telegram chatbot, you can also file the URL to redirect to your Telegram bot.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

After that click on the Start Bot to start the chat with the bot. Then type any message that you want such as “test bot” or anything you want.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

After writing “test bot” to your bot now go to the Vscode you will file the following JSON in your terminal.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Here we can see that the message that we have written to the telegram bot we can get at the backend in text.

Step 11: send the text message from the bot.

We will write the code to get the response for the “hi” message from the user and if anything other than “hi” is imputed then response with “from webhook”.
You can also add an extra parameter in send message for that you can follow the Documentation.

We will get the below response in the Telegram Bot.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 12: Get the Image.

Now we can also get the image from the telegram bot.

By adding the function for sending images in the code.
For more parameters, you can follow the Documentation.

Here is the response that you will get from the telegram.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 13: Get Audio.

Similar way you can send audio to the telegram. For more parameters, you can follow the Documentation.

Add this code to your index function.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 14: Get Video.

Add the code to get the video to the telegram. To add more parameters you can follow the Documentation.

Add this code to your index function.

You will get the following response in your telegram like this.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 15: Get the File.

Add the code to get the File to the telegram. To add more parameters you can follow the Documentation.

Add this code to your index function.

You will get the following response in your telegram like this.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 16: Get a Poll.

Add the code to get the Poll to the telegram. To add more parameters you can follow the Documentation.

Add this code to your index function.

You will get the following response in your telegram like this.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 17: Get Button.

Add the code to get the Button to the telegram bot.

Add this code to your index function.

You will get the following response in your telegram like this.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 18: Get the Inline Button.

Add the code to get the Inline Button to the telegram.

Add this code to your index function.

You will get the following response in your telegram.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 19: Get the Inline Button URL.

Add the code to get the Inline Button to the telegram.

Add this code to your index function.

You will get the following response in your telegram like this.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

For more information, you can follow the Telegram Bot Api Documentation.

Step 20: Share the image with the bot and get it on the server-side.

First of all, we will share the image to the bot and see what type of JSON we are receiving on our server-side.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

As we can see that we are receiving a file id for the file which we are sending to the telegram bot. Now, we will get that file id for the image.

Now by calling the given function in the index function, we can get the chat id and file id printed.

We will receive the response below.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Now we will use the file id which we get for the image to get the file path for the image which is stored on the telegram server.

For that we will have to redirect to another URL and pass our file id to it for that we had created a function.

We also need to call the function which we have created.

Here in the function first we are trying to get our file path for the image that we had shared from a JSON.

After getting the file path we are trying to get the file from the telegram server by redirecting the file path to the “url_1”.

From “url_1” we are trying to save the file to our computer.

On the server-side, you will see the print and JSON like this.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Here is the directory where we are writing our code. We need to create a folder named “photos” so that we can get the image that we send to the bot directly in our system.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 21: Now we will try to add a video to the telegram bot.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

When we send the video to the bot then we are receiving different types of JSON. So we need to extract the file id from it.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

It can be done with the help of the following code.

Now here also in a similar way, we will extract the file id and pass it to the function and get the file path and store the video on our server-side.

To store the video, we will need to create the folder name “videos” in which we can store the video.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 22: Now in a similar way we can do it for audio and files.

For storing the audio we need to create a folder named “music”.

For storing the documents we need to create a folder named “documents”.

Here in a similar way, we need to extract the file id and pass it to the file_upload function.

Step 23: As we have tried to store the image, video, audio, and file at our server-side and also done the code to get the different types of responses through the telegram bot.

You can also refer to the full code on our Github repository and test it to get the various responses through the telegram bot and send files to the server-side.

We have learned how we can get the text response from the bot and also the different types of files. After that, we have also seen how we can get the files that we send to the bot on our server-side.

Now you can have your bot work the way you want—go ahead and create the next big thing!

Hope you had fun building your first Telegram bot. If you face any difficulty then do let us know in the comment.

Sorry the username must end in bot e g tetris bot or tetrisbot

Чтобы скачать приложение на свой компьютер — перейдите по ссылке https://tlgrm.ru

Чтобы скачать приложение на свой смартфон- перейдите в магазин приложений на своем устройстве. Для андроида- Google Play, https://play.google.com/store/…Для устройств на IOS- App Store. Введите запрос в магазине: «Телеграм», или Telegram. https://itunes.apple.com/ru/ap…

Просто выбирайте команду: /newbot На это бот пришлет вам следующее сообщение: «Alright, a new bot. How are we going to call it? Please choose a name for your bot.»

Это означает, что пора выбрать Имя вашего бота. Не путайте имя бота с его линком (ссылкой, которую мы присвоим ему в следующем шаге. Имя может быть любым- это то, что будет в первую очередь бросаться в глаза, когда ваш клиент попадет в бота. Как правило, имя выбирают созвучным, или ассоциированным с названием вашего проекта/компании. Вы можете задать имя, как на руссом, так и на английском языке.

Написали имя и отправили боту?

Телеграм — бот почти готов.

Если вы выбрали свободный линк и сделали все верно, Бот Фазер пришлет вам такое сообщение:
Done! Congratulations on your new bot. You will find it at t.me/Manikurmskbot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.Use this token to access the HTTP API:889665446:AAEImtF9NRVZP3mL8r8DJIw2Va6H0n7gKeep your token secure and store it safely, it can be used by anyone to control your bot.For a description of the Bot API, see this page: https://core.telegram.org/bots…

Создаем описание бота.

Вернитесь к первому сообщению бота (в котором содержится перечень команд) и кликайте по команде /setdescription

Бот вернет вам вот такое сообщение: «Choose a bot to change description.» Это значит, что вам следует выбрать созданного бота (его название вам будет прислано)

Почему бот Father предлагает вам выбрать бота? Дело в том, что в Телеграм существует лимит созданных ботов на один номер телефона. Сейчас вы. можете создать 20 ботов на одной зарегистрированной сим- карте. Если вам потребуется больше ботов-больше-бооооольше, то просто зарегистрируете еще одну сим-карту и вам станет доступно создание еще 20 ботов.

Вы выбрали бота, чье описание хотите изменить? Бот Фазер вернул вам вот такое сообщение, если вы все сделали верно:»OK. Send me the new description for the bot. People will see this description when they open a chat with your bot, in a block titled ‘What can this bot do?’

Теперь осталось отправить ему в чат короткое описание вашего бота (подробно описано в видео).

Осталось оформить аватарку вашего бота. Для этого снова возвращаемся к первичному сообщению Bot Father и выбираем команду: /setuserpic

Действуем по уже знакомому сценарию: сначала выбираем бота, которому меняем аватарку (фото профайла), получаем от бота сообщение: «OK. Send me the new profile photo for the bot.»
Далее отправляем ему уже заготовленную фотографию. Для этого она должна быть доступна на вашем компьютере (на смартфоне, если вы создаете бота с него)

Telegram

Requirements​

An HTTPS Endpoint to your chatbot:

Create a Bot​

To create a bot on Telegram, use Telegram’s BotFather. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

Setup​

Generate an Authorization Token​

When you create a Telegram bot, Botfather will automatically generate a token. The token is a string that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely; anyone can use it to control your bot.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

enabled : set to true

botToken : your bot token

Your bot.config.json should look like this:

Requirements​

Create a Bot​

To create a bot on Telegram, use Telegram’s BotFather. The BotFather will ask you for a name and username, then generate an authorization token for your new bot

The name of your bot is displayed in contact details and elsewhere

Channel Configuration​

Generate an Authorization Token​

When you create a Telegram bot, Botfather will automatically generate a token. The token is a string that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely; anyone can use it to control your bot

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one

Bot Token​

Copy paste your telegram bot token into the Bot Token channel configuration and click Save. Webhooks will be created automatically

Bots: An introduction for developers

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s Bot API.

Telegram keeps evolving and adding new features, so this document may contain outdated information. We expect to finish updating the FAQ, Bot Manuals, and other documents by the end of Summer 2022.

To name just a few things, you could use bots to:

Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.

Accept payments from Telegram users. A bot can offer paid services or work as a virtual storefront. Read more » Demo Shop Bot, Demo Store

Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services. Markdown bot, Sticker bot, Vote bot, Like bot

Build single- and multiplayer games. A bot can offer rich HTML5 experiences, from simple arcades and puzzles to 3D-shooters and real-time strategy games. GameBot, Gamee

Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.

Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

Messages, commands and requests sent by users are passed to the software running on your servers. Our intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. We call that interface our Bot API.

A detailed description of the Bot API is available on this page »

There’s a. bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authentication token, head down to the Bot API manual to see what you can teach your bot to do.

You may also like to check out some code examples here »

Telegram bots are unique in many ways — we offer two kinds of keyboards, additional interfaces for default commands and deep linking as well as text formatting, integrated payments and more.

Users can interact with your bot via inline queries straight from the text input field in any chat. All they need to do is start a message with your bot’s username and then type a query.

Having received the query, your bot can return some results. As soon as the user taps one of them, it is sent to the user’s currently opened chat. This way, people can request content from your bot in any of their chats, groups or channels.

Check out this blog to see a sample inline bot in action. You can also try the @sticker and @music bots to see for yourself.

We’ve also implemented an easy way for your bot to switch between inline and PM modes.

You can use bots to accept payments from Telegram users around the world.

Bots can offer their users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. The platform allows your bot to keep track of high scores for every game played in every chat. Whenever there’s a new leader in the game, other playing members in the chat are notified that they need to step it up.

Since the underlying technology is HTML5, the games can be anything from simple arcades and puzzles to multiplayer 3D-shooters and real-time strategy games. Our team has created a couple of simple demos for you to try out:

You can also check out the @gamee bot that has more than 20 games.

Traditional chat bots can of course be taught to understand human language. But sometimes you want some more formal input from the user — and this is where custom keyboards can become extremely useful.

Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options (see ReplyKeyboardMarkup). Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

We currently support text and emoji for your buttons. Here are some custom keyboard examples:

For more technical information on custom keyboards, please consult the Bot API manual (see sendMessage).

There are times when you’d prefer to do things without sending any messages to the chat. For example, when your user is changing settings or flipping through search results. In such cases you can use Inline Keyboards that are integrated directly into the messages they belong to.

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn’t result in messages sent to the chat. Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

When callback buttons are used, your bot can update its existing messages (or just their keyboards) so that the chat remains tidy. Check out these sample bots to see inline keyboards in action: @music, @vote, @like.

Commands present a more flexible way to communicate with your bot. The following syntax may be used:

A command must always start with the ‘/’ symbol and may not be longer than 32 characters. Commands can use latin letters, numbers and underscores. Here are a few examples:

Messages that start with a slash are always passed to the bot (along with replies to its messages and messages that @mention the bot by username). Telegram apps will:

If multiple bots are in a group, it is possible to add bot usernames to commands in order to avoid confusion:

This is done automatically when commands are selected via the list of suggestions. Please remember that your bot needs to be able to process commands that are followed by its username.

In order to make it easier for users to navigate the bot multiverse, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

Users will see a Start button when they first open a conversation with your bot. Help and Settings links will be available in the menu on the bot’s profile page.

You can use bold, italic or fixed-width text, as well as inline links in your bots’ messages. Telegram clients will render them accordingly.

Bots are frequently added to groups in order to augment communication between human users, e.g. by providing news, notifications from external services or additional search functionality. This is especially true for work-related groups. Now, when you share a group with a bot, you tend to ask yourself «How can I be sure that the little rascal isn’t selling my chat history to my competitors?» The answer is — privacy mode.

A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:

On one hand, this helps some of us sleep better at night (in our tinfoil nightcaps), on the other — it allows the bot developer to save a lot of resources, since they won’t need to process tens of thousands irrelevant messages each day.

Privacy mode is enabled by default for all bots, except bots that were added to the group as admins (bot admins always receive all messages). It can be disabled, so that the bot receives all messages like an ordinary user (the bot will need to be re-added to the group for this change to take effect). We only recommend doing this in cases where it is absolutely necessary for your bot to work — users can always see a bot’s current privacy setting in the group members list. In most cases, using the force reply option for the bot’s messages should be more than enough.

Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an authentication token to connect the user’s Telegram account to their account on some external service.

Following a link with the start parameter will open a one-on-one conversation with the bot, showing a START button in the place of the input field. If the startgroup parameter is used, the user is prompted to select a group to add the bot to. As soon as a user confirms the action (presses the START button in their app or selects a group to add the bot to), your bot will receive a message from that user in this format:

PAYLOAD stands for the value of the start or startgroup parameter that was passed in the link.

Some bots need extra data from the user to work properly. For example, knowing the user’s location helps provide more relevant geo-specific results. The user’s phone number can be very useful for integrations with other services, like banks, etc.

Bots can ask a user for their location and phone number using special buttons. Note that both phone number and location request buttons will only work in private chats.

When these buttons are pressed, Telegram clients will display a confirmation alert that tells the user what’s about to happen.

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authentication token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and t.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

The remaining commands are pretty self-explanatory:

Edit bots

Edit settings

Manage games

Please note, that it may take a few minutes for changes to take effect.

Millions choose Telegram for its speed. To stay competitive in this environment, your bot also needs to be responsive. In order to help developers keep their bots in shape, Botfather will send status alerts if it sees something is wrong.

We will be checking the number of replies and the request/response conversion rate for popular bots (

300 requests per minute: but don’t write this down as the value may change in the future). If we get abnormally low readings, you will receive a notification from Botfather.

By default, you will only get one alert per bot per hour. Each alert has the following buttons:

We will currently notify you about the following issues:

1.

Your bot is sending much fewer messages than it did in the previous weeks. This is useful for newsletter-style bots that send out messages without prompts from the users. The larger the value, the more significant the difference.

2.

Your bot is not replying to all messages that are being sent to it (the request/response conversion rate for your bot was too low for at least two of the last three 5-minute periods). To provide a good user experience, please respond to all messages that are sent to your bot. Respond to message updates by calling send. methods (e.g. sendMessage).

3.

Your bot is not replying to all inline queries that are being sent to it, calculated in the same way as above. Respond to inline_query updates by calling answerInlineQuery.

4.

Your bot is not replying to all callback queries that are being sent to it (with or without games), calculated in the same way as above. Respond to callback_query updates by calling answerCallbackQuery.

Please note that the status alerts feature is still being tested and will be improved in the future.

That’s it for the introduction. You are now definitely ready to proceed to the BOT API MANUAL.

If you’ve got any questions, please check out our Bot FAQ »

Пишем бота для обратной связи с сайта. Часть 1. Создаем бота и настраиваем среду разработки.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Наличие лэндинга на вашем сайте ставит перед вами очевидную задачу – необходимость своевременно отвечать потенциальным клиентам на вопросы, задаваемые через встроенные в лэндинг формы.

Это может быть простая форма обратной связи или форма с заказом обратного звонка, в любом случае чем быстрее будет дан ответ, тем больше шансов, что посетитель станет вашим клиентом или покупателем.

Сегодня я начинаю цикл статей, в которых мы рассмотрим написание простого Телеграм-бота, который будет присылать сообщение в специально созданный канал, после того, как пользователь заполнил форму на вашем сайте.

Разработку мы будем осуществлять в Astra Linux, которую настроили в предыдущей статье

А чтобы не изобретать велосипед мы будем использовать готовую библиотеку:

Установка Composer

Актуальную команду для установки вы можете найти на странице проекта –

Создадим папку для будущего бота:

Перейдем в папку

Для упрощения разработки установим права доступа на папку:

Обратите внимание! При установке на продакшн-сервер права 777 на папку ставить строго не рекомендуется!

Перенесем скрипт в папку

Таким образом он будет глобально:

Проверим корректность установки:

Установка библиотеки telegram-bot-sdk

Обратите внимание строго не рекомендуется запускать composer из под пользователя root.

Используйте учетную запись обычного пользователя!

Я сильно сократил вывод команды, для экономии места!

После окончания установки будет создана папка

На этом установка библиотеки закончена!

Создание бота в Телеграм

Для того, чтобы бот мог отправлять сообщения, его нужно создать и пригласить на канал.

Откройте в Телеграм раздел Все чаты и введите в строку поиска:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Отец всех ботов выглядит ка как показано на рисунке. Разными «умниками» созданы поддельные боты, для продвижения всяческой чепухи, но нам нужен только главный!

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

В чат боту напишем

Напишем имя бота. Так как я создаю тестового бота, то и назову его:

Теперь нам нужно придумать внешнее имя, это имя, по которому его можно будет найти в Телеграм.

Обратите внимание, что многие имена уже зарегистрированы и даже имя Ru-Test9999-bot занято! Будем импровизировать:

Если всё прошло успешно, вы получите сообщение:

Нас интересует строчка вида:

Это токен вашего бота и вы должны бережно его хранить в недоступном месте! Никому не сообщать и не забывать удалять его из исходного кода, если размещаете его на github.com!

Для теста я создал группу:

и при создании ввел имя бота

Так же откроем Управление группой и сделаем Ru_Test9999_bot администратором.

На этом настройка бота завершена.

Чтобы бот из Телеграм имел доступ к программному коду на вашем сервере нам потребуется доменное имя и доступ к серверу по протоколу https://

Настройка Nginx

Бот должен быть доступен по https://. Давайте настроим Nginx для предоставления доступа к файлу с ботом.

Чтобы защититься от разных «хацкеров» я рекомендую создать на веб-сервере папку с длинным именем. Для этого сгенерируем UUID:

Каждый раз при запуске результат будет разным!

Создадим папку для веб-сервера

В папке создадим симлинк до папки /var/phpbots/landing-bot

Теперь, если мы напишем:

То увидим содержимое папки /var/phpbots/landing-bot

Создадим файл конфигурации для nginx

Создадим в папке

файл test.php с содержимым:

Откроется страница с phpinfo()

Настройка туннеля с помощью ngrok.com

Еще одной проблемой при разработке бота является то, что нам придется вносить изменения сразу на сервере. Не хотелось и не рекомендуется использовать продакшн-сервер для опытов.

Чтобы решить эту проблемы мы воспользуемся бесплатным планом сервиса https://ngrok.com

Установим клиент ngrok на наш локальный сервер:

Зарегистрируйтесь на сайте и в разделе

Скачайте файл ngrok-stable-linux-amd64.zip

На момент написания статьи ссылка была такой:

Но лучше скопировать свежую!

Скачаем в папку обычного пользователя, опять же, не запускайте ничего от root без необходимости!

Обратите внимание мы будем запускать ngrok от обычного пользователя!

вы найдете команду для добавления вашего токена в локальное хранилище ngrok

скопируйте и запустите строчку вида:

Обратите внимание, bc8ab1191806 меняется каждый раз, когда вы перезапускаете ngrok. Чтобы получить постоянное имя придется купить подписку!

Но нам для написания и отладки бота хватит и бесплатного функционала.

И увидим свою страницу phpinfo().

Привязываем Вебхук (Webhook)

Теперь, когда у нас есть внешний домен, пришла пора привязать к боту наш сайт через Вебхук.

Каждый раз, когда пользователь взаимодействует с ботом, тот отсылает сообщение на наш сервер, чтобы указать адрес, на который бот должен направлять запросы используется Вебхук.

Создадим файл для будущего бота:

Откроем в браузере:

Получим пустую страницу – это хорошо, значит файл доступен.

Далее не забудьте заменить

Обратите внимание, мы добавили bot перед токеном ЭТО ВАЖНО!

Для этого укажем токен и адрес файла с ботом!

Таким образом мы установили Вебхук!

Пишем код для бота

Напишем простой код для бота:

Так ка мы вызываем бот напрямую, он выдает множество нотисов, это нормально!

В будущем мы добавим проверку и в случае вызова напрямую, он будет отдавать страницу с кодом 403.

Откроем телеграм и найдем бот Ru_Test9999_bot нажмем на кнопку Запустить

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

И получим ответ:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Поздравляю! Мы с вами написали простой бот для Телеграм.

Заключение

Сегодня мы рассмотрели создание простого Телеграм-бота.

Был установлен Composer PHP.

Мы создали бот в Телеграм и добавили его в специально созданную группу и получили токен.

Настроили Nginx и скрипт для бота.

Установили ngrok для организации доступа к боту, размещенному на нашем локальном сервере, из интернета.

Привязали Вебхук к публичному адресу ngrok.

Написали и протестировали простой Телеграм-бот.

В следующей части мы рассмотрим отправку сообщения с формы сайта в группу Телеграм.

Пишем бота пересылки сообщений из VK в Telegram на Python

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Очень часто бывает что у вас группа в vk.com и вам бы хотелось завести канал в телеграмм но постить вручную сообщения в два источника не очень удобно. Ниже мы рассмотрим бота для пересылки сообщений из вконтакте в телеграм.

Регистрируем бота в Telegram

Добавляем в список контактов @BotFather

Отправляем ему команду:

Придумываем имя боту

Alright, a new bot. How are we going to call it? Please choose a name for your bot.
Good. Now let’s choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
Done! Congratulations on your new bot. You will find it at t.me/XXXXbot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Нам понадобятся библиотеки:

configparser и logging из стандартной библиотеки Python, и конечно сам Python, на момент написания статьи у меня была версия 3.6.2

Устанавливаем библиотеки через pip желательно в virtualenv, в консоли набираем:

Bots: An introduction for developers

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s Bot API.

Telegram keeps evolving and adding new features, so this document may contain outdated information.
We expect to finish updating the FAQ, Bot Manuals, and other documents by the end of Summer 2022.

To name just a few things, you could use bots to:

Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.

Accept payments from Telegram users. A bot can offer paid services or work as a virtual storefront. Read more »
Demo Shop Bot, Demo Store

Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services.
Markdown bot, Sticker bot, Vote bot, Like bot

Build single- and multiplayer games. A bot can offer rich HTML5 experiences, from simple arcades and puzzles to 3D-shooters and real-time strategy games.
GameBot, Gamee

Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.

Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

Messages, commands and requests sent by users are passed to the software running on your servers. Our intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. We call that interface our Bot API.

A detailed description of the Bot API is available on this page »

There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authentication token, head down to the Bot API manual to see what you can teach your bot to do.

You may also like to check out some code examples here »

Telegram bots are unique in many ways — we offer two kinds of keyboards, additional interfaces for default commands and deep linking as well as text formatting, integrated payments and more.

Users can interact with your bot via inline queries straight from the text input field in any chat. All they need to do is start a message with your bot’s username and then type a query.

Having received the query, your bot can return some results. As soon as the user taps one of them, it is sent to the user’s currently opened chat. This way, people can request content from your bot in any of their chats, groups or channels.

Check out this blog to see a sample inline bot in action. You can also try the @sticker and @music bots to see for yourself.

We’ve also implemented an easy way for your bot to switch between inline and PM modes.

You can use bots to accept payments from Telegram users around the world.

Bots can offer their users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. The platform allows your bot to keep track of high scores for every game played in every chat. Whenever there’s a new leader in the game, other playing members in the chat are notified that they need to step it up.

Since the underlying technology is HTML5, the games can be anything from simple arcades and puzzles to multiplayer 3D-shooters and real-time strategy games. Our team has created a couple of simple demos for you to try out:

You can also check out the @gamee bot that has more than 20 games.

Traditional chat bots can of course be taught to understand human language. But sometimes you want some more formal input from the user — and this is where custom keyboards can become extremely useful.

Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options (see ReplyKeyboardMarkup). Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

We currently support text and emoji for your buttons. Here are some custom keyboard examples:

For more technical information on custom keyboards, please consult the Bot API manual (see sendMessage).

There are times when you’d prefer to do things without sending any messages to the chat. For example, when your user is changing settings or flipping through search results. In such cases you can use Inline Keyboards that are integrated directly into the messages they belong to.

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn’t result in messages sent to the chat. Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

When callback buttons are used, your bot can update its existing messages (or just their keyboards) so that the chat remains tidy. Check out these sample bots to see inline keyboards in action: @music, @vote, @like.

Commands present a more flexible way to communicate with your bot. The following syntax may be used:

A command must always start with the ‘/’ symbol and may not be longer than 32 characters. Commands can use latin letters, numbers and underscores. Here are a few examples:

Messages that start with a slash are always passed to the bot (along with replies to its messages and messages that @mention the bot by username). Telegram apps will:

If multiple bots are in a group, it is possible to add bot usernames to commands in order to avoid confusion:

This is done automatically when commands are selected via the list of suggestions. Please remember that your bot needs to be able to process commands that are followed by its username.

In order to make it easier for users to navigate the bot multiverse, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

Users will see a Start button when they first open a conversation with your bot. Help and Settings links will be available in the menu on the bot’s profile page.

You can use bold, italic or fixed-width text, as well as inline links in your bots’ messages. Telegram clients will render them accordingly.

Bots are frequently added to groups in order to augment communication between human users, e.g. by providing news, notifications from external services or additional search functionality. This is especially true for work-related groups. Now, when you share a group with a bot, you tend to ask yourself “How can I be sure that the little rascal isn’t selling my chat history to my competitors?” The answer is — privacy mode.

A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:

On one hand, this helps some of us sleep better at night (in our tinfoil nightcaps), on the other — it allows the bot developer to save a lot of resources, since they won’t need to process tens of thousands irrelevant messages each day.

Privacy mode is enabled by default for all bots, except bots that were added to the group as admins (bot admins always receive all messages). It can be disabled, so that the bot receives all messages like an ordinary user (the bot will need to be re-added to the group for this change to take effect). We only recommend doing this in cases where it is absolutely necessary for your bot to work — users can always see a bot’s current privacy setting in the group members list. In most cases, using the force reply option for the bot’s messages should be more than enough.

Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an authentication token to connect the user’s Telegram account to their account on some external service.

Following a link with the start parameter will open a one-on-one conversation with the bot, showing a START button in the place of the input field. If the startgroup parameter is used, the user is prompted to select a group to add the bot to. As soon as a user confirms the action (presses the START button in their app or selects a group to add the bot to), your bot will receive a message from that user in this format:

PAYLOAD stands for the value of the start or startgroup parameter that was passed in the link.

Some bots need extra data from the user to work properly. For example, knowing the user’s location helps provide more relevant geo-specific results. The user’s phone number can be very useful for integrations with other services, like banks, etc.

Bots can ask a user for their location and phone number using special buttons. Note that both phone number and location request buttons will only work in private chats.

When these buttons are pressed, Telegram clients will display a confirmation alert that tells the user what’s about to happen.

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authentication token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and t.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

The remaining commands are pretty self-explanatory:

Edit bots

Edit settings

Manage games

Please note, that it may take a few minutes for changes to take effect.

Millions choose Telegram for its speed. To stay competitive in this environment, your bot also needs to be responsive. In order to help developers keep their bots in shape, Botfather will send status alerts if it sees something is wrong.

We will be checking the number of replies and the request/response conversion rate for popular bots (

300 requests per minute: but don’t write this down as the value may change in the future). If we get abnormally low readings, you will receive a notification from Botfather.

By default, you will only get one alert per bot per hour. Each alert has the following buttons:

We will currently notify you about the following issues:

1.

Your bot is sending much fewer messages than it did in the previous weeks. This is useful for newsletter-style bots that send out messages without prompts from the users. The larger the value, the more significant the difference.

2.

Your bot is not replying to all messages that are being sent to it (the request/response conversion rate for your bot was too low for at least two of the last three 5-minute periods). To provide a good user experience, please respond to all messages that are sent to your bot. Respond to message updates by calling send… methods (e.g. sendMessage).

3.

Your bot is not replying to all inline queries that are being sent to it, calculated in the same way as above. Respond to inline_query updates by calling answerInlineQuery.

4.

Your bot is not replying to all callback queries that are being sent to it (with or without games), calculated in the same way as above. Respond to callback_query updates by calling answerCallbackQuery.

Please note that the status alerts feature is still being tested and will be improved in the future.

That’s it for the introduction. You are now definitely ready to proceed to the BOT API MANUAL.

If you’ve got any questions, please check out our Bot FAQ »

ebaste / TelegramBot Goto Github PK

This project its to create an echo bot for Telegram

TelegramBot’s Introduction

This project its to create an echo bot for Telegram

##The BotFather is the manager of the BotSystem

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Create a new bot Use the /newbot command to create a new bot. The BotFather will ask you for a «name» and «username», then generate an authorization token for your new bot.

it’s a little tricky that you need two names. The important name it´s username. It’s the way the people will call your bot.

The name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

Generate an authorization token for your bot If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Bot generation example:

BotFather Alright, a new bot. How are we going to call it? Please choose a name for your bot.

BotFather Sorry, this username is already taken. Think of something different.

BotFather Done! Congratulations on your new bot. You will find it at telegram.me/zyx_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands.

Use this token to access the HTTP API: 116169643:AAGHoOYKNAjvCH1YtTaKGzUYn1tXQLA6rx8

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

BotFather Choose a bot to generate a new token.

BotFather You can use this token to access HTTP API: 9999999999:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Comunicating with your bot

You should call the telegram yourBot API to get info about the messages it receives:

All queries to the Telegram Bot API must be served over HTTPS and need to be presented in this form: https://api.telegram.org/bot/METHOD_NAME. Like this for example:

*Important: bot its bot, not the name of your bot.

With this call, remembert to put your own bot access key

We support GET and POST HTTP methods. Use either URL query string or application/x-www-form-urlencoded or multipart/form-data for passing parameters in Bot API requests.

The response contains a JSON object, which always has a Boolean field ‘ok’ and may have an optional String field ‘description’ with a human-readable description of the result. If ‘ok’ equals true, the request was successful and the result of the query can be found in the ‘result’ field. In case of an unsuccessful request, ‘ok’ equals false and the error is explained in the ‘description’. An Integer ‘error_code’ field is also returned, but its contents are subject to change in the future.

In this case you will get something like this.

All methods in the Bot API are case-insensitive. All queries must be made using UTF-8.

Getting chat input

There are two mutually exclusive ways to get chat input. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

GetUpdates: it’s an active option. You need to call Telegram to get info SetWebhook: it’s a pasive option. telegram will make a post call ehenever he receives a message.

Update This object represents an incoming update.

|update_id|Integer|The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.| |message|Message|Optional. New incoming message of any kind — text, photo, sticker, etc.|

With getUpdates you can setup a pooling mechanism to pool data from the bot and process it, we will use this method in our examples (only to obtain a chat_id).

getUpdates Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.

|offset|Integer|Optional|Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.| |limit|Integer|Optional|Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100| |timeout|Integer|Optional|Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling|

If there are not mesaages, you receive this

If there are mesaages, you receive something like this

In thes case, two messages, the beggining of the conversation and the message «hola».

With setWebhook we can setup a «callback» url where the bot will push everything received into a conversation.

Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts.

If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. www.example.com/. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.

|url|String|Optional|HTTPS url to send updates to. Use an empty string to remove webhook integration| Notes

To send a message:

The remaining commands are pretty self-explanatory:

/setname – change your bot’s name. /setdescription — changes the bot’s description, a short text of up to 512 characters, describing your bot. Users will see this text at the beginning of the conversation with the bot, titled ‘What can this bot do?’. /setabouttext — changes the bot’s about info, an even shorter text of up to 120 characters. Users will see this text on the bot’s profile page. When they share your bot with someone, this text will be sent together with the link. /setuserpic — changes the bot‘s profile pictures. It’s always nice to put a face to a name. /setcommands — changes the list of commands supported by your bot. Each command has a name (must start with a slash ‘/’, alphanumeric plus underscores, no more than 32 characters, case-insensitive), parameters, and a text description. Users will see the list of commands whenever they type ‘/’ in a conversation with your bot. /setjoingroups — determines whether your bot can be added to groups or not. Any bot must be able to process private messages, but if your bot was not designed to work in groups, you can disable this. /setprivacy — determines which messages your bot will receive when added to a group. With privacy mode disabled, the bot will receive all messages. We recommend leaving privacy mode enabled. /deletebot — deletes your bot and frees its username. Please note, that it may take a few minutes for changes to take effect.

Create a Telegram bot through BotFather.

Enter BotFather with the “@”symbol in the telegram.

Creating a new bot
Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot is displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and t.me links. Usernames are 5–32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of [1066870955:AAGgA7X3b-dHAAWvK_stTpboqCh0pWGfn20 ] that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

Generating an authorization token
If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Botfather commands
The remaining commands are pretty self-explanatory:

Please note, that it may take a few minutes for changes to take effect.

Status alerts

Millions choose Telegram for its speed. To stay competitive in this environment, your bot also needs to be responsive. In order to help developers keep their bots in shape, Botfather will send status alerts if it sees something is wrong.

We will be checking the number of replies and the request/response conversion rate for popular bots (

300 requests per minute: but don’t write this down as the value may change in the future). If we get abnormally low readings, you will receive a notification from Botfather.

Responding to alerts

By default, you will only get one alert per bot per hour. Each alert has the following buttons:

We will currently notify you about the following issues:

Your bot is sending much fewer messages than it did in the previous weeks. This is useful for newsletter-style bots that send out messages without prompts from the users. The larger the value, the more significant the difference.

Your bot is not replying to all messages that are being sent to it (the request/response conversion rate for your bot was too low for at least two of the last three 5-minute periods). To provide a good user experience, please respond to all messages that are sent to your bot. Respond to message updates by calling send… methods (e.g. sendMessage).

Your bot is not replying to all inline queries that are being sent to it, calculated in the same way as above. Respond to inline_query updates by calling answerInlineQuery.

Your bot is not replying to all callback queries that are being sent to it (with or without games), calculated in the same way as above. Respond to callback_query updates by calling answerCallbackQuery.

Please note that the status alerts feature is still being tested and will be improved in the future.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

That’s it for the introduction. You are now definitely ready to proceed to the BOT API MANUAL.

If you’ve got any questions, please check out our Bot FAQ

After creating the bot, you need to deploy the project code to Heroku. And after starting the server on Heroku, you will need to run several commands:

After all these actions, the bot will be active.

Telegram Bot Library

Host a Telegram Bot on your Arduino and chat with your brand new IoT device!

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Hardware components

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot
Arduino MKR1000
×1

Software apps and online services

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot
Arduino Web Editor

Learn how to use the Telegram Bot library, host a Telegram Bot on your Arduino/Genuino Board, and use the messaging app to interact with your device.

Step 1 (TelegramBot Library)

Download TelegramBot Library ( Download ).

Step 2 (ArduinoJson & WiFi101 Library)

Install ArduinoJson & WiFi101 Library from Library Manager.

Step 1 (Create a new TelegramBot )

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The Name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Now that we have our new bot we can set it to do what we want.

In this example we will make it turn on and off a LED by texting him a simple ‘On or Off’ message.

Let’s see in action

Notes about the groups

You can also create your own list of commands using /setcommands while chatting with the BotFather. This list will appear only in the mobile view, pressing the «/» icon.

Telegram Bot with Apps Script

Google Apps Script is a cloud scripting service based in JavaScript and makes it easy to do cool things with most of Google’s products. Lately, I’ve been a big fan of its flexibility and versatility, for example with just a few lines of code you can interact with the Telegram Bot API to control your bot, you won’t have to worry about having a server, SSL certificates or configure ports 😏.

🤔 What We Are Going to Do

Our goal is to create a simple Telegram bot that replies to a command with a random quote from Quotes on Design.

Now let’s get started with the step by step instructions 😊

🤖 Meet BotFather

The first step is to talk to BotFather to create and setup our bot, he will also give us our authorization token.

Sign in to Telegram from your favorite device and search for the account BotFather and start a conversation.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Click the Start button.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

He will reply with the list of commands supported by BotFather.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

The name of your bot will be displayed in contact details and elsewhere.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Now, BotFather will ask you for a username, let it be DesignQuotesBot.

The username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

🤓 Ok, It’s time to code!

Let’s jump to Google Apps Script, grab your browser and visit script.google.com/intro (You’ll need to be signed in to your Google account.) You’ll see the Script Editor with a Blank project, delete any code in the Code.gs file.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Telegram Bot API currently supports two (mutually exclusive) ways of receiving updates. We can either use long polling or Webhooks, for this example we’re going to use Webhooks, this means every time there is an update in for the bot (like when someone sends a command to our bot or add him to a group), they will send an HTTP POST request to a specified URL containing a JSON-serialized Update.

So, we need to create an application to be able to respond to POST requests sent from the Bot API, the good news are that Google Apps Script would let us deploy our script as a Web App that would let us interpret those request.

When an user or a program (in this case de Bot API) sends to our script an HTTP Post request, Apps Script will run the special callback function doPost(e) so all we need to do is define that function in our script. The e argument represents an event parameter that contains the information of the request. As we mentioned above, the Bot API will send the POST request containing a JSON-serialized, this means we’re gonna recieve an object converted into String, so we need to parse the text content of the POST body e.postBody.contents with the method JSON.parse().

When our script receives an update, in this case the command /quote the JSON-object should look similar to this example:

An incoming update can be of many types, for this example we’re going to focus on bot commands, so first we need to make sure the update is type message, in JavaScript we can use the method hasOwnProperty() to determine whether an object has the specified property.

At this point our doPost() function should look like this:

Google Apps Script can interact with APIs from all over the web, we can use the built-in URL Fetch Service with the method fetch() to make a request to the URL mentioned above.

The same as the Bot API, we need to parse the response to work with a JSON Object.

The returned value would look like an array of this:

The returned value is an Array, so we can use the JavaScript method shift() it will remove the first element from an Array and returns that element.

The Bot API supports basic formatting for messages, let’s take advantage of this and format the quote, we’re goinf to add quotations marks, an em dash and the author in bold.

«No matter how cool your interface is, it would be better if there were less of it.» — Alan Cooper

The next step is to send the Bot API our request, for this we’re also going to use the URL Fetch Service and the Bot API method sendMessage.

We need to define the POST body for the request containing the requiered parameters:

Because payload is a JavaScript object, it will be interpreted as an HTML form. (We do not need to specify contentType; it will automatically default to either ‘application/x-www-form-urlencoded’ or ‘multipart/form-data’)

We also need to specify the HTTP method for the request, in this case Post.

💪 The Full Code

🙄 Dude, Just Deploy It Already

To publish our script as a web app, we need to follow these steps:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Once we click Deploy, we’ll see one of the authorization dialogs, we need to authorize our script to Connect to an external services because we’re using the URL Fetch Service, click Review Permissions and then Allow.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

We’ll see a new dialog indicating that your project has been successfully deployed as a web app. The dialog provides two URLs for your app, the first labeled Current web app URL and ends in /exec we’re going to need this to set our Webhook.

The final step is to share the Bot API the URL they need to send the update requests, the easiest way is to open your browser and visit the following url:

Replacing with and with our respective token and URL.

If everything turns out as planned 🤞, after visiting the url we’ll see the response:

😎 Let’s Test It!

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

🙌 We’re done!

I hope this post gave you a better understanding of what we can achieve with Google Apps Script and a little more on how to create a Telegram Bot 😉.

[IoT] Telegram Bot with Arduino MKR WiFi 1010 © GPL3+

Automate everything with Arduino!

This project demonstrates how to interface Arduino with the Telegram Bot APIs. The project is built around the new MKR WiFi 1010 board equipped with an ESP32 module by U-BLOX.

At this stage, the project is no more than a proof of concept, just to show you what you could do with, so for this you need only the Arduino board.

Well, bots are simply Telegram accounts operated by software – not people – and they’ll often have AI features. They can do anything – teach, play, search, broadcast, remind, connect, integrate with other services, or even pass commands to the Internet of Things. (credits by Telegram: https://telegram.org/blog/bot-revolution )

In our case we’ll pass commands to Arduino building a simple IoT device. It will answer to simple commands and also turn on/off the built-in Led. I’ll let your imagination do more with it. (imagine to connect one or more relay to the I/O pins and turn on/off an heater or the air conditioning system with your smartphone, for example).

Step 1: What You Need

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

For this project you need:

Step 2: Installing the IDE

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Yeah, i know, i know. most of you already have the Arduino IDE installed in the PC, but this tutorials is intended also for beginners.

So, first of all, download the Arduino IDE 1.8.5 of your choice (zip file for ‘non administrators’ or exe file)

The 1.8.5 version is recommended, i didn’t test old versions and the new board used in the project could not be supported at all.

Now you need to install the new boards with their drivers:

Now connect your new Arduino board and wait for Windows to complete the driver installation.

From the Tools->Board menu you’ll find the new boards, choose the MKR WiFi 1010.

Choose the correct com port and test the board with the Get Board Info command.

Congrats, you’re done with the IDE!

Step 3: Creating the Telegram Bot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Creating a new Telegram bot is quite simple.

Open the Telegram app and, in the search bar, type @BotFather and start a chat with him (image1).BotFather is the. Bot factory. It will help you create a new bot and change it’s settings.

After the /start command you’ll see the help list (image2).

Advanced (optional)

Reopen the chat and type /help

Click on (or type) /setuserpic to upload a picture for your bot.Click on (or type) /setabouttext to set the About section for your bot: People will see this text on the bot’s profile page and it will be sent together with a link to your bot when they share it with someone.

Click on (or type) /setdescription to set a description section for your bot. People will see this description when they open a chat with your bot, in a block titled ‘What can this bot do?’

Step 4: Modify, Upload, and Test the Sketch

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

It’s time to upload the software to the Arduino MKR WiFi 1010 board.

Download the attached sketch and unzip it, please don’t change names and folders unless you know what you are doing.

Modify

Open the sketch, we need to fill some information (image1),

Goto to the arduino_secrets.h tab:

Upload

Make sure the board is correct (image2) in the ide and connected then try compile the code. If the compilation goes well, upload it to the board, it will take only few seconds.

In case of problems check for a typo and retry.

Test

[IMPORTANT!] The sketch sends logs to the IDE. The processor has a native USB port (like Leonardo boards). Once powered on, the code will wait until the serial monitor is running. So, let it connected to the PC and open the serial monitor. Arduino will first connect to internet, then it will start polling the Telegram server for new messages (image3).

Now open Telegram on your preferred device and, in the search box, type the name of your bot (not the username that ends with ‘bot’). Open a chat with it.

You are done with the test, if something is not working, check the infomations entered in the sketch (name, username, token. )

Certificates If you are experiencing errors with the connection to the telegram server (log: Bot not connected):

Use of Motion Sensor With RaspberryPi and Telegram Bot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Introduction: Use of Motion Sensor With RaspberryPi and Telegram Bot

In this post we are going to be using Raspberry Pi Telegram Bot with PIR(motion) sensor.

Step 1: Connect PIR

I had a PIR sensor before and I wanted to use my PIR sensor with Raspberry Pi. I followed a guide here is the link : https://www.raspberrypi.org/learning/parent-detector/worksheet/»

Step 2: How to Create a Telegram Bot

Click this link for “How to create a Telegram Bot”

Creating a new bot
Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot. The name of your bot is displayed in contact details and elsewhere. The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API.

Generating an authorization token If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Telegram Bot Library

Host a Telegram Bot on your Arduino and chat with your brand new IoT device!

Learn how to use the Telegram Bot library, host a Telegram Bot on your Arduino/Genuino Board, and use the messaging app to interact with your device.

Step 1 (TelegramBot Library)

Download TelegramBot Library ( Download ).

Step 2 (ArduinoJson & WiFi101 Library)

Install ArduinoJson & WiFi101 Library from Library Manager.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 1 (Create a new TelegramBot )

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The Name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Now that we have our new bot we can set it to do what we want.

In this example we will make it turn on and off a LED by texting him a simple ‘On or Off’ message.

Let’s see in action

Notes about the groups

You can also create your own list of commands using /setcommands while chatting with the BotFather. This list will appear only in the mobile view, pressing the «/» icon.

Telegram Bot Library

Host a Telegram Bot on your Arduino and chat with your brand new IoT device!

Learn how to use the Telegram Bot library, host a Telegram Bot on your Arduino/Genuino Board, and use the messaging app to interact with your device.

Step 1 (TelegramBot Library)

Download TelegramBot Library ( Download ).

Step 2 (ArduinoJson & WiFi101 Library)

Install ArduinoJson & WiFi101 Library from Library Manager.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 1 (Create a new TelegramBot )

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The Name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Now that we have our new bot we can set it to do what we want.

In this example we will make it turn on and off a LED by texting him a simple ‘On or Off’ message.

Let’s see in action

Notes about the groups

You can also create your own list of commands using /setcommands while chatting with the BotFather. This list will appear only in the mobile view, pressing the «/» icon.

I am a freelancer working at Origami IT Lab and I usually get most of my gigs from Freelancer.com

Now for those who don’t have any idea about Freelancer, it provides a platform for the employer to post jobs and freelancers like me to get jobs. The process to find a job is fairly simple, you just have to bid on a job you like, if the employer liked your bid they will connect with you and afterwards award you the project after evaluation among other bidders.

A bid usually consists of 3 parts — Bid Amount, Description and Duration, all three are equally important. So in order to get a job awarded, you must bid with the best price, and duration and provide a good writeup on how you would complete the job. You can refer to the Writing a Winning Bid article by Freelancer in order to gain more perspective.

Problem Statement: Even with all the above things done right you may not get awarded, worst you may even not get considered. You may ask why? and the answer is the huge number of bids (manual + automatic) a job receives. For a scraping project for example an employer might receive 50–100 bids and it’s a fact that most of the bids go unnoticed. The employer usually selects from the top 20 bids and the top 20 here means those who have applied as soon as the job was posted not those who actually match the skillset and commitment.

Today there are a lot of bots working and to compete with them on the timing is very hard. So I wanted something that can bid on my behalf even when I am sleeping or doing some other jobs. And thats where I started looking out for solutions

Solution: Create a bot that will post bids on your behalf. Using bots will increase the chances the employer will view/consider your bid. And might initiate a contact. So the success rate increases once an employer contacts you. Refer to the below image —

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Freelancer-Telegram Bot Workflow

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

I have selected “Scraping” as a skill for which I would like to bid, as I have 6+ years of experience in scraping so I am confident that any job related to scraping I will be able to complete.

Anatomy of a Bid

As you might have figured that “bid” is the most crucial step in getting the job. So bid consists of 3 parts

My Automated Bid

In our automated bid, we need to have all the above parameters. I have made some assumptions for my auto bid.

★★★ Scrapping / Python / Selenium Expert ★★★ 6+ Years of Experience ★★★

Please allow me to generate a few sample entries in order to gain your trust and satisfaction. I have reviewed your project requirements closely and can help you with this. We can discuss also the complexity of the project so I can provide you with a realistic ETA and feel free to contact me through chat to talk about your project in more detail.

I have extensive knowledge of web scrapping with Python,scrapy, BeautifulSoup, Selenium. My extensive experience with web scraping using IP proxy rotation, multi thread and Bypassing captcha. You can see my past work on freelancer and on github.

I’ll be glad to discuss project before start so let’s chat.

Sorry the username must end in bot e g tetris bot or tetrisbot

Copy raw contents

Telegram bot in OpenShift

This is a template to host in OpenShift a Python 3 Telegram bot using Flask. Build over aaossa/flask-openshift

Running on OpenShift

Create a Python application with this command

If you want to use Python 3.5, I recommend this custom cartridge. You can create your app with this command

If you’re interested in create your own app, you can use my template to create your own with just one command

Register your bot

To create a bot, you have to talk to @BotFather and follow this guide (is official). As a recomendation, learn everything you can about Telegram bots in their documentation. Anyway, this is the important part:

Create a new bot

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

Now we must set some environment variables in openshift:

TELEGRAM_BOT_USERNAME : Used to detect mentions to your bot.

TELEGRAM_TOKEN : Is our authorization to use the Bot API

Once we do this, we must restart the app (you could do this via web too):

If this does not work then try using rhc app stop

and then rhc app start

Recomended: Use the Python 3.6 secrets module to create a random and secret url. I made a secrets implementation in case you want to use it.

Connect OpenShift with Telegram

Now our bot is registered (in Telegram) and is ready to answer our commands (in OpenShift), but our messages to the bot are not sent to OpenShift, we must set the (webhook) url that Telegram will use to communicate with our OpenShift application.

We must use the setWebhook method. Is simpole, is a GET request, so you can do this in your browser or using cURL:

Make Your IoT Cloud Kit Send You Updates on Telegram © GPL3+

Read, monitor and get notified about environmental data using Arduino MKR(s), the Environmental Shield, and MKR Relay Proto Shield.

Note: This tutorial could be outdated, please go here for a more current version.

Wow! Let’s start toying the boards.

Create a New TelegramBot Using BotFather

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot. The Name of your bot will be displayed in contact details and elsewhere. The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Since this code relies on another Wifi Library, we’ll have to change the

Or even add this magic piece of code that would make the Arduino IDE call which of the two libraries based on the target board specified.

Now, if you updated the WiFi SSID and password, together with a valid bot token you should be replied with your latest message. Let’s add the data.

Important! In order to make the BOT talking to you (and just to you!) you need to sort out you chat_id (the number that Telegram assigns to the conversation between you and your BOT)

You can discover this by adding this string to the HandleNewMessages function.

Keep this code for you, and add it in the final code as Mychat_id String defined at the beginning of the sketch.

Environmental Data in the Replies

We are going to create a string that will be sent as an answer. We are going to store all the important information in the data string.

Adding the Relays

The MKR Relay Proto Shield has two relays on pin 1 and 2. We are going to add them. I have adapted this needs to a very powerful conversational UI example made by Giancarlo Bacchio and Brian Lough for the Universal Telegram Bot Library

Feel free to change bot_name to match the name of your real bot! Have fun!

Telegram Bot Library

Host a Telegram Bot on your Arduino and chat with your brand new IoT device!

Learn how to use the Telegram Bot library, host a Telegram Bot on your Arduino/Genuino Board, and use the messaging app to interact with your device.

Step 1 (TelegramBot Library)

Download TelegramBot Library ( Download ).

Step 2 (ArduinoJson & WiFi101 Library)

Install ArduinoJson & WiFi101 Library from Library Manager.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 1 (Create a new TelegramBot )

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The Name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Now that we have our new bot we can set it to do what we want.

In this example we will make it turn on and off a LED by texting him a simple ‘On or Off’ message.

Let’s see in action

Notes about the groups

You can also create your own list of commands using /setcommands while chatting with the BotFather. This list will appear only in the mobile view, pressing the «/» icon.

How to Create Telegram Bot in Python

A step-by-step guide to deploying a bot locally that handles private and group messages

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

The topic for today is setting up your own bot in Telegram and deploying it locally via a method called polling. This means you can develop and test your bot in your server, as long as it is connected to the internet. https is not required for this, which allows you to kickstart your project right away. You can always scale your project later by configuring your server with https and linking it to Telegram via a webhook.

In this article, you will learn to:

At the time of writing, there are a few different Python packages and interfaces for the Telegram Bot API. In this tutorial, I’m going to use a Python package called pyTelegramBotAPI. According to the official documentation, it is:

“… a simple, but extensible Python implementation for the Telegram Bot API.”

Let’s proceed to the first section and start installing the necessary modules.

1. Setup

Make sure you have installed Telegram on your phone. We’re going to create our bot directly inside Telegram by interacting with BotFather bot. This is the official bot created by Telegram to facilitate bot creation.

Searching BotFather

Open Telegram on your phone and click on the search button at the top right of the main interface. Then, type botfather in the search bar. You should see the following user interface.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Interacting with BotFather

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

You should see the following prompts which ask for the name and username of your bot.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Privacy in group chat

If you intend to use your bot inside a Telegram group, you need to understand how privacy works in Telegram. By default, the bot will not receive all the messages in a group chat. Based on the official documentation, it will only receive:

Generally, Telegram recommends using commands for interacting with bots. In the event where there are multiple bots in the same group, you can post-fix their usernames at the back of each command to prevent confusion. Please note that you need to process and handle it on your own in your server:

In the latest version, the @ symbol can be used when creating inline bots — where users can interact with your bot via inline queries without sending a message. However, one major downside is that you will lose the flexibility to provide any dynamic input, like this:

Configuring bot to access all messages in group chat

You may prefer to use the old convention, where the bot only responds when it’s tagged with the @ symbol:

If so, you need to turn off the group privacy setting or make it as an admin (not recommended) to allow it to access all messages.

To do so, send the following message to BotFather :

It will list out all the bots that you have. Since I have only created one bot, only one selection is available.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

You should see a few options related to the group. Click on the Group Privacy button.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Disable the group privacy setting by clicking on the Turn off button. Your bot will now have access to messages sent in group chats. If your bot is already in a group, the new changes might not be reflected or propagated. If you experience an issue with it, just remove it from the group and add it back to the group again.

Adding a bot to group chat

There are quite a few ways to add a bot to group chat. The easiest method is to just do it directly from Telegram. Search for your bot and click on the Start button to initiate a conversation with it. Next, click the name of the bot which is located at the top bar.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

You should see the following interface. Continue by clicking on the triple dots at the top right of the interface.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

A popup will appear with the following options. Tap the Add to group selection.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Select the desired group and confirm the addition. Head back to the group and check the setting to make sure that your bot has access to group messages.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Installing Python packages

We’re done with the Telegram setup, now let’s install the required Python packages for this tutorial. Before that, make sure you’ve created a virtual environment. Activate it and run the following command in your terminal.

You can easily verify if you have installed the package by running the following:

The following text will be output to the console:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Once you have finished the installation, move to the next section and start writing Python code.

2. Implementation

Create a new Python file in your working directory. For simplicity, I’m going to name it testbot.py (modify the name accordingly).

Importing the module

Add the following import statement at the top of the file:

Instantiating a new instance

Instantiate a new TeleBot instance by passing in the Telegram token that we created earlier:

Formatting text

Please be noted that you cannot combine both types of formatting in your messages. Setting the parse_mode during instance creation will propagate the formatting to all returned responses. Should a need to send messages with different formatting arise, it’s recommended to set it to None during instance creation and pass the parse_mode parameter when sending individual messages.

Handling incoming messages

Let’s create a new message handler which represents a set of filters for incoming messages. If a message passes the filter, it will call the decorated functions with the original message as the parameter. At the time of writing, it comes with the following filters:

Here is a simple message handler that handles /start commands. /start will be called automatically when a user interacts with the bot for the first time after clicking on the Start button. Commands refer to messages that start with the / sign.

Continue by adding another message handler that instead uses the func filter below the code. You can define your own lambda function in which messages will be handled by this decorated function as it is passed the criteria. I’m going to set the return as True since I want to handle all incoming messages.

Then, call the reply_to function which accepts two parameters:

Let’s set it to message.text to echo the same text back to the user.

Please note that message handlers are tested based on the order that they’re declared. A bot will return a response from the first matching message handler. Be sure to place message handlers with high priority, such as commands, at the top of the order.

Polling

Now, let’s add a final touch to our file with the following code:

polling creates a new thread that calls an internal function to retrieve updates automatically and pass the messages to your message handlers.

It’s a blocking function which means that codes below it will not be executed. Make sure to place it at the end of your file. Also, do not call it more than once, or an error will occur. If you are looking to scale your project, use a webhook instead. Running multiple polling servers will not work!

The polling function accepts the following parameters:

You can find the complete code in the following Gist:

Running Your Server

Make sure the terminal is now pointing at the working directory where your Python file is located. Make sure that your machine is connected to the internet. Run the following command to start polling, modifying the name as required:

Head back to Telegram and start chatting with your bot. You should get a reply whenever you send a message privately, or in a group where your bot is a member:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Differentiating Private and Group Messages

You can easily distinguish private incoming messages from group ones by checking the message.chat.type variable. The available options are as follows:

Let’s modify the handle_all_message functions with the following control flow:

Re-run your polling service again and you should get a different response when sending a message to a group.

Replying Only When Tagged

Now, we have a new problem: Our bot will respond to every single message in the chat if you have set it to be admin or have disabled the privacy setting. In order to resolve this, set another condition that limits the reply if and only if the bot is tagged in the message. Replace username_of_your_bot with the username that you’ve set:

Handling Other Content Types

For now, our bot is only capable of replying to text messages. It will not work properly when the users send a file or sticker. You can create a new message handler and specify the accepted content_types in a list. The following code illustrates how you can echo the same sticker back to users:

Re-run your server and you should see the something like this when you send a sticker to your bot:

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Conclusion

Congratulations on completing this tutorial! Let’s recap what we’ve learned today.

After that, we moved on to instantiate a new TeleBot instance based on the token that we obtained early from the bot creation. We implemented a few message handlers to handle commands and all the incoming messages.

Apart from that, we also learned to distinguish between private and group messages. We can easily handle stickers by specifying the accepted content_types in our message handlers.

By now, you should be able to create your own Telegram bot locally in your machine, as long as it’s connected to the internet.

Thanks for reading this article — I hope to see you again in the next one!

Telegram Bot Library

Host a Telegram Bot on your Arduino and chat with your brand new IoT device!

Learn how to use the Telegram Bot library, host a Telegram Bot on your Arduino/Genuino Board, and use the messaging app to interact with your device.

Step 1 (TelegramBot Library)

Download TelegramBot Library ( Download ).

Step 2 (ArduinoJson & WiFi101 Library)

Install ArduinoJson & WiFi101 Library from Library Manager.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 1 (Create a new TelegramBot )

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The Name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Now that we have our new bot we can set it to do what we want.

In this example we will make it turn on and off a LED by texting him a simple ‘On or Off’ message.

Let’s see in action

Notes about the groups

You can also create your own list of commands using /setcommands while chatting with the BotFather. This list will appear only in the mobile view, pressing the «/» icon.

Telegram Bot Library

Host a Telegram Bot on your Arduino and chat with your brand new IoT device!

Learn how to use the Telegram Bot library, host a Telegram Bot on your Arduino/Genuino Board, and use the messaging app to interact with your device.

Step 1 (TelegramBot Library)

Download TelegramBot Library ( Download ).

Step 2 (ArduinoJson & WiFi101 Library)

Install ArduinoJson & WiFi101 Library from Library Manager.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Step 1 (Create a new TelegramBot )

Be sure you have installed Telegram on your phone or your laptop, then, in the search bar, look for @botfather.

Talk to him and use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The Name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

Now that we have our new bot we can set it to do what we want.

In this example we will make it turn on and off a LED by texting him a simple ‘On or Off’ message.

Let’s see in action

Notes about the groups

You can also create your own list of commands using /setcommands while chatting with the BotFather. This list will appear only in the mobile view, pressing the «/» icon.

401 Response ERROR!! #168

Comments

MojtabaMonfared commented May 21, 2016

i Runned echo_bot.py But i Getting This Error:

Please Help Me!!

The text was updated successfully, but these errors were encountered:

pevdh commented May 21, 2016 •

MojtabaMonfared commented May 21, 2016

Yes,
Now i getting this:

Bots: An introduction for developers

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to our bot API.

To name just a few things, you could use bots to:

Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.
Forbes Bot, TechCrunch Bot

Integrate with other services. A bot can enrich Telegram chats with content from external services.
Image Bot, GIF bot, IMDB bot, Wiki bot, Music bot (NEW), Youtube bot (NEW)

Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services.
Poll bot, GitHub bot, Markdown bot, Sticker bot (NEW)

Build single- and multiplayer games. A bot can play chess and checkers against you, act as host in quiz games, or even take up the dungeon master’s dice for an RPG.
Trivia bot

Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.
HotOrBot

Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

Messages, commands and requests sent by users are passed to the software running on your servers. Our intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. We call that interface our Bot API.

A detailed description of the Bot API is available on this page »

There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authorization token, head down to the Bot API manual to see what you can teach your bot to do.

You may also like to check out some code examples here »

Telegram bots are unique in many ways — we offer two kinds of keyboards, additional interfaces for default commands and deep linking as well as markdown support and much, much more.

Users can interact with your bot via inline queries straight from the text input field in any chat. All they need to do is start a message with your bot’s username and then type a query.

Having received the query, your bot can return some results. As soon as the user taps one of them, it will be sent to the user’s currently opened chat. This way, people can request content from your bot in any of their chats, groups or channels.

Check out this blog to see a sample inline bot in action. You can also try the @sticker and @music bots to see for yourself.

We’ve also implemented an easy way for your bot to switch between inline and PM modes.

Traditional chat bots can of course be taught to understand human language. But sometimes you want some more formal input from the user — and this is where custom keyboards can become extremely useful.

Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options (see ReplyKeyboardMarkup). Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

We currently support text and emoji for your buttons. Here are some custom keyboard examples:

For more technical information on custom keyboards, please consult the Bot API manual (see sendMessage).

There are times when you’d prefer to do things without sending any messages to the chat. For example, when your user is changing settings or flipping through search results. In such cases you can use Inline Keyboards that are integrated directly into the messages they belong to.

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn’t result in messages sent to the chat. Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

When callback buttons are used, your bot can update its existing messages (or just their keyboards) so that the chat remains tidy. Check out this sample bot to see inline keyboards in action: @music.

Commands present a more flexible way to communicate with your bot. The following syntax may be used:

A command must always start with the ‘/’ symbol and may not be longer than 32 characters. Commands can use latin letters, numbers and underscores. Here are a few examples:

Messages that start with a slash will be always passed to the bot (along with replies to its messages and messages that @mention the bot by username). Telegram apps will:

If multiple bots are in a group, it is possible to add bot usernames to commands in order to avoid confusion:

This is done automatically when commands are selected via the list of suggestions. Please remember that your bot needs to be able to process commands that are followed by its username.

In order to make it easier for users to navigate the bot multiverse, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

Users will see a Start button when they first open a conversation with your bot. Help and Settings links will be available in the menu on the bot’s profile page.

You can use bold, italic or fixed-width text, as well as inline links in your bots’ messages. Telegram clients will render them accordingly.

Bots are frequently added to groups in order to augment communication between human users, e.g. by providing news, notifications from external services or additional search functionality. This is especially true for work-related groups. Now, when you share a group with a bot, you tend to ask yourself “How can I be sure that the little rascal isn’t selling my chat history to my competitors?” The answer is — privacy mode.

A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:

On one hand, this helps some of us sleep better at night (in our tinfoil nightcaps), on the other — it allows the bot developer to save a lot of resources, since they won’t need to process tens of thousands irrelevant messages each day.

Privacy mode is enabled by default for all bots, except bots that were added to the group as admins. It can be disabled, so that the bot will begin receiving all messages like an ordinary user. We only recommend doing this in cases where it is absolutely necessary for your bot to work — users can always see a bot’s current privacy setting in the group members list. In most cases, using the force reply option for the bot’s messages should be more than enough.

Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an auth token to connect the user’s Telegram account to their account on some external service.

Following a link with the start parameter will open a one-on-one conversation with the bot, showing a START button in the place of the input field. If the startgroup parameter is used, the user will be prompted to select a group to add the bot to. As soon as a user confirms the action (presses the START button in their app or selects a group to add the bot to), your bot will receive a message from that user in this format:

PAYLOAD stands for the value of the start or startgroup parameter that was passed in the link.

Some bots need extra data from the user to work properly. For example, knowing the user‘s location helps provide more relevant geo-specific results. The user’s phone number can be very useful for integrations with other services, like banks, etc.

Bots can ask a user for their location and phone number using special buttons. Note that both phone number and location request buttons will only work in private chats.

When these buttons are pressed, Telegram clients will display a confirmation alert that tells the user what’s about to happen.

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot will be displayed in contact details and elsewhere.

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that will be required to authorize the bot and send requests to the Bot API.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

The remaining commands are pretty self-explanatory:

Please note, that it may take a few minutes for changes to take effect.

That’s it for the introduction, you are now definitely ready to proceed to the BOT API MANUAL.

If you’ve got any questions, please check out our Bot FAQ »

natzcam/TetrisBot

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

The algorithm used is mainly based on El-Tetris but implemented in java.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Marathon Mode: Reduce the number of buildup limit and breakdown limit ex: 5/0

This will not make you rank 100 in Tetris Battle. Skilled humans can beat this bot.

[C programming] Resource management system using Telegram Bot

A guide to creating a system resource information messaging system using the Telegram Bot API in C/C++

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Introduction

The increasing popularity of alternative messaging apps like Telegram, Signal, Tox and many others, has led to a rapid development in a variety of aspects in these social platforms. More capabilities have been added in order to stay competitive in the market; APIs have been gradually broadening their features.

This development expansion has given both users and developers a vast range of opportunities to implement their own systems on-top of these APIs.

In this article I will be describing the process of creating a simple telegram bot service using a specialized C/C++ library and systemd services on Linux.

The TgBot-cpp Library

This library gives the programmer a wide variety of classes and functions which communicate with the Telegram API. The library can be found on GitHub, as well as documentation here.

The library consists of 3 modules:

These 3 modules lay the foundation to all Telegram Bots that use this library. The usual process of creating a bot object and binding it to a real Telegram Bot is simple.

Creating a Telegram Bot

As show in the official website here, creating a Telegram Bot does not require any special programming skills. The process is quite simple, and anyone with an active Telegram account can create a number of bots.

As described in the Bot Father section, the first step in creating a Bot is to open a chat with Bot Father — Telegrams specialized Frond-end for creating other bots. Then send the command /newbot ( strings starting with “/” represent commands to be executed by the bots ) to the chat with Bot Father. The third step is to provide the newly created Bot with a display name and a username. After all the above steps have been completed successfully, Bot Father will display general information about the newly created bot.

The most important piece of information regarding your bot is the TOKEN. Only through the token can one access the capabilities of the bot and program specialized software for bot management. The token usually is a string with the following format: :

The important parameters (as listed in the original documentation) for any Telegram Bot are shown below :

System Architecture

Main Goal

The main goal of the program that I will be showing here is to send messages to a particular char in Telegram. The contents of these messages shall be acquired from files within a specific directory. This can be very useful, especially in system administration. In my particular case, I have important information like CPU usage, RAM usage, CPU temperature, etc. which in some extreme situations, needs to be managed, in some sense, directly by me. In order to be notified immediately of a particular circumstance, I need something to act immediately and send that information directly to me. I designed this simple program to make use of the Telegram API and send me information directly to my Telegram account.

Architecture

The architecture of the system is quite simple. I will divide each feature of this system into a specific module. In order to get the needed information from the system, like CPU, RAM etc. I have written other programs/scripts that fetch that particular information, format it and store it in files on the filesystem. This is the information gathering module. The communication module is the program that we will discuss today in this article — the Telegram Bot; It checks the files for new information and sends the new information directly to the chat that I have opened with this Bot. The system manger module here is represented by systemd. I have created a simple service that is responsible for the Telegram Bot and its child processes. Simply said, the design of this system goes something along the lines of:

There are some scripts that are execute and gather information about the system; They write that information into files; The Telegram Bot program will create N processes for each file that needs to be watched. Each process is responsible for one file only ; If a file gets modified, a message will be sent to the recipient using the Telegram Bot API with the modified file contents. All of this will be managed by a systemd service.

In order to make things clear, I would like to conceptually divide the content information from the actual perpetrator which will send messages through the Telegram Bot API. The program responsible for the Telegram Bot will not deal with or manage any files on the filesystem, it will only be allowed to read a particular file and nothing more. This will increases the security of the system overall. The main reason being the low coupling of the module responsible for file management and the module responsible for sending the messages. Another reason I believe increases the level of security is the fact that even if, one day, a particular bug is found in the Telegram API that grants access to the remote executing program, the program itself will not have many features/options that give the attacker any type of advantage over the system.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Figure 1 provides a simple example of how the system architecture will look. In this example there are 5 resources that need to be managed by the system — CPU usage, RAM usage, Network traffic, system temperature and some other resource. There are 5 jobs belonging to the information gathering module which write information to their respective files on the filesystem. The main Telegram Bot process creates 5 child processes to manage each resource file. Each child process is responsible for one file only and it checks its file descriptor every M milliseconds for modifications. If the file has been modified, the contents are sent to the Telegram Bot object shared by all child processes and then sent to a specific chat. If the file has not been modified, the child process does not execute any additional code.

1. Information gathering module

This paragraph is mainly informative and therefore does not dive deep in specifics on how to implement such modules.

This module consists mainly of bash scripts, that are executed at a given interval. the output of these scripts is then piped >> to a file, which later on the Telegram Bot process reads.

You can implement your own information gathering module by again using bash scripts, compiling a program, overwriting files through the network by another machine etc.

2. Communication module

This paragraph describes the design of the communication module, responsible for reading the file contents and sending messages to the appointed chat id.

The main Telegram Bot process will be responsible for the creation of N child processes, which will constantly be checking if their designated file has been modified. On Figure 1 the main Telegram Bot process is represented as a blue square, each child process is a line inside the square which gets information from a specific file on the filesystem. For example, the CPU process reads the cpu.file.txt every M milliseconds and keeps track of the last modified timestamp.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

In order to optimize this service a bit, we can implement an environment variable specific for each child process. This environment variable will contain the value of the last_modified_timestamp of the respective file [in Unix time]. In this way, each child process is self-sufficient and does not rely on anything else for its execution. The environment variable names are shown on Figure 2 in each child process box in green.

[ Note ] In GNU/Linux when a process creates a child process, the child process is “ granted access” to the parent processes’ resources i.e. environment variables. However, the child does not share its environment with its parent.

Once this environment variable has been set, it is then compared to the real-time last_modified_timestamp every M milliseconds.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Figure 3 shows the process of sending the file contents from the cpu.file.txt. After the cpu get info job has written the new content to the file, the modified flag has changed. As this happens, the child process responsible for the cpu file has waited M milliseconds and therefore can go and compare the last_modified_timestamp value, stored in CPU_ENV_VAR with the current modified flag of the file. Because the file was modified within the M millisecond “ sleep” time period of the child process, the two modified values do not match. Therefore, the contents of the file have to be sent to the Telegram Bot object, which is shared among all child processes. After that the Telegram Bot object can call send_message() function and send the new file content to a specific chat [chat_id].

The process of sending the modified file contents with the help of the Telegram Bot object is the same amongst all child processes.

3. System Manager module

This paragraph describes the design of the system manager module, responsible for the creation and termination of any Telegram Bot service here.

The system manager module will be able to create and manage any given Telegram Bot service. This module consists of a give number of telegram bot services — systemd service files located in the /etc/systemd/system/ directory. Each service will have its main process [ ExecStart=] set to the already compiled Telegram Bot executable. The executable will take 2 arguments; the first argument will be the configuration directory that stores the resource files needed to be watched; the second argument will be process verbosity.

Termination of the service and all its subsequent child processes will also be managed through systemd. Because the main parent process will create N number of child processes and then exit [ return 0] this leaves these N child processes in the CGroup of the service. In order to stop the service these child processes need to be stopped/terminated.

[ Note ] If you are not familiar with systemd unit file syntax or need a reminder of how some simple services are created, I encourage you to go read my article [Systemd] simple service examples.

[Code] Communication module

The communication module is separated into 3 files: main.cpp, config.h and config.cpp. As you are familiar with C/C++ the main.cpp file contains the main function; the config.h is the header file and config.cpp is the implementation of the config header. I have decided to use this simple structure in order to contain most of the program within a small number of files, as well as having a clear logical distinction between them.

The basic program logic contains the following functions:

The config.h Header

This header file contains include directives for the required libraries, definitions for length and size of different buffers and variables, and also function declarations.

Inside config.h there is also a structure called directory_files, which includes two variables; _p which is the pointer to an allocated space where the file names of a particular directory are stored; _count which returns the number of files in that particular directory. This structure is used in the return type of the function list_files_in_directory().

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Function declarations include the following functions:

The config.cpp Implementation

The config.cpp file contains implementations of the function definitions from the config.h header file.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Firstly, this functions tries to get the environment variable env_var_name and its value. If this process is not successful, the loop is broken and there is nothing else to do. Therefore the programmer must investigate this issue.

Once the environment variable with the last_modified_timestamp has been gotten, then the function executes get_last_modified_time() onto the file with path _file_path. Then this value gets stored inside a string _last_modified_char. Afterwards the environment variable value and the current last modified time stamp are to be compared. If they differ this means that the file has been modified within the sleep period, therefore a message must be send to chat_id. If they are the same nothing is to be done.

Secondly, the file contents must be acquired. We allocate CONTENT_BUFFER_SIZE amount of space for the contents of the file. Afterwards while the content of the file is being looped over a temporary character stores the current character of the file content in the content buffer. Once the End Of the File has been reached, we append 0x00 to indicate the end of the content buffer. After this procedure has been done, we can close the file.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Thirdly, after the information from the file has been copied to the content buffer, it must be appended inside a message variable of type string. This message variable is later passed to the sendMessage() function by the Telegram Bot object. Sending a message using the Telegram Bot object must be enclosed inside a try..catch.. block because of error prevention. For example, if for some reason the machine that is running this service is not connected to the internet and does not have the possibility to contact the Telegram API, then sending a message will result in an error. We catch 2 types of errors inside this block: 1) a system error and 2) TgException error.

Finally, we clean up all the allocated space for the buffers and flush all the printf statements to stdout and we sleep for 5 seconds. This is the final statement that gets executed before running the loop again from the beginning.

[ Note ] When _flag is set to 1, the print statements get executed, when _flag is set to 0 the print statements are not executed. This is a simple implementation of verbosity management.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

The main.cpp Program

The main.cpp file contains the execution sequence of the designed architecture. The sequence of function execution is broken up into several parts.

Firstly, we pass 2 arguments to the main program: the path to the directory containing the files that are going to be watched by each child process and a verbosity parameter. The directory that is being passed as the 1st argument must be named after the desired chat id to which the Telegram Bot will send the messages. For example /home/user/.config/telegram_bot/123456789/ is a valid path and /home/user/.config/telegram_bot/chatBot100/ is NOT a valid path.

Secondly, before compiling the program, please make sure that the token variable is set to the the desired Telegram Bots’ token. Otherwise, there will be no communication with the Telegram API.

Afterwards the program continues its execution by converting the chat id folder name to a long long integer and storing its value inside the _chat_id variable. Then the files under that specific directory are listed inside the _files directory_files structure.

Consequently, the program enters a for loop looping over the number of files inside the directory. We pass each filename through the function that reduces the passed string value to only a file name without any extensions. Then we get the last_modified_timestamp flag of the current file and create an environment variable with this value.

Finally, a new process is forked for the current file name and assigned the recently created environment variable. From this point on the child process enters the while loop inside the send_message_to_chat() function and the parent process continues looping through the files and spawning child processes.

[ Note ] When looping through the files in the directory_files structure, the increment is not 1, rather than the predefined SIZE_FILE_NAME.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

[ Note ] In order to compile the program correctly, you need to have the TgBot, Boost system, SSL, Cryptography and Threading libraries installed on your system and point the library files to the compiler.

[Code] System Manager module

In the System Manager module we create a simple systemd service that is going to execute our already compiled Telegram Bot executable. The executable has 2 parameters, as we already discussed, these parameters are the directory which stores the resource files and a verbosity flag.

[ Note ] Make sure to have KillMode= set to process. This is not recommended in regular process management, but here this is the simplest solution to stopping the service with just one command.

For more information please visit this link.

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot

In order to stop/kill the service and all its CGroup processes use systemctl kill

Final Results

The final product can be seen on the image below. Here I am showing how to start the Telegram Bot systemd service. This is also a demonstration of the response time of the Telegram Bot system when a particular file get modified.

We can conclude that this resource management system is quite reliable and robust. I hope

Telegram Bot API

The Bot API is an HTTP-based interface created for developers keen on building bots for Telegram.
To learn how to create and set up a bot, please consult our Introduction to Bots and Bot FAQ.

Subscribe to @BotNews to be the first to know about the latest updates and join the discussion in @BotTalk

Bot API 6.2

Custom Emoji Support

Web App Improvements

Other Changes

Bot API 6.1

Media in Descriptions

Web App Improvements

Join Requests & Payments

Telegram Premium Support (more info)

Attachment Menu Integration

Other Changes

Bot API 6.0

Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbotWARNING! Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot
After the next update, only HTTPS links will be allowed in login_url inline keyboard buttons.

Bot API 5.7

We support GET and POST HTTP methods. We support four ways of passing parameters in Bot API requests:

The response contains a JSON object, which always has a Boolean field ‘ok’ and may have an optional String field ‘description’ with a human-readable description of the result. If ‘ok’ equals True, the request was successful and the result of the query can be found in the ‘result’ field. In case of an unsuccessful request, ‘ok’ equals false and the error is explained in the ‘description’. An Integer ‘error_code’ field is also returned, but its contents are subject to change in the future. Some errors may also have an optional field ‘parameters’ of the type ResponseParameters, which can help to automatically handle the error.

If you’re using webhooks, you can perform a request to the Bot API while sending an answer to the webhook. Use either application/json or application/x-www-form-urlencoded or multipart/form-data response content type for passing parameters. Specify the method to be invoked in the method parameter of the request. It’s not possible to know that such a request was successful or get its result.

The majority of bots will be OK with the default configuration, running on our servers. But if you feel that you need one of these features, you’re welcome to switch to your own at any time.

Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

This object represents an incoming update.
At most one of the optional parameters can be present in any given update.

Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.

ParameterTypeRequiredDescription
offsetIntegerOptionalIdentifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
limitIntegerOptionalLimits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.
timeoutIntegerOptionalTimeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
allowed_updatesArray of StringOptionalA JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.

Please note that this parameter doesn’t affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.

Notes
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.

Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.

If you’d like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.

Notes
1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.
2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.
3. Ports currently supported for webhooks: 443, 80, 88, 8443.

If you’re having any trouble setting up webhooks, please check out this amazing guide to webhooks.

Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.

ParameterTypeRequiredDescription
drop_pending_updatesBooleanOptionalPass True to drop all pending updates

Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.

Describes the current status of a webhook.

FieldTypeDescription
urlStringWebhook URL, may be empty if webhook is not set up
has_custom_certificateBooleanTrue, if a custom certificate was provided for webhook certificate checks
pending_update_countIntegerNumber of updates awaiting delivery
ip_addressStringOptional. Currently used webhook IP address
last_error_dateIntegerOptional. Unix time for the most recent error that happened when trying to deliver an update via webhook
last_error_messageStringOptional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
last_synchronization_error_dateIntegerOptional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters
max_connectionsIntegerOptional. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
allowed_updatesArray of StringOptional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member

All types used in the Bot API responses are represented as JSON-objects.

It is safe to use 32-bit signed integers for storing all Integer fields unless otherwise noted.

Optional fields may be not returned when irrelevant.

This object represents a Telegram user or bot.

FieldTypeDescription
idIntegerUnique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
is_botBooleanTrue, if this user is a bot
first_nameStringUser’s or bot’s first name
last_nameStringOptional. User’s or bot’s last name
usernameStringOptional. User’s or bot’s username
language_codeStringOptional. IETF language tag of the user’s language
is_premiumTrueOptional. True, if this user is a Telegram Premium user
added_to_attachment_menuTrueOptional. True, if this user added the bot to the attachment menu
can_join_groupsBooleanOptional. True, if the bot can be invited to groups. Returned only in getMe.
can_read_all_group_messagesBooleanOptional. True, if privacy mode is disabled for the bot. Returned only in getMe.
supports_inline_queriesBooleanOptional. True, if the bot supports inline queries. Returned only in getMe.

This object represents a chat.

FieldTypeDescription
idIntegerUnique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
typeStringType of chat, can be either “private”, “group”, “supergroup” or “channel”
titleStringOptional. Title, for supergroups, channels and group chats
usernameStringOptional. Username, for private chats, supergroups and channels if available
first_nameStringOptional. First name of the other party in a private chat
last_nameStringOptional. Last name of the other party in a private chat
photoChatPhotoOptional. Chat photo. Returned only in getChat.
bioStringOptional. Bio of the other party in a private chat. Returned only in getChat.
has_private_forwardsTrueOptional. True, if privacy settings of the other party in the private chat allows to use tg://user?id= links only in chats with the user. Returned only in getChat.
has_restricted_voice_and_video_messagesTrueOptional. True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat. Returned only in getChat.
join_to_send_messagesTrueOptional. True, if users need to join the supergroup before they can send messages. Returned only in getChat.
join_by_requestTrueOptional. True, if all users directly joining the supergroup need to be approved by supergroup administrators. Returned only in getChat.
descriptionStringOptional. Description, for groups, supergroups and channel chats. Returned only in getChat.
invite_linkStringOptional. Primary invite link, for groups, supergroups and channel chats. Returned only in getChat.
pinned_messageMessageOptional. The most recent pinned message (by sending date). Returned only in getChat.
permissionsChatPermissionsOptional. Default chat member permissions, for groups and supergroups. Returned only in getChat.
slow_mode_delayIntegerOptional. For supergroups, the minimum allowed delay between consecutive messages sent by each unpriviledged user; in seconds. Returned only in getChat.
message_auto_delete_timeIntegerOptional. The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in getChat.
has_protected_contentTrueOptional. True, if messages from the chat can’t be forwarded to other chats. Returned only in getChat.
sticker_set_nameStringOptional. For supergroups, name of group sticker set. Returned only in getChat.
can_set_sticker_setTrueOptional. True, if the bot can change the group sticker set. Returned only in getChat.
linked_chat_idIntegerOptional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier 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. Returned only in getChat.
locationChatLocationOptional. For supergroups, the location to which the supergroup is connected. Returned only in getChat.

This object represents a message.

FieldTypeDescription
message_idIntegerUnique message identifier inside this chat
fromUserOptional. Sender of the message; empty for messages sent to channels. For backward compatibility, the field contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
sender_chatChatOptional. 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, the field from contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
dateIntegerDate the message was sent in Unix time
chatChatConversation the message belongs to
forward_fromUserOptional. For forwarded messages, sender of the original message
forward_from_chatChatOptional. For messages forwarded from channels or from anonymous administrators, information about the original sender chat
forward_from_message_idIntegerOptional. For messages forwarded from channels, identifier of the original message in the channel
forward_signatureStringOptional. For forwarded messages that were originally sent in channels or by an anonymous chat administrator, signature of the message sender if present
forward_sender_nameStringOptional. Sender’s name for messages forwarded from users who disallow adding a link to their account in forwarded messages
forward_dateIntegerOptional. For forwarded messages, date the original message was sent in Unix time
is_automatic_forwardTrueOptional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
reply_to_messageMessageOptional. 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.
via_botUserOptional. Bot through which the message was sent
edit_dateIntegerOptional. Date the message was last edited in Unix time
has_protected_contentTrueOptional. True, if the message can’t be forwarded
media_group_idStringOptional. The unique identifier of a media message group this message belongs to
author_signatureStringOptional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator
textStringOptional. For text messages, the actual UTF-8 text of the message
entitiesArray of MessageEntityOptional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
animationAnimationOptional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set
audioAudioOptional. Message is an audio file, information about the file
documentDocumentOptional. Message is a general file, information about the file
photoArray of PhotoSizeOptional. Message is a photo, available sizes of the photo
stickerStickerOptional. Message is a sticker, information about the sticker
videoVideoOptional. Message is a video, information about the video
video_noteVideoNoteOptional. Message is a video note, information about the video message
voiceVoiceOptional. Message is a voice message, information about the file
captionStringOptional. Caption for the animation, audio, document, photo, video or voice
caption_entitiesArray of MessageEntityOptional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
contactContactOptional. Message is a shared contact, information about the contact
diceDiceOptional. Message is a dice with random value
gameGameOptional. Message is a game, information about the game. More about games »
pollPollOptional. Message is a native poll, information about the poll
venueVenueOptional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set
locationLocationOptional. Message is a shared location, information about the location
new_chat_membersArray of UserOptional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)
left_chat_memberUserOptional. A member was removed from the group, information about them (this member may be the bot itself)
new_chat_titleStringOptional. A chat title was changed to this value
new_chat_photoArray of PhotoSizeOptional. A chat photo was change to this value
delete_chat_photoTrueOptional. Service message: the chat photo was deleted
group_chat_createdTrueOptional. Service message: the group has been created
supergroup_chat_createdTrueOptional. 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_createdTrueOptional. 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_changedMessageAutoDeleteTimerChangedOptional. Service message: auto-delete timer settings changed in the chat
migrate_to_chat_idIntegerOptional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
migrate_from_chat_idIntegerOptional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
pinned_messageMessageOptional. 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.
invoiceInvoiceOptional. Message is an invoice for a payment, information about the invoice. More about payments »
successful_paymentSuccessfulPaymentOptional. Message is a service message about a successful payment, information about the payment. More about payments »
connected_websiteStringOptional. The domain name of the website on which the user has logged in. More about Telegram Login »
passport_dataPassportDataOptional. Telegram Passport data
proximity_alert_triggeredProximityAlertTriggeredOptional. Service message. A user in the chat triggered another user’s proximity alert while sharing Live Location.
video_chat_scheduledVideoChatScheduledOptional. Service message: video chat scheduled
video_chat_startedVideoChatStartedOptional. Service message: video chat started
video_chat_endedVideoChatEndedOptional. Service message: video chat ended
video_chat_participants_invitedVideoChatParticipantsInvitedOptional. Service message: new participants invited to a video chat
web_app_dataWebAppDataOptional. Service message: data sent by a Web App
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.

This object represents a unique message identifier.

FieldTypeDescription
message_idIntegerUnique message identifier

This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

This object represents one size of a photo or a file / sticker thumbnail.

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
widthIntegerPhoto width
heightIntegerPhoto height
file_sizeIntegerOptional. File size in bytes

This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
widthIntegerVideo width as defined by sender
heightIntegerVideo height as defined by sender
durationIntegerDuration of the video in seconds as defined by sender
thumbPhotoSizeOptional. Animation thumbnail as defined by sender
file_nameStringOptional. Original animation filename as defined by sender
mime_typeStringOptional. MIME type of the file as defined by sender
file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.

This object represents an audio file to be treated as music by the Telegram clients.

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
durationIntegerDuration of the audio in seconds as defined by sender
performerStringOptional. Performer of the audio as defined by sender or by audio tags
titleStringOptional. Title of the audio as defined by sender or by audio tags
file_nameStringOptional. Original filename as defined by sender
mime_typeStringOptional. MIME type of the file as defined by sender
file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
thumbPhotoSizeOptional. Thumbnail of the album cover to which the music file belongs

This object represents a general file (as opposed to photos, voice messages and audio files).

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
thumbPhotoSizeOptional. Document thumbnail as defined by sender
file_nameStringOptional. Original filename as defined by sender
mime_typeStringOptional. MIME type of the file as defined by sender
file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.

This object represents a video file.

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
widthIntegerVideo width as defined by sender
heightIntegerVideo height as defined by sender
durationIntegerDuration of the video in seconds as defined by sender
thumbPhotoSizeOptional. Video thumbnail
file_nameStringOptional. Original filename as defined by sender
mime_typeStringOptional. MIME type of the file as defined by sender
file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.

This object represents a video message (available in Telegram apps as of v.4.0).

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
lengthIntegerVideo width and height (diameter of the video message) as defined by sender
durationIntegerDuration of the video in seconds as defined by sender
thumbPhotoSizeOptional. Video thumbnail
file_sizeIntegerOptional. File size in bytes

This object represents a voice note.

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
durationIntegerDuration of the audio in seconds as defined by sender
mime_typeStringOptional. MIME type of the file as defined by sender
file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.

This object represents a phone contact.

FieldTypeDescription
phone_numberStringContact’s phone number
first_nameStringContact’s first name
last_nameStringOptional. Contact’s last name
user_idIntegerOptional. Contact’s user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
vcardStringOptional. Additional data about the contact in the form of a vCard

This object represents an animated emoji that displays a random value.

FieldTypeDescription
emojiStringEmoji on which the dice throw animation is based
valueIntegerValue of the dice, 1-6 for “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” and “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” base emoji, 1-5 for “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” and “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” base emoji, 1-64 for “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” base emoji

This object contains information about one answer option in a poll.

FieldTypeDescription
textStringOption text, 1-100 characters
voter_countIntegerNumber of users that voted for this option

This object represents an answer of a user in a non-anonymous poll.

FieldTypeDescription
poll_idStringUnique poll identifier
userUserThe user, who changed the answer to the poll
option_idsArray of Integer0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote.

This object contains information about a poll.

FieldTypeDescription
idStringUnique poll identifier
questionStringPoll question, 1-300 characters
optionsArray of PollOptionList of poll options
total_voter_countIntegerTotal number of users that voted in the poll
is_closedBooleanTrue, if the poll is closed
is_anonymousBooleanTrue, if the poll is anonymous
typeStringPoll type, currently can be “regular” or “quiz”
allows_multiple_answersBooleanTrue, if the poll allows multiple answers
correct_option_idIntegerOptional. 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot.
explanationStringOptional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters
explanation_entitiesArray of MessageEntityOptional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation
open_periodIntegerOptional. Amount of time in seconds the poll will be active after creation
close_dateIntegerOptional. Point in time (Unix timestamp) when the poll will be automatically closed

This object represents a point on the map.

FieldTypeDescription
longitudeFloatLongitude as defined by sender
latitudeFloatLatitude as defined by sender
horizontal_accuracyFloat numberOptional. The radius of uncertainty for the location, measured in meters; 0-1500
live_periodIntegerOptional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only.
headingIntegerOptional. The direction in which user is moving, in degrees; 1-360. For active live locations only.
proximity_alert_radiusIntegerOptional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.

This object represents a venue.

FieldTypeDescription
locationLocationVenue location. Can’t be a live location
titleStringName of the venue
addressStringAddress of the venue
foursquare_idStringOptional. Foursquare identifier of the venue
foursquare_typeStringOptional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
google_place_idStringOptional. Google Places identifier of the venue
google_place_typeStringOptional. Google Places type of the venue. (See supported types.)

Describes data sent from a Web App to the bot.

FieldTypeDescription
dataStringThe data. Be aware that a bad client can send arbitrary data in this field.
button_textStringText of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field.

This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.

FieldTypeDescription
travelerUserUser that triggered the alert
watcherUserUser that set the alert
distanceIntegerThe distance between the users

This object represents a service message about a change in auto-delete timer settings.

FieldTypeDescription
message_auto_delete_timeIntegerNew auto-delete time for messages in the chat; in seconds

This object represents a service message about a video chat scheduled in the chat.

FieldTypeDescription
start_dateIntegerPoint in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator

This object represents a service message about a video chat started in the chat. Currently holds no information.

This object represents a service message about a video chat ended in the chat.

FieldTypeDescription
durationIntegerVideo chat duration in seconds

This object represents a service message about new members invited to a video chat.

FieldTypeDescription
usersArray of UserNew members that were invited to the video chat

This object represent a user’s profile pictures.

FieldTypeDescription
total_countIntegerTotal number of profile pictures the target user has
photosArray of Array of PhotoSizeRequested profile pictures (in up to 4 sizes each)

The maximum file size to download is 20 MB

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
file_pathStringOptional. File path. Use https://api.telegram.org/file/bot / to get the file.
FieldTypeDescription
urlStringAn HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps

This object represents a custom keyboard with reply options (see Introduction to bots for details and examples).

Example: A user requests to change the bot’s language, bot replies to the request with a keyboard to select the new language. Other users in the group don’t see the keyboard.

This object represents one button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields web_app, request_contact, request_location, and request_poll are mutually exclusive.

FieldTypeDescription
textStringText of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed
request_contactBooleanOptional. If True, the user’s phone number will be sent as a contact when the button is pressed. Available in private chats only.
request_locationBooleanOptional. If True, the user’s current location will be sent when the button is pressed. Available in private chats only.
request_pollKeyboardButtonPollTypeOptional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only.
web_appWebAppInfoOptional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.

Note: request_contact and request_location options will only work in Telegram versions released after 9 April, 2016. Older clients will display unsupported message.
Note: request_poll option will only work in Telegram versions released after 23 January, 2020. Older clients will display unsupported message.
Note: web_app option will only work in Telegram versions released after 16 April, 2022. Older clients will display unsupported message.

This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.

FieldTypeDescription
typeStringOptional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.

Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup).

FieldTypeDescription
remove_keyboardTrueRequests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup)
selectiveBooleanOptional. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot’s message is a reply (has reply_to_message_id), sender of the original message.

Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven’t voted yet.

This object represents an inline keyboard that appears right next to the message it belongs to.

FieldTypeDescription
inline_keyboardArray of Array of InlineKeyboardButtonArray of button rows, each represented by an Array of InlineKeyboardButton objects

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will display unsupported message.

This object represents one button of an inline keyboard. You must use exactly one of the optional fields.

FieldTypeDescription
textStringLabel text on the button
urlStringOptional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.
callback_dataStringOptional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
web_appWebAppInfoOptional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot.
login_urlLoginUrlOptional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.
switch_inline_queryStringOptional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field. May be empty, in which case just the bot’s username will be inserted.

NOTE: This type of button must always be the first button in the first row.

payBooleanOptional. Specify True, to send a Pay button.

NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages.

This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in:

Telegram apps support these buttons as of version 5.7.

FieldTypeDescription
urlStringAn HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.

NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization.forward_textStringOptional. New text of the button in forwarded messages.bot_usernameStringOptional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot’s username will be assumed. The url‘s domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details.request_write_accessBooleanOptional. Pass True to request the permission for your bot to send messages to the user.

This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.

FieldTypeDescription
idStringUnique identifier for this query
fromUserSender
messageMessageOptional. Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old
inline_message_idStringOptional. Identifier of the message sent via the bot in inline mode, that originated the query.
chat_instanceStringGlobal identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.
dataStringOptional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data.
game_short_nameStringOptional. Short name of a Game to be returned, serves as the unique identifier for the game

NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters).

Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot’s message and tapped ‘Reply’). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.

FieldTypeDescription
force_replyTrueShows reply interface to the user, as if they manually selected the bot’s message and tapped ‘Reply’
input_field_placeholderStringOptional. The placeholder to be shown in the input field when the reply is active; 1-64 characters
selectiveBooleanOptional. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot’s message is a reply (has reply_to_message_id), sender of the original message.

Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:

This object represents a chat photo.

FieldTypeDescription
small_file_idStringFile identifier of small (160×160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
small_file_unique_idStringUnique file identifier of small (160×160) chat photo, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
big_file_idStringFile identifier of big (640×640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
big_file_unique_idStringUnique file identifier of big (640×640) chat photo, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.

Represents an invite link for a chat.

FieldTypeDescription
invite_linkStringThe invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”.
creatorUserCreator of the link
creates_join_requestBooleanTrue, if users joining the chat via the link need to be approved by chat administrators
is_primaryBooleanTrue, if the link is primary
is_revokedBooleanTrue, if the link is revoked
nameStringOptional. Invite link name
expire_dateIntegerOptional. Point in time (Unix timestamp) when the link will expire or has been expired
member_limitIntegerOptional. The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
pending_join_request_countIntegerOptional. Number of pending join requests created using this link

Represents the rights of an administrator in a chat.

FieldTypeDescription
is_anonymousBooleanTrue, if the user’s presence in the chat is hidden
can_manage_chatBooleanTrue, if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege
can_delete_messagesBooleanTrue, if the administrator can delete messages of other users
can_manage_video_chatsBooleanTrue, if the administrator can manage video chats
can_restrict_membersBooleanTrue, if the administrator can restrict, ban or unban chat members
can_promote_membersBooleanTrue, if the administrator can add new administrators with a subset of their own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user)
can_change_infoBooleanTrue, if the user is allowed to change the chat title, photo and other settings
can_invite_usersBooleanTrue, if the user is allowed to invite new users to the chat
can_post_messagesBooleanOptional. True, if the administrator can post in the channel; channels only
can_edit_messagesBooleanOptional. True, if the administrator can edit messages of other users and can pin messages; channels only
can_pin_messagesBooleanOptional. True, if the user is allowed to pin messages; groups and supergroups only

This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:

Represents a chat member that owns the chat and has all administrator privileges.

FieldTypeDescription
statusStringThe member’s status in the chat, always “creator”
userUserInformation about the user
is_anonymousBooleanTrue, if the user’s presence in the chat is hidden
custom_titleStringOptional. Custom title for this user

Represents a chat member that has some additional privileges.

FieldTypeDescription
statusStringThe member’s status in the chat, always “administrator”
userUserInformation about the user
can_be_editedBooleanTrue, if the bot is allowed to edit administrator privileges of that user
is_anonymousBooleanTrue, if the user’s presence in the chat is hidden
can_manage_chatBooleanTrue, if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege
can_delete_messagesBooleanTrue, if the administrator can delete messages of other users
can_manage_video_chatsBooleanTrue, if the administrator can manage video chats
can_restrict_membersBooleanTrue, if the administrator can restrict, ban or unban chat members
can_promote_membersBooleanTrue, if the administrator can add new administrators with a subset of their own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user)
can_change_infoBooleanTrue, if the user is allowed to change the chat title, photo and other settings
can_invite_usersBooleanTrue, if the user is allowed to invite new users to the chat
can_post_messagesBooleanOptional. True, if the administrator can post in the channel; channels only
can_edit_messagesBooleanOptional. True, if the administrator can edit messages of other users and can pin messages; channels only
can_pin_messagesBooleanOptional. True, if the user is allowed to pin messages; groups and supergroups only
custom_titleStringOptional. Custom title for this user

Represents a chat member that has no additional privileges or restrictions.

FieldTypeDescription
statusStringThe member’s status in the chat, always “member”
userUserInformation about the user

Represents a chat member that is under certain restrictions in the chat. Supergroups only.

FieldTypeDescription
statusStringThe member’s status in the chat, always “restricted”
userUserInformation about the user
is_memberBooleanTrue, if the user is a member of the chat at the moment of the request
can_change_infoBooleanTrue, if the user is allowed to change the chat title, photo and other settings
can_invite_usersBooleanTrue, if the user is allowed to invite new users to the chat
can_pin_messagesBooleanTrue, if the user is allowed to pin messages
can_send_messagesBooleanTrue, if the user is allowed to send text messages, contacts, locations and venues
can_send_media_messagesBooleanTrue, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes
can_send_pollsBooleanTrue, if the user is allowed to send polls
can_send_other_messagesBooleanTrue, if the user is allowed to send animations, games, stickers and use inline bots
can_add_web_page_previewsBooleanTrue, if the user is allowed to add web page previews to their messages
until_dateIntegerDate when restrictions will be lifted for this user; unix time. If 0, then the user is restricted forever

Represents a chat member that isn’t currently a member of the chat, but may join it themselves.

FieldTypeDescription
statusStringThe member’s status in the chat, always “left”
userUserInformation about the user

Represents a chat member that was banned in the chat and can’t return to the chat or view chat messages.

FieldTypeDescription
statusStringThe member’s status in the chat, always “kicked”
userUserInformation about the user
until_dateIntegerDate when restrictions will be lifted for this user; unix time. If 0, then the user is banned forever

This object represents changes in the status of a chat member.

FieldTypeDescription
chatChatChat the user belongs to
fromUserPerformer of the action, which resulted in the change
dateIntegerDate the change was done in Unix time
old_chat_memberChatMemberPrevious information about the chat member
new_chat_memberChatMemberNew information about the chat member
invite_linkChatInviteLinkOptional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only.

Represents a join request sent to a chat.

FieldTypeDescription
chatChatChat to which the request was sent
fromUserUser that sent the join request
dateIntegerDate the request was sent in Unix time
bioStringOptional. Bio of the user.
invite_linkChatInviteLinkOptional. Chat invite link that was used by the user to send the join request

Describes actions that a non-administrator user is allowed to take in a chat.

FieldTypeDescription
can_send_messagesBooleanOptional. True, if the user is allowed to send text messages, contacts, locations and venues
can_send_media_messagesBooleanOptional. True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages
can_send_pollsBooleanOptional. True, if the user is allowed to send polls, implies can_send_messages
can_send_other_messagesBooleanOptional. True, if the user is allowed to send animations, games, stickers and use inline bots, implies can_send_media_messages
can_add_web_page_previewsBooleanOptional. True, if the user is allowed to add web page previews to their messages, implies can_send_media_messages
can_change_infoBooleanOptional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups
can_invite_usersBooleanOptional. True, if the user is allowed to invite new users to the chat
can_pin_messagesBooleanOptional. True, if the user is allowed to pin messages. Ignored in public supergroups

Represents a location to which a chat is connected.

FieldTypeDescription
locationLocationThe location to which the supergroup is connected. Can’t be a live location.
addressStringLocation address; 1-64 characters, as defined by the chat owner

This object represents a bot command.

FieldTypeDescription
commandStringText of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores.
descriptionStringDescription of the command; 1-256 characters.

This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:

The following algorithm is used to determine the list of commands for a particular user viewing the bot menu. The first list of commands which is set is returned:

Commands in the chat with the bot

Commands in group and supergroup chats

Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user.

FieldTypeDescription
typeStringScope type, must be default

Represents the scope of bot commands, covering all private chats.

FieldTypeDescription
typeStringScope type, must be all_private_chats

Represents the scope of bot commands, covering all group and supergroup chats.

FieldTypeDescription
typeStringScope type, must be all_group_chats

Represents the scope of bot commands, covering all group and supergroup chat administrators.

FieldTypeDescription
typeStringScope type, must be all_chat_administrators

Represents the scope of bot commands, covering a specific chat.

FieldTypeDescription
typeStringScope type, must be chat
chat_idInteger or StringUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )

Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.

FieldTypeDescription
typeStringScope type, must be chat_administrators
chat_idInteger or StringUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )

Represents the scope of bot commands, covering a specific member of a group or supergroup chat.

FieldTypeDescription
typeStringScope type, must be chat_member
chat_idInteger or StringUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )
user_idIntegerUnique identifier of the target user

This object describes the bot’s menu button in a private chat. It should be one of

If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands.

Represents a menu button, which opens the bot’s list of commands.

FieldTypeDescription
typeStringType of the button, must be commands

Represents a menu button, which launches a Web App.

FieldTypeDescription
typeStringType of the button, must be web_app
textStringText on the button
web_appWebAppInfoDescription of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery.

Describes that no specific value for the menu button was set.

FieldTypeDescription
typeStringType of the button, must be default

Describes why a request was unsuccessful.

FieldTypeDescription
migrate_to_chat_idIntegerOptional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
retry_afterIntegerOptional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated

This object represents the content of a media message to be sent. It should be one of

Represents a photo to be sent.

FieldTypeDescription
typeStringType of the result, must be photo
mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach:// ” to upload a new one using multipart/form-data under name. More information on Sending Files »
captionStringOptional. Caption of the photo to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the photo caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode

Represents a video to be sent.

Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.

Represents an audio file to be treated as music to be sent.

Represents a general file to be sent.

This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser.

There are three ways to send files (photos, stickers, audio, media, etc.):

Sending by file_id

Sending by URL

Objects and methods used in the inline mode are described in the Inline mode section.

All methods in the Bot API are case-insensitive. We support GET and POST HTTP methods. Use either URL query string or application/json or application/x-www-form-urlencoded or multipart/form-data for passing parameters in Bot API requests.
On successful call, a JSON-object containing the result will be returned.

A simple method for testing your bot’s authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.

Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters.

Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn’t launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters.

Use this method to send text messages. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
textStringYesText of the message to be sent, 1-4096 characters after entities parsing
parse_modeStringOptionalMode for parsing entities in the message text. See formatting options for more details.
entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
disable_web_page_previewBooleanOptionalDisables link previews for links in this message
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

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.

Note that Telegram clients will display an alert to the user before opening an inline link (‘Open this link?’ together with the full URL).

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.

Links tg://user?id= can be used to mention a user by their ID without using a username. Please note:

To use this mode, pass MarkdownV2 in the parse_mode field. Use the following syntax in your message:

To use this mode, pass HTML in the parse_mode field. The following tags are currently supported:

This is a legacy mode, retained for backward compatibility. To use this mode, pass Markdown in the parse_mode field. Use the following syntax in your message:

Use this method to forward messages of any kind. Service messages can’t be forwarded. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
from_chat_idInteger or StringYesUnique identifier for the chat where the original message was sent (or channel username in the format @channelusername )
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the forwarded message from forwarding and saving
message_idIntegerYesMessage identifier in the chat specified in from_chat_id

Use this method to copy messages of any kind. Service messages and invoice messages can’t be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn’t have a link to the original message. Returns the MessageId of the sent message on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
from_chat_idInteger or StringYesUnique identifier for the chat where the original message was sent (or channel username in the format @channelusername )
message_idIntegerYesMessage identifier in the chat specified in from_chat_id
captionStringOptionalNew caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept
parse_modeStringOptionalMode for parsing entities in the new caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

Use this method to send photos. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
photoInputFile or StringYesPhoto to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo’s width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files »
captionStringOptionalPhoto caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing
parse_modeStringOptionalMode for parsing entities in the photo caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

For sending voice messages, use the sendVoice method instead.

Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
voiceInputFile or StringYesAudio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
captionStringOptionalVoice message caption, 0-1024 characters after entities parsing
parse_modeStringOptionalMode for parsing entities in the voice message caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
durationIntegerOptionalDuration of the voice message in seconds
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
mediaArray of InputMediaAudio, InputMediaDocument, InputMediaPhoto and InputMediaVideoYesA JSON-serialized array describing messages to be sent, must include 2-10 items
disable_notificationBooleanOptionalSends messages silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent messages from forwarding and saving
reply_to_message_idIntegerOptionalIf the messages are a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found

Use this method to send point on the map. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
latitudeFloat numberYesLatitude of the location
longitudeFloat numberYesLongitude of the location
horizontal_accuracyFloat numberOptionalThe radius of uncertainty for the location, measured in meters; 0-1500
live_periodIntegerOptionalPeriod in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400.
headingIntegerOptionalFor live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
proximity_alert_radiusIntegerOptionalFor live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
latitudeFloat numberYesLatitude of new location
longitudeFloat numberYesLongitude of new location
horizontal_accuracyFloat numberOptionalThe radius of uncertainty for the location, measured in meters; 0-1500
headingIntegerOptionalDirection in which the user is moving, in degrees. Must be between 1 and 360 if specified.
proximity_alert_radiusIntegerOptionalThe maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new inline keyboard.

Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message with live location to stop
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new inline keyboard.

Use this method to send information about a venue. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
latitudeFloat numberYesLatitude of the venue
longitudeFloat numberYesLongitude of the venue
titleStringYesName of the venue
addressStringYesAddress of the venue
foursquare_idStringOptionalFoursquare identifier of the venue
foursquare_typeStringOptionalFoursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
google_place_idStringOptionalGoogle Places identifier of the venue
google_place_typeStringOptionalGoogle Places type of the venue. (See supported types.)
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

Use this method to send phone contacts. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
phone_numberStringYesContact’s phone number
first_nameStringYesContact’s first name
last_nameStringOptionalContact’s last name
vcardStringOptionalAdditional data about the contact in the form of a vCard, 0-2048 bytes
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user.

Use this method to send a native poll. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
questionStringYesPoll question, 1-300 characters
optionsArray of StringYesA JSON-serialized list of answer options, 2-10 strings 1-100 characters each
is_anonymousBooleanOptionalTrue, if the poll needs to be anonymous, defaults to True
typeStringOptionalPoll type, “quiz” or “regular”, defaults to “regular”
allows_multiple_answersBooleanOptionalTrue, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False
correct_option_idIntegerOptional0-based identifier of the correct answer option, required for polls in quiz mode
explanationStringOptionalText that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing
explanation_parse_modeStringOptionalMode for parsing entities in the explanation. See formatting options for more details.
explanation_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the poll explanation, which can be specified instead of parse_mode
open_periodIntegerOptionalAmount of time in seconds the poll will be active after creation, 5-600. Can’t be used together with close_date.
close_dateIntegerOptionalPoint in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can’t be used together with open_period.
is_closedBooleanOptionalPass True if the poll needs to be immediately closed. This can be useful for poll preview.
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
emojiStringOptionalEmoji on which the dice throw animation is based. Currently, must be one of “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, or “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”. Dice can have values 1-6 for “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” and “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, values 1-5 for “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot” and “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”, and values 1-64 for “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot”. Defaults to “Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть фото Sorry the username must end in bot e g tetris bot or tetrisbot. Смотреть картинку Sorry the username must end in bot e g tetris bot or tetrisbot. Картинка про Sorry the username must end in bot e g tetris bot or tetrisbot. Фото Sorry the username must end in bot e g tetris bot or tetrisbot
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

Use this method when you need to tell the user that something is happening on the bot’s side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.

Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.

We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
actionStringYesType of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.

Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.

ParameterTypeRequiredDescription
user_idIntegerYesUnique identifier of the target user
offsetIntegerOptionalSequential number of the first photo to be returned. By default, all photos are returned.
limitIntegerOptionalLimits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100.
ParameterTypeRequiredDescription
file_idStringYesFile identifier to get information about

Note: This function may not preserve the original file name and MIME type. You should save the file’s MIME type and name (if available) when the File object is received.

Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target group or username of the target supergroup or channel (in the format @channelusername )
user_idIntegerYesUnique identifier of the target user
until_dateIntegerOptionalDate when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only.
revoke_messagesBooleanOptionalPass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.

Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don’t want this, use the parameter only_if_banned. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target group or username of the target supergroup or channel (in the format @channelusername )
user_idIntegerYesUnique identifier of the target user
only_if_bannedBooleanOptionalDo nothing if the user is not banned

Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )
user_idIntegerYesUnique identifier of the target user
permissionsChatPermissionsYesA JSON-serialized object for new user permissions
until_dateIntegerOptionalDate when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever

Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
user_idIntegerYesUnique identifier of the target user
is_anonymousBooleanOptionalPass True if the administrator’s presence in the chat is hidden
can_manage_chatBooleanOptionalPass True if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege
can_post_messagesBooleanOptionalPass True if the administrator can create channel posts, channels only
can_edit_messagesBooleanOptionalPass True if the administrator can edit messages of other users and can pin messages, channels only
can_delete_messagesBooleanOptionalPass True if the administrator can delete messages of other users
can_manage_video_chatsBooleanOptionalPass True if the administrator can manage video chats
can_restrict_membersBooleanOptionalPass True if the administrator can restrict, ban or unban chat members
can_promote_membersBooleanOptionalPass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)
can_change_infoBooleanOptionalPass True if the administrator can change chat title, photo and other settings
can_invite_usersBooleanOptionalPass True if the administrator can invite new users to the chat
can_pin_messagesBooleanOptionalPass True if the administrator can pin messages, supergroups only

Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )
user_idIntegerYesUnique identifier of the target user
custom_titleStringYesNew custom title for the administrator; 0-16 characters, emoji are not allowed

Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won’t be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
sender_chat_idIntegerYesUnique identifier of the target sender chat

Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
sender_chat_idIntegerYesUnique identifier of the target sender chat

Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )
permissionsChatPermissionsYesA JSON-serialized object for new default chat permissions

Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )

Note: Each administrator in a chat generates their own invite links. Bots can’t use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.

Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
nameStringOptionalInvite link name; 0-32 characters
expire_dateIntegerOptionalPoint in time (Unix timestamp) when the link will expire
member_limitIntegerOptionalThe maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
creates_join_requestBooleanOptionalTrue, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can’t be specified

Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
invite_linkStringYesThe invite link to edit
nameStringOptionalInvite link name; 0-32 characters
expire_dateIntegerOptionalPoint in time (Unix timestamp) when the link will expire
member_limitIntegerOptionalThe maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
creates_join_requestBooleanOptionalTrue, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can’t be specified

Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier of the target chat or username of the target channel (in the format @channelusername )
invite_linkStringYesThe invite link to revoke

Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
user_idIntegerYesUnique identifier of the target user

Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
user_idIntegerYesUnique identifier of the target user

Use this method to set a new profile photo for the chat. Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
photoInputFileYesNew chat photo, uploaded using multipart/form-data

Use this method to delete a chat photo. Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )

Use this method to change the title of a chat. Titles can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
titleStringYesNew chat title, 1-255 characters

Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
descriptionStringOptionalNew chat description, 0-255 characters

Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ administrator right in a supergroup or ‘can_edit_messages’ administrator right in a channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerYesIdentifier of a message to pin
disable_notificationBooleanOptionalPass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats.

Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ administrator right in a supergroup or ‘can_edit_messages’ administrator right in a channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalIdentifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned.

Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ administrator right in a supergroup or ‘can_edit_messages’ administrator right in a channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )

Use this method for your bot to leave a group, supergroup or channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername )

Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername )

Use this method to get a list of administrators in a chat, which aren’t bots. Returns an Array of ChatMember objects.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername )

Use this method to get the number of members in a chat. Returns Int on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername )

Use this method to get information about a member of a chat. Returns a ChatMember object on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername )
user_idIntegerYesUnique identifier of the target user

Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )
sticker_set_nameStringYesName of the sticker set to be set as the group sticker set

Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @supergroupusername )

Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.

Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.

Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.cache_timeIntegerOptionalThe maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.

ParameterTypeRequiredDescription
commandsArray of BotCommandYesA JSON-serialized list of bot commands to be set as the list of the bot’s commands. At most 100 commands can be specified.
scopeBotCommandScopeOptionalA JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands

Use this method to delete the list of the bot’s commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.

ParameterTypeRequiredDescription
scopeBotCommandScopeOptionalA JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands

Use this method to get the current list of the bot’s commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren’t set, an empty list is returned.

ParameterTypeRequiredDescription
scopeBotCommandScopeOptionalA JSON-serialized object, describing scope of users. Defaults to BotCommandScopeDefault.
language_codeStringOptionalA two-letter ISO 639-1 language code or an empty string

Use this method to change the bot’s menu button in a private chat, or the default menu button. Returns True on success.

ParameterTypeRequiredDescription
chat_idIntegerOptionalUnique identifier for the target private chat. If not specified, default bot’s menu button will be changed
menu_buttonMenuButtonOptionalA JSON-serialized object for the bot’s new menu button. Defaults to MenuButtonDefault

Use this method to get the current value of the bot’s menu button in a private chat, or the default menu button. Returns MenuButton on success.

ParameterTypeRequiredDescription
chat_idIntegerOptionalUnique identifier for the target private chat. If not specified, default bot’s menu button will be returned

Use this method to change the default administrator rights requested by the bot when it’s added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.

ParameterTypeRequiredDescription
rightsChatAdministratorRightsOptionalA JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared.
for_channelsBooleanOptionalPass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.

Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.

ParameterTypeRequiredDescription
for_channelsBooleanOptionalPass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned.

Methods and objects used in the inline mode are described in the Inline mode section.

The following methods allow you to change an existing message in the message history instead of sending a new one with a result of an action. This is most useful for messages with inline keyboards using callback queries, but can also help reduce clutter in conversations with regular chat bots.

Please note, that it is currently only possible to edit messages without reply_markup or with inline keyboards.

Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
textStringYesNew text of the message, 1-4096 characters after entities parsing
parse_modeStringOptionalMode for parsing entities in the message text. See formatting options for more details.
entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
disable_web_page_previewBooleanOptionalDisables link previews for links in this message
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard.

Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
captionStringOptionalNew caption of the message, 0-1024 characters after entities parsing
parse_modeStringOptionalMode for parsing entities in the message caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard.

Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can’t be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
mediaInputMediaYesA JSON-serialized object for a new media content of the message
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new inline keyboard.

Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard.

Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerYesIdentifier of the original message with the poll
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new message inline keyboard.

Use this method to delete a message, including service messages, with the following limitations:
— A message can only be deleted if it was sent less than 48 hours ago.
— A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
— Bots can delete outgoing messages in private chats, groups, and supergroups.
— Bots can delete incoming messages in private chats.
— Bots granted can_post_messages permissions can delete outgoing messages in channels.
— If the bot is an administrator of a group, it can delete any message there.
— If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername )
message_idIntegerYesIdentifier of the message to delete

The following methods and objects allow your bot to handle stickers and sticker sets.

This object represents a sticker.

This object represents a sticker set.

This object describes the position on faces where a mask should be placed by default.

Use this method to get a sticker set. On success, a StickerSet object is returned.

ParameterTypeRequiredDescription
nameStringYesName of the sticker set

Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.

ParameterTypeRequiredDescription
custom_emoji_idsArray of StringYesList of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.
ParameterTypeRequiredDescription
user_idIntegerYesUser identifier of sticker file owner
png_stickerInputFileYesPNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More information on Sending Files »

Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Returns True on success.

Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.

ParameterTypeRequiredDescription
user_idIntegerYesUser identifier of sticker set owner
nameStringYesSticker set name
png_stickerInputFile or StringOptionalPNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
tgs_stickerInputFileOptionalTGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/stickers#animated-sticker-requirements for technical requirements
webm_stickerInputFileOptionalWEBM video with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/stickers#video-sticker-requirements for technical requirements
emojisStringYesOne or more emoji corresponding to the sticker
mask_positionMaskPositionOptionalA JSON-serialized object for position where the mask should be placed on faces

Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.

ParameterTypeRequiredDescription
stickerStringYesFile identifier of the sticker
positionIntegerYesNew sticker position in the set, zero-based

Use this method to delete a sticker from a set created by the bot. Returns True on success.

ParameterTypeRequiredDescription
stickerStringYesFile identifier of the sticker

Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only. Returns True on success.

ParameterTypeRequiredDescription
nameStringYesSticker set name
user_idIntegerYesUser identifier of the sticker set owner
thumbInputFile or StringOptionalA PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements, or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated sticker set thumbnails can’t be uploaded via HTTP URL.

The following methods and objects allow your bot to work in inline mode.
Please see our Introduction to Inline bots for more details.

To enable this option, send the /setinline command to @BotFather and provide the placeholder text that the user will see in the input field after typing your bot’s name.

This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

FieldTypeDescription
idStringUnique identifier for this query
fromUserSender
queryStringText of the query (up to 256 characters)
offsetStringOffset of the results to be returned, can be controlled by the bot
chat_typeStringOptional. Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat
locationLocationOptional. Sender location, only for bots that request user location

Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results per query are allowed.

Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a ‘Connect your YouTube account’ button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot’s inline capabilities.

This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:

Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public.

Represents a link to an article or web page.

FieldTypeDescription
typeStringType of the result, must be article
idStringUnique identifier for this result, 1-64 Bytes
titleStringTitle of the result
input_message_contentInputMessageContentContent of the message to be sent
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
urlStringOptional. URL of the result
hide_urlBooleanOptional. Pass True if you don’t want the URL to be shown in the message
descriptionStringOptional. Short description of the result
thumb_urlStringOptional. Url of the thumbnail for the result
thumb_widthIntegerOptional. Thumbnail width
thumb_heightIntegerOptional. Thumbnail height

Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.

FieldTypeDescription
typeStringType of the result, must be photo
idStringUnique identifier for this result, 1-64 bytes
photo_urlStringA valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB
thumb_urlStringURL of the thumbnail for the photo
photo_widthIntegerOptional. Width of the photo
photo_heightIntegerOptional. Height of the photo
titleStringOptional. Title for the result
descriptionStringOptional. Short description of the result
captionStringOptional. Caption of the photo to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the photo caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the photo

Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

FieldTypeDescription
typeStringType of the result, must be gif
idStringUnique identifier for this result, 1-64 bytes
gif_urlStringA valid URL for the GIF file. File size must not exceed 1MB
gif_widthIntegerOptional. Width of the GIF
gif_heightIntegerOptional. Height of the GIF
gif_durationIntegerOptional. Duration of the GIF in seconds
thumb_urlStringURL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
thumb_mime_typeStringOptional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
titleStringOptional. Title for the result
captionStringOptional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the GIF animation

Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

FieldTypeDescription
typeStringType of the result, must be mpeg4_gif
idStringUnique identifier for this result, 1-64 bytes
mpeg4_urlStringA valid URL for the MPEG4 file. File size must not exceed 1MB
mpeg4_widthIntegerOptional. Video width
mpeg4_heightIntegerOptional. Video height
mpeg4_durationIntegerOptional. Video duration in seconds
thumb_urlStringURL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
thumb_mime_typeStringOptional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
titleStringOptional. Title for the result
captionStringOptional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video animation

Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.

If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content.

FieldTypeDescription
typeStringType of the result, must be video
idStringUnique identifier for this result, 1-64 bytes
video_urlStringA valid URL for the embedded video player or video file
mime_typeStringMIME type of the content of the video URL, “text/html” or “video/mp4”
thumb_urlStringURL of the thumbnail (JPEG only) for the video
titleStringTitle for the result
captionStringOptional. Caption of the video to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the video caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
video_widthIntegerOptional. Video width
video_heightIntegerOptional. Video height
video_durationIntegerOptional. Video duration in seconds
descriptionStringOptional. Short description of the result
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).

Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.

FieldTypeDescription
typeStringType of the result, must be audio
idStringUnique identifier for this result, 1-64 bytes
audio_urlStringA valid URL for the audio file
titleStringTitle
captionStringOptional. Caption, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the audio caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
performerStringOptional. Performer
audio_durationIntegerOptional. Audio duration in seconds
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the audio

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

FieldTypeDescription
typeStringType of the result, must be voice
idStringUnique identifier for this result, 1-64 bytes
voice_urlStringA valid URL for the voice recording
titleStringRecording title
captionStringOptional. Caption, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the voice message caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
voice_durationIntegerOptional. Recording duration in seconds
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the voice recording

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.

FieldTypeDescription
typeStringType of the result, must be document
idStringUnique identifier for this result, 1-64 bytes
titleStringTitle for the result
captionStringOptional. Caption of the document to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the document caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
document_urlStringA valid URL for the file
mime_typeStringMIME type of the content of the file, either “application/pdf” or “application/zip”
descriptionStringOptional. Short description of the result
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the file
thumb_urlStringOptional. URL of the thumbnail (JPEG only) for the file
thumb_widthIntegerOptional. Thumbnail width
thumb_heightIntegerOptional. Thumbnail height

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.

FieldTypeDescription
typeStringType of the result, must be location
idStringUnique identifier for this result, 1-64 Bytes
latitudeFloat numberLocation latitude in degrees
longitudeFloat numberLocation longitude in degrees
titleStringLocation title
horizontal_accuracyFloat numberOptional. The radius of uncertainty for the location, measured in meters; 0-1500
live_periodIntegerOptional. Period in seconds for which the location can be updated, should be between 60 and 86400.
headingIntegerOptional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
proximity_alert_radiusIntegerOptional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the location
thumb_urlStringOptional. Url of the thumbnail for the result
thumb_widthIntegerOptional. Thumbnail width
thumb_heightIntegerOptional. Thumbnail height

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.

FieldTypeDescription
typeStringType of the result, must be venue
idStringUnique identifier for this result, 1-64 Bytes
latitudeFloatLatitude of the venue location in degrees
longitudeFloatLongitude of the venue location in degrees
titleStringTitle of the venue
addressStringAddress of the venue
foursquare_idStringOptional. Foursquare identifier of the venue if known
foursquare_typeStringOptional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
google_place_idStringOptional. Google Places identifier of the venue
google_place_typeStringOptional. Google Places type of the venue. (See supported types.)
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the venue
thumb_urlStringOptional. Url of the thumbnail for the result
thumb_widthIntegerOptional. Thumbnail width
thumb_heightIntegerOptional. Thumbnail height

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.

FieldTypeDescription
typeStringType of the result, must be contact
idStringUnique identifier for this result, 1-64 Bytes
phone_numberStringContact’s phone number
first_nameStringContact’s first name
last_nameStringOptional. Contact’s last name
vcardStringOptional. Additional data about the contact in the form of a vCard, 0-2048 bytes
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the contact
thumb_urlStringOptional. Url of the thumbnail for the result
thumb_widthIntegerOptional. Thumbnail width
thumb_heightIntegerOptional. Thumbnail height

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

FieldTypeDescription
typeStringType of the result, must be game
idStringUnique identifier for this result, 1-64 bytes
game_short_nameStringShort name of the game
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message

Note: This will only work in Telegram versions released after October 1, 2016. Older clients will not display any inline results if a game result is among them.

Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.

FieldTypeDescription
typeStringType of the result, must be photo
idStringUnique identifier for this result, 1-64 bytes
photo_file_idStringA valid file identifier of the photo
titleStringOptional. Title for the result
descriptionStringOptional. Short description of the result
captionStringOptional. Caption of the photo to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the photo caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the photo

Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation.

FieldTypeDescription
typeStringType of the result, must be gif
idStringUnique identifier for this result, 1-64 bytes
gif_file_idStringA valid file identifier for the GIF file
titleStringOptional. Title for the result
captionStringOptional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the GIF animation

Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

FieldTypeDescription
typeStringType of the result, must be mpeg4_gif
idStringUnique identifier for this result, 1-64 bytes
mpeg4_file_idStringA valid file identifier for the MPEG4 file
titleStringOptional. Title for the result
captionStringOptional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video animation

Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.

FieldTypeDescription
typeStringType of the result, must be sticker
idStringUnique identifier for this result, 1-64 bytes
sticker_file_idStringA valid file identifier of the sticker
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the sticker

Note: This will only work in Telegram versions released after 9 April, 2016 for static stickers and after 06 July, 2019 for animated stickers. Older clients will ignore them.

Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.

FieldTypeDescription
typeStringType of the result, must be document
idStringUnique identifier for this result, 1-64 bytes
titleStringTitle for the result
document_file_idStringA valid file identifier for the file
descriptionStringOptional. Short description of the result
captionStringOptional. Caption of the document to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the document caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the file

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.

FieldTypeDescription
typeStringType of the result, must be video
idStringUnique identifier for this result, 1-64 bytes
video_file_idStringA valid file identifier for the video file
titleStringTitle for the result
descriptionStringOptional. Short description of the result
captionStringOptional. Caption of the video to be sent, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the video caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video

Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.

FieldTypeDescription
typeStringType of the result, must be voice
idStringUnique identifier for this result, 1-64 bytes
voice_file_idStringA valid file identifier for the voice message
titleStringVoice message title
captionStringOptional. Caption, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the voice message caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the voice message

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.

FieldTypeDescription
typeStringType of the result, must be audio
idStringUnique identifier for this result, 1-64 bytes
audio_file_idStringA valid file identifier for the audio file
captionStringOptional. Caption, 0-1024 characters after entities parsing
parse_modeStringOptional. Mode for parsing entities in the audio caption. See formatting options for more details.
caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the audio

Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.

This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types:

Represents the content of a text message to be sent as the result of an inline query.

FieldTypeDescription
message_textStringText of the message to be sent, 1-4096 characters
parse_modeStringOptional. Mode for parsing entities in the message text. See formatting options for more details.
entitiesArray of MessageEntityOptional. List of special entities that appear in message text, which can be specified instead of parse_mode
disable_web_page_previewBooleanOptional. Disables link previews for links in the sent message

Represents the content of a location message to be sent as the result of an inline query.

FieldTypeDescription
latitudeFloatLatitude of the location in degrees
longitudeFloatLongitude of the location in degrees
horizontal_accuracyFloat numberOptional. The radius of uncertainty for the location, measured in meters; 0-1500
live_periodIntegerOptional. Period in seconds for which the location can be updated, should be between 60 and 86400.
headingIntegerOptional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
proximity_alert_radiusIntegerOptional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.

Represents the content of a venue message to be sent as the result of an inline query.

FieldTypeDescription
latitudeFloatLatitude of the venue in degrees
longitudeFloatLongitude of the venue in degrees
titleStringName of the venue
addressStringAddress of the venue
foursquare_idStringOptional. Foursquare identifier of the venue, if known
foursquare_typeStringOptional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
google_place_idStringOptional. Google Places identifier of the venue
google_place_typeStringOptional. Google Places type of the venue. (See supported types.)

Represents the content of a contact message to be sent as the result of an inline query.

FieldTypeDescription
phone_numberStringContact’s phone number
first_nameStringContact’s first name
last_nameStringOptional. Contact’s last name
vcardStringOptional. Additional data about the contact in the form of a vCard, 0-2048 bytes

Represents the content of an invoice message to be sent as the result of an inline query.

Represents a result of an inline query that was chosen by the user and sent to their chat partner.

FieldTypeDescription
result_idStringThe unique identifier for the result that was chosen
fromUserThe user that chose the result
locationLocationOptional. Sender location, only for bots that require user location
inline_message_idStringOptional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message.
queryStringThe query that was used to obtain the result

Note: It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates.

Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.

ParameterTypeRequiredDescription
web_app_query_idStringYesUnique identifier for the query to be answered
resultInlineQueryResultYesA JSON-serialized object describing the message to be sent

Describes an inline message sent by a Web App on behalf of a user.

FieldTypeDescription
inline_message_idStringOptional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message.

Your bot can accept payments from Telegram users. Please see the introduction to payments for more details on the process and how to set up payments for your bot. Please note that users will need Telegram v.4.0 or higher to use payments (released on May 18, 2017).

Use this method to send invoices. On success, the sent Message is returned.

Use this method to create a link for an invoice. Returns the created invoice link as String on success.

If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.

ParameterTypeRequiredDescription
shipping_query_idStringYesUnique identifier for the query to be answered
okBooleanYesPass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
shipping_optionsArray of ShippingOptionOptionalRequired if ok is True. A JSON-serialized array of available shipping options.
error_messageStringOptionalRequired if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. «Sorry, delivery to your desired address is unavailable’). Telegram will display this message to the user.

Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.

ParameterTypeRequiredDescription
pre_checkout_query_idStringYesUnique identifier for the query to be answered
okBooleanYesSpecify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
error_messageStringOptionalRequired if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. «Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!»). Telegram will display this message to the user.

This object represents a portion of the price for goods or services.

This object contains basic information about an invoice.

This object represents a shipping address.

FieldTypeDescription
country_codeStringTwo-letter ISO 3166-1 alpha-2 country code
stateStringState, if applicable
cityStringCity
street_line1StringFirst line for the address
street_line2StringSecond line for the address
post_codeStringAddress post code

This object represents information about an order.

FieldTypeDescription
nameStringOptional. User name
phone_numberStringOptional. User’s phone number
emailStringOptional. User email
shipping_addressShippingAddressOptional. User shipping address

This object represents one shipping option.

FieldTypeDescription
idStringShipping option identifier
titleStringOption title
pricesArray of LabeledPriceList of price portions

This object contains basic information about a successful payment.

This object contains information about an incoming shipping query.

FieldTypeDescription
idStringUnique query identifier
fromUserUser who sent the query
invoice_payloadStringBot specified invoice payload
shipping_addressShippingAddressUser specified shipping address

This object contains information about an incoming pre-checkout query.

Telegram Passport is a unified authorization method for services that require personal identification. Users can upload their documents once, then instantly share their data with services that require real-world ID (finance, ICOs, etc.). Please see the manual for details.

Describes Telegram Passport data shared with the bot by the user.

FieldTypeDescription
dataArray of EncryptedPassportElementArray with information about documents and other Telegram Passport elements that was shared with the bot
credentialsEncryptedCredentialsEncrypted credentials required to decrypt the data

This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don’t exceed 10MB.

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file
file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can’t be used to download or reuse the file.
file_sizeIntegerFile size in bytes
file_dateIntegerUnix time when the file was uploaded

Describes documents or other Telegram Passport elements shared with the bot by the user.

FieldTypeDescription
typeStringElement type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”.
dataStringOptional. Base64-encoded encrypted Telegram Passport element data provided by the user, available for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials.
phone_numberStringOptional. User’s verified phone number, available only for “phone_number” type
emailStringOptional. User’s verified email address, available only for “email” type
filesArray of PassportFileOptional. Array of encrypted files with documents provided by the user, available for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
front_sidePassportFileOptional. Encrypted file with the front side of the document, provided by the user. Available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
reverse_sidePassportFileOptional. Encrypted file with the reverse side of the document, provided by the user. Available for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
selfiePassportFileOptional. Encrypted file with the selfie of the user holding a document, provided by the user; available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
translationArray of PassportFileOptional. Array of encrypted files with translated versions of documents provided by the user. Available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
hashStringBase64-encoded element hash for using in PassportElementErrorUnspecified

Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.

FieldTypeDescription
dataStringBase64-encoded encrypted JSON-serialized data with unique user’s payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication
hashStringBase64-encoded data hash for data authentication
secretStringBase64-encoded secret, encrypted with the bot’s public RSA key, required for data decryption

Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.

Use this if the data submitted by the user doesn’t satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.

ParameterTypeRequiredDescription
user_idIntegerYesUser identifier
errorsArray of PassportElementErrorYesA JSON-serialized array describing the errors

This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:

Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field’s value changes.

FieldTypeDescription
sourceStringError source, must be data
typeStringThe section of the user’s Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”
field_nameStringName of the data field which has the error
data_hashStringBase64-encoded data hash
messageStringError message

Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.

FieldTypeDescription
sourceStringError source, must be front_side
typeStringThe section of the user’s Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
file_hashStringBase64-encoded hash of the file with the front side of the document
messageStringError message

Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.

FieldTypeDescription
sourceStringError source, must be reverse_side
typeStringThe section of the user’s Telegram Passport which has the issue, one of “driver_license”, “identity_card”
file_hashStringBase64-encoded hash of the file with the reverse side of the document
messageStringError message

Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.

FieldTypeDescription
sourceStringError source, must be selfie
typeStringThe section of the user’s Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
file_hashStringBase64-encoded hash of the file with the selfie
messageStringError message

Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.

FieldTypeDescription
sourceStringError source, must be file
typeStringThe section of the user’s Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
file_hashStringBase64-encoded file hash
messageStringError message

Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.

FieldTypeDescription
sourceStringError source, must be files
typeStringThe section of the user’s Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
file_hashesArray of StringList of base64-encoded file hashes
messageStringError message

Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.

FieldTypeDescription
sourceStringError source, must be translation_file
typeStringType of element of the user’s Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
file_hashStringBase64-encoded file hash
messageStringError message

Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change.

FieldTypeDescription
sourceStringError source, must be translation_files
typeStringType of element of the user’s Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
file_hashesArray of StringList of base64-encoded file hashes
messageStringError message

Represents an issue in an unspecified place. The error is considered resolved when new data is added.

FieldTypeDescription
sourceStringError source, must be unspecified
typeStringType of element of the user’s Telegram Passport which has the issue
element_hashStringBase64-encoded element hash
messageStringError message

Your bot can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. Create games via @BotFather using the /newgame command. Please note that this kind of power requires responsibility: you will need to accept the terms for each game that your bots will be offering.

Use this method to send a game. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idIntegerYesUnique identifier for the target chat
game_short_nameStringYesShort name of the game, serves as the unique identifier for the game. Set up your games via @BotFather.
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found
reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game.

This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.

FieldTypeDescription
titleStringTitle of the game
descriptionStringDescription of the game
photoArray of PhotoSizePhoto that will be displayed in the game message in chats.
textStringOptional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters.
text_entitiesArray of MessageEntityOptional. Special entities that appear in text, such as usernames, URLs, bot commands, etc.
animationAnimationOptional. Animation that will be displayed in the game message in chats. Upload via BotFather

A placeholder, currently holds no information. Use BotFather to set up your game.

Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user’s current score in the chat and force is False.

ParameterTypeRequiredDescription
user_idIntegerYesUser identifier
scoreIntegerYesNew score, must be non-negative
forceBooleanOptionalPass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters
disable_edit_messageBooleanOptionalPass True if the game message should not be automatically edited to include the current scoreboard
chat_idIntegerOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the sent message
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message

Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects.

This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change.

ParameterTypeRequiredDescription
user_idIntegerYesTarget user id
chat_idIntegerOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat
message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the sent message
inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message

This object represents one row of the high scores table for a game.

FieldTypeDescription
positionIntegerPosition in high score table for the game
userUserUser
scoreIntegerScore

And that’s about all we’ve got for now.
If you’ve got any questions, please check out our Bot FAQ »

Источники:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *