From e40d0cc3972c2e95dbbc47e53261a1081cd2c3f0 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 7 Oct 2022 15:53:38 +0000 Subject: [PATCH] Update content of files --- .../blogfork.telegram.org/bots/features.html | 583 +++++++++++++++++ .../blogfork.telegram.org/bots/tutorial.html | 590 ++++++++++++++++++ data/web/core.telegram.org/bots/features.html | 583 +++++++++++++++++ data/web/core.telegram.org/bots/tutorial.html | 590 ++++++++++++++++++ 4 files changed, 2346 insertions(+) create mode 100644 data/web/blogfork.telegram.org/bots/features.html create mode 100644 data/web/blogfork.telegram.org/bots/tutorial.html create mode 100644 data/web/core.telegram.org/bots/features.html create mode 100644 data/web/core.telegram.org/bots/tutorial.html diff --git a/data/web/blogfork.telegram.org/bots/features.html b/data/web/blogfork.telegram.org/bots/features.html new file mode 100644 index 0000000000..7588bcdde7 --- /dev/null +++ b/data/web/blogfork.telegram.org/bots/features.html @@ -0,0 +1,583 @@ + + + + + Telegram Bot Features + + + + + + + + + + + + + + + + +
+ +
+
+
+ +

Telegram Bot Features

+ +
+ +

This page describes individual bot elements and features in detail. See also:

+ +

What features do bots have?

+ +
+

Inputs

+

Users can send messages of all types to bots, including text, files, locations, stickers, voice messages and even dice if they're feeling lucky. However, Telegram bots offer many other tools for building flexible interfaces tailored to your specific needs:

+
    +
  • Commands that are highlighted in messages and can be selected from a list after typing /.
  • +
  • Keyboards that replace the user's keyboard with predefined answer options.
  • +
  • Buttons that are shown next to messages from the bot.
  • +
+

For even more flexibility, Web Apps support 100% custom interfaces with Javascript.

+
+ +
+ +
+

Note: Telegram bots can support multiple languages that adapt to the users' language settings in the app.

+
+

Commands

+

A command is a simple /keyword that tells the bot what to do. Telegram apps will:

+
    +
  • Highlight commands in messages. When the user taps a highlighted command, that command is immediately sent again.
  • +
  • Suggest a list of supported commands with descriptions when the user enters a / (for this to work, you need to have provided a list of commands to @BotFather or via the appropriate API method). Selecting a command from the list immediately sends it.
  • +
  • Show a menu button containing all or some of a bot’s commands (which you set via @BotFather).
  • +
+

Commands must always start with the / symbol and contain up to 32 characters. They can use Latin letters, numbers and underscores, though simple lowercase text is recommended for a cleaner look.

+

Here are a few examples:

+
    +
  • /next
  • +
  • /cancel
  • +
  • /newlocation
  • +
  • /newrule
  • +
+

Commands should be as specific as possible – for example /newlocation or /newrule is better than a /new command that then requires an additional parameter from the user like "location“ or ”rule".

+
+ +
+ +
+

We require all developers to support several Global Commands to make sure Telegram bots offer a consistent and user-friendly experience.

+
+
Command Scopes
+

Your bot is able to show different commands to different users and groups – you can control this using scopes. For example, your bot could show additional commands to group admins or translate the list based on the user’s language_code.

+
+

Keep in mind that Bot API updates will not contain any information about the scope of a command sent by the user – in fact, they may contain commands that don’t exist at all in your bot. Your backend should always verify that received commands are valid and that the user was authorized to use them regardless of scope.

+

Bots with privacy mode enabled will only receive commands in groups under special conditions, see here.

+
+

Keyboards

+

Bots are able to interpret free text input from users, but offering specific suggestions is often more intuitive – this is where custom keyboards can be extremely useful.

+

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

+
+ +
+ +
+

Check out the one_time_keyboard parameter to automatically hide your bot's keyboard as soon as it's been used.

+
+

Inline Keyboards

+

There are times when you'd prefer to do things without sending any messages to the chat – like when a user is changing settings, toggling options or navigating search results. In such cases, you can use Inline Keyboards that are shown directly below their relevant messages.

+

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn't send messages to the chat. Instead, inline keyboards support buttons that can work behind the scenes or open different interfaces: callback buttons, URL buttons, switch-to-inline buttons, game buttons and payment buttons.

+
+ +
+ +
+

To provide a better user experience, consider editing your keyboard when the user toggles a setting button or navigates to a new page – this is both faster and smoother than sending a whole new message and deleting the previous one.

+
+

Menu Button

+

In all bot chats, a menu button appears near the message field. By default, tapping this button opens a menu that can hold some or all of a bot's commands, including a short description for each. Users can then select a command from the menu without needing to type it out.

+

You can set different texts of the menu button and its command descriptions for various individual users or groups of users – for example, showing translated text based on the user’s language, as explained here.

+
+ +
+ +
+

Remember that you can also customize the text placeholder in the input field by setting the input_field_placeholder parameter.

+
+

The menu button can alternatively be used to launch a Web App.

+

Global Commands

+

To make basic interactions more uniform, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

+
    +
  • /start - begins the interaction with the user, like sending an introductory message. This command can also be used to pass additional parameters to the bot (see Deep Linking).
  • +
  • /help - returns a help message, like a short text about what your bot can do and a list of commands.
  • +
  • /settings - (if applicable) shows the bot's settings for this user and suggests commands to edit them.
  • +
+

Users will see a Start button the first time they open a chat with your bot. Help and Settings links will be available in the menu on the bot's profile page if you add them in @BotFather.

+
+

Interactions

+

In addition to sending commands and messages to the chat with the bot, there are several ways of interacting with them without opening any specific chat or group.

+
    +
  • Inline mode allows sending requests to bots right from the input field – from any chat on Telegram.
  • +
  • Deep linking allows special links that send certain parameters to the bot when opened.
  • +
  • Attachment menu integration makes it possible to use bots from the attachment menu in chats.
  • +
+

Inline Requests

+

Users can interact with your bot via inline queries straight from the message field in any chat. All they need to do is start a message with your bot's @username and enter a keyword.

+

Having received the query, your bot can return some results. As soon as the user selects one, it is sent to the relevant chat. This way, people can request and send content from your bot in any of their chats, groups or channels.

+

Remember that inline functionality has to be enabled via @BotFather, or your bot will not receive inline Updates.

+
+ +
+ +
+

Examples of inline bots include @gif, @bing and @wiki.

+
+

Deep Linking

+

Telegram bots have a deep linking mechanism that allows additional parameters to be passed 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 another platform.

+

Each bot has a link that opens a conversation with it in Telegram – https://t.me/<bot_username>. Parameters can be added directly to this link to let your bot work with additional information on the fly, without any user input.

+
+

A-Z, a-z, 0-9, _ and - are allowed. We recommend using base64url to encode parameters with binary and other types of content. The parameter can be up to 64 characters long.

+
+

Private Chats
In private chats, you can use the start parameter to automatically pass any value to your bot whenever a user presses the link. For example, you could use:

+
https://t.me/your_bot?start=airplane
+

When someone opens a chat with your bot via this link, you will receive:

+
/start airplane
+

Groups
In groups, you can add the parameter startgroup to this link. For example:

+
https://t.me/your_bot?startgroup=spaceship
+

Following a link with this parameter prompts the user to select a group to add the bot to – the resulting update will contain text in the form:

+
/start@your_bot spaceship
+
+

Web Apps also support deep linking, for more information check out our dedicated guide.

+
+

Attachment Menu

+

Certain bots can be added directly to a user’s attachment menu – giving them easy access to the bot in any chat. Currently, this option is restricted to certain approved bots, but may be expanded later.

+
+ +
+ +
+

Try adding @DurgerKingBot to your attachment menu.

+
+
+

Integration

+

There are various ways of futher integrating bots with Telegram and other services.

+
    +
  • Use Web Apps to replace any website.
  • +
  • Accept Payments via dozens of integrated third-party payment providers.
  • +
  • Connect to Telegram using the Web Login functionality.
  • +
  • Create gaming bots by integrating HTML5 Games.
  • +
  • Help users create and manage Telegram Stickers.
  • +
+

Web Apps

+

Bots can easily process complex inputs of any kind and dynamic interaction flows via Web Apps. With this unique feature, you can develop any number of flexible, streamlined interfaces in JavaScript.

+
+

Web Apps are covered in detail in our dedicated guide – you should read it carefully to learn the wide variety of features they can offer.

+
+
+ +
+ +

If you develop a Web App, be sure to follow our design guidelines – you'll want your custom interface to seamlessly integrate into the app to provide users the best possible experience.

+

Payments

+

Telegram bots can accept payments with a sleek, streamlined interface that collects all necessary data from the user. Telegram doesn't collect any payment data – like the user's credit card information – and sends it directly to one of the supported payment providers.

+

Here is a quick start guide to implement payments:

+ +

Then, to issue an invoice and process the order flow:

+ +

A full and exhaustive guide, including live checklist, parameters and in-depth method descriptions is available here. We strongly recommend that you read the full guide before going live.

+
+ +
+ +
+

Telegram does not directly process the payments, does not store data about orders and does not collect any fees. Invoices are forwarded directly to the payment provider.
For this reason, disputes must be solved between the user, the bot developer and the payment provider. You can read more about this in the Privacy Policy.

+
+

Web Login

+

Telegram offers a flexible, lightweight and free framework to authenticate users on any website and app. This can be used to bridge your platform with Telegram, providing a smooth experience to your users. You can also freely rely on this framework to implement a fast and signup-free login on your site, regardless of its connection to Telegram.

+

Widgets

+

The Telegram login widget is a simple and secure way to authorize users on your website.

+
    +
  1. Choose a bot – ideally its name and profile pic should match the website title and logo.
  2. +
  3. Use the /setdomain command in @BotFather to pair the bot with your website domain.
  4. +
  5. Configure your widget using our dedicated tool and embed it on your website.
  6. +
+

Inline Login

+

When users open your website via an inline button, you can use the login_url parameter as an alternative to login widgets. This way, you'll be able to seamlessly authorize them on your website or app before the page even loads.

+
+ +
+ +
+

Make sure to review our guide on authenticating the received data as well as our sample code.

+
+

HTML5 Games

+

Bots can serve as standalone gaming platforms – with our HTML5 Gaming API you can develop multiplayer or single-player games and let your users have fun comparing ranks, scores and much more.

+

To get started, follow these simple steps:

+
    +
  • Send the /newgame command to @BotFather
  • +
  • Provide a description text, an image or an optional gif to showcase its gameplay
  • +
  • Send the game to users via the sendGame method or via an inline query
  • +
  • When someone wants to play, you'll receive the appropriate game_short_name in a CallbackQuery
  • +
  • To launch the game, provide the HTML5 Game URL as the url param of answerCallbackQuery
  • +
