This guide shows how to control the ESP32 or ESP8266 NodeMCU GPIOs from anywhere in the world using Telegram. As an example, we’ll control an LED, but you can control any other output. You just need to send a message to your Telegram Bot to set your outputs HIGH or LOW. The ESP boards will be programmed using Arduino IDE.
Project Overview
In this tutorial we’ll build a simple project that allows you to control ESP32 or ESP8266 NodeMCU GPIOs using Telegram. You can also control a relay module.
- You’ll create a Telegram bot for your ESP32/ESP8266 board;
- You can start a conversation with the bot;
- When you send the message /led_on to the bot, the ESP board receives the message and turns GPIO 2 on;
- Similarly, when you send the message /led_off, it turns GPIO 2 off;
- Additionally, you can also send the message /state to request the current GPIO state. When the ESP receives that message, the bot responds with the current GPIO state;
- You can send the /start message to receive a welcome message with the commands to control the board.
This is a simple project, but shows how you can use Telegram in your IoT and Home Automation projects. The idea is to apply the concepts learned in your own projects.
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. In this tutorial you’ll learn how to use Telegram to send messages to your bot to control the ESP outputs from anywhere (you just need Telegram and access to the internet).
Creating a Telegram Bot
Go to Google Play or App Store, download and install Telegram.
Open Telegram and follow the next steps to create a Telegram Bot. First, search for “botfather” and click the BotFather as shown below. Or open this link t.me/botfather in your smartphone.
The following 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.
Get Your Telegram User ID
Anyone that knows your bot username can interact with it. To make sure that we ignore messages that are not from our Telegram account (or any authorized users), you can get your Telegram User ID. Then, when your telegram bot receives a message, the ESP can check whether the sender ID corresponds to your User ID and handle the message or ignore it.
In your Telegram account, search for “IDBot” or open this link t.me/myidbot in your smartphone.
Start a conversation with that bot and type /getid. You will get a reply back with your user ID. Save that user ID, because you’ll need it later in this tutorial.
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.
- Installing the ESP32 Board in Arduino IDE (Windows, Mac OS X, Linux)
- Installing ESP8266 Board in Arduino IDE (Windows, Mac OS X, Linux)
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.
- Click here to download the Universal Arduino Telegram Bot library.
- Go to Sketch > Include Library > Add.ZIP Library...
- 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.
- Go to Skech > Include Library > Manage Libraries.
- Search for “ArduinoJson”.
- Install the library.
We’re using ArduinoJson library version 6.15.2.
Parts Required
For this example we’ll control the ESP on-board LEDs:
- ESP32 board (read Best ESP32 dev boards)
- Alternative – ESP8266 board (read Best ESP8266 dev boards)
Control Outputs using Telegram – ESP32/ESP8266 Sketch
The following code allows you to control your ESP32 or ESP8266 NodeMCU GPIOs by sending messages to a Telegram Bot. To make it work for you, you need to insert your network credentials (SSID and password), the Telegram Bot Token and your Telegram User ID.
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/telegram-control-esp32-esp8266-nodemcu-outputs/
Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
Example based on the Universal Arduino Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/examples/ESP8266/FlashLED/FlashLED.ino
*/
#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"
#ifdef ESP8266
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
#endif
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 == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following commands to control your outputs.\n\n";
welcome += "/led_on to turn GPIO ON \n";
welcome += "/led_off to turn GPIO OFF \n";
welcome += "/state to request current GPIO state \n";
bot.sendMessage(chat_id, welcome, "");
}
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
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
#endif
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
#ifdef ESP32
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
}
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();
}
}
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
This sections explain how the code works. Continue reading or skip to the Demonstration section.
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";
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.
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 User ID
Insert your chat ID. The one you’ve got from the IDBot.
#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;
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 ID (CHAT_ID), it means that someone (that is not you) 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 a valid user, 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 /start message, we’ll send the valid commands to control the ESP32/ESP8266. This is useful if you happen to forget what are the commands to control your board.
if (text == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following commands to control your outputs.\n\n";
welcome += "/led_on to turn GPIO ON \n";
welcome += "/led_off to turn GPIO OFF \n";
welcome += "/state to request current GPIO state \n";
bot.sendMessage(chat_id, welcome, "");
}
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 = "")
In our particular example, we’ll send the message to the ID stored on the chat_id variable (that corresponds to the person who’ve sent the message) and send the message saved on the welcome variable.
bot.sendMessage(chat_id, welcome, "");
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);
}
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“.
We have a tutorial showing how to make HTTPS requests with the ESP8266: ESP8266 NodeMCU HTTPS Requests (Arduino IDE).
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 a conversation with your bot. Send the following commands and see the bot responding:
- /start shows the welcome message with the valid commands.
- /led_on turns the LED on.
- /led_off turns the LED off.
- /state requests the current LED state.
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).
At the same time, on the Serial Monitor you should see that the ESP is receiving the messages.
If you try to interact with your bot from another account, you’ll get the the “Unauthorized user” message.
Wrapping Up
In this tutorial you’ve learned how to create a Telegram Bot to interact with the ESP32 or ESP8266. With this bot, you can use your Telegram account to send messages to the ESP and control its outputs. The ESP can also interact with the bot to send responses.
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 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:
- Learn ESP32 with Arduino IDE (eBook + Video Course)
- Home Automation using ESP8266
- More ESP32 projects and tutorials…
- More ESP8266 projects and tutorials…
Thanks for reading.
Hi Sara and Rui,
do you happen to know if the same functionality exists for the messenger Signal?
I prefer Signal over Telegram.
We haven’t looked into any libraries or APIs for Signals, but if it offers a similar API you might also be able to do it with that app.
There are somethings already for Signal. However I don’t know how flexible they are as Telegram is..
community.signalusers.org/t/signal-bot-framework/6741/5
Hi, Sara.
Congratulations for another amazing project. If I connect a PIR sensor or another sensor, I will be able get the state of that input? It´s possible?
Yes. Next week, we’ll be posting motion detection with Telegram notifications!
Ok, It will very useful. If it possible to implement a schedule for this notifications, will be very good too. For example, send a command to activate/army the system, and then notifications can arrive.
*To Arm
Hi Sara,
Is telegram the same (System) as Blynk?
Telegram is a messaging app that has an API that allows you to interact with your ESP (but it’s all done using messages, you don’t add buttons, sliders, color pickers, etc like you can do with Blynk)
Hi, excellent tutorial as usual, thank you.
In all your tutorials I’ve seen, my network credentials have to be programmed in !
Would it be an easy mod to replace this with Auto Connect please ?
Many thanks in advance
Terry
It has a notice “Important: don’t install the library through the Arduino Library Manager because it might install a deprecated version.” but when you go to Github it outlines using the Arduino library manager? Which process is to be used?
Just ensure that you are installing the latest version and it should be fine (it wasn’t allowing us to install the latest version in Arduino IDE using the libraries manager).
Receiving a photo from Esp32cam board via Telegram upon request would be a great project, I have never been able to get it to work but I am sure a great number of people would be interested.
Thanks
We will post something like that in a near future! Thanks for the suggestion Steve.
Hello, a very good idea. I just scanned the instructions. I should enter my WiFi access (SSID / password) in plain text. What happens to it? Is the password encrypted and stored securely? Or do you recommend setting up a separate WiFi network for the test? Thanks in advance
ja49
The ESP stores the password in its firmware, someone would need physical access to your device in order to get it and having quite a bit of knowledge to retrieve the firmware and decode it.
What types of messages can be sent from the bot? Can you send audio or jpeg? Thanks
Hi.
I haven’t tried audio. But you can send a jpeg file.
Regards,
Sara
Hi Sara and Rui,
thank you for your tutorial
I use nodemcu
I faced to this error:
‘class axTLS::WiFiClientSecure’ has no member named ‘setInsecure’
please help me
Hello Ramazan, do you have the latest version of the ESP32/ESP8266 board add-on?
Regards,
Rui
thank you sara
as i said, board connected to wifi and shows ip in serial monitor. in the telegram bot i write the command like led_on and other command ,i dont get any respons on board or not show respons in serial monitor
thanks alot sara
Hi.
You probably have the botToken wrong.
Go the Telegram web interface and copy the telegram botToken directly from there: https://web.telegram.org/
Regards,
Sara
Check this:
bot.sendMessage(chat_id, welcome, “”);
Check that chat_id is not CHAT_ID.
I also comment #include <Arduino.h>
Tschüss!
Hi there, I’ve got this project up and running, excellent tutorial. Thanks.
I couldn’t get the program to compile with ArduinoJson 6.15.2 so I reverted to v6.11.0 and all was good.
Small problem. I did everything as described in step / step. However, I don’t get a response from Telegram in the serial monitor as you show. I also don’t get an error. So I don’t know now what would be wrong. Any idea ?
Did you get the exact user ID and Bot tokens? Do you have the correct SSID and password in your code? did you select the right baud rate in your Arduino IDE serial monitor (115200)?
I found that the ESP32 I was using was not good. He came up with the IP address but then stopped. now everything goes as it should with an esp8266 wemos D1.
Thanks for your comment.
Greetings Bert
I did everything according to your example. it looks like i am not connected to Telegram. I assume ID and token are good because there is no error message. In the Serial monitor I only see the IP address, no further info as you show it in the demo.
What can I do ?
Hi Bart, Nothing appears in the serial monitor until you send a message in telegram, i.e. /state. Once you do that then you’ll see the result in the monitor as below
Before.
entry 0x400806b8
Connecting to WiFi..
192.168.1.112
After
entry 0x400806b8
Connecting to WiFi..
192.168.1.112
got response
handleNewMessages
1
/state
I trust that this helps. Ian
Sorry is not working, thanks for the reaction.
In the end it works now. I used a different esp32. Thanks
I had trouble getting my Telegram User ID following your tutorial.
Finally I was able to find it by typing ‘@my_id_bot’ in the message box of my new bot which then brought up my user ID.
I hope this helps
Ian
Good day I happen to have an error. I am using ESP8266, it states “Class, classwifi has no class mode”
I updated my esp8266 community libraries then I loaded, the second time I tried loading the code the same error came back.
Is there any way of solving this issue?
Thanks
Hi.
Make sure you have an ESP8266 board selected in the Tools>Boards menu.
Regards,
Sara
Hi Sara and Rui,
If your ESP is connected to the internet through your home network, I am wondering: does the command “client.setInsecure()“ make your home network insecure or vulnerable for attacks?
Thanks a lot,
Steven
No Steven, you don’t need to worry about that, but it just means that your ESP is not making encrypted requests. Your network is still secure. I hope that helps!
Well, that does not directly expose you home network via the ESP, but makes ESP ignore Telegram server validation. A potential attacker may eavesdrop the communication of your ESP and Telegram servers and steal your token or even pretend to be a real Telegram server and respond with malicious data. While it’s rather harmless for a blinking LED, it may cause harm if ESP is used to control something more serious. I suggest to learn how to use certificate validation on ESP and verify it if you want to protect your device from unauthorized access.
Well, that does not directly expose you home network via the ESP, but makes ESP ignore Telegram server validation. A potential attacker may eavesdrop the communication of your ESP and Telegram servers and steal your token or even pretend to be a real Telegram server and respond with malicious data. While it’s rather harmless for a blinking LED, it may cause harm if ESP is used to control something more serious. I suggest to learn how to use certificate validation on ESP and verify it if you want to protect your device from unauthorized access.
Hi.
We have a tutorial showing how to make HTTPS requests with the ESP8266 https://randomnerdtutorials.com/esp8266-nodemcu-https-requests/#esp8266-https-requests-root-certificate
That you can use as reference and adapt to make HTTPS requests to Telegram servers.
Regards,
Sara
Oh, that’s an awesome tutorial. Thank you!
I believe it may be helpful to link this tutorial somewhere around the code snippet with
secInsecure()
call.Thanks for the suggestion.
I added a note about that in the tutorial.
Regards,
Sara
Hi Rui and Sara, I’m using NodeMCU,
I did everything according to your example. it looks like i am not connected to Telegram. I assume ID and token are good because there is no error message. In the Serial monitor I only see the IP address, no further info as you show it in the demo.
What can I do ? please help me to find out solution.
For a better (safer) approach to client.setinsecure for https requests, see this hackaday post:
hackaday.com/2020/07/02/easy-secure-https-with-an-esp8266/
Thanks for sharing Henk!
Hi Ruis,
this is a good example how to control IoT over a smartfone by using text messages.
Is it possible to get pictures from an ESP cam too?
Best regards
Tom
it works fine
Hi Rui and Sara,
Excellent tutorial, worked on the first try with bot ESP32 and ESP8266!
Is it possible to add more users ID’s in the sketch, for example if i want to give another user access to my data (such as temp, humidity, etc..(future project))
Regards,
Leon
Never mind, I got it working
Hi Rui and Sara,
Can this be adapted to work on a Sonoff switch, still using Telegram?
Regards,
Leon
Hello Rui And Sara. i am a big fan of your work. you are just like teacher for me. i have learned a lot from you. thank you for your efforts.
I was trying to implement it but i don’t know whats the reason i wasn’t able to connect with telegram. can you please tell me the possible reason for it.
i didn’t get any error but serial says connected to telegram failed.
Hi.
Double-check your botToken.
It is a very long string. So, you may have a small error somewhere in the string.
Regards,
Sara
hi. Sara, i follow your excellent work. As for this one. I keep having this message when i compile, it gives the same either if it a 32 or a 8266. Have you had this case.
exit status 1
Error compilando para la tarjeta WeMos D1 R1.
Hi.
Can you give more information about the error?
Regards,
Sara
Ok, I kept working on this and finally solved it. I found that the problem has to do specifically with the use of a Telegram Library (I tried several) and a combination between the Arduinojson Library Version and the Arduino Ide Version.
After lot of trying, I found this:
Arduino Ide Arduinojson Esp8266 Esp32
1.8.3 5.13.5 ok no ok
1.8.13 5.13.5 ok ok
I have the same problem, I am using Wemos ESP8266 D1R1. the problem is the versions?, because I had had trying and it doesnt work yet. Please, help I really want this.
Funciona FUNCIOOOOOOONNNNAAA Thanks you have right!!!!. It was the version of IDE Arduino. ♥ ♥ ♥
Thanks Rui and sara , I tried your code for esp 8266 to control single output ie led and it is working good, I am going to implement 4 outputs with relays to control my drip irrigation electro valves with little modification in the code.
Thanks once again for sharing your knowledge.
S.Yogaraja.
hi,thanks alot
I install latest version and upload successfully.
now my board is connected to wifi and show the IP in serial monitor.
but I cannot control LED from telegram
there is no response.
thank you
Hi.
When you say you cannot control the LED, what exaclty happens?
Double-check your bot token. You may have a typo in that long string.
Regards,
Sara
Hello sara
thanks alot
well done….
Thanks 😀
Thank you! It`s work!
Hi, Sara & Rui,
thanks for your excellent tutorials.
I’ve been trying to implement this tutorial in telegram and I am not able to obtain any response either in the phone or in the Serial Monitor.
What can be happening?
Enrique
Hi.
Double-check that you’ve inserted the right Bot Token. It is a very long string – it is easy to get it wrong.
Regards,
Sara
hi dudes, i have facing this issue,
‘class axTLS::WiFiClientSecure’ has no member named ‘setInsecure’
what to do next!??
Hi.
Which board are you using?
Regards,
Sara
Hello Sara, Rui,
I am from Spain . Thank you for your projects. Perfectly explained.
I tested some sensors and it is very interesting.
Could you tell me if you know how to create buttons instead written instructions? I saw that the messages are sent by “html” style but I tested to send an html function but I had not success ;-).
Thanks again and kind regards,
Lorenzo
Solucionada la cuestión en la documentación de la librería Telegram. Os lo pongo por si a alguien le interesa incluir botones:
Solo hay que incluir otra línea de código donde se envía el tipo de mensaje “inlineKeyboard”:
bot.sendMessageWithInlineKeyboard(chatId, “Presiona el botón deseado”, “”, keyboardJson);
Donde keyboardjson en un String que crearemos previamente, donde incluiremos tantos botones como queramos, con sus respectivas palabras clave -las mismas que pondríamos escritas normalmente-. Comodísimo!!!
Un saludo, y gracias de nuevo por estas paginas que nos ayudan a todos.
Lorenzo.
No funciona en Wemos D1 R1, it doesn’t work in Wemos D1 R1 … Arduino:1.8.12 (Windows 8.1), Tarjeta:”WeMos D1 R1, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 921600″
C:\Users\Mariu\Documents\Arduino\libraries\UniversalTelegramBot\src\UniversalTelegramBot.cpp:319:11: error: DynamicJsonBuffer is a class from ArduinoJson 5. Please see arduinojson.org/upgrade to learn how to upgrade your program to ArduinoJson version 6
You need to have ArduinoJson library version 6.15.2.
Regards,
Sara
Please, write a version for ESP32 SIM800L
Thanks in advance.
Is it possible to retrieve analog data using telegram?
TIA.
Yes, you can reply with any type of data.
Hello Sara,
Thanks for great tutorial.
I have problem bot telegram not respon while ” /start ” .
is there Doit ESP32 DEVKIT V1 compatible with this program ?
Thanks before
Regard,
Hi.
Double-check that you’ve inserted the bot token right.
It is not an issue with the board.
Regards,
Sara
it’s the same for me, bot token is right
Hey Sara and Ruiz,
Thanks for another great project!
Unfortunately I can’t get it to work on my ESP32. WiFi connects well, but communication with the Telegram server does not seem to get started. I’m not getting any “got response” messages.
I added to UniversalTelegramBot.cpp (I’m using version 1.3.0)
#define TELEGRAM_DEBUG 1
I’m now getting the error message:
GET Update Messages
[BOT]Connecting to server
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
[BOT]Conection error
Received empty string in response!
I’ve tried several things:
1) Add to setup:
client.setInescure();
This gives compilation error:
‘class WiFiClientSecure’ has no member named ‘setInescure’
I’m using WiFiClientSecure version=1.0 author=Evandro Luis Copercini
2) Add to setup:
client.setFingerprint(“BB DC 45 2A 07 E3 4A 71 33 40 32 DA BE 81 F7 72 6F 4A 2B 6B”);
Gives me also a ‘has no member named’ error message.
What else can I try?
Hi.
There was an update on the library and our codes weren’t working properly.
I only noticed this yesterday.
The code is now updated.
Make sure you have the latest version of the library installed and try again.
Regards,
Sara
Upon terrible unsuccessful trials on get connected to telegram by introduced in code library, I did a try to use CTBot: github.com/shurillu/CTBot and Wow! It’s done now.
with beautiful buttons, instead of typing /on, /off: github.com/shurillu/CTBot/blob/master/examples/inlineKeyboard/inlineKeyboard.ino
Thanks a lot for this hint.
I had similar problems: Telegram communication with an ESP32 (Modified code with various temperature, humidity and CO2 sensors – I2C, oneWire, UART – SD card for data logging, SSD1306 monitor) worked sometimes – sometimes not, i.e., everything started without errors, but handleNewMessages was never called). As soon as I replaced
#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
by the much simpler
#include “CTBot.h”
and made some small adaptations in the code, everything worked very well. In the future, I will certainly prefer CTBot.
Incidentally, the statement client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org caused a compiler error. I updated all libraries, but TELEGRAM_CERTIFICATE_ROOT is not defined anywhere.
Try to click on security icon before address bar in browser window and find SHA256 fingerprint code on second tab. It is the variable you are looking for.
Of course, I mean the telegram.com Every secure session backed site has own fingerprint.
Is it possible that others than me can also operate a Bot? For example after I have given permission for it?
Hi.
What do you mean?
Do you want to have several people able to control the ESP via Telegram?
You can give permission to multiple IDs or you can create a telegram group. See this tutorial: https://randomnerdtutorials.com/telegram-group-esp32-esp8266/
Regards,
Sara
thanks for this
Hi! Nice tutorial!
However, it doesn’t work with my ESP32. I think the reason is the incompatibility between some libraries versions and Arduino IDE version .
Could someone tell me what versions of libraries and Arduino IDE work fine, please?
Thanks a lot.
Hi.
I’m using Arduino 1.8.13.
Use this version of the library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/archive/master.zip
Install it as mentioned in the tutorial
Regards,
Sara
Hi! Nice job!
Could someone tell me the Arduino version a libraries version that work to ESP32, please?
I have a versions issue and I’m getting crazy
Thanks a lot
Hi.
I’m using Arduino 1.8.13.
Use this version of the library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/archive/master.zip
Install it as mentioned in the tutorial. Sketch > Include Library > Add ZIP library
Regards,
Sara
Thank you so much!
However, the communication doesn’t work either. I checked the Token and Id are correct. Could you tell me what version of esp32 board are you using?
Hi.
My ESP32 boards version is 1.0.4
Regards,
Sara
Hey this is great, only have a question
haven’t had the chance to test if it would work or if its possible to use the same token/bot on multiple devices.
i need to have multiple esp32 with sensors and would like to receive updates from all of them without needing to create a separate bot for each
Hi – did you resolve this?
I want to send request (eg. /value) and have each esp32 respond.
Currently, only the first esp32 to pick up a request answers
Did Telegram.org change something in the platform in use for the bot?
I have an ESP32 board operating for more than a year to send or receive messages, and a week it has not received messages sent from my cell phone.
The cell phone receives message sent from the ESP32 board.
I changed the board, created a new bot and nothing works.
Something different happens in the Telegram bot.
Hi.
The library has changed to comply with some changes.
Please install the latest version of the library using the Github link and then, use our updated codes.
The codes in our tutorials are already updated.
Regards,
Sara
Hi Sara and Rui!
I have an ESP32 card working using Telegram and for over a year without problems. The board worked by receiving messages from the cell phone and also being able to send messages to the cell phone. About a week ago 6/16/21 I noticed that the card was no longer receiving a message from the cell phone, but it can send a message. I used another ESP32 board reprogrammed and nothing on the board received a message. I noticed by the ESP32 serial if the cell id reaches the ESP32 but it doesn’t, I also created another Token and nothing. I suspect that Telegram has made some platform change that makes the UniversalTelegramBot lib not fully functional.
Sorry, I have no solution. I simply noticed the same. Maybe, the root certificate plays a role, but…
Hello Helio,
I have been unsuccessful with two different types of ESP32 board, the Fire Beetle and the WEMOS D1 MINI. However it works fine with my ESP8266 AI-Thinker board. I think that something has changed somewhere as you said. I have sent a comment to Brian Lough who wrote this library but I will have to wait and see whether he replies.
Hi David.
What was exactly the issue you got with the ESP32 boards?
Regards,
Sara
Hello Sara and Rui!
i couldn’t find the library WiFiClientSecure.h
please help me.
Thanks
Hi.
It is included by default with the ESP32 core.
You don’t need to install it.
Regards,
Sara
Hi:
Very NIce Work! Thanks!!
It’s work perfect to me when i use your code alone, but I got a problem when i add a Router/Repeater with NAPT.
I’m Using code :
github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino
When i disable line 71and NAPT not init, obviously repeater fail but Telegram work.
When i enable that line repeater work and telegram init ok but do not receive messages from my cell.
Could you please give me some lights about why ? or better, if can fix my issue by, you make me really happy! 😉 i Lost 1 week trying to do it!!!
I can support your help if necesary.
Best regards and Thanks in advance.
What is NTP time server doing in this… I see there is configtime… but the time value is not utilized anywhere…
I was wondering how to use the time value that we get to activate photo at fixed time of day…
Also how often this ask for time from NTP server… once in a day or once in hour…
I also have the same question. It does seem relevant, commenting the call to the NTP server out results in not receiving the Telegram messages on the ESP8266. I don’t see a mention of this on the library’s author git readme page
Hi Rui & Sara,
I am trying to use the ESP32+SIM800L, is there a work around for this
<client.setCACert(TELEGRAM_CERTIFICATE_ROOT)> since the TinyGSM does not have the relevant method.
Thanks but no thanks. I got it working few months back, and willing to help others for free.
My internet speed is quite fine 40mbps but still response from esp arrives late, and same actiom is too late like send picture, if I command flash it on after 5 minutes, same picture takes 5 minutes.
Can any one respond?
Hello,
Excellent project as always.
I have made a similar implementation, following your instructions, and am using it for water flow control in orchard irrigation. The volume, flow, temperature and humidity metrics are sent to the Telegram.
One problem I encountered is the fact that the Telegram API is synchronous and thus the ESP8266 loop is delayed until the message is sent. I was wondering if it would be interesting, in this case, to connect ESP to MQTT and this to Node-RED. In this way a Node-RED chatBOT could send the message, thus freeing the ESP8266 from being directly connected to the Telegram. I believe the infrastructure needed will increase considerably but in return it would free up resources in ESP8266. What do you think ?
Thanks again for the excellent material on your site.
Hi.
You can try it and see if it improves the workflow.
I found this node-red node that might be useful: https://flows.nodered.org/node/node-red-contrib-telegrambot
Regards,
Sara
Yes, there is a library in Arduino for MQTT, and it works well. I use it and Node red to monitor solar heaters.
I tried to do the ESP32 with Telegram and PIR and it did not work so I thought I would try this simpler one and still had this error
Error compiling for board DOIT ESP32 DEVKIT V1.
after I checked thebot token and wifi credentials 3 times , then checked the Json library was the one in the tutorial, is ther any way to get a clue as to what went wrong?
is the statement Error Compliing any clue ? thanks
Hi.
Can you provide more details about the error?
What is the line of code highlighted by the error?
Regards,
Sara
that is all it said was compiling error … it did not elaborate, I wondered what they mean by compiling? a piece of code wrong? or a library not correct or another setting?
Hi again.
But there should be a line highlighted in the code.
Otherwise, it is very difficult to find out what might be wrong.
thanks yes I think I will try to wipe it all clean and start from square one sine it was not giving me any error diretion
Thanks for sharing this, it works great.
On the ESP32 it works fine on the latest boards version, but note that on the ESP8266 it only works for me on Arduino ESP8266 firmware boards version 2.7.4 – I tried running the latest version which is 3.0.2 but it doesn’t send the Telegram message. I don’t receive any error messages, it just takes longer to execute bot.sendMessage and no Telegram message is sent.
There seems to be a problem with the latest version of the Arduino ESP8266 firmware and setting the CA cert
Hi Rui and Sara!
Can I get information if you have tested the use of shield with w5500 chip to provide communication with Telegram server? I tested a shield with w5100 chip and it doesn’t work. I believe in the impossibility of not operating with https.
Hi.
I didn’t test that scenario.
Regards,
Sara
hi sara. i am using telegram to control thermostat and heater. everything has power backup. is there a change to use telegam direct to ESP when public electricity goes down and i dont have internet?
Hi.
The ESP needs access to the internet to connect to Telegram.
So, I don’t think that is possible.
Regards,
Sara
I thought that. So what do you recommend? use telegram and web server together?
I’ve been experimenting with ESP8266 Nodemcu and ESP.deepSleep() and Blynk.email without much success. I see this application uses a PIR with Telegram Bot app. Wonder if I can include the ESP.deepSleep() function with an external wake using a transistor switch?
Hi.
Yes, you can add deep sleep, but you won’t be able to send messages while the ESP is sleeping.
Regards,
Sara
‘TELEGRAM_CERTIFICATE_ROOT’ was not declared in this scope
help! i’ve tried everything from updating to redownload all the driver still doesnt work
ArduinoJson version 6.x
Universal telegram bot version 1.3.x
Hi Sara, thank you for sharing!
I wonder if it is possible to set the SSID and password using the telegram app instead of manually input them using the arduino IDE ?
Hi.
To be able to receive messages from telegram, the ESP needs to be connected to the internet.
So, it needs the SSID and password before connecting to telegram.
Regards,
Sara
Hi Sara,
great project and thanks for the clear explanation.
I’m trying to apply telegram module (based on this project) in a ESP12F equipped with Asynchronous Web Server (I’ve used ESP8266 DHT11/DHT22 Temperature and Humidity Web Server with Arduino IDE scheme); telegram module works fine if I don’t acced in to the web page, but once I’ve acceded in web page, some ESP reset occours and than telegram function doesn’t work anymore till an ESP button reset…do you think Asynchronous WEB server and telegram functionality can live together? thanks a lot for suggestions.
Hello, I load the program in my esp32 and it only sends the setup message (bot.sendMessage(CHAT_ID, “Bot Started”, “”);) and I receive it on my cell phone.
When the loop() enters, the numNewMessages variable always receives 0.
I send the orders from telegram (/led_on or /lef_off) and they don’t reach esp32. (numNewMessages = 0).
I would like to know what could be the problem of not receiving them.
The program loads it without modification, just add my ssid, pass and token.
Thanks
Hi.
Are you sure you’re sending the messages to the right ESP32 bot?
Regards,
Sara
It is for sure due to the core 2.0.2 problem. Read the closed issues on the Telegram Library github page.
Can I send a command to my ESP8266 via curl?
In my Telegram App I can send e.g.: “/start” or “/help” etc.
How can I send such a command in a browser or with curl?
Thank.
After some days later, I found out, that this is not possible.
The messages should be sent from the Bot TO the Bot, which is not allowed.
If I try I get a message that sending to a bot is not possible.
The Bots Chat-ID is, by the way, the first number-part of the token, which seems somehow obvious 🙂
Never mind.
Hi Rui, thank you guys so much for your excellently-presented tutorials, I have found them extremely useful.
I get the Telegram bot working perfectly, and I get the Wifi Autoconnect working perfectly, but when I try to use them both (to get a Telegram bot to work with wifi autoconnect, the two components seem to use two different versions of ArduinoJson (ver. 5 and ver. 6), and the project fails.
Is there any simple way to migrate to version 6 in both components, so that they can be used together?
Kind regards from South Africa,
Jules
Hello.
Just to avoid headaches. The Telegram Library does fail with ESP32 core 2.0.2. You can find workarounds in the closed issues list of the Library github page.
Regards.
Hi
I got an arduino program which reads from 3 sensors and display the reds on SSD1306. It also shows current date and BTC rate. The whole loop() least by me about ~60 seconds. How can I add the code to my loop If want the BOT response often than 1 minute?
Is there any other way to use the Mobile data using SIM800 and connect to Telegram? useful if there is no Wifi available.
Hi.
Yes. It is possible, but at the moment we don’t have any tutorials about that subject.
Regards,
Sara
I want to build a gps tracker with bot telegram & gps modul (like sim 800l) ,how to make bot to display map location?
Hi Rui,
Great project !
but I have a problem here.
after conection to wifi, the monitor show
2:28:57.942 -> [ 6693][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -1
12:29:02.032 -> [ 10790][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -1
12:29:03.343 -> [ 12120][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -1
12:29:04.693 -> [ 13452][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -1
12:29:06.045 -> [ 14783][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -1
12:29:07.346 -> [ 16114][E][WiFiClientSecure.cpp:135] connect(): start_ssl_client: -1
is it a certifcate error ?
how i fix it ?
thank you
This is great and it works well. I’m fairly new to using microcontrollers, but was wondering 2 things.
1.) is it possible to use something like the ticker library to have it periodically check for messages without disrupting other code? I’ve tried but can’t seem to get everything else to run while this is running in setup(). Note: I’m also using just the setup() because i’m doing deep sleep.
2.) Wondering if it would be possible to wakeup from a sleep while a new message is received. I can’t imagine it being possible, at least not from a deep sleep but would be curious if it is possible.
Hi.
While the ESP is in deep sleep, it can’t listen for new messages.
So, you won’t receive new messages while the ESP is asleep.
Regards,
Sara
Thanks for this tutorial, it was very helpful and worked right away on an ESP32 board.
I noticed that the function bot.getUpdates(bot.last_message_received + 1); it takes about 800mS to execute, even in the absence of incoming messages. It’s normal? Is there any way to reduce this time?
Thank you.
Livio
Can someone explain to me why the “LedState” variable is used if the port mode is read in the “/LedState” query and “LedState” is not seen? Thanks
Codigo:
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", "");
}
Tengo problemas con el telegram_certificate_root. Was no declared in this scope ayuda xf
Hi.
Check that you have the latest version of the library.
Install it by following the instructions in our tutorial.
Regards,
Sara
Hi, great tutorial!! I learned a lot from you, how about other telegram bot libraries for example asycntelegram2? Thank You
Hi.
Thanks for the suggestion.
I have to try it our.
Regards.
Sara
hey sara, how about library version 2.0.1? i have compile and eror. after i searching in internet, it says downgrade to version 2.0.1. I searched universal telegram bot 2.0.1, but i cant find it, can you give the link sara? Thank you
Jusuf
Yet another wonderful tutorial from you two – I always tell my students to check with you for quality tutorials.
I got the Telegram bot to run nicely to turn on and off the LED. Then I tried to add a command /reboot to achieve reboot of the ESP32:
if (text == "/reboot") {
bot.sendMessage(chat_id, "ESP32 will now reboot", "");
ESP.restart();
}
But this does restart the device, but in a boot loop. What should I do in the code to achieve a single restart?
Hi.
What do you mean that it restarts in a boot loop?
What happens exactly? Can you provide more details?
Regards,
Sara
It keeps on rebooting, and doesn’t listen to the message queue any longer. Is there a way to flush the queue before issuing the ESP.restart() command?
I sent a picture of it via email.
This is a very old post, and I doubt if you will see this, but, the problem is you are calling the reboot function, before the bot has a chance to realize that it’s already executed the message, so, when it restarts, the message is still there. The easiest way around this is rather than running the reboot function, just set a variable to true, and in your loop when that variable is true then run the reboot function. That won’t give the message a time to clear from the queue, it will reboot, and then not loop.
Hola les consulto no he podido conseguir la libreria WiFiClientSecure.h me podrian indicar de donde descargarla ? Desde ya gracias
Hi.
That library is included in the ESP32/ESP8266 core when you install them on the Arduino IDE.
Just make sure you have an ESP32 or ESP8266 board selected in Tools > Board.
You may also need to update your boards installation to most recent versions.
Regards,
Sara
Ok yo ne he probado de compilar porque pense que me faltaba esa libreria. Muchas gracias.
Olá a todos, seu exemplo acima você coloca o BOTtoken no inicio do código, e quando o valor BOTtoken virá depois, exemplo: logo a pós a função Serial.Bluetooth, através de um app, como eu mostro para biblioteca UniversalTelegramBot a string recebida na Serial.Buletooth ?
Hi,
I am using a struct and saving ssid, password, bottoken, chatid to eeprom using setup webpage to input the parameters. I only can send a text message if an event occurs if i hard code the bottoken in. Has anyone been successful from saving to eeprom and pulling the info to send a text using Universaltelegrambot?
struct settings {
char ssid[32];
char password[32];
char BOTtoken[64];
char CHAT_ID[16];
} user_wifi = {};
//WiFi Stuff
const char* ssid = “your ssid”;
const char* password = “your password”;
const char* BOTtoken = “your bot token”;
const char* CHAT_ID = “your chat id”;
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot (BOTtoken, client);
void setup(){
Serial.begin(9600);
EEPROM.begin(sizeof(struct settings));
EEPROM.get(0, user_wifi);
WiFi.mode(WIFI_STA);
WiFi.begin(user_wifi.ssid, user_wifi.password);
Serial.print(“Connecting to WiFi”);
Serial.println();
Serial.println(“Connection”);
byte tries = 0;
while(WiFi.status() != WL_CONNECTED){
WiFi.softAPdisconnect(true);
delay(500);
if (tries++ >30) {
WiFi.mode(WIFI_AP);
WiFi.softAP(“Setup Portal”, “bigdaddy”);
break;
}
}
Serial.println(“NodeMCU IP Address: “);
Serial.println(WiFi.localIP());
server.on(“/”, handlePortal);
server.begin();
configTime(0,0, “pool.ntp.org”);
client.setInsecure();
Wifi connects ok. i verified eeprom data is correct. Am i missing something.
Thank You,
Dan
Hi Sarah
How many ESP8266 I can add on the same telegram phone number?
To control as this project
Did something happen to the telegram API recently?
I had been using this bot for home automation tasks for a few years, and overnight it is now no longer working…
Hi.
Do you have more information about your issue?
Regards,
Sara
Hi Sara,
Yesterday, the ESP32 loaded with the above tutorial code (modified to suit my tasks) just stopped registering when new messages appeared in the telegram chat. I had not changed any settings on telegram or with the ESP32 code at all prior to this occurring.
I have since been trying to get it working again. I have tried again using:
– Latest version of UniversalTelegramBot library from github
– Tried using different versions of ArduinoJson library (latest version, and also tried using the 16.15.2 version used in this tutorial)
– I’ve confirmed the bot token / chatid has not changed and is correct
– Tried it on different esp32 dev chips – all show the same behavior
– I even tried using a different library – CTBot instead here: https://github.com/shurillu/CTBot/blob/master/examples/lightBot/lightBot.ino – and this didn’t work either – wasn’t connecting to telegram properly
– Tried to create a new bot, but after creating it, I receive no response at all when sending /start or /getid as I would expect (again, maybe points to an api / telegram bot problem?)
Interestingly, I am experimenting with using the telepot python library on a raspberrypi, and this bot is functioning normally (on the same chat as original)…..
Back to the esp32 / this issue: My code complies, i see the wifi connects correctly in the serial monitor – but I am apparently getting no response from the bot.getUpdates call – so the esp32 is never getting the new messages.
Does this telegram bot still work for you on your end? Are you able to create a new bot and have it respond when asking for /getid ?
Many thanks in advance for any help,
Brin
Just coming back to comment that I managed to get this working again by updating to the latest Arduino IDE…
On startup, it has a button to update all libraries, which I did. Not sure if this was the issue, or something to do with IDE itself, or something changing on the telegram API side – but in any case it’s working!
Could you pls tell what version of all software you are using. Such as Arudino Version, telegrambot version and ArudinoJson Version.. I have similar problems that the ESP32 run smoothly for 2-3 minutes and receive any message. But after then the system halts. If reset the ESP then the system works again.. What Might the problem
Here i am using ESP32 DEVKITV1
Arduino IDE 2.3.2
UniversalTelegramBot 1.3.0
ArudinoJson 6.15.2
HI!
I’ve used this code in some other project and I get the Telegram bot working, but once i send it the ‘/start’ command, it retrieves the message, displays it, and then loops displaying the message, both in the serial console and telegram chat.
It looks like it reads the same message time and time again.
Am missing a line where once it retrieves the message, it marks it as old message or something?
any pointers?
Thank you.
And thanks a lot for your tutorials, they are awesome and resourceful!
Hi! I just nailed the problem!!!
There’s a line that reads:
“numNewMessages = bot.getUpdates(bot.last_message_received + 1);”
and it’s written twice in the message checking code. I commented the second one thinking it had been my mistake.
I uncommented it, and it now works as intended.
Thanks again for your great tutorials.
Good afternoon !!!
I’m developing an amateur project for my garden, it already has 26 commands that will help me control my garden, but I came across a curious problem, as I said it already has 26 commands, when I create the twenty-seventh one and go to Telegram and I send the command “/start” Telegram returns the NULL message, when I delete the twenty-seventh command it works again, Telegram limits it to 26 commands? Detail!!!! I create a new command and delete any other command, it’s the same. I’ve already looked for any syntax errors, does anyone know the reason for the limitation????? THANKS !!!!!!
Hi.
Unfortunately, I’m not familiar with that issue.
Maybe it’s better to check their API to see if there is some sort of limitation.
Regards,
Sara
Thank you, it works on esp 01 relay just change the pin to 0
While I was writing code, I founf ” clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT);” doesnt work with Static IP. Can you please check if its the same or I am making some error.
Connecting to API api.telegram.org
Connection to api.telegram.org failed.
After commenting below all works fine.
/*
#ifdef STATIC_IP
WiFi.config(ip, gateway, subnet);
#endif
*/
Hello. I use ISP8266, in which the LED is turned on by the led-off command and vice versa. Actually, are there any options for the LED to turn on following the correct command, that is, led-on and so on?
Hi guys, great tutorial! I’m curious to know is there any limit to how many telegram commands the esp32 can handle? Thanks!
Hi.
I don’t think there is a limit on the ESP32. It will depend on how much space the program will need.
Check the Telegram Bot documentation because the bot can have a limit of commands, but I’m not sure of that.
Regards,
Sara
Bom dia lindona !!!!
Eu passei por esse problema com limites de comando no bot Telegram, de tanto pesquisar achei a solução nesse link: limits.tginfo.me/pt-BR, acredito que vá ajudar muita gente. Belo trabalho feito por você e o nosso amado Rui. Nós temos que respeitar alguns limites no numero de caracteres do comando e também respeitar o numero de caracteres na descrição do comando.
Obrigada pela partilha.
Regards,
Sara
Hello, this project works well for me, I use it to activate and deactivate a relay that activates a lamp.
But I have a problem, I have the bot added to a family Telegram group, so that all the members of the group can activate the relay, and until a month ago it worked for me, but now it works for all the members of the group when we try to activate the relay It tells us: “unauthorized user”
Telegram message menu buttons wifi thermostat esp8266
t.me/Luberth_Dijkman
I’ve tried to make this project, but I’m struggling some difficulties.
After uploading the sketch I see the following in the serial port:
Connecting to WiFi..
10.0.0.14
When I start the bot with /start command I don’t get the welcome response, so my guess is that the esp32 is connencted only to my router, and not to the web, and I have to configure the router and do some port-forwarding or something similar.
Am I right? If so, what are the right definitions/values that I have to use?
Hi.
You don’t need to do any port forwarding.
Maybe something is wrong with the configuration of your bot…
Check the UUID and API key.
Regards,
Sara
Thank you for your reply.
I’ve figured out that port forwarding is really not necessary, since I tried later on to download some html content from the web and display it in the serial port (I did it with this excellent guide – https://randomnerdtutorials.com/esp32-http-get-post-arduino/).
Then I tried to use another telegram library, from an article on a different site, and it worked, so the bot’s configuration, uuid and api key are all good.
Can you suggest how to debug the sketch further on?
hi which library u used for telegram
Hi
After connecting my esp8266 to wifi,
should it be within the wifi range to receive the messages ?
Hi.
No. In this project, it doesn’t need to be on the same network.
Regards.
Rui
Dear Sara and Rui:
Thank you very much for your post and all the good work.
I am having problems reproducing the Telegram example. I followed all the steps but I do not receive any messages. I am using an ESP01 but as far as I know it should work. The Serial monitor says ‘Connecting to WiFi..’ and gives me the IP. And nothing else.
I checked the Telegram token and it is correct. I suppose the ID is also correct but anyway it doesn’t tell me it is not authorized. Telegram server receives the commands but does not dispatch them.
I suppose there is something else I have to do with Telegram but I’m blocked. Can you suggest anything to try?
Thank you very much again.
Rafael Caballos
I met the same problem when using XIAO esp32c3. can anyone help? It seems the library problem.
Hi i got xiao esp32c3 connected to wifi, but didnt get any response. and i make sure all IDs correct. can help me check which parts wrong?
I “built” a small circuit that drives a transistor. Those who are familiar with electronics will surely know the banality of the project. I relied on this sketch with an esp8266 to send a reset command to my homelab server in case of an unresolvable crash via VPN. Result: I left for vacation on September 2nd. On September 3rd, the day after, I can no longer access the server… and I say…”thank goodness I built the esp8266 to reset it”. I send the telegram message to the esp8266. No response. (Very good. Always better!) I send my brother home who informs me that the server, with a sequence of LEDs, signals a motherboard failure. I make some assumptions and try to disconnect the reset cable connected to the esp8266. Voilà! The esp8266 has not responded via telegram since then, but takes care to keep the relay closed for no reason. I reserve the right to comment again after diagnosis when I return from vacation, but given the banality of the circuit I struggle to accuse a hardware problem. On the contrary, a super bug in the library seems very likely.
Where is my comment of yesterday?
Hi.
It was approved today.
Regards,
Sara