Posted in raspberrypi, telegram, bot

How is Telegram different from WhatsApp?(photo made by Sfecles Petru)

I spent some time trying to figure out how to create a telegram bot. I really got lost in the official documentation. Then, I found the framework that has made everything easier, telepot.

What is telegram? Telegram is a messaging app that is simple to use and one of the main focuses is security. This sound very similar to WhatsApp, but you can find here how it's different.

I find bots being very useful, especially when I remotely trying to control something from my house. If you like creating bots, find that I created a similar post, but using a discord bot.

The simple hardware 

As you can see in the image below, the circuit is very simple. When you connect the LED to the Raspberry Pi, don't forget to add the resistor (I use one of 1K ohm).

 LED connected to Raspberry Pi Zero

Control your bot like a 'boss'

But first, let's create the bot by chatting with @BotFather (they have a good sense of humor), the bot above all bots. Write the following command /newbot and follow the steps to configure the name and the id for the bot. I named the bot I created it, TheHumbleCodeBot. After you finish this steps you will be given a unique token, save it, we will need it later.

Creating a telegram bot with the help of BotFather

Now, we have to install telepot. It supports multiple version of Python. You can find more details in the introduction of the telepot framework.

pip install telepot

The good thing is that we don't have to make a request in order to see if something wrote something in the chat. Instead, we can use a built-in functionality, Message Loop, from telebot that makes use of Webhooks and continuously will apply a handling function for every message received. 

import RPi.GPIO as GPIO
import telepot
import time
from telepot.loop import MessageLoop

# use channel numbers on the Broadcom SOC
GPIO.setmode(GPIO.BCM)

LED_PIN = 19
GPIO.setup(LED_PIN, GPIO.OUT)

bot = telepot.Bot('579430837:AAEG-ll76_EnQ2XBQqaN3B4wQpptpCB5PY0')

def turnOn(chatId):
    GPIO.output(LED_PIN, True)
    bot.sendMessage(chatId, 'The led is ON now!')

def turnOff(chatId):
    GPIO.output(LED_PIN, False)
    bot.sendMessage(chatId, 'The led is OFF now!')

def handleCommand(msg):
    contentType, chatType, chatId = telepot.glance(msg) # extract “headline info”
    print(contentType, chatType, chatId)

    if contentType != 'text':
        return # nothing to do

    message = msg['text']

    if not message.startswith('!'):
        return # not a command
    
    command = message[1:].lower() # remove ! from the command name
    if command == 'on':
        turnOn(chatId)
    elif command == 'off':
        turnOff(chatId)

if __name__ == '__main__':
    try:
        MessageLoop(bot, handleCommand).run_as_thread()

        while 1:
            # just don't finish the program
            time.sleep(10)
        # close execution by pressing CTRL + C
    except KeyboardInterrupt:
        print("Intrerrupted by user")
        pass
    finally:
        print("Program stopped")
        GPIO.cleanup()

To start the bot is pretty easy, save the above code in a file named bot.py and run it using the following command in the console:

python bot.py

In order to chat with your bot, you can replace the bot id in the following name, https://web.telegram.org/#/im?p=@YOUR_BOT_ID (mine is TheHumbleCodeBot).

Chatting with the telegram bot

Conclusion

The bots have a good potential, especially when you want to control something from your home or just receiving updates. You can append anything you want to your bot, temperature, motion sensor, led matrixes and many others. 

I hope this post helps you to create a bot much easier for your current/future projects.

Thank you for reading, and never stop receiving knowledge!

Comments

Be the first to post a comment

Post a comment