Telegram Group: Control ESP32/ESP8266 Outputs (Arduino IDE)

This tutorial shows how to control your ESP32 or ESP8266 boards through a Telegram group. Using a Telegram group to control your boards may be useful if you want to have several people interacting with a bot on the same chat and you want all those people to get notifications from the bot.

Telegram Group: Control ESP32/ESP8266 Outputs (Arduino IDE)

We have other tutorials about Telegram that we recommend reading:

Project Overview

Control ESP32 and ESP8266 boards using a Telegram Group with several members
  • In this tutorial you’ll create a telegram bot to interact with the ESP32 or ESP8266 boards;
  • You’ll create a group where you can add several people you want to have control and receive notifications from the bot;
  • The bot will be added to the group so that the members can interact with it;
  • As an example, we’ll show you how to send commands to control outputs and how to send responses from the bot to the group.

Introducing Telegram

Telegram Messenger is a cloud-based instant messaging and voice over IP service. You can easily install it in your smartphone (Android and iPhone) or computer (PC, Mac and Linux). It is free and without any ads. Telegram allows you to create bots that you can interact with.

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram Bot API“.

The ESP32/ESP8266 will interact with the Telegram bot to receive and handle the messages, and send responses to the Telegram group.

Install Telegram

Go to Google Play or App Store, download and install Telegram.

Install and Download Telegram

Creating a Telegram Bot

The following steps are easier to follow on your computer. Open a browser, go to the Telegram Web App and login into your account.

If you’ve followed previous projects and you already have a telegram bot, you can skip this section.

On the top left corner, search for “botfather” and click the BotFather as shown below.

Search for Botfather Telegram Web App

A new window should open and you’ll be prompted to click the start button. Type /newbot and follow the instructions to create your bot. Give it a name and username.

If your bot is successfully created, you’ll receive a message with a link to access the bot and the bot token. Save the bot token because you’ll need it so that the ESP32/ESP8266 can interact with the bot.

Create a Telegram Bot on Telegram Web App

Creating a Telegram Group

The next step is creating the Telegram group. On the top left corner, click on New group.

Create a new group web telegram

Add members to your group and give it a name.

Give name to a group Telegram

Add the Bot to the Group

Once the group is created, click on the group name to add your bot.

Search for your bot name and add it to the group.

Add bot to telegram group

Get the Group ID

To interact with the Telegram group, the ESP32 needs to know the telegram group ID. In you Telegram account, open your group. The group ID should be on the URL as shown below.

Get the Telegram group ID

Save the group ID because you’ll need it later.

Preparing Arduino IDE

We’ll program the ESP32 and ESP8266 boards using Arduino IDE, so make sure you have them installed in your Arduino IDE.

Universal Telegram Bot Library

To interact with the Telegram bot, we’ll use the Universal Telegram Bot Library created by Brian Lough that provides an easy interface for the Telegram Bot API.

Follow the next steps to install the latest release of the library.

  1. Click here to download the Universal Arduino Telegram Bot library.
  2. Go to Sketch > Include Library > Add.ZIP Library...
  3. Add the library you’ve just downloaded.

And that’s it. The library is installed.

Important: don’t install the library through the Arduino Library Manager because it might install a deprecated version.

For all the details about the library, take a look at the Universal Arduino Telegram Bot Library GitHub page.

ArduinoJson Library

You also have to install the ArduinoJson library. Follow the next steps to install the library.

  1. Go to Skech > Include Library > Manage Libraries.
  2. Search for “ArduinoJson”.
  3. Install the library.

We’re using ArduinoJson library version 6.15.2.

Parts Required

For this example you just need one ESP32 or an ESP8266 board.

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Control ESP32/ESP8266 using Telegram Group – Sketch

The following code allows you to control your ESP32 or ESP8266 NodeMCU GPIOs by sending messages to a group where your Telegram Bot is a member.

To make this sketch work for you, you need to insert your network credentials (SSID and password), the Telegram Bot Token and your Telegram Group ID.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/telegram-group-esp32-esp8266/
  
  Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
*/

#ifdef ESP32
  #include <WiFi.h>
#else
  #include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>   // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Initialize Telegram BOT
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)

// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "-XXXXXXXXXX"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

const int ledPin = 2;
bool ledState = LOW;

