How to Create a Bot for Telegram (Python)

Tiempo de lectura: 3 minutos

Reading time: 4 minutes

Hello everyone, today I’m going to show you how to create a small bot to use with Telegram.

A bot is just another user in a chat, but one that only responds. In other words, it’s a small robot that has a user image, a name, and the ability to respond to a message or write automatic messages based on the question asked.

In this example, we’re going to create a small bot that responds to everything that is written to it. It will also serve as an example for you to develop your own bots using it as a base.

First of all, we need to register the bot using BotFather, a bot created by Telegram for registering our new bots.

@botFather

To use it, click on https://t.me/botfather

To create our bot, we type /newbot in the chat:

/newbot

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

Now we have to enter the name of the bot, and it’s important to know that the name has to be name_bot:

nombre_bot

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

Use this token to access the HTTP API:
543759345:AHsjdfUUdfsi2kjksaKKKdmmmsddd
Keep your token secure and store it safely, it can be used by anyone to control your bot.

For a description of the Bot API, see this page:

https://core.telegram.org/bots/api

Once created, BotFather sends us the access token for our bot:

543759345:AHsjdfUUdfsi2kjksaKKKdmmmsddd

We will need to add this token later in our code to fully use our bot registered on Telegram.

Let’s program this bot using Python.

We start by installing Python 3:

sudo apt install python3.8

In my case, I’m installing Python 3.8, but you can install the Python version you prefer and is compatible with telebot (https://pypi.org/project/pyTelegramBotAPI/)

Now we install pip to be able to install the necessary libraries:

sudo apt install python3-pip

And now we install the Telebot library (version of pytelegrambotapi):

pip install pytelegrambotapi

Once installed, our environment is ready.

Now we open our favorite code editor, it can be Visual Studio Code, Notepad++, etc.

We create a file called bot.py and add the following code:

# -*- coding: utf-8 -*-

# Import telebot
import telebot

# Add the token given by BotFather
token_bot = "543759345:AHsjdfUUdfsi2kjksaKKKdmmmsddd"

# Initialize the bot by registering it with the token
bot = telebot.TeleBot(token_bot)

With this code, we register the bot to communicate with Telegram.

And now let’s do the magic:

bot)
Creamos una función dónde vamos a recibir todos los mensajes del chat en el que esté incluido el bot
Pasamos mensajes (es una lista de mensajes)
def recibir_mensajes(mensajes):
# Recorremos la lista de mensajes:
for mensaje in mensajes:
# Ejemplo para imprimir el mensaje que llega
print('El mensaje es ', mensaje.json['text'])
# Obtiene id del chat para poder responder con el bot
id_chat = mensaje.chat.id
# Respondemos un texto usando el bot
bot.send_message(id_chat, "Te respondo y soy un Bot")
Registramos la función dónde vamos a recibir los mensajes del chat
bot.set_update_listener(recibir_mensajes)
Decimos que el bot no finalice
bot.polling(none_stop=True)

We have created the receive messages function, as I indicated in the comments, this function goes through all the messages that are written within a chat or channel and the bot responds automatically.

To reply, use the send_message function, passing it the id_chat and the String text that we want to reply with the Bot.

Then we register the function where Telegram will send the messages using the set_update_listener

To give you an idea, a Telegram message is a JSON with the following structure:

 {
  "message_id": 123,
  "from": {
    "id": 456,
    "is_bot": false,
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "language_code": "en"
  },
  "chat": {
    "id": 789,
    "first_name": "Jane",
    "last_name": "Smith",
    "username": "janesmith",
    "type": "private"
  },
  "date": 1625664097,
  "text": "Hello, bot!"
}

Seeing this structure, we can choose which fields to use to respond with our Bot. For example, we could use a field to know if the user has finished entering the chat.

Finally, to run our code, we type in the console:

python3 bot.py

And the bot will be waiting to receive a message.

For it to work in a chat or group, we will have to search for the bot indicating the name that we have registered with BotFather (in the example it is @bot_name) and add it to the group.

For the bot to have permissions to read the messages, it must be given administrator permissions.

And with these steps we have created a bot for Telegram.

If you want to see how to add commands to this Bot, you can visit

Añadir comandos a un bot de Telegram (Python).

Leave a Comment