Learn how to use a Raspberry Pi and the Telegram app to create a bot to help you with tasks around the house!

In this article, we will create a telegram bot capable of sending and receiving messages from a Raspberry Pi. We’ll program the Raspberry Pi to obtain the time and date. We will also be able to control the GPIO pins of the Raspberry Pi, by connecting the two LEDs on the Raspberry Pi GPIO pins.

Telegram is a messaging app like WhatsApp, but Telegram can create the bots. It has an API bot that not only allows the human to talk to it, but also machines.

With this tutorial, you can use Telegram to control anything in your home or even feed your dog when you’re away.

Required Components for Your Telegram Bot

  • Raspberry Pi
  • 2 LEDs
  • 2 220 ohm resistors

Installing and Creating Your Telegram Bot

First, go to the Google Play store and download the Telegram app.

telegram_bot_MP7.jpg

When you open the app, it will ask for your number. Enter the number, and Telegram will send a verification code. You will need to enter the code to confirm your account.

telegram_bot_MP9.jpg

After adding the number, it will take you to the home screen, which will look like this:

telegram_bot_MP8.jpg

Now we need to create a new bot that will send and receive messages with the Raspberry Pi. Telegram has a BotFather that will help us create a bot. Search for “botfather” in the app. 

telegram_bot_MP5.jpg

Next write “/start” to start chatting with the bot.

telegram_bot_MP10.jpg

After that, write “/newbot’ to request a new bot.

telegram_bot_MP2.jpg

Now it will ask you to name your new bot.

telegram_bot_MP1.jpg

Next, it will ask for a username for the bot. Enter a unique username to create your bot. In the message you receive, there will be a token. Save it, as you will need it in the code.

telegram_bot_MP4.jpg

Next, search for the bot using its to confirm that the bot has been created.

telegram_bot_MP3.jpg

We have finished creating the bot. Now, we need to write some code for the Raspberry Pi that will make it respond to messages from the bot.  Before that, hook up the connections for the Raspberry Pi.

Circuit Diagram for the Telegram Bot

Connect the positive lead of the red LED to GPIO 21 of the Raspberry Pi and connect the negative lead of the red LED to the ground through the 220-ohm resistor.

Similarly, connect the positive lead of the green LED to GPIO 20 of the Raspberry Pi and the negative lead of the green LED to the ground through the 220-ohm resistor.

telegram_bot_MP6.png

Installing the Correct Library Into Raspbian 

We need to install the teleport library into Raspbian. Type the command below in the terminal to install it:

sudo pip install telepot

Telegram Bot Code Explanation

First, we added the required libraries for this project. The teleport library enables the Raspberry Pi to communicate with the Telegram bot using the API. The datetime library is used to get the date and time. The GPIO library is used to light the LEDs. 

    import datetime  # Importing the datetime library
import telepot   # Importing the telepot library
from telepot.loop import MessageLoop    # Library function to communicate with telegram bot
import RPi.GPIO as GPIO     # Importing the GPIO library to use the GPIO pins of Raspberry pi
from time import sleep      # Importing the time library to provide the delays in program

Whenever the Pi receives a message from the Telegram bot, it will call the handle function In this function, we read the message and separate the text from it. Then, we compare the text and reply to it accordingly.

    def handle(msg):
    chat_id = msg['chat']['id'] # Receiving the message from telegram
    command = msg['text']   # Getting text from the message

    print ('Received:')
    print(command)

    # Comparing the incoming message to send a reply according to it
    if command == '/hi':
        bot.sendMessage (chat_id, str("Hi! MakerPro"))
    elif command == '/time':
        bot.sendMessage(chat_id, str("Time: ") + str(now.hour) + str(":") + str(now.minute) + str(":") + str(now.second))
    elif command == '/date':
        bot.sendMessage(chat_id, str("Date: ") + str(now.day) + str("/") + str(now.month) + str("/") + str(now.year))
    elif command == '/red_1':
        bot.sendMessage(chat_id, str("Red led is ON"))
        GPIO.output(red_led_pin, True)

You will need to enter your bot token in the comman below. The “bot.getMe()” will check whether a connection between the Pi and the Telegram bot was made successfully by printing a response.

    bot = telepot.Bot('542543102:AAE7xb6_XGAn9Yh-4PPJmfK5YK9TEA4')
print (bot.getMe())

The command below will start listening to the bot, and whenever a message is received, it will call the handle function.

    MessageLoop(bot, handle).run_as_thread()

You have now created your telegram bot program! Watch this project take shape in the video below!

Full Telegram Bot With Raspberry Pi Code

    import datetime  # Importing the datetime library
import telepot   # Importing the telepot library
from telepot.loop import MessageLoop    # Library function to communicate with telegram bot
import RPi.GPIO as GPIO     # Importing the GPIO library to use the GPIO pins of Raspberry pi
from time import sleep      # Importing the time library to provide the delays in program

red_led_pin = 21                # Initializing GPIO 21 for red led
green_led_pin = 20                # Initializing GPIO 20 for green led

GPIO.setmode(GPIO.BCM)      # Use Board pin numbering
GPIO.setup(red_led_pin, GPIO.OUT) # Declaring the GPIO 21 as output pin
GPIO.setup(green_led_pin, GPIO.OUT) # Declaring the GPIO 20 as output pin

now = datetime.datetime.now() # Getting date and time

def handle(msg):
    chat_id = msg['chat']['id'] # Receiving the message from telegram
    command = msg['text']   # Getting text from the message

    print ('Received:')
    print(command)

    # Comparing the incoming message to send a reply according to it
    if command == '/hi':
        bot.sendMessage (chat_id, str("Hi! MakerPro"))
    elif command == '/time':
        bot.sendMessage(chat_id, str("Time: ") + str(now.hour) + str(":") + str(now.minute) + str(":") + str(now.second))
    elif command == '/date':
        bot.sendMessage(chat_id, str("Date: ") + str(now.day) + str("/") + str(now.month) + str("/") + str(now.year))
    elif command == '/red_1':
        bot.sendMessage(chat_id, str("Red led is ON"))
        GPIO.output(red_led_pin, True)
    elif command == '/red_0':
        bot.sendMessage(chat_id, str("Red led is OFF"))
        GPIO.output(red_led_pin, False)
    elif command == '/green_1':
        bot.sendMessage(chat_id, str("Green led is ON"))
        GPIO.output(green_led_pin, True)
    elif command == '/green_0':
        bot.sendMessage(chat_id, str("Green led is OFF"))
        GPIO.output(green_led_pin, False)

# Insert your telegram token below
bot = telepot.Bot('542543102:AAE7xb6_XGAn9Yh-4PPJmfK5YK9TEA4')
print (bot.getMe())

# Start listening to the telegram bot and whenever a message is  received, the handle function will be called.
MessageLoop(bot, handle).run_as_thread()
print ('Listening....')

while 1:
    sleep(10)
Muhammad Aqib
I am an embedded programmer with the expertise in Arduino, Raspberry pi, ESP8266, IOT and OpenCV.

Maker Pro Logo
Continue to site
Quote of the day

-