// Handle what happens when you receive new messages
void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

  for (int i=0; i<numNewMessages; i++) {
    // Chat id of the requester
    String chat_id = String(bot.messages[i].chat_id);
    if (chat_id != CHAT_ID){
      bot.sendMessage(chat_id, "Unauthorized user", "");
      continue;
    }
    
    // Print the received message
    String text = bot.messages[i].text;
    Serial.println(text);

    String from_name = bot.messages[i].from_name;

    if (text == "/led_on") {
      bot.sendMessage(chat_id, "LED state set to ON", "");
      ledState = HIGH;
      digitalWrite(ledPin, ledState);
    }
    
    if (text == "/led_off") {
      bot.sendMessage(chat_id, "LED state set to OFF", "");
      ledState = LOW;
      digitalWrite(ledPin, ledState);
    }
    
    if (text == "/state") {
      if (digitalRead(ledPin)){
        bot.sendMessage(chat_id, "LED is ON", "");
      }
      else{
        bot.sendMessage(chat_id, "LED is OFF", "");
      }
    }
  }
}

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

  #ifdef ESP8266
    client.setInsecure();
  #endif

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
  
  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

  bot.sendMessage(CHAT_ID, "Bot Started", "");
}

void loop() {
  if (millis() > lastTimeBotRan + botRequestDelay) {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    lastTimeBotRan = millis();
  }
}

View raw code

The code is compatible with ESP32 and ESP8266 NodeMCU boards (it’s based on the Universal Arduino Telegram Bot library example). The code will load the right libraries accordingly to the selected board.

How the Code Works

Start by importing the required libraries.

#ifdef ESP32
  #include <WiFi.h>
#else
  #include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

Network Credentials

Insert your network credentials in the following variables.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Telegram Bot Token

Insert your Telegram Bot token you’ve got from Botfather on the BOTtoken variable.

#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)

Telegram Group ID

Insert your Telegram group ID. It should start with a “-” signal.

#define CHAT_ID "-XXXXXXXXXX"

Create a new WiFi client with WiFiClientSecure.

WiFiClientSecure client;

Create a bot with the token and client defined earlier.

UniversalTelegramBot bot(BOTtoken, client);

The botRequestDelay and lastTimeBotRan are used to check for new Telegram messages every x number of seconds. In this case, the code will check for new messages every second (1000 milliseconds). You can change that delay time in the botRequestDelay variable.

int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

Define Output

Set the GPIO you want to control. In our case, we’ll control GPIO 2 (built-in LED) and its state is LOW by default.

const int ledPin = 2;
bool ledState = LOW;

Note: if you’re using an ESP8266, the built-in LED works with inverted logic. So, you should send a LOW signal to turn the LED on and a HIGH signal to turn it off.

handleNewMessages()

The handleNewMessages() function handles what happens when new messages arrive.

void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

It checks the available messages:

for (int i=0; i<numNewMessages; i++) {

Get the chat ID for that particular message and store it in the chat_id variable. The chat ID allows us to identify who sent the message.

String chat_id = String(bot.messages[i].chat_id);

If the chat_id is different from your chat group ID (CHAT_ID), it means that someone (that is not in the group) has sent a message to your bot. If that’s the case, ignore the message and wait for the next message.

if (chat_id != CHAT_ID) {
  bot.sendMessage(chat_id, "Unauthorized user", "");
  continue;
}

Otherwise, it means that the message was sent from someone in your group, so we’ll save it in the text variable and check its content.

String text = bot.messages[i].text;
Serial.println(text);

The from_name variable saves the name of the sender.

String from_name = bot.messages[i].from_name;

If it receives the /led_on message, turn the LED on and send a message confirming we’ve received the message. Also, update the ledState variable with the new state.

if (text == "/led_on") {
  bot.sendMessage(chat_id, "LED state set to ON", "");
  ledState = HIGH;
  digitalWrite(ledPin, ledState);
}

Sending a message to the bot is very simply. You just need to use the sendMessage() method on the bot object and pass as arguments the recipient’s chat ID, the message, and the parse mode.

bool sendMessage(String chat_id, String text, String parse_mode = "")

Do something similar for the /led_off message.

if (text == "/led_off") {
  bot.sendMessage(chat_id, "LED state set to OFF", "");
  ledState = LOW;
  digitalWrite(ledPin, ledState);
}

Note: if you’re using an ESP8266, the built-in LED works with inverted logic. So, you should send a LOW signal to turn the LED on and a HIGH signal to turn it off.

Finally, if the received message is /state, check the current GPIO state and send a message accordingly.

if (text == "/state") {
  if (digitalRead(ledPin)){
    bot.sendMessage(chat_id, "LED is ON", "");
  }
  else{
    bot.sendMessage(chat_id, "LED is OFF", "");
  }
}

setup()

In the setup(), initialize the Serial Monitor.

Serial.begin(115200);

If you’re using the ESP8266, you need to use the following line:

#ifdef ESP8266
  client.setInsecure();
#endif

In the library examples for the ESP8266 they say: “This is the simplest way of getting this working. If you are passing sensitive information, or controlling something important, please either use certStore or at least client.setFingerPrint“.

Set the LED as an output and set it to LOW when the ESP first starts:

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);

