UniversalTelegramBot: control an ESP32 from a Telegram chat
Yes, with limits. You can use the UniversalTelegramBot library online in Mokxi with nothing to install, and the sketch runs in your browser. Part of it is not simulated, and the notes below say which. The example below, "ESP32 Telegram doorbell with a PIR sensor", runs on the ESP32 DevKit V1.
Built in on Mokxi: #include <UniversalTelegramBot.h> and it builds, with nothing to install. Free, and no account needed.
What UniversalTelegramBot does
UniversalTelegramBot, by Brian Lough, lets an ESP32 or ESP8266 act as a Telegram bot. You create the bot with BotFather in the Telegram app, paste the token it gives you into the sketch, and the board can then read the messages people send the bot and answer them: "/led_on" switches a relay, "/status" replies with a temperature.
There is no push from Telegram to the board. The sketch polls: every second or so it calls getUpdates() with the ID after the last message it handled, and the library fills bot.messages[] with what is new, each with its text, chat_id and sender’s name. Replies go back with sendMessage(), or with sendMessageWithReplyKeyboard() and sendMessageWithInlineKeyboard() for buttons. ArduinoJson does the parsing underneath.
In Mokxi the EchoBot example runs on an ESP32-C3. Telegram is a real service, so the calls only reach api.telegram.org with Real internet switched on in the Cloud panel (signed in); the gateway does the TLS and the free plan allows 10 requests a minute. With it off, each call returns false or 0 and the serial monitor says why once. Photo uploads by binary are not carried.
| Library Manager name | UniversalTelegramBot |
|---|---|
| Author | Brian Lough |
| Include | #include <UniversalTelegramBot.h> |
| Boards | ESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32, ESP8266 NodeMCU, Raspberry Pi Pico W, Arduino Uno R4 WiFi |
| In the simulator | Runs, with a gap the note below names. |
Install it
It builds on ESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32, ESP8266 NodeMCU, Raspberry Pi Pico W, Arduino Uno R4 WiFi.
In Mokxi it is built in: #include <UniversalTelegramBot.h> and the sketch compiles, with no download, no zip and no Library Manager.
On a real board, install "UniversalTelegramBot" by Brian Lough from the Arduino IDE’s Library Manager (Sketch, Include Library, Manage Libraries), or add UniversalTelegramBot to lib_deps in PlatformIO. Mokxi follows the calls of release 1.3.0, so a sketch written here builds there too.
What to know in the simulator: Telegram is real, so it needs real internet mode (the Cloud panel, signed in): each call then goes to api.telegram.org through Mokxi’s gateway, which does the TLS, and the Client given to the bot is not used. With real internet off, the default, every call returns false or 0 and the serial monitor says why once. The gateway’s caps apply (Free: 10 requests a minute, 100 a day), and binary uploads (sendPhotoByBinary, multipart) are not carried. On the ESP8266, whose code runs from 32 KB of instruction RAM here, the EchoBot fits with little to spare.
The calls you will use
In the order a sketch meets them.
UniversalTelegramBot bot(BOT_TOKEN, secured_client)
Creates the bot with the BotFather token and a WiFiClientSecure, which on a real board needs the Telegram root certificate set first.
bot.getUpdates(bot.last_message_received + 1)
Fetches messages newer than the last one handled and returns how many arrived. Loop on it until it returns 0.
bot.messages[i].text
The text of message i. Next to it are bot.messages[i].chat_id, the chat to reply to, and bot.messages[i].from_name.
for (int i = 0; i < n; i++) {
if (bot.messages[i].text == "/led_on") digitalWrite(LED, HIGH);
}bot.sendMessage(chat_id, "LED is on", "")
Sends a reply to a chat. The third argument is the parse mode: "" for plain text, "Markdown" or "HTML" for formatting.
bot.sendMessageWithReplyKeyboard(chat_id, "Choose", "", keyboardJson, true)
Replies and shows a custom keyboard of buttons, described as a JSON array of rows. The last argument resizes it to fit.
bot.sendChatAction(chat_id, "typing")
Shows "typing..." in the chat while the board reads a slow sensor or takes a photo.
bot.setMyCommands(commandsJson)
Sets the command list that Telegram suggests when the user types a slash, from a JSON array of command and description pairs.
Example: ESP32 Telegram doorbell with a PIR sensor
On the ESP32 DevKit V1. It runs in the browser exactly as printed.
/*
* ESP32 Telegram doorbell: press the button and the buzzer rings and your
* phone gets a Telegram message. A PIR sensor at the door sends another when
* someone moves there, at most once a minute.
*
* Button one side -> GPIO 4 (D4), other side -> GND (INPUT_PULLUP)
* Buzzer active buzzer, + -> GPIO 25 (D25), - -> GND
* PIR HC-SR501, VCC -> 5 V, OUT -> GPIO 27 (D27), GND -> GND
* (its output is 3.3 V, safe for the ESP32)
*
* Library: UniversalTelegramBot (Brian Lough), which needs ArduinoJson.
*
* Before uploading to a real board:
* 1. In Telegram, talk to @BotFather, send /newbot and copy the token it
* gives you into BOT_TOKEN.
* 2. Talk to @userinfobot to get your chat id, and put it in CHAT_ID.
* 3. Send your new bot any message once, so it is allowed to message you.
* 4. Put your WiFi name and password in SSID and PASSWORD.
*
* In Mokxi the buzzer and the Serial Monitor work as soon as you press Run.
* The message itself goes out only with Real internet switched on in the
* Cloud panel (signed in) and a real token; otherwise the Serial Monitor
* says why nothing was sent, and the doorbell still rings.
*/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
const char *SSID = "Mokxi-Lab";
const char *PASSWORD = "breadboard";
#define BOT_TOKEN "123456789:REPLACE_WITH_YOUR_BOT_TOKEN"
#define CHAT_ID "123456789"
const int BUTTON_PIN = 4;
const int BUZZER_PIN = 25;
const int PIR_PIN = 27;
const unsigned long MOTION_GAP_MS = 60000; // one motion message a minute at most
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
unsigned long lastMotionMessage = 0;
bool motionSentOnce = false;
int rings = 0;
void ring()
{
// ding ... dong: two beeps from an active buzzer
digitalWrite(BUZZER_PIN, HIGH);
delay(300);
digitalWrite(BUZZER_PIN, LOW);
delay(150);
digitalWrite(BUZZER_PIN, HIGH);
delay(500);
digitalWrite(BUZZER_PIN, LOW);
}
void notify(const String &text)
{
if (bot.sendMessage(CHAT_ID, text, "")) {
Serial.println("Telegram message sent");
} else {
Serial.println("Telegram message NOT sent");
}
}
void setup()
{
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(PIR_PIN, INPUT);
Serial.print("Connecting to ");
Serial.println(SSID);
WiFi.begin(SSID, PASSWORD);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // api.telegram.org's root certificate
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected, IP ");
Serial.println(WiFi.localIP());
Serial.println("Doorbell ready");
}
void loop()
{
if (digitalRead(BUTTON_PIN) == LOW) {
rings++;
Serial.print("Ding dong! Ring ");
Serial.println(rings);
ring();
notify("Ding dong! Someone is at the door.");
// wait for the button to be let go, so one press is one ring
while (digitalRead(BUTTON_PIN) == LOW) delay(10);
delay(50);
}
if (digitalRead(PIR_PIN) == HIGH) {
unsigned long now = millis();
if (!motionSentOnce || now - lastMotionMessage >= MOTION_GAP_MS) {
motionSentOnce = true;
lastMotionMessage = now;
Serial.println("Motion at the door");
notify("Motion at the front door.");
}
}
delay(20);
}Open it in the editor, wired and ready to run · ESP32 Telegram doorbell with a PIR sensor: the project page
Common errors and how to fix them
getUpdates() always returns 0, even after sending the bot a message
The secure connection fails before Telegram answers. On an ESP32 set secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); on an ESP8266 the certificate check needs the right time, so run configTime() before the first call, as the examples do. In Mokxi, switch on Real internet.
Strangers can switch my relay from their own Telegram account
Anyone who finds the bot’s name can message it. Compare bot.messages[i].chat_id with your own chat ID (ask a bot such as IDBot for it) and ignore every other chat before acting on a command.
The bot answers once, then the board hangs or resets
Polling every pass of loop() floods the connection and runs the board out of memory. Poll on a millis() timer, once a second on a board or every ten seconds in Mokxi, and keep message handling short.
Questions and answers
Does this need ArduinoJson?
Yes. The library parses Telegram’s replies with ArduinoJson, so it must be installed alongside. In Mokxi both are built in, so the include is all you need.
How do I find my chat ID?
Send any message to your bot, then print bot.messages[i].chat_id on Serial, or ask a helper bot such as IDBot. Keep that number in the sketch to check incoming messages against.
Try UniversalTelegramBot without installing anything
Open the example, change the sketch, and keep your version in a free account.