Skip to content

How to step by step. Creation telegram bot in Lazarus (longpolling)

Renat Suleymanov edited this page Dec 5, 2023 · 2 revisions

1 Introduction

Telegram Bot API is an interface (HTTP transport protocol) created for implementing bots that work through Telegram.

Essentially, Telegram bots are applications (written in any programming language and running either on a server or desktop computer), where a Telegram client program acts as the interface for interaction with the user.

1.1 @BotFather and Token

To start, you need to register an alias (username) for your bot and authorize it in the system. Every bot should have an authentication (secret) token, which can be obtained from the "father" of all bots BotFather (@BotFather) by sending the command /newbot. After following the instructions, you will get a token like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. More details about this step can be found on this page.

At the next step, we can already test how the API works for our bot. The template for requests to the bot is https://api.telegram.org/bot<token>/METHOD_NAME. The simplest example of a request in the Telegram Bot API is the getMe method, so the request will look like https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getMe.

You can verify the token even in DesignTime by clicking the right button on the TDLongPolBot component and clicking the menu item send getMe command. If the token is correct, you will receive a reply message and the Bot User name property will be filled in automatically. In the RunTime message does not appear, of course.

1.2 Longpolling for receiving bot updates

Everything that was said earlier is true for bots operating both in long polling mode and webhook. If you do not specify a webhook address for the bot, the bot will work in longpolling mode by default.

This longpolling is characterized by receiving updates by constantly requesting updates from the telegram server using the getUpdates method of the TTelegramSender. This is usually required to handle in a separate thread. There are demo programs in the examples folder. In the DTLongPolBot component, thread control takes place inside the component and you do not have to worry about it: it will be enough to activate the receiver of this component.

Long polling can be used for a wide range of applications: GUI and non-GUI embedded applications, daemons and services, etc. Webhooks are designed for web servers and require the creation of an endpoint on the side of the serviced application.

2 Creating an application in Lazarus IDE

2.1 Longpolling, designtime component

The easiest way to create an application with telegram bot is DTLongPolBot component. Just specify token for it and the HelloWorld bot is ready!

Of course You can use also single-threaded class TTelegramBot or TTelegramSender and manage threads yourself.

2.5 Platform and Processor

Package is crossplatform