How ToIoT HardwaresRaspberry PiTutorials/DIY

Control LED using Raspberry Pi with Telegram Bot

In this tutorial, we are going to control a LED connected with Raspberry Pi using Telegram Bot. For this, we will create a telegram bot which is capable of sending and receiving messages from a Raspberry Pi. Not only the LED, we can control any home appliance using this Telegram bot.

What is Telegram ?

Telegram is a cloud-based instant messaging and voice over IP service. Telegram client apps are available for Android, iOS, Windows Phone, Windows NT, macOS and Linux. Users can send messages and exchange photos, videos, stickers, audio and files of any type. Telegram is almost similar to Whatsapp. Telegram’s client-side code is open-source software but the source code for recent versions is not always immediately published, whereas its server-side code is closed-source and proprietary. The service also provides APIs to independent developers. In March 2018, Telegram stated that it had 200 million monthly active users.

Telegram bot is like a robot which programmed with a set of instruction and answer to interact with the user.

Control LED using Raspberry Pi with Telegram Bot

Requirements

  • Raspberry Pi
  • LED
  • Breadboard
  • Resistor (250 ohm)
  • Jumper Wires

Circuit Diagram

rpi led

Connect positive pin of LED with Pi’s GPIO26 and negative pin with ground GND through a 250 ohm resistor.

Setup Telegram Bot

First Download Telegram app from Play store and Sign up. After this, it will take you to the home screen. Now we need to create a new bot that will send and receive messages with the Raspberry Pi. Search for ‘botfather’ in the search menu.

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

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

Now it will ask you to enter a name for the new bot.

Next, it will ask you to enter a username for the bot. Enter a unique username to create your bot.

Therefore, check your received message, there will be a token. Save it, as we will need it in the code.

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

Setup Raspberry Pi for Telegram Bot

Start with installing the telepot library on your Pi.

sudo pip install telepot

Now, make a new file using this command:

Sudo vi ledbot.py

After this, copy the complete code given at the end, and save into the above created file.

Code Explanation

Import all the necessary libraries in the code, as shown below:

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

Initialize and define the LED pin as output pin and setup the GPIO’s.

led = 26
now = datetime.datetime.now()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
 #LED
GPIO.setup(led, GPIO.OUT)
GPIO.output(led, 0) #Off initially

Whenever the Pi receives a message from the Telegram bot, it will call the action function and this function reads the message and separate the text from it.

def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print 'Received: %s' % command

Now using if condition will check for keywords and toggle the led according to the keyword. While message string is used to reply back to the user.

    if 'on' in command:
        message = "Turned on "
        if 'led' in command:
            message = message + "led"
            GPIO.output(led, 1)
            telegram_bot.sendMessage (chat_id, message)

    if 'off' in command:
        message = "Turned off "
        if 'led' in command:
            message = message + "led "
            GPIO.output(led, 0)
           telegram_bot.sendMessage (chat_id, message)

Now, in the below code enter token details in the commas. The “bot.getMe()” will check whether a connection between the Pi and the Telegram bot was made successfully by printing a response.

telegram_bot = telepot.Bot('bot token')
print (telegram_bot.getMe())

MessageLoop(telegram_bot, action).run_as_thread()
print 'Up and Running....'

while 1:
    time.sleep(10)

After this, run your code using this command:

Python ledbot.py

Now start your bot and send commands to turn on led and turn off led.

telegrm bot

Hence, we have successfully controlled the LED with the telegram app, you can also replace the LED with any other home appliances.

Complete Code


import time, datetime

import RPi.GPIO as GPIO

import telepot

from telepot.loop import MessageLoop

led = 26

now = datetime.datetime.now()

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

 #LED

GPIO.setup(led, GPIO.OUT)

GPIO.output(led, 0) #Off initially

def action(msg):

    chat_id = msg['chat']['id']

    command = msg['text']

    print 'Received: %s' % command

    if 'on' in command:

        message = "Turned on "

        if 'led' in command:

            message = message + "led"

            GPIO.output(led, 1)

            telegram_bot.sendMessage (chat_id, message)

 

    if 'off' in command:

        message = "Turned off "

        if 'led' in command:

            message = message + "led "

            GPIO.output(led, 0)        

        telegram_bot.sendMessage (chat_id, message)

telegram_bot = telepot.Bot('870666670:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxY')

print (telegram_bot.getMe())

MessageLoop(telegram_bot, action).run_as_thread()

print 'Up and Running....'

while 1:

    time.sleep(10)

I hope you like this post ”Control LED using Raspberry Pi with Telegram Bot”.  Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

Explore Some more Raspberry Pi Tutorials :

Upvote on Reddit

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

4 thoughts on “Control LED using Raspberry Pi with Telegram Bot

Leave a Reply

Your email address will not be published. Required fields are marked *