Init Wi-Fi

Initialize Wi-Fi and connect the ESP to your local network with the SSID and password defined earlier.

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.println("Connecting to WiFi..");
}

loop()

In the loop(), check for new messages every second.

void loop() {
  if (millis() > lastTimeBotRan + botRequestDelay)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    lastTimeBotRan = millis();
  }
}

When a new message arrives, call the handleNewMessages() function.

while(numNewMessages) {
  Serial.println("got response");
  handleNewMessages(numNewMessages);
  numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}

That’s pretty much how the code works.

Demonstration

Upload the code to your ESP32 or ESP8266 board. Don’t forget to go to Tools > Board and select the board you’re using. Go to Tools > Port and select the COM port your board is connected to.

After uploading the code, press the ESP32/ESP8266 on-board EN/RST button so that it starts running the code. Then, you can open the Serial Monitor to check what’s happening in the background.

Go to your Telegram account and open the group.

Send the following commands and see the bot responding:

  • /led_on turns the LED on.
  • /led_off turns the LED off.
  • /state requests the current LED state.
Control ESP32 ESP8266 using Telegram Group Demonstration

The on-board LED should turn on and turn off accordingly (the ESP8266 on-board LED works in reverse, it’s off when you send /led_on and on when you send /led_off).

When you add your telegram bot to a group, everyone in the group can interact with the bot and receive messages from the bot. For example, in this case we can both (Sara and Rui) control the bot and see the commands that the other is sending. Additionally, in a project with notifications, we’d both be notified on the group.

You can add more people to the group, for example all family members.

ESP32 board Built in LED turned on HIGH

On the Serial Monitor you should see that the ESP is receiving the messages.

Control ESP32 ESP8266 Outputs Telegram Serial Monitor Demonstration

Wrapping Up

In this tutorial you’ve learned how to get and send messages to the ESP32 or ESP8266 using a Telegram group. Using a Telegram group to control your ESP32 might be advantageous over a single chat, if you want to have several people able to control and monitor the same board.

We’ve shown you a simple example on how to control an output. The idea is to modify the project to add more commands to execute other tasks. For example, you can request sensor readings or send a telegram message when motion is detected.

The great thing about using Telegram to control your ESP boards, is that as long as you have an internet connection (and your boards too), you can control and monitor them from anywhere in the world.

We hope you’ve found this project interesting.

Learn more about the ESP32 and ESP8266 with our resources:

Thanks for reading.



Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

