DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Integrating Redis With Message Brokers
  • Terraform State File: Key Challenges and Solutions
  • How to Reorganize and Rebuild Indexes in MS SQL?
  • Essential GitHub Enterprise Admin Commands

Trending

  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  • Agile’s Quarter-Century Crisis
  • The Future of Java and AI: Coding in 2025
  • The Role of AI in Identity and Access Management for Organizations

ESP8266 and Telegram Bot: Home Automation

Learn more about home automation with Telegram Bot.

By 
Francesco Azzola user avatar
Francesco Azzola
·
Nov. 06, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
18.5K Views

Join the DZone community and get the full member experience.

Join For Free

Home automation with Telegram Bot

Learn more about home automation with Telegram Bot

This tutorial describes how to use ESP8266 with Telegram bot to automate tasks in your home. In more detail, we want to create a bot based on Telegram that uses an ESP8266 to control peripherals such as LEDs or to turn on or off an external device automating some home tasks. We can integrate ESP8266 and Telegram Bot in two different steps:

  • Define a bot in Telegram
  • Build an ESP8266 sketch that handles bot commands and controls external peripherals

Where can you use this project? There are several ways to use ESP8266 and Telegram bot, for example, to automate tasks using simple commands or to remotely control devices. For example, home automation is one of the most simple use cases where this project can be applied. We can use this project to turn on or off lights in our home or some appliances, making the first step in home automation.

During this tutorial, you will learn:

  • How to connect ESP8266 to Telegram
  • How to use Telegram bot library for ESP8266
  • How to implement Telegram bot commands to control the ESP8266

How to Configure a Telegram Bot

In this first step, we will create and configure a Telegram bot so that we can use it to send commands to the ESP8266 once they are connected. You can use the following link to start using Telegram:

https://web.telegram.org

Let us start a chat with @BotFather:

telegram search botfahter
Search for @BotFather in Telegram

Now, you can start creating a new bot using /newbot. The video below shows how to do it:

How to integrate ESP8266 with Telegram bot

Our Telegram bot is named  ESP_IoTBot while it has  SwA_IoT_bot as a nickname. Once you have created the bot, you will get an API token that we will use later when we will connect the ESP8266 to a Telegram bot. By now, you should have saved the API token somewhere.

Other useful resources:

ESP8266 with Firebase realtime database: IoT Controlled

ESP8266 with Firebase realtime database: IoT Controlled RGB LEDs

Connecting ESP8266 to the Telegram Bot

Now it is time to connect the ESP8266 to the Telegram bot. To do it, we will use the ESP8266-Telegrambot library. You can import it directly from the Arduino IDE using the Library Manager.

First, let's create the function to connect to the Wi-Fi:

void connect2Wifi() {
  Serial.print("Connecting to "); 
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pwd);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("\nWifi connected");
}


Where

char ssid[] = "your_ssid";
char pwd[] = "Wifi password";


Now, it is time to initialize the library that helps us to connect ESP8266 to Telegram:

#include <ESP8266TelegramBOT.h>
#define BOT_TOKEN "Token_API"

TelegramBOT bot(BOT_TOKEN, "ESP_IoTBot", "ESP_IoTBot");

void setup() {
  Serial.begin(115200);

  connect2Wifi();
  bot.begin();
}


Remember to replace the Token_API with the token you get when you have created your bot in Telegram. Now, we are ready to check if new messages are present. 

Checking Telegram Bot Messages

To check if new messages are present, it is necessary to keep on polling, verifying if a new message is available:

uint32_t lastTime;

void checkMessages() {
   uint32_t now = millis();
   if (now - lastTime < 1000) {
      //Serial.println("Checking new messages....");   
      bot.getUpdates(bot.message[0][1]);
      int numNewMessages = bot.message[0][0].toInt() + 1;
       for (int i = 1;  i < numNewMessages; i++) {
        // Get the next message    
        String chatId = bot.message[i][4];
        String message = bot.message[i][5];
        handleMessage(message, chatId);
      }
   }
   lastTime = now;
}


The code uses getUpdates to verify if a new message exists. Next, we start retrieving these messages. In more detail, we get the real message content and the chatId. Finally, the code handles the message; we will see later how to do it.

Implementing the Telegram Bot Commands to Control ESP8266

How to implement the Telegram bot commands? We can do it in handleMessage, where we will handle commands as turning on or off the LEDs. Let's add this code:

void handleMessage(String message, String chatId) {
  if (message.equalsIgnoreCase("/start")) 
    sendMessage(handleStartCommand(), chatId);
  else if (message.equalsIgnoreCase("/yel_on")) 
     digitalWrite(YELLOW_LED_PIN, HIGH);
  else if (message.equalsIgnoreCase("/yel_off")) 
     digitalWrite(YELLOW_LED_PIN, LOW);
  else if (message.equalsIgnoreCase("/blue_on")) 
     digitalWrite(BLUE_LED_PIN, HIGH);
  else if (message.equalsIgnoreCase("/blue_off")) 
     digitalWrite(BLUE_LED_PIN, LOW);

   bot.message[0][0] = ""; 
}


The bot handles the /start command too. Using these commands, the bot will return all the available commands:

String handleStartCommand() {
  String response = "Available commands:";
  response += "Yel_on Turns on the Yellow LED\n\r";
  response += "Yel_off Turns off the Blue LED\n\r";
  response += "Blue_on Turns on the Blue LED\n\r";
  response += "Blue_off Turns off the Blue LED\n\r";
  response += "Temperature Returns the current temperature\n";
  response += "Humidity Returns the current humidity\n";
  return response; 
}


To send a message back to the client, the bot uses the chatId to identify the chat where to send the message. The chatId is a parameter we obtain from the incoming message:

void sendMessage(String message, String chatId) {
  Serial.println("Sending message...");
  Serial.print(chatId);
  Serial.print("----");
  Serial.println(message);
  bot.sendMessage(chatId, message, "");
}


It is time to create the sketch using ESP8266.

Home Automation Using ESP8266 and Telegram Bot

Once the code is ready, we can connect ESP8266 to the components that emulate our peripherals in our home. We can suppose we want to control some LEDs light connected to the ESP8266. To make things simple, we will use two LEDs, but you can use other components too and extend this project using other kinds of peripherals. The sketch is shown below:

ESP8266 Telegram LEDs

The code simply turns on or two pins on ESP8266.

Summary

At the end of this tutorial, we have discovered how to integrate ESP8266 with Telegram and how to send commands to ESP8266 using a Telegram bot. We have discovered how to automate some tasks using bots. You can use this project in home automation to control remotely appliances or home lights.

Further Reading

Home Automation Using IoT

Command (computing)

Published at DZone with permission of Francesco Azzola, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Integrating Redis With Message Brokers
  • Terraform State File: Key Challenges and Solutions
  • How to Reorganize and Rebuild Indexes in MS SQL?
  • Essential GitHub Enterprise Admin Commands

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!