Al-Muhandis / fp-telegram

Telegram bots in Lazarus (and FreePascal)
MIT License
78 stars 16 forks source link

Сделал перевод wiki на eng с помощью chatGPT, только ссылки поправить #9

Closed delphius closed 1 year ago

delphius commented 1 year ago

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

1.2 Webhook for receiving bot updates

Next, we need to choose the method for receiving updates.

Updates are information about messages sent to the bot by users and other events (for example, receiving various information from the Telegram channel or group to which the bot belongs). By message, I mean not only text messages, but also contacts, geographic coordinates, images, audio, and other media content that a user can send to our bot.

There are two mutually exclusive ways to receive updates for our bot: getUpdates requests and setting up a webhook. In the first case, we receive updates by executing requests to the Telegram server. In the second case, the Telegram server sends us updates automatically. All we have to do is specify the address to which the server should send requests. This is called a webhook. Please note that the webhook address should remain secret, as a malicious user can gain control over your bot by finding out this address. Therefore, the webhook address often includes the token of the same bot. Although this is not necessary.

2 Creating an application in FreePascal

2.1 Webhook, web application

The easiest way to create an application is to make it work through a webhook. Many people are deterred by the hassle of setting up a web server and the HTTPS protocol, but this is solvable. Additionally, if you have a web service/site, it is logical and beautiful to add a Telegram interface to it using a webhook bot.

So, if our application will work through a webhook, we will need to write a web application. You can read more about writing web applications in Lazarus/FreePascal here and here. You can also choose another method of receiving updates (by requesting getUpdates), and in this case, it is not necessary to create a web application; you can even create a desktop application since the application does not need to receive HTTP requests, only send and process responses. So we have chosen a webhook, and between CGI and FastCGI, we choose the latter as the most modern and optimal solution. You can write a web application using web-fcl or other libraries. I chose this framework.

2.2 Configuring the web server

I posted a tutorial on configuring a web server to work with the Brook framework on this forum. In short, virtual hosting is not suitable on this forum. In short, virtual hosting is not suitable for these purposes, but you can use a virtual or dedicated server.

2.3 HTTPS

Webhook

The webhook address must be accessible over a secure protocol. You can, of course, install a certificate (there are paid and free options) and make the necessary manipulations with the server to make the site work over HTTPS. But I chose the easiest option and delegated the domain on which the webhook will be hosted to Cloudflare. This way, we immediately provided access to our server over both regular HTTP and HTTPS. Note that in this case, there is no need to install any certificates on our server.

Requests to secure endpoint APIs in Telegram

At one time, I actively used Synapse to work with networks. However, it turned out that the built-in web-fcl libraries for network operation already work perfectly with the HTTPS library. Moreover, I didn't need to install OpenSSL or even throw libraries into the program folder. At least in the latest versions of Windows 10, as well as in Debian/Ubuntu (both desktop and server), HTTPS requests with the TFPHTTPClient class were processed perfectly.

2.4 Wrapper libraries for working with Telegram bots API

A wrapper that encapsulates API work for bots in Telegram - fp-telegram. It is made in such a way that it can be used independently, as well as part of other libraries, in particular, Brookframework. In the latter case, the binding class will be Brook-telegram. Download them (preferably via SVN/Git to timely receive updates). You will also need Brookframework (the library is also included in the FPCDeluxe package!).

The FreePascal library implements API methods (not all of them yet, but they can be easily added to the library), as well as receiving updates by processing OnRecieve events ... receiving various types of updates.

2.5 Platform and Processor

Compile the built application. Don't forget to correctly set the -T -P keys (operating system and processor), if the server OS is Debian/Ubuntu, then it's Linux and x86_64, respectively. If your working computer, on which Lazarus is installed, runs on a different operating system, then you can use cross-compilation. In this case, the above-mentioned fpcdeluxe will be helpful again.

2.6 Uploading the Built Application to the Server

If our server is already configured to work with fastcgi, all that remains is to upload the helloworld.fcgi application to the /cgi-bin/ folder. As a result, our application will be available at a certain public address, for example, https://sample.com/cgi-bin/helloworld.fcgi.

2.7 Setting Up the Webhook

I set up a webhook for our bot using the setWebhook API method directly through the browser, for example: https://api.telegram.org/bot/setWebhook?url=https://sample.com/cgi-bin/helloworld.fcgi//. In the TMyAction registration procedure (a descendant of TWebhookAction and TBrookAction), I will specify TMyAction.Register('/:token/');

It is possible to make it even easier and immediately place the application in a secret folder like /cgi-bin/bla-bla-bla-and-or-token-also/helloworld.fcgi. However, dynamic token verification in the code itself will allow you to have more than one bot on a single web application or create a Telegram bot in the same web application as the website on the same framework.

3 Examples Links

Simplest Hello World application example (webhook, brookframework+fp-telegram)

There is also an implementation of the fp-telegram library via longpolling getUpdates in the examples.

Al-Muhandis commented 1 year ago

Спасибо. Вот думаю логичней создать раздел wiki в этом репозитарии, а не в Brook-Telegram?

delphius commented 1 year ago

Да, сто процентов в этой репе, в процентном соотношении пользователей врапера к пользователям фреймворка 90/10 наверное....

Al-Muhandis commented 1 year ago

Done