18 thoughts on “Telegram Group: Control ESP32/ESP8266 Outputs (Arduino IDE)”

  1. Hello Rui, how are you? I really enjoyed this tutorial from you, congratulations. But I would like to check if there is a way to perform just one pulse, simulating a remote control.
    For example I have a friend who owns a garage which he rents a box, sometimes someone forgets the control there he or the manager opens the gate via app with a pulse which activates the remote control through a transistor. Before I used Cayenne but it is discontinued by the app.
    I don’t know if that would be possible. I used Amazon’s cloud but I have compatibility problems, because we found an App on Android but IOS is very complicated, this idea of ​​Telegram would be a great idea, because in both operating systems we can use the same App.

    Hugs,

    Eliseu

    Reply
    • Hi.
      The easiest way is to set the GPIO to HIGH and then to LOW again. Add a delay between each command depending on the duration of the pulse.
      For example:
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW)
      I hope this helps.
      Regards,
      Sara

      Reply
      • Thanks Sara,
        I’ll try it….tomorrow.
        Now here it’s pillow time😂!
        Thank U very much.
        P. S.
        I made a telegram group of 6 ESP32-CAM with some relays and buzzers. I can interact them with single or multiple commands! (I’m so happy)

        Reply
  2. Hello Sara and Rui,
    thanks for your great work: I made a Telegram group of ESP32-cam bot! They work perfectly!
    I only want to ask You a little thing: I wanna attach 2 led at those (mine) ESP32-cam.
    What pin can I use? I tried GPIO 1 e 3, or 16 e 2 but they don’t work.
    Thanks Renzo (from farfar away Italy)

    Reply
  3. Nice project – thank you but is there a way to allow a few chat id without using the group function so that response is directly to the person who asked and will not ping other members.eg joe and bob are valid users but dont want to be disturbed with lots of messages rudy needs to know the status every hour of the pump”led”.

    Reply
    • Hi
      You can add multiple personal IDs and check them individually.
      For example:
      #define CHAT_ID_1 “XXXXXXXXXX”
      #define CHAT_ID_2 “XXXXXXXXXX”

      Then, in the handleNewMessages() function check whether the message came from one of those users:
      for (int i=0; i<numNewMessages; i++) {
      // Chat id of the requester
      String chat_id = String(bot.messages[i].chat_id);
      if (chat_id != CHAT_ID_1 || chat_id != CHAT_ID_2){
      bot.sendMessage(chat_id, “Unauthorized user”, “”);
      continue;
      }

      I hope this helps.
      Regards,
      Sara

      Reply
      • Hi Sara,
        Thank you for this amazing project.
        I think the code above should be like that “if (chat_id != CHAT_ID_1 && chat_id != CHAT_ID_2)” not if (chat_id != CHAT_ID_1 || chat_id != CHAT_ID_2)”

        Reply
  4. Excellent and practical.
    Perhaps more program lines should be added to be more specific when you do not want to share with the group each program that is executed (to add more features to the application).

    When adding group members, the administrator should generate the corresponding permissions individually for each one.
    I think the great solution would be for the administrator to turn esp32 into a webserver mode so that he can program the module’s exclusive use parameters on his screen and finally, since the group members are already programmed, they can no longer modify that data.
    It would be a good extension of this benefit, right?

    And the “icing on the cake” as we say at least in Argentina, would be to carry out this entire tutorial using the ESP32 SIM800L so that in case there is no Wi-Fi in place, you can communicate with Telegram through the SIM800.
    If it is possible to do it, I think it would be very useful for all the followers of Rui and Sara.
    Thank you very much

    Reply
    • Hi Alejandro.
      Yes, you can add other lines of code to check who sent the message and allow the user to execute a certain task or not.
      Here, we’re just showing the simplest example so that our readers can easily modify it for their own projects.

      As you mention, it can be also a good idea to establish an internet connection using a SIM800L module or any other data module so that you don’t need to connect the ESP to a router.
      We have this tutorial about connecting the ESP32 to the internet using SIM800L: https://randomnerdtutorials.com/esp32-sim800l-publish-data-to-cloud/

      Thanks for following our work.
      Regards,
      Sara

      Reply
  5. Yesterday I sent a comment about this tutorial, some suggestions of interest perhaps for the followers.
    After a while where it said “in the process of moderation” or something like that, my submission disappeared.
    This is the third time that has happened to me. I don’t know what mistake I’m making or is it because I sent it from Argentina, or are there character limitations or specific topics?
    Should I write in “Contact” for certain topics?
    Thanks for your attention.

    Reply
    • Hi Alejandro.

      Your previous comment was now approved.

      We receive lots of comments everyday.
      It is impossible for us to review, approve and answer all comments on the day they were published.
      Sometimes, we can’t even keep up with all the comments we receive.

      Thanks for your understanding.
      Regards,
      Sara

      Reply
      • Hi Rui and Sara

        I regret my anxiety to see that my posts were not together with others sent by their followers and I believed that I was sending incorrect information.

        I have certainly always added more lines of code to your excellent tutorials.

        I loved this Telegram project so much, that I did the tests for individual control, of several enabled users entering their IDBot and in a group, with selection of permissions from the administrator or owner.
        I think it just lacks the addition of “automatic switching” between ESP32 wifi and the ESP32 / SIM800L module. in the absence of Wi-Fi connection with Telegram.
        I have bought 2 of these devices just to do these tests.

        I would only suggest if they could complete, in an additional or complementary tutorial, what is necessary to use the SIM800 mode with communication exclusively with Telegram bots for communication and reception of the information that is exchanged.

        Once again I congratulate them for their work and how they have given us tools to their followers to continue learning topics with their very practical, clear and useful explanation.

        Reply
        • Hi Alejandro.
          I’m really glad that you liked this tutorial and found it useful.
          Thanks for the suggestion of the SIM800L project. I’ll add it to my list of projects/tutorial ideas.
          Then, let us know your results.
          Regards,
          Sara

          Reply
  6. Hi Rui,
    I tried this group communication with ESP32. For the Android phones, it’s working perfectly, but for Apple phones it’s not working correctly. sometime only the first command works, after that no responses from the ESP32.

    Kindly advise a solution.

    Thanks,

    Reply
  7. How to fix this problem

    Leaving…
    Hard resetting via RTS pin…

    After uploading code my Nord MCU resetting again and again

    Please help

    Same issue in every code

    Reply
    • That’s not an error.
      That’s the normal message after uploading the code.
      You just need to press the board RST button to run the code.
      Regards,
      Sara

      Reply

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.