Telegram is a well-known mobile messaging application, similar in many respects to WhatsApp, which came before it. However, this application has many other features that, together with its large number of users, make it a unique communication application.
One of these features is bots, which are robots – as their name suggests – or automated programs that can interact with the user in a wide range of scenarios. For example, @Pollbot lets you create polls so that group members can vote for one option or another. Another different example is @APODNASA_bot , which lets you get NASA's Astronomical Picture of the Day, among several other features.
Getting started with BotFather
To create a bot, you need a Telegram account and must have it installed on a device. This step is mandatory because creating bots requires using another bot, specifically @BotFather which will give us the identifier to add our bot to Telegram's bot database.
To begin, we must open a new chat with @BotFather and type “/start”. Bots can have different commands, which are executed with a slash (“/”) followed by the command. You can open the command list by pressing the button next to the emoticons, whose icon is also a slash. In our case, to create a new bot, we type “/newbot”.
It will ask us for various details to identify our bot. The first is the bot's name, not the one displayed on screen but the identifier, the one that comes after “@”, like Twitter usernames, for example. This name must have the suffix “bot”; if we do not follow this rule, it will give us an error message until we enter a valid name.
IMPORTANT
Immediately after entering a valid name, it will return a message with a token, which is unique and necessary to access the Telegram API. It is very important not to share it with anyone. If the token has been compromised, we can generate another with the /revoke command, which will invalidate the previous one.
Now it is useful to change some of our bot's parameters to make it more “attractive” to the user, such as giving it a name with “/setname”, a description (“/setdescription”), or an image (“/setuserpic”).
Starting to program
In this post we will use Python version 2, so basic knowledge of this language and of hosting applications on a VPS is recommended.
Before starting, we must install a package so we can import it into our program. It is installed with pip. On Debian- or Ubuntu-based systems, run
# apt-get install python3 python3-pip python3-venv. Since recent versions of Debian and Ubuntu do not allow installing packages with pip directly on the system, using a virtual environment is recommended:
# python3 -m venv venv # source venv/bin/activate # pip install pyTelegramBotAPI
We create a new file, for example main.py, and add the following lines:
import telebot # Add the necessary libraries
token = "" # Replace with the one obtained in the previous section
bot = telebot.TeleBot(token) # Initialize the bot
@bot.message_handler(commands=["start"])
def handle_start(message):
bot.reply_to(message, "Hola mundo")
bot.infinity_polling()As you can see in the code above, we have created a bot that replies to the user with __Hola mundo__ when the /start command (the default for starting the bot) is used. To test that it works locally, run the file (`python3 main.py`) and access the bot from Telegram.
Commands (which are sent to the bot with the syntax “/” + command) can be any word we want. For example, a function to send a YouTube video when the /video command is executed would be as follows:
@bot.message_handler(commands=["video"])
def handle_video(message):
bot.reply_to(message, "https://www.youtube.com/watch?v=wjU8j2bj3RY")There are countless other predefined functions available; the most common ones in chats are:
- send_message(chatid, text): instead of replying to a previous message as in the examples above, it simply sends a message to the user.
- send_photo(chatid, photo): sends a photo to the user, which must have been processed in python with the command `photo = open(‘/tmp/photo.png’, ‘rb’)`, although it is also possible to use libraries such as Pillow.
- send_audio(chatid, audio): sends audio, which must have been opened in the same way as the photo.
- send_location(chatid, lat, lng): sends a Google Maps map with a marker at the point specified by the latitude and longitude.
You can read about the other functions in the documentation for pyTelegramAPI or directly in the Telegram documentation.
As you can see in Telegram's message input bar, you can display the available commands by pressing the “/” button. To do this, we must create a list of commands, since the bot does not automatically take them from our code. To do so, we must activate it with BotFather and the /setcommands command.
Server
Telegram bots run on the server side, not on users' devices. We must host them on a web platform such as a VPS (at https://clouding.io/ for example). There is no need to allocate too much CPU, RAM, or disk space to them, since they are generally lightweight, although if many requests are received at once, increasing the CPU may be advisable, especially if they connect to other servers or must process a lot of data.
They run perfectly on a GNU/Linux system. To do this, we must have the following packages installed; run the pip command inside the virtual environment:
# apt-get update
# apt-get install python3 python3-pip python3-venv screen
# pip install pyTelegramBotAPI # dentro del entorno virtualAfter installing all the packages, you must use __screen__ to keep the bot waiting for users:“`screen -S mybotpython main.py“`
Everything should now be configured. To stop a bot from running, simply run `screen -r mybot`.