+

Then, to handle highscores:

+ +

You can also embed a share button within your game, play around with custom inline buttons, URL parameters and much more. To get a better idea, make sure to check out:

+ +
+ +
+ +
+

Check out @GameBot and @gamee for examples of what you can do using our Gaming Platform.

+
+

Stickers

+

Stickers are a distinctive Telegram feature used by millions of users to share artwork every day. Stickers take many forms – ranging from basic images to smooth vector animations and high-detail .WEBM videos.

+

All these formats are supported by our Bot API, which allows bots to create, edit, delete and share new sticker packs on the fly. Telegram's Import API lets users migrate packs from other platforms and sticker apps.

+

To create a new sticker pack, follow these simple steps:

+
    +
  • Upload a new sticker file via uploadStickerFile. Repeat for all the stickers in the set. You will use the returned files in the next step, so keep them around.
  • +
  • Create a new sticker pack via createStickerSet. Attach the files you collected in step 1 and remember to only specify one of the three avaiable fields – png_sticker, tgs_sticker and webm_sticker – depending on which sticker format you uploaded.
  • +
  • Complete the pack by adding each remaining sticker in sequence via addStickerToSet.
  • +
+
+

Once you're done, don't forget to check out our remaining sticker methods to find out how to edit, delete and even reorder your pack.
Note that these methods will only work on packs created by the bot that is calling them.

+
+

Language Support

+

Bots can tailor their interfaces to support multiple languages – updating inputs and information on the fly. A user’s in-app language_code is included in every relevant update as an IETF language tag, allowing bots to adapt accordingly.

+

We recommend that you follow our guidelines to provide the best user experience.

+
    +
  • Your interfaces, texts and inline results should adapt seamlessly to the language_code, without user intervention.
  • +
  • Connected WebApps will receive the user's language_code – your HTML page should account for it.
  • +
  • HTML5 Games can obtain language information if you specify it as a URL parameter. You can generate this parameter from the language_code field in the User object served with the initial game CallbackQuery.
  • +
  • Command lists can also be specified for individual languages – more on this here.
  • +
+
+ +
+ +
+

The language_code is an optional field – it could be empty.
If you target the general public, your code should always fall back to either the last recorded language tag or English (in this order) when the field is missing for a specific user.

+
+
+

Bot Management

+

Privacy Mode

+

Bots are frequently added to groups to perform basic tasks or assist moderators – like automatically posting company announcements or even celebrating birthdays. By default, all bots added to groups run in Privacy Mode and only see relevant messages and commands:

+
    +
  • Commands explicitly meant for them (e.g., /command@this_bot).
  • +
  • General commands (e.g. /start) if the bot was the last bot to send a message to the group.
  • +
  • Inline messages sent via the bot.
  • +
  • Replies to any messages implicitly or explicitly meant for this bot.
  • +
+

All bots will also receive, regardless of privacy mode:

+
    +
  • All service messages.
  • +
  • All messages from private chats.
  • +
  • All messages from channels where they are a member.
  • +
+

Privacy mode is enabled by default for all bots, except bots that were added to a 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. In most cases, using the force reply option for the bot's messages should be more than enough.

+
+ +
+ +
+

This mode not only increases user privacy, but also makes the bot more efficient by reducing the number of inputs it needs to process. Users can always see a bot’s current privacy setting in the list of group members.

+
+

Status alerts

+

Millions choose Telegram for its speed. To best benefit users, 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 check the number of replies and the request/response conversion rate for popular bots (~300 requests per minute, this value may change in the future). If your bot returns an abnormally low number, 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:

+
    +
  • Fixed - Use this if you found an issue with your bot and fixed it. If you press the fix button, we will resume sending alerts in the regular way so that you can see if your fix worked within 5-10 minutes instead of having to wait for an hour.
  • +
  • Support - Use this to open a chat with @BotSupport if you don't see any issues with your bot or if you think the problem is on our side.
  • +
  • Mute for 8h/1w - Use this if you can't fix your bot at the moment. This will disable all alerts for the bot in question for the specified period of time. We do not recommend using this option since your users may migrate to a more stable bot. You can unmute alerts in your bot's settings via @BotFather.
  • +
+
Monitored issues
+

We currently notify you about the following issues:

+
    +
  • Too few private messages are sent. Value: {value} - Your bot is sending far fewer messages than it did in previous weeks. This is useful for newsletter-style bots that send messages without prompts from users. The larger the value, the more significant the difference.

    +
  • +
  • Too few replies to incoming private messages. Conversion rate: {value} - 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).

+
+
    +
  • Too few answers to inline queries. Conversion rate: {value} - 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.
  • +
+
    +
  • Too few answers to callback queries. Conversion rate: {value}
  • +
  • Too few answers to callback game queries. Conversion rate: {value} - 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.
  • +
+

Local Bot API

+

You can host and work with your own instance of our open-source Bot API.
The source code is available here, along with a quick installation guide.

+

After installing the server, remember to use the logOut method before redirecting requests to your new local API URL.

+
+

Your local instance runs on port 8081 by default and will only accept HTTP requests, so a TLS termination proxy has to be used to handle remote HTTPS requests.

+
+

By hosting our API locally you'll gain access to some upgrades, including:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
APIMax File DownloadMax File UploadWHook URLWHook PortWHook Max Connections
Official20MB50MBHTTPS443,80,88,84431-100
LocalUnlimited2000MBHTTPAny port1-100000
+
+

You can find an exhaustive list here.
All limits may be subject to change in the future, so make sure to follow @BotNews.

+
+
+

BotFather

+

Below is a detailed guide to using @BotFather, Telegram’s tool for creating and managing bots.

+

Creating a new bot

+

Use the /newbot command to create a new bot. @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, used in search, mentions and t.me links. Usernames are 5-32 characters long and not case sensitive – but may only include Latin characters, numbers, and underscores. Your bot's username must end in 'bot’, like 'tetris_bot' or 'TetrisBot'.

    +
  • +
  • The token is a string, like 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw, which 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.

    +
  • +
+
+

Unlike the bot’s name, the username cannot be changed later – so choose it carefully.
When sending a request to api.telegram.org, remember to prefix the word ‘bot’ to your token.

+
+

About text, description and profile media

+

When new users open your bot, they will be met with a helpful description in a box titled “What can this bot do?”.

+

Properly setting this field in @BotFather allows everyone to immediately get an idea of what your bot can do – your description should be brief, to the point and on topic.

+
+

You can also add a photo or video to this field with Edit Description Picture in @BotFather.

+
+

Additionally, just like normal users, bots also come with a short bio available on their profile. If you didn't specify this field while first creating your bot, you can set it at any time with the /setabouttext command in @BotFather. Users can interact with many bots and they won't have access to their description after starting them – having a quick reminder of the bot's purpose can be very useful.

+

Bots can also have a profile picture – you should pick something unique and original so that users can find it in their chat list at a glance.

+
+

Once set, the description, about text and profile pic can be replaced but never fully removed.

+
+

Generating an authentication token

+

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

+

Transfer ownership

+

You can transfer ownership of your bot to another user.
To do this, send /mybots, select your bot, then transfer ownership.
You can only transfer a bot to users who have interacted with it at least once.

+
+

Transferring ownership will give full control of the bot to another user – they will be able to access the bot’s messages and even delete it. The transfer is permanent, so please consider it carefully.

+
+

BotFather commands

+

The remaining commands are pretty self-explanatory:

+
    +
  • /mybots – returns a list of your bots with handy controls to edit their settings.
  • +
  • /mygames – does the same for your games.
  • +
+

Edit bots

+

To edit your bot, you have two options.

+

You can use the available commands:

+
    +
  • /setname – change your bot's name.
  • +
  • /setdescription – change the bot's description (short text up to 512 characters). Users will see this text at the beginning of the conversation with the bot, titled 'What can this bot do?'.
  • +
  • /setabouttext – change the bot's about info, a shorter text up to 120 characters. Users will see this text on the bot's profile page. When they share your bot with someone, this text is sent together with the link.
  • +
  • /setuserpic – change the bot's profile picture.
  • +
  • /setcommands – change the list of commands supported by your bot. Users will see these commands as suggestions when they type / in the chat with your bot. See commands for more info.
  • +
  • /setdomain – link a website domain to your bot. See the login widget section.
  • +
  • /deletebot – delete your bot and free its username. Cannot be undone.
  • +
+

Or you can use the /mybots command, tap on your bot and use the modern inline interface to edit it.

+

Edit settings

+
    +
  • /setinline – toggle inline mode for your bot.
  • +
  • /setinlinegeo – request location data to provide location-based inline results.
  • +
  • /setjoingroups – toggle whether your bot can be added to groups or not. All bots must be able to process direct messages, but if your bot was not designed to work in groups, you can disable this.
  • +
  • /setinlinefeedback – toggle whether the API should send updates about the results chosen by users. See an in-depth explanation here.
  • +
  • /setprivacy – set which messages your bot will receive when added to a group. See privacy-mode for more info.
  • +
+

Manage games

+
    +
  • /newgame – create a new game.
  • +
  • /listgames – see a list of your games.
  • +
  • /editgame – edit a game.
  • +
  • /deletegame – delete an existing game.
  • +
+
+

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

+
+
+

With this information, you are ready to proceed to our Full API Reference for Developers.

+
    +
  • If you have any questions, check out our Bot FAQ.
  • +
  • If you're experiencing issues with our API, please contact @BotSupport on Telegram.
  • +
+
+ +
+ +
+
+ +
+ + + + + + + + diff --git a/data/web/blogfork.telegram.org/bots/tutorial.html b/data/web/blogfork.telegram.org/bots/tutorial.html new file mode 100644 index 0000000000..1103fc3faf --- /dev/null +++ b/data/web/blogfork.telegram.org/bots/tutorial.html @@ -0,0 +1,590 @@ + + + + + From BotFather to 'Hello World' + + + + + + + + + + + + + + + + +
+ +
+
+
+ +

From BotFather to 'Hello World'

+ +
+ +

This guide will walk you through everything you need to know to build your first Telegram Bot.
If you already know your way around some of the basic steps, you can jump directly to the part you're missing. Equivalent examples are available in C#, Python, Go and TypeScript .

+ + + + + + + + + +
+

Introduction

+

At its core, you can think of the Telegram Bot API as software that provides JSON-encoded responses to your queries.

+

A bot, on the other hand, is essentially a routine, software or script that queries the API by means of an HTTPS request and waits for a response. There are several types of requests you can make, as well as many different objects that you can use and receive as responses.

+

Since your browser is capable of sending HTTPS requests, you can use it to quickly try out the API. After obtaining your token, try pasting this string into your browser:

