Coding di ikkoyeah

In this post we will see how-to create a Telegram Bot to send messages in a Telegram chat group using the Python programming language.

BotFather: how-to create and manage the Bot

BotFather

First of all we have to create the Bot on Telegram. To do that we have to use the Telegram Bot BotFather.

This Bot allows to create anew one and manage all the bots you have created in the past. You can find it in the search bar of Telegram typing “BotFather” or via direct link https://t.me/botfather.

The Bot creation

  • Step 1: open BotFather
  • Step 2: Click on the Bot menu (icon / near the chat box) and select the command /newbot
  • Step 3: Type the bot name
  • Step 4: Type the Bot username
  • Step 5: Copy the token to access HTTP API
BotFather steps

Setup the coding tools

Technology vector created by stories – freepik.com
Technology vector created by stories – freepik.com

We have to use a Python script to send message in a group exploting the Bot.

First of all we have to check to have Python3. If you have Ubuntu, to install Python3 we have to type in the shell:


sudo apt install python3


Now we have to check that we have the Python3 package manager pip3 installed. If you have Ubuntu, to install Python3 we have to type in the shell:


sudo apt install python3-pip


Now we have to install the library telepot. If you have Ubuntu, to install Python3 we have to type in the shell:


pip3 install telepot


The structure of the Python Code

Once we have set all the tools we can write the Python script to send the message via the Bot.

The structure of the Python code is the following:


import telepot

TOKEN="xxxxxxxxxxxxxxx"
chat_id="xxxxxxxxxxxxxx"

bot=telepot.Bot(TOKEN)
bot.sendMessage(chat_id,"Il testo del messaggio")


Let’s break up the code:

import telepot is how we include the telepot library

TOKEN is the variable where we store the TOKEN of the HTTP API access

chat_ID is the group id where you want use the bot. If you don’t now hot-to find the chat_id go to this link.

Final considerations

Light vector created by rawpixel.com – freepik.com
Light vector created by rawpixel.com – freepik.com

Obviously the Python code structure is very simple, but with a little modification for example you can create a bot that every defined time slot it sends the data of a sensor in a domotic system.