Telegram Bot and ESP8266

This tutorial describes how to use ESP8266 with Telegram bot to automate some tasks. In more details, 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 some tasks using simple commands or to control remotely some devices. For example, home automation is one the most simple use case 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 the 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 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 Telegram bot. By now save the API token somewhere.

Connecting ESP8266 to the Telegram bot

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

First let us create the function to connect to the WiFi:

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&gt;
#define BOT_TOKEN "Token_API"

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

void setup() {
  Serial.begin(115200);
 
  connect2Wifi();
  bot.begin();
}

Remeber 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 necesary 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 details, 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 this 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 emulates 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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here