+
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getMe
+

In theory, you could interact with the API with basic requests like this, either via your browser or other tailor-made tools like cURL. While this can work for simple requests like the example above, it's not practical for larger applications and doesn't scale well.
For that reason, this guide will show you how to use libraries and frameworks, along with some basic programming skills, to build a more robust and scalable project.

+

If you know how to code, you'll fly right through each step in no time – and if you're just starting out, this guide will show you everything you need to learn.

+
+

We will use Java throughout this guide as it's one of the most popular programming languages, however, you can follow along with any language as all the steps are fundamentally the same.
Since Java is fully cross-platform, each code example will work with any operating system.
If you pick another language, equivalent examples are available in C#, Python, Go and TypeScript .

+
+

Getting Ready

+

First, we will briefly cover how to create your first project, obtain your API token and download all necessary dependencies and libraries.

+

Obtain Your Bot Token

+

In this context, a token is a string that authenticates your bot (not your account) on the bot API. Each bot has a unique token which can also be revoked at any time via @BotFater.

+

Obtaining a token is as simple as contacting @BotFater, issuing the /newbot command and following the steps until you're given a new token. You can find a step-by-step guide here.

+

Your token will look something like this:

+
4839574812:AAFD39kkdpWt3ywyRZergyOLMaJhac60qc
+
+

Make sure to save your token in a secure place, treat it like a password and don't share it with anyone.

+
+

Download an IDE

+

To program in Java you'll need an IDE – a special text editor that will let you write, compile and run your code.
In this tutorial, we'll use IntelliJ – there are several free, open source alternatives like Eclipse or NetBeans which work in the exact same way.

+

You will also need a JDK, a software kit that allows your Java code to run.
Most IDEs don't include a JDK, so you should download a version compatible with your operating system separately. You can find a free, open source version here.

+
+

If you use another language, the steps are identical. You will just have to download a different IDE and software development kit.

+
+

Pick a Framework or Library

+

You can think of a framework as software that handles all the low-level logic for you, including the API calls, and lets you focus on your bot-specific logic.

+

In this tutorial, we'll use TelegramBots, but you can follow along with any equivalent implementation, since all the underlying methods are either similar or exactly the same.

+
+

You can find many frameworks, along with code examples, in our dedicated list.

+
+

Create Your Project

+

In IntelliJ, go to File > New > Project.

+

Fill in the fields accordingly:

+
    +
  • Name - The name of your project. For example, BotTutorial.
  • +
  • Location - Where to store your project. You can use the default value.
  • +
  • Language - Java
  • +
  • Build System - The framework that will handle your dependencies. Pick Maven.
  • +
  • JDK - Pick whichever version you downloaded. We'll be using version 17.
  • +
  • Add Sample Code - Leave this selected, it will generate some needed files for you.
  • +
  • Advanced Settings > GroupId - We suggest tutorial.
  • +
  • Advanced Settings > ArtifactId - You can use the default value.
  • +
+

After hitting Create, if you did everything correctly, your Project view in the top left should show a project structure along these lines:

+
BotTutorial
+├─ .idea
+├─ src
+│  └─ main
+│     └─ java
+│        └─ tutorial
+│           └─ Main
+└─ pom.xml
+
+

