Home Automation With Telegram and Raspberry Pi

by Jun 1, 2020Raspberry Pi projects

In this Article we will see how we can use Telegram for Home Automation. Telegram is an extremely popular multi-platform messaging service. Just like any other messaging platform, it is used to send messages and exchange photos, videos, stickers, audio, and files of any type. Their user base is also enormous with around 400 million active users per month. However, unlike many widely used messaging services, Telegram has support for bots that can serve various functions. Some notable Telegram bots are storebot, deloreanbot, Wikipedia search, and stickerbot. Telegram also allows us to create our own bots. In this article, we will be creating our own bot in python and Telegram for Home Automation.

Hardware Setup

The hardware setup is fairly simple for this project. We will be using 5 different LEDs to represent the different appliances at our homes. You will have to make the connections as shown below.

  • Connect the positive terminals of each of the LEDs to pins 31,33,36,38 and 40.
  • Connect the negative terminals of all the LEDs to the ground rail of the breadboard.
circuit diagram with fritzing

Setting Up The Bot

  • For this step, you need to open the Telegram app
  • In the Search bar type BotFather
  • Once you open the chat you will have to follow something like this:
Telegram commands for BotFather

Code Explanation

If you would like to clone this code from GitHub you can find it here.

  • First let’s import all the required packages.
import logging
from telegram.ext import Updater, CommandHandler
import RPi.GPIO as GPIO
  • Next, we will have to setup our logger. This logger is required to view any errors that take place during runtime.

  • Now let’s create a device dictionary that matches the name of the device to the pins that they are connected to.
device_dict = {"livingroom":31, "bedroom":36, "kitchen":33, "bathroom":38 ,"attic":40}
  • Now we can define our first, command 1: /start. This command will just send out the following text Hi!, run /help to view the commands.
def start(update, context):
    update.message.reply_text('Hi!, run /help to view the commands')
  • command 2: /listdevices. This is the command that lists out all the devices (from device_dict) for the user to know what devices are connected.
def list_devices(update, context):
    out_str = ""
    for a in device_dict:
        out_str+=a+'\n' 
    update.message.reply_text("Your devices are :" +'\n'+out_str)     
  • command 3: /help. This command will list out all the available commands.
def help(update, context):
    update.message.reply_text('''commands:
/switchon your_device  : start the switch on process
/switchoff your_device : start the switch off process
/listdevices           : list out all available devices
        ''')
  • command 4: /switchon. This command switches on the appliance based on the argument passed by the user. We can read the argument with the help of " ".join(context.args)
def switchon(update, context):
    param = " ".join(context.args)
    if param == "all":
        for i in device_dict:
            if i != "all":
                GPIO.output(device_dict[i], GPIO.HIGH)
    else:
        out = device_dict[param]
        GPIO.output(out, GPIO.HIGH)
  • command 5: /switchoff. This command helps us switch off any appliance that has been turned on.
def switchoff(update, context):
    param = " ".join(context.args)
    if param == "all":
        for i in device_dict:
            if i != "all":
                GPIO.output(device_dict[i], GPIO.LOW)
    else:
        out = device_dict[param]
        GPIO.output(out, GPIO.LOW)
  • Finally, we can create the main function.
def main_func():
    GPIO.setwarnings(False)  
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(31, GPIO.OUT)
    GPIO.setup(36, GPIO.OUT)
    GPIO.setup(33, GPIO.OUT)
    GPIO.setup(38, GPIO.OUT)
    GPIO.setup(40, GPIO.OUT)
    
    updater = Updater("Your API Key", use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("listdevices", list_devices))
    dp.add_handler(CommandHandler("switchon", switchon))
    dp.add_handler(CommandHandler("switchoff", switchoff))
    updater.start_polling()
    updater.idle()


main_func()

Again, you can find the entire code on GitHub here

Output

Thank you for reading!! Hope you learnt something new about telegram bots as well as home automation.

Leave any comments, suggestions and questions in the comments section below, I will answer them as soon as possible

Happy Learning !! 😄

Creating a multiplication Skill in Alexa using python

Written By Sashreek Shankar

Hey reader! I am Sashreek, a 16 year old programmer who loves Robotics, IoT and Open Source. I am extremely enthusiastic about the Raspberry Pi and Arduino hardware as well. I also believe in sharing any knowledge I have so feel free to ask me anything 🙂

RELATED POSTS

Magic Wand using Raspberry Pi and OpenCV

Magic Wand using Raspberry Pi and OpenCV

What if I could do things with a swing of a wand? Practically impossible but with technology maybe not. In this tutorial, we will use a raspberry pi and OpenCV to try and recreate something similar to a wand. It will perform specific functions when it recognizes...

IBM Watson IoT Platform with Raspberry Pi

IBM Watson IoT Platform with Raspberry Pi

IBM Watson is one of the leading cloud computing platforms there is. It has almost all the features one could expect from a modern-day cloud platform, from machine learning support to IoT, even till edge computing. In this tutorial, we will use raspberry pi and an...

Home Automation System with Raspberry Pi and Flask

Home Automation systems are becoming increasingly popular for the level of convenience they offer. Imagine sitting on your couch and turning on/off lights or fans in the room without having to get up. You could also control blinds or even door locks. This project is a...

Smart Alarm Clock with Raspberry Pi

Smart Alarm Clock with Raspberry Pi

Smart Alarms are very common today yet the good ones expensive. What if you wanted to make a smart alarm clock on your own using as little hardware and cost as possible? You may ask isn't the RPI costly, yes it is but, the only purpose of using an RPI is easy to net...

Spy Bot with Raspberry Pi

Spy Bot with Raspberry Pi

Spy bot is a raspberry pi bot that uses its camera to take secret pictures, encrypt them using RSA encryption and upload it safely to a database/server. Today, security and surveillance have become very important. To take inspiration from world scenario we start off...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....