Other IDEs will follow a similar pattern. Your dependency management system will have a different name (or no name at all if it's built-in) depending on the language you chose.

+
+

If this looks scary, don't worry. We will only be using the Main file and the pom.xml file.
In fact, to check that everything is working so far, double click on Main and click on the small green arrow on the left of public class Main, then select the first option.
If you followed the steps correctly, Hello world! should appear in the console below.

+

Add Framework Dependency

+

We will now instruct the IDE to download and configure everything needed to work with the API.
This is very easy and happens automatically behind the scenes.

+

First, locate your pom.xml file on the left side of the screen.
Open it by double-clicking and simply add:

+
<dependencies>
+    <dependency>
+        <groupId>org.telegram</groupId>
+        <artifactId>telegrambots</artifactId>
+        <version>6.0.1</version>
+    </dependency>
+</dependencies>
+

right after the </properties> tag.

+

When you're done, your pom.xml should look something like this.

+

Start Coding

+

We are ready to start coding. If you're a beginner, consider that being familiar with your language of choice will greatly help. With this tutorial, you'll be able to teach your bot basic behaviors, though more advanced features will require some coding experience.

+

Creating a Bot Class

+

If you're familiar with object-oriented programming, you'll know what a class is.
If you've never heard of it before, consider a class as a file where you write some logic.

+

To create the class that will contain the bot logic, right click on tutorial from the project tree on the left and select New > Java Class. Name it Bot and hit enter.

+

Now we have to connect this class to the bot framework. In other words, we must make sure it extends TelegramLongPollingBot. To do that, just add extends TelegramLongPollingBot right after Bot.
A red line will appear – it simply means we're missing some important methods.

+

To fix this, hover over the red line, click on implement methods, then hit OK.
Depending on the IDE, this option may be called implement missing methods or something similar.

+

You should end up with this – if something went wrong, feel free to copy it from here and paste it in your class:

+
package tutorial;
+import org.telegram.telegrambots.bots.TelegramLongPollingBot;
+import org.telegram.telegrambots.meta.api.objects.Update;
+
+public class Bot extends TelegramLongPollingBot {
+
+  @Override
+  public String getBotUsername() {
+      return null;
+  }
+
+  @Override
+  public String getBotToken() {
+      return null;
+  }
+
+  @Override
+  public void onUpdateReceived(Update update) {}
+
+}
+
+

If you get a red line under TelegramLongPollingBot, it means you didn't set up your pom.xml correctly. If this is the case, restart from here.

+
+

Available Methods

+

Let's look into these 3 methods one by one.

+
    +
  • getBotUsername - This method must be edited to always return your bot's username. You should replace the null return value with it.
  • +
  • getBotToken - This method will be used by the framework to retrieve your bot token. You should replace the null return value with the token.
  • +
  • onUpdateReceived - This is the most important method. It will be called automatically whenever a new Update is available. Let's add a System.out.println(update); call in there to quickly show what we are getting.
  • +
+

After you've replaced all the strings, you should end up with this:

+
@Override
+public String getBotUsername() {
+    return "TutorialBot";
+}
+
+@Override
+public String getBotToken() {
+    return "4839574812:AAFD39kkdpWt3ywyRZergyOLMaJhac60qc";
+}
+
+@Override
+public void onUpdateReceived(Update update) {
+    System.out.println(update);
+}
+

At this point, the bot is configured and ready to go – time to register it on the API and start processing updates.

+
+

In the future, you should consider storing your token in a dedicated settings file or in environment variables. Keeping it in the code is fine for the scope of this tutorial, however, it's not very versatile and is generally considered bad practice.

+
+

Registering the Bot

+

To register the bot on the API, simply add a couple of lines in the main method that will launch the application. If you named your class Bot, this is what your main method should look like:

+
public static void main(String[] args) throws TelegramApiException {
+  TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
+  botsApi.registerBot(new Bot());
+}
+
+

You can place this method in any class. Since we have an auto-generated main method in the Main class, we'll be using that one for this tutorial.

+
+

First Run

+

It's time to run your bot for the first time.
Hit the green arrow to the left of public static void main and select the first option.

+

And then there was nothing. Yes, a bit anticlimactic.
This is because your bot has nothing to print – there are no new updates because nobody messaged it yet.

+

If you try messaging the bot on Telegram, you'll then see new updates pop up in the console. At this point, you have your very own Telegram Bot – quite the achievement. Now, on to making it a bit more intelligent.

+
+

If nothing pops up, make sure you messaged the right bot and that the token you pasted in the code is correct.

+
+

Receiving Messages

+

Every time someone sends a private message to your bot, your onUpdateReceived method will be called automatically and you'll be able to handle the update parameter, which contains the message, along with a great deal of other info which you can see detailed here.

+

Let's focus on two values for now:

+
    +
  • The user - Who sent the message. Access it via update.getMessage().getFrom().
  • +
  • The message - What was sent. Access it via update.getMessage().
  • +
+

Knowing this, we can make it a bit more clear in the console output.

+
@Override
+public void onUpdateReceived(Update update) {
+    var msg = update.getMessage();
+    var user = msg.getFrom();
+
+    System.out.println(user.getFirstName() + " wrote " + msg.getText());
+}
+

This is just a basic example – you can now play around with all the methods to see everything you can pull out of these objects. You can try getUsername, getLanguageCode, and dozens more.

+

Knowing how to receive, process and print incoming messages, now it's time to learn how to answer them.

+
+

Remember to stop and re-launch your bot after each change to the code.

+
+

Sending Messages

+

To send a private text message, you generally need three things:

+
    +
  • The user must have contacted your bot first. (Unless the user sent a join request to a group where your bot is an admin, but that's a more advanced scenario).
  • +
  • You must have previously saved the User ID (user.getId())
  • +
  • A String object containing the message text, 1-4096 characters.
  • +
+

With that out of the way, let's create a new method to send the first message:

+
public void sendText(Long who, String what){
+   SendMessage sm = SendMessage.builder()
+                    .chatId(who.toString()) //Who are we sending a message to
+                    .text(what).build();    //Message content
+   try {
+        execute(sm);                        //Actually sending the message
+   } catch (TelegramApiException e) {
+        throw new RuntimeException(e);      //Any error will be printed here
+   }
+}
+

And proceed to run this in the main method, right after registering the bot.
For this example, we'll assume your User ID is 1234.

+
public static void main(String[] args) throws TelegramApiException {
+   TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
+   Bot bot = new Bot();                  //We moved this line out of the register method, to access it later
+   botsApi.registerBot(bot);            
+   bot.sendText(1234L, "Hello World!");  //The L just turns the Integer into a Long
+}
+

If you did everything correctly, your bot should text you Hello World! every time you launch your code. Sending messages to groups or channels – assuming you have the relevant permissions – is as simple as replacing 1234 with the ID of the respective chat.

+
+

Try experimenting with other types of messages, like SendPhoto, SendSticker, SendDice…
A full list is available starting here.

+
+

Echo Bot

+

Let's practice everything we tried so far by coding an Echo Bot.
Its functionality will be rather simple: every text message it receives will be sent right back to the user.

+

Copying Text

+

The most intuitive way of coding this is saving the User ID and calling sendText right after each update.

+

In other words:

+
@Override
+public void onUpdateReceived(Update update) {
+    var msg = update.getMessage();
+    var user = msg.getFrom();
+    var id = user.getId();
+
+    sendText(id, msg.getText());
+}
+

This works for text but can be extended to stickers, media and files.

+

Copying Everything

+

There are more specific functions that can be used to copy messages and send them back.
Let's build a method to do just that:

+
public void copyMessage(Long who, Integer msgId){
+   CopyMessage cm = CopyMessage.builder()
+              .fromChatId(who.toString())  //We copy from the user
+           .chatId(who.toString())      //And send it back to him
+           .messageId(msgId)            //Specifying what message
+           .build();
+    try {
+        execute(cm);
+    } catch (TelegramApiException e) {
+        throw new RuntimeException(e);
+    }
+}
+

After replacing the method call inonUpdateReceived, running the code will result in a fully functional Echo Bot.

+
+

This tutorial assumes that updates always contain messages for the sake of simplicity. This may not always be true – be sure to implement all the proper checks in your code to handle every type of update with the appropriate methods.

+
+

Executing Commands

+

To learn what a command is and how it works, we recommend reading this dedicated summary.
In this guide, we'll focus on the technical side of things.

+

Creating Your Command

+

Begin by opening @BotFater.
Type /mybots > Your_Bot_Name > Edit Bot > Edit Commands.

+

Now send a new command, followed by a brief description.
For the purpose of this tutorial, we'll implement two simple commands:

+
scream - Speak, I'll scream right back 
+whisper - Shhhhhhh
+

Command Logic

+

We want the Echo Bot to reply in uppercase when it's in scream mode and normally otherwise.

+

First, let's create a variable to store the current mode.

+
public class Bot extends TelegramLongPollingBot {
+
+   private boolean screaming = false;
+
+   [...]
+}
+

Then, let's change some logic to account for this mode.

+
public void onUpdateReceived(Update update) {
+    [...]                                   //Same variables as the previous versions
+   if(screaming)                            //If we are screaming
+       scream(id, update.getMessage());     //Call a custom method
+   else
+       copyMessage(id, msg.getMessageId()); //Else proceed normally
+}
+
+private void scream(Long id, Message msg) {
+   if(msg.hasText())
+       sendText(id, msg.getText().toUpperCase());
+   else
+       copyMessage(id, msg.getMessageId());  //We can't really scream a sticker
+}
+

Finally, let's add a couple more lines to the onUpdateReceived method to process each command before replying.

+
if(msg.isCommand()){ 
+   if(msg.getText().equals("/scream"))         //If the command was /scream, we switch gears
+      screaming = true;
+   else if (msg.getText().equals("/whisper"))  //Otherwise, we return to normal
+      screaming = false;
+
+   return;                                     //We don't want to echo commands, so we exit
+}
+

As you can see, it checks if the message is a command. If it is, the bot enters scream mode.
In the update method, we check which mode we are in and either copy the message or convert it to upper case before sending it back.

+

And that's it. Now the bot can execute commands and change its behavior accordingly.

+

Naturally, this simplified logic will change the bot's behavior for everyone – not just the person who sent the command. This can be fun for this tutorial but won't work in a production environment – consider using a Map, dictionary or equivalent data structure to assign settings for individual users.

+
+

Remember to always implement a few basic global commands.
You can practice by implementing a simple feedback to the /start command, which we intentionally left out.

+
+

Buttons and Keyboards

+

To streamline and simplify user interaction with your bot, you can replace many text-based exchanges with handy buttons. These buttons can perform a wide variety of actions and can be customized for each user.

+

Button Types

+

There are two main types of buttons:

+
    +
  • Reply Buttons - used to provide a list of predefined text reply options.
  • +
  • Inline Buttons - used to offer quick navigation, shortcuts, URLs, games and so much more.
  • +
+

Using these buttons is as easy as attaching a ReplyKeyboardMarkup or an InlineKeyboardMarkup to your SendMessage object.

+

This guide will focus on inline buttons since they only require a few extra lines of code.

+

Creating Buttons

+

First of all, let's create some buttons.

+
 var next = InlineKeyboardButton.builder()
+            .text("Next").callbackData("next")           
+            .build();
+
+ var back = InlineKeyboardButton.builder()
+            .text("Back").callbackData("back")
+            .build();
+
+ var url = InlineKeyboardButton.builder()
+            .text("Tutorial")
+            .url("https://core.telegram.org/bots/api")
+            .build();
+

Let's go back through the fields we specified:

+
    +
  • Text - This is what the user will see, the text that appears on the button
  • +
  • Callback Data - This will be sent back to the code instance as part of a new Update, so we can quickly identify what button was clicked.
  • +
  • Url - A button that specifies a URL doesn't specify callbackdata since its behavior is predefined – it will open the given link when tapped.
  • +
+

Creating Keyboards

+

The buttons we created can be assembled into two keyboards, which will then be used to navigate back and forth between two sample menus.

+

First, add two fields to store the necessary keyboards.

+
private boolean screaming = false;
+
+private InlineKeyboardMarkup keyboardM1;
+private InlineKeyboardMarkup keyboardM2;
+

Then, build and assign them.

+
keyboardM1 = InlineKeyboardMarkup.builder()
+          .keyboardRow(List.of(next)).build();  
+
+//Buttons are wrapped in lists since each keyboard is a set of button rows
+keyboardM2 = InlineKeyboardMarkup.builder()
+          .keyboardRow(List.of(back))
+          .keyboardRow(List.of(url))
+          .build();
+
+

You can place this code wherever you prefer, the important thing is making sure that keyboard variables are accessible from the method call that will send the new menu. If you're confused by this concept and don't know where to put them, just paste them above the command processing flow.

+
+

Sending Keyboards

+

Sending a keyboard only requires specifying a reply markup for the message.

+
public void sendMenu(Long who, String txt, InlineKeyboardMarkup kb){
+    SendMessage sm = SendMessage.builder().chatId(who.toString())
+            .parseMode("HTML").text(txt)
+            .replyMarkup(kb).build();
+
+    try {
+        execute(sm);
+    } catch (TelegramApiException e) {
+        throw new RuntimeException(e);
+    }
+}
+
+

You may have noticed that we also added a new parameter, HTML.
This is called a formatting option and will allow us to use HTML tags and add formatting to the text later on.

+
+

Menu Trigger

+

We could send a new menu for each new user, but for simplicity let's add a new command that will spawn a menu. We can achieve this by adding a new else clause to the previous command flow.

+
 var txt = msg.getText();
+ if(msg.isCommand()) {
+        if (txt.equals("/scream"))
+            screaming = true;
+        else if (txt.equals("/whisper"))
+            screaming = false;
+        else if (txt.equals("/menu"))
+            sendMenu(id, "<b>Menu 1</b>", keyboard1);
+        return;
+ }
+

Try sending /menu to your bot now. If you did everything correctly, you should see a brand new menu pop up.

+
+

In a production environment, commands should be handled with an appropriate design pattern that isolates them into different executor classes – modular and separated from the main logic.

+
+

Navigation

+

When building complex bots, navigation is essential. Your users must be able to move seamlessly from one menu to the next.

+

In this example, we want the Next button to lead the user to the second menu.
The Back button will send us back.
To do that, we will start processing incoming CallbackQueries, which are the results we get after the user taps on a button.

+

A CallbackQuery is essentially composed of three main parameters:

+
    +
  • queryId - Needed to close the query. You must always close new queries after processing them – if you don't, a loading symbol will keep showing on the user's side on top of each button.
  • +
  • data - This identifies which button was pressed.
  • +
  • from - The user who pressed the button.
  • +
+

Processing in this context just means executing the action uniquely identified by the button, then closing the query.

+

A very basic button handler could look something like:

+
private void buttonTap(Long id, String queryId, String data, int msgId) {
+
+    EditMessageText newTxt = EditMessageText.builder()
+            .chatId(id.toString())
+            .messageId(msgId).text("").build();
+
+    EditMessageReplyMarkup newKb = EditMessageReplyMarkup.builder()
+            .chatId(id.toString()).messageId(msgId).build();                           
+
+    if(data.equals("next")) {
+        newTxt.setText("MENU 2");
+        newKb.setReplyMarkup(keyboardM2);
+    } else if(data.equals("back")) {
+        newTxt.setText("MENU 1");
+        newKb.setReplyMarkup(keyboardM1);
+    }
+
+    AnswerCallbackQuery close = AnswerCallbackQuery.builder()
+            .callbackQueryId(queryId).build();
+
+    execute(close);
+    execute(newTxt);
+    execute(newKb);
+}
+

With this handler, whenever a button is tapped, your bot will automatically navigate between inline menus.
Expanding on this concept allows for endless combinations of navigable submenus, settings and dynamic pages.

+

Database

+

Telegram does not host an update database for you – once you process and consume an update, it will no longer be available. This means that features like user lists, message lists, current user inline menu, settings, etc. have to be implemented and maintained by bot developers.

+

If your bot needs one of these features and you want to get started on data persistence, we recommend that you look into serialization practices and libraries for your language of choice, as well as available databases.

+

Implementing a database is out of scope for this guide, however, several guides are available online for simple embedded open source software solutions like SQLite, HyperSQL, Derby and many more.

+
+

Your language of choice will also influence which databases are available and supported – the list above assumes you followed this Java tutorial.

+
+

Hosting

+

So far, your bot has been running on your local machine – your PC. While this may be good for developing, testing and debugging, it is not ideal for a production environment.
You'll want your bot to be available and responsive at all times, but your computer might not always be online.

+

This can be done in four steps:

+
    +
  • Package your code
    Making your bot easy to move and runnable outside of an IDE is essential to host it elsewhere.
    If you followed this tutorial, this standard guide will work for you. If you didn't, look into export or packaging guides for your IDE and language of choice – procedures may vary but the end result is the same.

    +
  • +
  • Purchase a VPS or equivalent service
    A server is essentially a machine that is always online and running, without you having to worry about anything. To host your bot, you can opt for a VPS which serves this purpose and can be rented from several different providers.
    Another option would be to purchase a network-capable microcontroller, which come in all different specs and sizes depending on your needs.

    +
  • +
+
+

You should ensure that all user data remains heavily encrypted at all times in your database to guarantee the privacy of your users. The same concept applies to your local instance, however, this becomes especially important once you transfer your database to a remote server.

+
+
    +
  • Upload your executable/package
  • +
+

Once you have a working ssh connection between your machine and your new server, you should upload your executable and all associated files.
We will assume the runnable jar TutorialBot.jar and its database dbase.db are currently in the /TBot folder.

+
$ scp -r /TBot/ username@server_ip:/bots/TBotRemote/
+
    +
  • Run your application
  • +
+

Depending on which language you chose, you might have to configure your server environment differently. If you chose Java, you just need to install a compatible JDK.

+
$ apt install openjdk-17-jre
+$ java -version
+

If you did everything correctly, you should see a Java version as the output, along with a few other values. This means you're ready to run your application.

+

Now, to run the executable:

+
$ cd /bots/TBotRemote/
+$ java -jar TutorialBot.jar
+

Your bot is now online and users can interact with it at any time.

+
+

To streamline and modularize this process, you could employ a specialized docker container or equivalent service.
If you followed along in one of the equivalent examples (C#, Python, Go and TypeScript) you can find a detailed set of instructions to export and run your code here.

+
+

Further Reading

+

If you got this far, you might be interested in these additional guides and docs:

+ +

If you encounter any issues while following this guide, you can contact us on Telegram at @BotSupport.

+
+ +
+ +
+
+ +
+ + + + + + + + diff --git a/data/web/core.telegram.org/bots/features.html b/data/web/core.telegram.org/bots/features.html new file mode 100644 index 0000000000..fd19844ffc --- /dev/null +++ b/data/web/core.telegram.org/bots/features.html @@ -0,0 +1,583 @@ + + + + + Telegram Bot Features + + + + + + + + + + + + + + + + +
+ +
+
+
+ +

Telegram Bot Features

+ +
+ +

This page describes individual bot elements and features in detail. See also:

+ +

What features do bots have?

+ +
+

Inputs

+

Users can send messages of all types to bots, including text, files, locations, stickers, voice messages and even dice if they're feeling lucky. However, Telegram bots offer many other tools for building flexible interfaces tailored to your specific needs:

+
    +
  • Commands that are highlighted in messages and can be selected from a list after typing /.
  • +
  • Keyboards that replace the user's keyboard with predefined answer options.
  • +
  • Buttons that are shown next to messages from the bot.
  • +
+

For even more flexibility, Web Apps support 100% custom interfaces with Javascript.

+
+ +
+ +
+

Note: Telegram bots can support multiple languages that adapt to the users' language settings in the app.

+
+

Commands

+

A command is a simple /keyword that tells the bot what to do. Telegram apps will:

+
    +
  • Highlight commands in messages. When the user taps a highlighted command, that command is immediately sent again.
  • +
  • Suggest a list of supported commands with descriptions when the user enters a / (for this to work, you need to have provided a list of commands to @BotFather or via the appropriate API method). Selecting a command from the list immediately sends it.
  • +
  • Show a menu button containing all or some of a bot’s commands (which you set via @BotFather).
  • +
+

Commands must always start with the / symbol and contain up to 32 characters. They can use Latin letters, numbers and underscores, though simple lowercase text is recommended for a cleaner look.

+

Here are a few examples:

+
    +
  • /next
  • +
  • /cancel
  • +
  • /newlocation
  • +
  • /newrule
  • +
+

Commands should be as specific as possible – for example /newlocation or /newrule is better than a /new command that then requires an additional parameter from the user like "location“ or ”rule".

+
+ +
+ +
+

We require all developers to support several Global Commands to make sure Telegram bots offer a consistent and user-friendly experience.

+
+
Command Scopes
+

Your bot is able to show different commands to different users and groups – you can control this using scopes. For example, your bot could show additional commands to group admins or translate the list based on the user’s language_code.

+
+

Keep in mind that Bot API updates will not contain any information about the scope of a command sent by the user – in fact, they may contain commands that don’t exist at all in your bot. Your backend should always verify that received commands are valid and that the user was authorized to use them regardless of scope.

+

Bots with privacy mode enabled will only receive commands in groups under special conditions, see here.

+
+

Keyboards

+

Bots are able to interpret free text input from users, but offering specific suggestions is often more intuitive – this is where custom keyboards can be extremely useful.

+

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

+
+ +
+ +
+

Check out the one_time_keyboard parameter to automatically hide your bot's keyboard as soon as it's been used.

+
+

Inline Keyboards

+

There are times when you'd prefer to do things without sending any messages to the chat – like when a user is changing settings, toggling options or navigating search results. In such cases, you can use Inline Keyboards that are shown directly below their relevant messages.

+

Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn't send messages to the chat. Instead, inline keyboards support buttons that can work behind the scenes or open different interfaces: callback buttons, URL buttons, switch-to-inline buttons, game buttons and payment buttons.

+
+ +
+ +
+

To provide a better user experience, consider editing your keyboard when the user toggles a setting button or navigates to a new page – this is both faster and smoother than sending a whole new message and deleting the previous one.

+
+

Menu Button

+

In all bot chats, a menu button appears near the message field. By default, tapping this button opens a menu that can hold some or all of a bot's commands, including a short description for each. Users can then select a command from the menu without needing to type it out.

+

You can set different texts of the menu button and its command descriptions for various individual users or groups of users – for example, showing translated text based on the user’s language, as explained here.

+
+ +
+ +
+

Remember that you can also customize the text placeholder in the input field by setting the input_field_placeholder parameter.

+
+

The menu button can alternatively be used to launch a Web App.

+

Global Commands

+

To make basic interactions more uniform, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

+
    +
  • /start - begins the interaction with the user, like sending an introductory message. This command can also be used to pass additional parameters to the bot (see Deep Linking).
  • +
  • /help - returns a help message, like a short text about what your bot can do and a list of commands.
  • +
  • /settings - (if applicable) shows the bot's settings for this user and suggests commands to edit them.
  • +
+

Users will see a Start button the first time they open a chat with your bot. Help and Settings links will be available in the menu on the bot's profile page if you add them in @BotFather.

+
+

Interactions

+

In addition to sending commands and messages to the chat with the bot, there are several ways of interacting with them without opening any specific chat or group.

+
    +
  • Inline mode allows sending requests to bots right from the input field – from any chat on Telegram.
  • +
  • Deep linking allows special links that send certain parameters to the bot when opened.
  • +
  • Attachment menu integration makes it possible to use bots from the attachment menu in chats.
  • +
+

Inline Requests

+

Users can interact with your bot via inline queries straight from the message field in any chat. All they need to do is start a message with your bot's @username and enter a keyword.

+

Having received the query, your bot can return some results. As soon as the user selects one, it is sent to the relevant chat. This way, people can request and send content from your bot in any of their chats, groups or channels.

+

Remember that inline functionality has to be enabled via @BotFather, or your bot will not receive inline Updates.

+
+ +
+ +
+

Examples of inline bots include @gif, @bing and @wiki.

+
+

Deep Linking

+

Telegram bots have a deep linking mechanism that allows additional parameters to be passed 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 another platform.

+

Each bot has a link that opens a conversation with it in Telegram – https://t.me/<bot_username>. Parameters can be added directly to this link to let your bot work with additional information on the fly, without any user input.

+
+

A-Z, a-z, 0-9, _ and - are allowed. We recommend using base64url to encode parameters with binary and other types of content. The parameter can be up to 64 characters long.

+
+

Private Chats
In private chats, you can use the start parameter to automatically pass any value to your bot whenever a user presses the link. For example, you could use:

+
https://t.me/your_bot?start=airplane
+

When someone opens a chat with your bot via this link, you will receive:

+
/start airplane
+

Groups
In groups, you can add the parameter startgroup to this link. For example:

+
https://t.me/your_bot?startgroup=spaceship
+

Following a link with this parameter prompts the user to select a group to add the bot to – the resulting update will contain text in the form:

+
/start@your_bot spaceship
+
+

Web Apps also support deep linking, for more information check out our dedicated guide.

+
+

Attachment Menu

+

Certain bots can be added directly to a user’s attachment menu – giving them easy access to the bot in any chat. Currently, this option is restricted to certain approved bots, but may be expanded later.

+
+ +
+ +
+

Try adding @DurgerKingBot to your attachment menu.

+
+
+

Integration

+

There are various ways of futher integrating bots with Telegram and other services.

+
    +
  • Use Web Apps to replace any website.
  • +
  • Accept Payments via dozens of integrated third-party payment providers.
  • +
  • Connect to Telegram using the Web Login functionality.
  • +
  • Create gaming bots by integrating HTML5 Games.
  • +
  • Help users create and manage Telegram Stickers.
  • +
+

Web Apps

+

Bots can easily process complex inputs of any kind and dynamic interaction flows via Web Apps. With this unique feature, you can develop any number of flexible, streamlined interfaces in JavaScript.

+
+

Web Apps are covered in detail in our dedicated guide – you should read it carefully to learn the wide variety of features they can offer.

+
+
+ +
+ +

If you develop a Web App, be sure to follow our design guidelines – you'll want your custom interface to seamlessly integrate into the app to provide users the best possible experience.

+

Payments

+

Telegram bots can accept payments with a sleek, streamlined interface that collects all necessary data from the user. Telegram doesn't collect any payment data – like the user's credit card information – and sends it directly to one of the supported payment providers.

+

Here is a quick start guide to implement payments:

+ +

Then, to issue an invoice and process the order flow:

+ +

A full and exhaustive guide, including live checklist, parameters and in-depth method descriptions is available here. We strongly recommend that you read the full guide before going live.

+
+ +
+ +
+

Telegram does not directly process the payments, does not store data about orders and does not collect any fees. Invoices are forwarded directly to the payment provider.
For this reason, disputes must be solved between the user, the bot developer and the payment provider. You can read more about this in the Privacy Policy.

+
+

Web Login

+

Telegram offers a flexible, lightweight and free framework to authenticate users on any website and app. This can be used to bridge your platform with Telegram, providing a smooth experience to your users. You can also freely rely on this framework to implement a fast and signup-free login on your site, regardless of its connection to Telegram.

+

Widgets

+

The Telegram login widget is a simple and secure way to authorize users on your website.

+
    +
  1. Choose a bot – ideally its name and profile pic should match the website title and logo.
  2. +
  3. Use the /setdomain command in @BotFather to pair the bot with your website domain.
  4. +
  5. Configure your widget using our dedicated tool and embed it on your website.
  6. +
+

Inline Login

+

When users open your website via an inline button, you can use the login_url parameter as an alternative to login widgets. This way, you'll be able to seamlessly authorize them on your website or app before the page even loads.

+
+ +
+ +
+

Make sure to review our guide on authenticating the received data as well as our sample code.

+
+

HTML5 Games

+

Bots can serve as standalone gaming platforms – with our HTML5 Gaming API you can develop multiplayer or single-player games and let your users have fun comparing ranks, scores and much more.

+

To get started, follow these simple steps:

+
    +
  • Send the /newgame command to @BotFather
  • +
  • Provide a description text, an image or an optional gif to showcase its gameplay
  • +
  • Send the game to users via the sendGame method or via an inline query
  • +
  • When someone wants to play, you'll receive the appropriate game_short_name in a CallbackQuery
  • +
  • To launch the game, provide the HTML5 Game URL as the url param of answerCallbackQuery
  • +
+

Then, to handle highscores:

+ +

You can also embed a share button within your game, play around with custom inline buttons, URL parameters and much more. To get a better idea, make sure to check out:

+ +
+ +
+ +
+

Check out @GameBot and @gamee for examples of what you can do using our Gaming Platform.

+
+

Stickers

+

Stickers are a distinctive Telegram feature used by millions of users to share artwork every day. Stickers take many forms – ranging from basic images to smooth vector animations and high-detail .WEBM videos.

+

All these formats are supported by our Bot API, which allows bots to create, edit, delete and share new sticker packs on the fly. Telegram's Import API lets users migrate packs from other platforms and sticker apps.

+

To create a new sticker pack, follow these simple steps:

+
    +
  • Upload a new sticker file via uploadStickerFile. Repeat for all the stickers in the set. You will use the returned files in the next step, so keep them around.
  • +
  • Create a new sticker pack via createStickerSet. Attach the files you collected in step 1 and remember to only specify one of the three avaiable fields – png_sticker, tgs_sticker and webm_sticker – depending on which sticker format you uploaded.
  • +
  • Complete the pack by adding each remaining sticker in sequence via addStickerToSet.
  • +
+
+

Once you're done, don't forget to check out our remaining sticker methods to find out how to edit, delete and even reorder your pack.
Note that these methods will only work on packs created by the bot that is calling them.

+
+

Language Support

+

Bots can tailor their interfaces to support multiple languages – updating inputs and information on the fly. A user’s in-app language_code is included in every relevant update as an IETF language tag, allowing bots to adapt accordingly.

+

We recommend that you follow our guidelines to provide the best user experience.

+
    +
  • Your interfaces, texts and inline results should adapt seamlessly to the language_code, without user intervention.
  • +
  • Connected WebApps will receive the user's language_code – your HTML page should account for it.
  • +
  • HTML5 Games can obtain language information if you specify it as a URL parameter. You can generate this parameter from the language_code field in the User object served with the initial game CallbackQuery.
  • +
  • Command lists can also be specified for individual languages – more on this here.
  • +
+
+ +
+ +
+

The language_code is an optional field – it could be empty.
If you target the general public, your code should always fall back to either the last recorded language tag or English (in this order) when the field is missing for a specific user.

+
+
+

Bot Management

+

Privacy Mode

+

Bots are frequently added to groups to perform basic tasks or assist moderators – like automatically posting company announcements or even celebrating birthdays. By default, all bots added to groups run in Privacy Mode and only see relevant messages and commands:

+
    +
  • Commands explicitly meant for them (e.g., /command@this_bot).
  • +
  • General commands (e.g. /start) if the bot was the last bot to send a message to the group.
  • +
  • Inline messages sent via the bot.
  • +
  • Replies to any messages implicitly or explicitly meant for this bot.
  • +
+

All bots will also receive, regardless of privacy mode:

+
    +
  • All service messages.
  • +
  • All messages from private chats.
  • +
  • All messages from channels where they are a member.
  • +
+

Privacy mode is enabled by default for all bots, except bots that were added to a 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. In most cases, using the force reply option for the bot's messages should be more than enough.

+
+ +
+ +
+

This mode not only increases user privacy, but also makes the bot more efficient by reducing the number of inputs it needs to process. Users can always see a bot’s current privacy setting in the list of group members.

+
+

Status alerts

+

Millions choose Telegram for its speed. To best benefit users, 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 check the number of replies and the request/response conversion rate for popular bots (~300 requests per minute, this value may change in the future). If your bot returns an abnormally low number, 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:

+
    +
  • Fixed - Use this if you found an issue with your bot and fixed it. If you press the fix button, we will resume sending alerts in the regular way so that you can see if your fix worked within 5-10 minutes instead of having to wait for an hour.
  • +
  • Support - Use this to open a chat with @BotSupport if you don't see any issues with your bot or if you think the problem is on our side.
  • +
  • Mute for 8h/1w - Use this if you can't fix your bot at the moment. This will disable all alerts for the bot in question for the specified period of time. We do not recommend using this option since your users may migrate to a more stable bot. You can unmute alerts in your bot's settings via @BotFather.
  • +
+
Monitored issues
+

We currently notify you about the following issues:

+
    +
  • Too few private messages are sent. Value: {value} - Your bot is sending far fewer messages than it did in previous weeks. This is useful for newsletter-style bots that send messages without prompts from users. The larger the value, the more significant the difference.

    +
  • +
  • Too few replies to incoming private messages. Conversion rate: {value} - 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).

+
+
    +
  • Too few answers to inline queries. Conversion rate: {value} - 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.
  • +
+
    +
  • Too few answers to callback queries. Conversion rate: {value}
  • +
  • Too few answers to callback game queries. Conversion rate: {value} - 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.
  • +
+

Local Bot API

+

You can host and work with your own instance of our open-source Bot API.
The source code is available here, along with a quick installation guide.

+

After installing the server, remember to use the logOut method before redirecting requests to your new local API URL.

+
+

Your local instance runs on port 8081 by default and will only accept HTTP requests, so a TLS termination proxy has to be used to handle remote HTTPS requests.

+
+

By hosting our API locally you'll gain access to some upgrades, including:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
APIMax File DownloadMax File UploadWHook URLWHook PortWHook Max Connections
Official20MB50MBHTTPS443,80,88,84431-100
LocalUnlimited2000MBHTTPAny port1-100000
+
+

You can find an exhaustive list here.
All limits may be subject to change in the future, so make sure to follow @BotNews.

+
+
+

BotFather

+

Below is a detailed guide to using @BotFather, Telegram’s tool for creating and managing bots.

+

Creating a new bot

+

Use the /newbot command to create a new bot. @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, used in search, mentions and t.me links. Usernames are 5-32 characters long and not case sensitive – but may only include Latin characters, numbers, and underscores. Your bot's username must end in 'bot’, like 'tetris_bot' or 'TetrisBot'.

    +
  • +
  • The token is a string, like 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw, which 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.

    +
  • +
+
+

Unlike the bot’s name, the username cannot be changed later – so choose it carefully.
When sending a request to api.telegram.org, remember to prefix the word ‘bot’ to your token.

+
+

About text, description and profile media

+

When new users open your bot, they will be met with a helpful description in a box titled “What can this bot do?”.

+

Properly setting this field in @BotFather allows everyone to immediately get an idea of what your bot can do – your description should be brief, to the point and on topic.

+
+

You can also add a photo or video to this field with Edit Description Picture in @BotFather.

+
+

Additionally, just like normal users, bots also come with a short bio available on their profile. If you didn't specify this field while first creating your bot, you can set it at any time with the /setabouttext command in @BotFather. Users can interact with many bots and they won't have access to their description after starting them – having a quick reminder of the bot's purpose can be very useful.

+

Bots can also have a profile picture – you should pick something unique and original so that users can find it in their chat list at a glance.

+
+

Once set, the description, about text and profile pic can be replaced but never fully removed.

+
+

Generating an authentication token

+

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

+

Transfer ownership

+

You can transfer ownership of your bot to another user.
To do this, send /mybots, select your bot, then transfer ownership.
You can only transfer a bot to users who have interacted with it at least once.

+
+

Transferring ownership will give full control of the bot to another user – they will be able to access the bot’s messages and even delete it. The transfer is permanent, so please consider it carefully.

+
+

BotFather commands

+

The remaining commands are pretty self-explanatory:

+
    +
  • /mybots – returns a list of your bots with handy controls to edit their settings.
  • +
  • /mygames – does the same for your games.
  • +
+

Edit bots

+

To edit your bot, you have two options.

+

You can use the available commands:

+
    +
  • /setname – change your bot's name.
  • +
  • /setdescription – change the bot's description (short text up to 512 characters). Users will see this text at the beginning of the conversation with the bot, titled 'What can this bot do?'.
  • +
  • /setabouttext – change the bot's about info, a shorter text up to 120 characters. Users will see this text on the bot's profile page. When they share your bot with someone, this text is sent together with the link.
  • +
  • /setuserpic – change the bot's profile picture.
  • +
  • /setcommands – change the list of commands supported by your bot. Users will see these commands as suggestions when they type / in the chat with your bot. See commands for more info.
  • +
  • /setdomain – link a website domain to your bot. See the login widget section.
  • +
  • /deletebot – delete your bot and free its username. Cannot be undone.
  • +
+

Or you can use the /mybots command, tap on your bot and use the modern inline interface to edit it.

+

Edit settings

+
    +
  • /setinline – toggle inline mode for your bot.
  • +
  • /setinlinegeo – request location data to provide location-based inline results.
  • +
  • /setjoingroups – toggle whether your bot can be added to groups or not. All bots must be able to process direct messages, but if your bot was not designed to work in groups, you can disable this.
  • +
  • /setinlinefeedback – toggle whether the API should send updates about the results chosen by users. See an in-depth explanation here.
  • +
  • /setprivacy – set which messages your bot will receive when added to a group. See privacy-mode for more info.
  • +
+

Manage games

+
    +
  • /newgame – create a new game.
  • +
  • /listgames – see a list of your games.
  • +
  • /editgame – edit a game.
  • +
  • /deletegame – delete an existing game.
  • +
+
+

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

+
+
+

With this information, you are ready to proceed to our Full API Reference for Developers.

+
    +
  • If you have any questions, check out our Bot FAQ.
  • +
  • If you're experiencing issues with our API, please contact @BotSupport on Telegram.
  • +
+
+ +
+ +
+
+ +
+ + + + + + + + diff --git a/data/web/core.telegram.org/bots/tutorial.html b/data/web/core.telegram.org/bots/tutorial.html new file mode 100644 index 0000000000..1103fc3faf --- /dev/null +++ b/data/web/core.telegram.org/bots/tutorial.html @@ -0,0 +1,590 @@ + + + + + From BotFather to 'Hello World' + + + + + + + + + + + + + + + + +
+ +
+
+
+ +

From BotFather to 'Hello World'

+ +
+ +

This guide will walk you through everything you need to know to build your first Telegram Bot.
If you already know your way around some of the basic steps, you can jump directly to the part you're missing. Equivalent examples are available in C#, Python, Go and TypeScript .

+ + + + + + + + + +
+

Introduction

+

At its core, you can think of the Telegram Bot API as software that provides JSON-encoded responses to your queries.

+

A bot, on the other hand, is essentially a routine, software or script that queries the API by means of an HTTPS request and waits for a response. There are several types of requests you can make, as well as many different objects that you can use and receive as responses.

+

Since your browser is capable of sending HTTPS requests, you can use it to quickly try out the API. After obtaining your token, try pasting this string into your browser:

+
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getMe
+

In theory, you could interact with the API with basic requests like this, either via your browser or other tailor-made tools like cURL. While this can work for simple requests like the example above, it's not practical for larger applications and doesn't scale well.
For that reason, this guide will show you how to use libraries and frameworks, along with some basic programming skills, to build a more robust and scalable project.

+

If you know how to code, you'll fly right through each step in no time – and if you're just starting out, this guide will show you everything you need to learn.

+
+

We will use Java throughout this guide as it's one of the most popular programming languages, however, you can follow along with any language as all the steps are fundamentally the same.
Since Java is fully cross-platform, each code example will work with any operating system.
If you pick another language, equivalent examples are available in C#, Python, Go and TypeScript .

+
+

Getting Ready

+

First, we will briefly cover how to create your first project, obtain your API token and download all necessary dependencies and libraries.

+

Obtain Your Bot Token

+

In this context, a token is a string that authenticates your bot (not your account) on the bot API. Each bot has a unique token which can also be revoked at any time via @BotFater.

+

Obtaining a token is as simple as contacting @BotFater, issuing the /newbot command and following the steps until you're given a new token. You can find a step-by-step guide here.

+

Your token will look something like this:

+
4839574812:AAFD39kkdpWt3ywyRZergyOLMaJhac60qc
+
+

Make sure to save your token in a secure place, treat it like a password and don't share it with anyone.

+
+

Download an IDE

+

To program in Java you'll need an IDE – a special text editor that will let you write, compile and run your code.
In this tutorial, we'll use IntelliJ – there are several free, open source alternatives like Eclipse or NetBeans which work in the exact same way.

+

You will also need a JDK, a software kit that allows your Java code to run.
Most IDEs don't include a JDK, so you should download a version compatible with your operating system separately. You can find a free, open source version here.

+
+

If you use another language, the steps are identical. You will just have to download a different IDE and software development kit.

+
+

Pick a Framework or Library

+

You can think of a framework as software that handles all the low-level logic for you, including the API calls, and lets you focus on your bot-specific logic.

+

In this tutorial, we'll use TelegramBots, but you can follow along with any equivalent implementation, since all the underlying methods are either similar or exactly the same.

+
+

You can find many frameworks, along with code examples, in our dedicated list.

+
+

Create Your Project

+

In IntelliJ, go to File > New > Project.

+

Fill in the fields accordingly:

+
    +
  • Name - The name of your project. For example, BotTutorial.
  • +
  • Location - Where to store your project. You can use the default value.
  • +
  • Language - Java
  • +
  • Build System - The framework that will handle your dependencies. Pick Maven.
  • +
  • JDK - Pick whichever version you downloaded. We'll be using version 17.
  • +
  • Add Sample Code - Leave this selected, it will generate some needed files for you.
  • +
  • Advanced Settings > GroupId - We suggest tutorial.
  • +
  • Advanced Settings > ArtifactId - You can use the default value.
  • +
+

After hitting Create, if you did everything correctly, your Project view in the top left should show a project structure along these lines:

+
BotTutorial
+├─ .idea
+├─ src
+│  └─ main
+│     └─ java
+│        └─ tutorial
+│           └─ Main
+└─ pom.xml
+
+

Other IDEs will follow a similar pattern. Your dependency management system will have a different name (or no name at all if it's built-in) depending on the language you chose.

+
+

If this looks scary, don't worry. We will only be using the Main file and the pom.xml file.
In fact, to check that everything is working so far, double click on Main and click on the small green arrow on the left of public class Main, then select the first option.
If you followed the steps correctly, Hello world! should appear in the console below.

+

Add Framework Dependency

+

We will now instruct the IDE to download and configure everything needed to work with the API.
This is very easy and happens automatically behind the scenes.

+

First, locate your pom.xml file on the left side of the screen.
Open it by double-clicking and simply add:

+
<dependencies>
+    <dependency>
+        <groupId>org.telegram</groupId>
+        <artifactId>telegrambots</artifactId>
+        <version>6.0.1</version>
+    </dependency>
+</dependencies>
+

right after the </properties> tag.

+

When you're done, your pom.xml should look something like this.

+

Start Coding

+

We are ready to start coding. If you're a beginner, consider that being familiar with your language of choice will greatly help. With this tutorial, you'll be able to teach your bot basic behaviors, though more advanced features will require some coding experience.

+

Creating a Bot Class

+

If you're familiar with object-oriented programming, you'll know what a class is.
If you've never heard of it before, consider a class as a file where you write some logic.

+

To create the class that will contain the bot logic, right click on tutorial from the project tree on the left and select New > Java Class. Name it Bot and hit enter.

+

Now we have to connect this class to the bot framework. In other words, we must make sure it extends TelegramLongPollingBot. To do that, just add extends TelegramLongPollingBot right after Bot.
A red line will appear – it simply means we're missing some important methods.

+

To fix this, hover over the red line, click on implement methods, then hit OK.
Depending on the IDE, this option may be called implement missing methods or something similar.

+

You should end up with this – if something went wrong, feel free to copy it from here and paste it in your class:

+
package tutorial;
+import org.telegram.telegrambots.bots.TelegramLongPollingBot;
+import org.telegram.telegrambots.meta.api.objects.Update;
+
+public class Bot extends TelegramLongPollingBot {
+
+  @Override
+  public String getBotUsername() {
+      return null;
+  }
+
+  @Override
+  public String getBotToken() {
+      return null;
+  }
+
+  @Override
+  public void onUpdateReceived(Update update) {}
+
+}
+
+

If you get a red line under TelegramLongPollingBot, it means you didn't set up your pom.xml correctly. If this is the case, restart from here.

+
+

Available Methods

+

Let's look into these 3 methods one by one.

+
    +
  • getBotUsername - This method must be edited to always return your bot's username. You should replace the null return value with it.
  • +
  • getBotToken - This method will be used by the framework to retrieve your bot token. You should replace the null return value with the token.
  • +
  • onUpdateReceived - This is the most important method. It will be called automatically whenever a new Update is available. Let's add a System.out.println(update); call in there to quickly show what we are getting.
  • +
+

After you've replaced all the strings, you should end up with this:

+
@Override
+public String getBotUsername() {
+    return "TutorialBot";
+}
+
+@Override
+public String getBotToken() {
+    return "4839574812:AAFD39kkdpWt3ywyRZergyOLMaJhac60qc";
+}
+
+@Override
+public void onUpdateReceived(Update update) {
+    System.out.println(update);
+}
+

At this point, the bot is configured and ready to go – time to register it on the API and start processing updates.

+
+

In the future, you should consider storing your token in a dedicated settings file or in environment variables. Keeping it in the code is fine for the scope of this tutorial, however, it's not very versatile and is generally considered bad practice.

+
+

Registering the Bot

+

To register the bot on the API, simply add a couple of lines in the main method that will launch the application. If you named your class Bot, this is what your main method should look like:

+
public static void main(String[] args) throws TelegramApiException {
+  TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
+  botsApi.registerBot(new Bot());
+}
+
+

You can place this method in any class. Since we have an auto-generated main method in the Main class, we'll be using that one for this tutorial.

+
+

First Run

+

It's time to run your bot for the first time.
Hit the green arrow to the left of public static void main and select the first option.

+

And then there was nothing. Yes, a bit anticlimactic.
This is because your bot has nothing to print – there are no new updates because nobody messaged it yet.

+

If you try messaging the bot on Telegram, you'll then see new updates pop up in the console. At this point, you have your very own Telegram Bot – quite the achievement. Now, on to making it a bit more intelligent.

+
+

If nothing pops up, make sure you messaged the right bot and that the token you pasted in the code is correct.

+
+

Receiving Messages

+

Every time someone sends a private message to your bot, your onUpdateReceived method will be called automatically and you'll be able to handle the update parameter, which contains the message, along with a great deal of other info which you can see detailed here.

+

Let's focus on two values for now:

+
    +
  • The user - Who sent the message. Access it via update.getMessage().getFrom().
  • +
  • The message - What was sent. Access it via update.getMessage().
  • +
+

Knowing this, we can make it a bit more clear in the console output.

+
@Override
+public void onUpdateReceived(Update update) {
+    var msg = update.getMessage();
+    var user = msg.getFrom();
+
+    System.out.println(user.getFirstName() + " wrote " + msg.getText());
+}
+

This is just a basic example – you can now play around with all the methods to see everything you can pull out of these objects. You can try getUsername, getLanguageCode, and dozens more.

+

Knowing how to receive, process and print incoming messages, now it's time to learn how to answer them.

+
+

Remember to stop and re-launch your bot after each change to the code.

+
+

Sending Messages

+

To send a private text message, you generally need three things:

+
    +
  • The user must have contacted your bot first. (Unless the user sent a join request to a group where your bot is an admin, but that's a more advanced scenario).
  • +
  • You must have previously saved the User ID (user.getId())
  • +
  • A String object containing the message text, 1-4096 characters.
  • +
+

With that out of the way, let's create a new method to send the first message:

+
public void sendText(Long who, String what){
+   SendMessage sm = SendMessage.builder()
+                    .chatId(who.toString()) //Who are we sending a message to
+                    .text(what).build();    //Message content
+   try {
+        execute(sm);                        //Actually sending the message
+   } catch (TelegramApiException e) {
+        throw new RuntimeException(e);      //Any error will be printed here
+   }
+}
+

And proceed to run this in the main method, right after registering the bot.
For this example, we'll assume your User ID is 1234.

+
public static void main(String[] args) throws TelegramApiException {
+   TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
+   Bot bot = new Bot();                  //We moved this line out of the register method, to access it later
+   botsApi.registerBot(bot);            
+   bot.sendText(1234L, "Hello World!");  //The L just turns the Integer into a Long
+}
+

If you did everything correctly, your bot should text you Hello World! every time you launch your code. Sending messages to groups or channels – assuming you have the relevant permissions – is as simple as replacing 1234 with the ID of the respective chat.

+
+

Try experimenting with other types of messages, like SendPhoto, SendSticker, SendDice…
A full list is available starting here.

+
+

Echo Bot

+

Let's practice everything we tried so far by coding an Echo Bot.
Its functionality will be rather simple: every text message it receives will be sent right back to the user.

+

Copying Text

+

The most intuitive way of coding this is saving the User ID and calling sendText right after each update.

+

In other words:

+
@Override
+public void onUpdateReceived(Update update) {
+    var msg = update.getMessage();
+    var user = msg.getFrom();
+    var id = user.getId();
+
+    sendText(id, msg.getText());
+}
+

This works for text but can be extended to stickers, media and files.

+

Copying Everything

+

There are more specific functions that can be used to copy messages and send them back.
Let's build a method to do just that:

+
public void copyMessage(Long who, Integer msgId){
+   CopyMessage cm = CopyMessage.builder()
+              .fromChatId(who.toString())  //We copy from the user
+           .chatId(who.toString())      //And send it back to him
+           .messageId(msgId)            //Specifying what message
+           .build();
+    try {
+        execute(cm);
+    } catch (TelegramApiException e) {
+        throw new RuntimeException(e);
+    }
+}
+

After replacing the method call inonUpdateReceived, running the code will result in a fully functional Echo Bot.

+
+

This tutorial assumes that updates always contain messages for the sake of simplicity. This may not always be true – be sure to implement all the proper checks in your code to handle every type of update with the appropriate methods.

+
+

Executing Commands

+

To learn what a command is and how it works, we recommend reading this dedicated summary.
In this guide, we'll focus on the technical side of things.

+

Creating Your Command

+

Begin by opening @BotFater.
Type /mybots > Your_Bot_Name > Edit Bot > Edit Commands.

+

Now send a new command, followed by a brief description.
For the purpose of this tutorial, we'll implement two simple commands:

+
scream - Speak, I'll scream right back 
+whisper - Shhhhhhh
+

Command Logic

+

We want the Echo Bot to reply in uppercase when it's in scream mode and normally otherwise.

+

First, let's create a variable to store the current mode.

+
public class Bot extends TelegramLongPollingBot {
+
+   private boolean screaming = false;
+
+   [...]
+}
+

Then, let's change some logic to account for this mode.

+
public void onUpdateReceived(Update update) {
+    [...]                                   //Same variables as the previous versions
+   if(screaming)                            //If we are screaming
+       scream(id, update.getMessage());     //Call a custom method
+   else
+       copyMessage(id, msg.getMessageId()); //Else proceed normally
+}
+
+private void scream(Long id, Message msg) {
+   if(msg.hasText())
+       sendText(id, msg.getText().toUpperCase());
+   else
+       copyMessage(id, msg.getMessageId());  //We can't really scream a sticker
+}
+

Finally, let's add a couple more lines to the onUpdateReceived method to process each command before replying.

+
if(msg.isCommand()){ 
+   if(msg.getText().equals("/scream"))         //If the command was /scream, we switch gears
+      screaming = true;
+   else if (msg.getText().equals("/whisper"))  //Otherwise, we return to normal
+      screaming = false;
+
+   return;                                     //We don't want to echo commands, so we exit
+}
+

As you can see, it checks if the message is a command. If it is, the bot enters scream mode.
In the update method, we check which mode we are in and either copy the message or convert it to upper case before sending it back.

+

And that's it. Now the bot can execute commands and change its behavior accordingly.

+

Naturally, this simplified logic will change the bot's behavior for everyone – not just the person who sent the command. This can be fun for this tutorial but won't work in a production environment – consider using a Map, dictionary or equivalent data structure to assign settings for individual users.

+
+

Remember to always implement a few basic global commands.
You can practice by implementing a simple feedback to the /start command, which we intentionally left out.

+
+

Buttons and Keyboards

+

To streamline and simplify user interaction with your bot, you can replace many text-based exchanges with handy buttons. These buttons can perform a wide variety of actions and can be customized for each user.

+

Button Types

+

There are two main types of buttons:

+
    +
  • Reply Buttons - used to provide a list of predefined text reply options.
  • +
  • Inline Buttons - used to offer quick navigation, shortcuts, URLs, games and so much more.
  • +
+

Using these buttons is as easy as attaching a ReplyKeyboardMarkup or an InlineKeyboardMarkup to your SendMessage object.

+

This guide will focus on inline buttons since they only require a few extra lines of code.

+

Creating Buttons

+

First of all, let's create some buttons.

+
 var next = InlineKeyboardButton.builder()
+            .text("Next").callbackData("next")           
+            .build();
+
+ var back = InlineKeyboardButton.builder()
+            .text("Back").callbackData("back")
+            .build();
+
+ var url = InlineKeyboardButton.builder()
+            .text("Tutorial")
+            .url("https://core.telegram.org/bots/api")
+            .build();
+

Let's go back through the fields we specified:

+
    +
  • Text - This is what the user will see, the text that appears on the button
  • +
  • Callback Data - This will be sent back to the code instance as part of a new Update, so we can quickly identify what button was clicked.
  • +
  • Url - A button that specifies a URL doesn't specify callbackdata since its behavior is predefined – it will open the given link when tapped.
  • +
+

Creating Keyboards

+

The buttons we created can be assembled into two keyboards, which will then be used to navigate back and forth between two sample menus.

+

First, add two fields to store the necessary keyboards.

+
private boolean screaming = false;
+
+private InlineKeyboardMarkup keyboardM1;
+private InlineKeyboardMarkup keyboardM2;
+

Then, build and assign them.

+
keyboardM1 = InlineKeyboardMarkup.builder()
+          .keyboardRow(List.of(next)).build();  
+
+//Buttons are wrapped in lists since each keyboard is a set of button rows
+keyboardM2 = InlineKeyboardMarkup.builder()
+          .keyboardRow(List.of(back))
+          .keyboardRow(List.of(url))
+          .build();
+
+

You can place this code wherever you prefer, the important thing is making sure that keyboard variables are accessible from the method call that will send the new menu. If you're confused by this concept and don't know where to put them, just paste them above the command processing flow.

+
+

Sending Keyboards

+

Sending a keyboard only requires specifying a reply markup for the message.

+
public void sendMenu(Long who, String txt, InlineKeyboardMarkup kb){
+    SendMessage sm = SendMessage.builder().chatId(who.toString())
+            .parseMode("HTML").text(txt)
+            .replyMarkup(kb).build();
+
+    try {
+        execute(sm);
+    } catch (TelegramApiException e) {
+        throw new RuntimeException(e);
+    }
+}
+
+

You may have noticed that we also added a new parameter, HTML.
This is called a formatting option and will allow us to use HTML tags and add formatting to the text later on.

+
+

Menu Trigger

+

We could send a new menu for each new user, but for simplicity let's add a new command that will spawn a menu. We can achieve this by adding a new else clause to the previous command flow.

+
 var txt = msg.getText();
+ if(msg.isCommand()) {
+        if (txt.equals("/scream"))
+            screaming = true;
+        else if (txt.equals("/whisper"))
+            screaming = false;
+        else if (txt.equals("/menu"))
+            sendMenu(id, "<b>Menu 1</b>", keyboard1);
+        return;
+ }
+

Try sending /menu to your bot now. If you did everything correctly, you should see a brand new menu pop up.

+
+

In a production environment, commands should be handled with an appropriate design pattern that isolates them into different executor classes – modular and separated from the main logic.

+
+

Navigation

+

When building complex bots, navigation is essential. Your users must be able to move seamlessly from one menu to the next.

+

In this example, we want the Next button to lead the user to the second menu.
The Back button will send us back.
To do that, we will start processing incoming CallbackQueries, which are the results we get after the user taps on a button.

+

A CallbackQuery is essentially composed of three main parameters:

+
    +
  • queryId - Needed to close the query. You must always close new queries after processing them – if you don't, a loading symbol will keep showing on the user's side on top of each button.
  • +
  • data - This identifies which button was pressed.
  • +
  • from - The user who pressed the button.
  • +
+

Processing in this context just means executing the action uniquely identified by the button, then closing the query.

+

A very basic button handler could look something like:

+
private void buttonTap(Long id, String queryId, String data, int msgId) {
+
+    EditMessageText newTxt = EditMessageText.builder()
+            .chatId(id.toString())
+            .messageId(msgId).text("").build();
+
+    EditMessageReplyMarkup newKb = EditMessageReplyMarkup.builder()
+            .chatId(id.toString()).messageId(msgId).build();                           
+
+    if(data.equals("next")) {
+        newTxt.setText("MENU 2");
+        newKb.setReplyMarkup(keyboardM2);
+    } else if(data.equals("back")) {
+        newTxt.setText("MENU 1");
+        newKb.setReplyMarkup(keyboardM1);
+    }
+
+    AnswerCallbackQuery close = AnswerCallbackQuery.builder()
+            .callbackQueryId(queryId).build();
+
+    execute(close);
+    execute(newTxt);
+    execute(newKb);
+}
+

With this handler, whenever a button is tapped, your bot will automatically navigate between inline menus.
Expanding on this concept allows for endless combinations of navigable submenus, settings and dynamic pages.

+

Database

+

Telegram does not host an update database for you – once you process and consume an update, it will no longer be available. This means that features like user lists, message lists, current user inline menu, settings, etc. have to be implemented and maintained by bot developers.

+

If your bot needs one of these features and you want to get started on data persistence, we recommend that you look into serialization practices and libraries for your language of choice, as well as available databases.

+

Implementing a database is out of scope for this guide, however, several guides are available online for simple embedded open source software solutions like SQLite, HyperSQL, Derby and many more.

+
+

Your language of choice will also influence which databases are available and supported – the list above assumes you followed this Java tutorial.

+
+

Hosting

+

So far, your bot has been running on your local machine – your PC. While this may be good for developing, testing and debugging, it is not ideal for a production environment.
You'll want your bot to be available and responsive at all times, but your computer might not always be online.

+

This can be done in four steps:

+
    +
  • Package your code
    Making your bot easy to move and runnable outside of an IDE is essential to host it elsewhere.
    If you followed this tutorial, this standard guide will work for you. If you didn't, look into export or packaging guides for your IDE and language of choice – procedures may vary but the end result is the same.

    +
  • +
  • Purchase a VPS or equivalent service
    A server is essentially a machine that is always online and running, without you having to worry about anything. To host your bot, you can opt for a VPS which serves this purpose and can be rented from several different providers.
    Another option would be to purchase a network-capable microcontroller, which come in all different specs and sizes depending on your needs.

    +
  • +
+
+

You should ensure that all user data remains heavily encrypted at all times in your database to guarantee the privacy of your users. The same concept applies to your local instance, however, this becomes especially important once you transfer your database to a remote server.

+
+
    +
  • Upload your executable/package
  • +
+

Once you have a working ssh connection between your machine and your new server, you should upload your executable and all associated files.
We will assume the runnable jar TutorialBot.jar and its database dbase.db are currently in the /TBot folder.

+
$ scp -r /TBot/ username@server_ip:/bots/TBotRemote/
+
    +
  • Run your application
  • +
+

Depending on which language you chose, you might have to configure your server environment differently. If you chose Java, you just need to install a compatible JDK.

+
$ apt install openjdk-17-jre
+$ java -version
+

If you did everything correctly, you should see a Java version as the output, along with a few other values. This means you're ready to run your application.

+

Now, to run the executable:

+
$ cd /bots/TBotRemote/
+$ java -jar TutorialBot.jar
+

Your bot is now online and users can interact with it at any time.

+
+

To streamline and modularize this process, you could employ a specialized docker container or equivalent service.
If you followed along in one of the equivalent examples (C#, Python, Go and TypeScript) you can find a detailed set of instructions to export and run your code here.

+
+

Further Reading

+

If you got this far, you might be interested in these additional guides and docs:

+ +

If you encounter any issues while following this guide, you can contact us on Telegram at @BotSupport.

+
+ +
+ +
+
+ +
+ + + + + + + +