Guide no. 57
You create the bot with BotFather, the ESP32 reads the commands and replies: temperature and LED from anywhere, without touching the router.
By Ada Intelisano · informaticait.it technical team
- You create the bot with @BotFather; keep the token secret.
- The board asks for messages every second: no ports to open.
- The sketch only answers your chat number.
- Libraries: UniversalTelegramBot, ArduinoJson 6, Adafruit BME280.
Send /status to your bot on Telegram and it replies with the temperature at home; send /led_on and a light turns on. It works from anywhere, even away from home, without opening ports on the router: it is the board that goes and asks Telegram for messages.
1Create the bot
- On Telegram search for @BotFather (the one with the blue check mark) and send it
/newbot. - Choose a name and a username that ends in “bot”.
- BotFather gives you the token, a line like
110201543:AAHdqTcvCH1v…. Copy it. - With
/setcommandsyou can give BotFather the list of commands: they will show up as suggestions when you type “/”.
- The token is like your house key: whoever has it controls the bot. Do not publish it, do not send it in a chat, do not leave it in a sketch you share.
2How it works
The phone sends the message to the Telegram servers. Every second the board asks “any new messages?” (this is called polling); if there are, it reads them, runs the command and replies. Everything goes over HTTPS, which is why the sketch contains the Telegram certificate.
3Find your chat number
Anyone can find a bot by searching for its name and write to it. That is why the sketch
only obeys one chat, yours. To find its number: send any message to your bot, then open in the browser
https://api.telegram.org/botTOKEN/getUpdates (with your token in place of TOKEN). In the response look for "chat":{"id"::
the number that follows is the one to put in MY_CHAT.
4Connect the sensor and upload
The sensor is connected as in guide no. 56. Install the UniversalTelegramBot (Brian Lough), ArduinoJson (version 6) and Adafruit BME280 libraries. Write your network, password, token and chat number in the first lines.
// Telegram bot: turn the LED on and off and ask for the temperature from your phone. It only answers your chat. #include <WiFi.h> #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> #include <Adafruit_BME280.h> const char* NETWORK = "your-network-name"; const char* PASSWORD = "your-network-password"; #define TOKEN "123456789:the-token-BotFather-gave-you" // secret: never publish it const String MY_CHAT = "123456789"; // your chat number (step 3) const int LED = 2; WiFiClientSecure client; UniversalTelegramBot bot(TOKEN, client); Adafruit_BME280 bme; unsigned long lastCheck = 0; void reply(int count) { for (int i = 0; i < count; i++) { String chat = bot.messages[i].chat_id; String text = bot.messages[i].text; if (chat != MY_CHAT) { // a stranger: do not obey bot.sendMessage(chat, "You are not authorized.", ""); continue; } if (text == "/led_on") { digitalWrite(LED, HIGH); bot.sendMessage(chat, "LED on", ""); } else if (text == "/led_off") { digitalWrite(LED, LOW); bot.sendMessage(chat, "LED off", ""); } else if (text == "/status") { String r = "Temperature: " + String(bme.readTemperature(), 1) + " °C\n"; r += "Humidity: " + String(bme.readHumidity(), 0) + " %\n"; r += "LED: " + String(digitalRead(LED) ? "on" : "off"); bot.sendMessage(chat, r, ""); } else { bot.sendMessage(chat, "Commands: /led_on, /led_off, /status", ""); } } } void setup() { Serial.begin(115200); pinMode(LED, OUTPUT); if (!bme.begin(0x77)) Serial.println("BME280 not found: check the wires"); WiFi.mode(WIFI_STA); WiFi.begin(NETWORK, PASSWORD); client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // the certificate to talk to Telegram securely while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } configTime(0, 0, "pool.ntp.org"); // the exact time, as in the library example Serial.println("\nConnected. Write to your bot."); } void loop() { if (millis() - lastCheck > 1000) { // one check per second, as in the library example int newCount = bot.getUpdates(bot.last_message_received + 1); while (newCount) { reply(newCount); newCount = bot.getUpdates(bot.last_message_received + 1); } lastCheck = millis(); } }
5Try it
- It never replies: did you copy the whole token, with no spaces? Is the board connected to the network (check the Serial Monitor)?
- It replies “You are not authorized” to you too: the number in MY_CHAT is not the right one (repeat step 3).
- Compile errors with ArduinoJson: you have version 7; the bot library is written for version 6.
6Two things to know
- Telegram asks you not to send more than one message per second in the same chat: no loops that fire off messages in bursts.
- A bot receives messages either by polling or through a webhook, not both: if one day you set a webhook, this sketch stops receiving.
7Challenge yourself
- An alarm: if the temperature goes above 30 °C the bot writes to you on its own (once, not at every reading).
- Control the relay from guide no. 43 instead of the LED.
- you create a bot with BotFather and control it with a secret token;
- the board goes and asks for messages (polling), so there is no need to open ports on the router;
- a bot is public: the sketch must only answer your chat.
Useful products
Other guides
- Resistor colour code and tolerances
- N-channel and P-channel MOSFETs
- Bipolar transistor (BJT) or MOSFET?
- Relays: how to drive them and how much current they draw
- THT and SMD/SMT components
- XIAO board pinouts
- LEDs: forward voltage and series resistor
- The multimeter: measuring voltage and current
- Wemos D1 mini: first steps
- MOSFET module with Arduino and ESP32
- Relay module with Arduino and ESP32
- 3D printing filaments: PLA, PETG and fibre-filled versions
- Analog and digital: the differences
- ADS1115: 16-bit converter with Arduino and ESP32
- From bits to real values: converting sensor readings
- DS3231 RTC clock with Arduino and ESP32
- Linear or switching regulator: which one to choose
- Step-down, step-up and buck-boost: choosing the right module
- Voltage divider: reading voltages higher than 5 V or 3.3 V
- Pull-up, pull-down and bounce: wiring a button properly
- 3.3 V and 5 V logic levels: getting an ESP32 and an Arduino to talk
- The I²C bus: addresses, pull-ups and the scanner
- Lithium batteries: voltages, charging and protection
- ESP32 power consumption and deep sleep: how long the battery lasts
- Temperature sensors compared
- ESP32: which pins to use and which to avoid
- Getting started with the ESP32 in Arduino IDE 2 and PlatformIO
- SSD1306 OLED display and 16×2 I²C LCD with Arduino and ESP32
- PIR motion sensor and HC-SR04 ultrasonic sensor
- Date and time from the Internet with the ESP32: NTP, Italian time zone and daylight saving time
- MicroSD data logger: saving measurements to CSV
- Solar-powered ESP32: panel, charger and the numbers for Italy
- Web server on the ESP32: control a relay from your phone
- Your first LED: wire it up and make it blink
- The button: let Arduino decide
- The potentiometer: turn a knob and read its value
- Soft light: adjusting the brightness of an LED
- The buzzer: playing notes and melodies
- The traffic light: three LEDs in sequence
- The thermometer: reading the temperature with the TMP36
- The servo motor: moving an arm with Arduino
- The night light: the photoresistor and your first decision
- The relay: switching on a light bulb with Arduino
- The LCD display: making Arduino write
- The electronic dice: your first complete project
- The RGB LED: every color from three lights
- The joystick: two-axis control with a shield
- The LED ring: twelve colors from a single pin
- The DC motor: driving it with a MOSFET
- Soil moisture: the plant that asks for water
- The stepper motor: turn exactly as far as you want
- The parking sensor: faster and faster beeps
- The 7-segment display: big, bright numbers
- Automatic watering: the plant that waters itself
- The keypad: a lock with a secret code
- Networked weather station: values and chart on your phone
- MQTT with the ESP32: the language of connected devices
- Updating the ESP32 over Wi-Fi (OTA)
- ESP-NOW: two ESP32 boards talking without a router
- WebSocket with the ESP32: the LED that follows the slider
- Readings on a Google sheet, with deep sleep
- WiFiManager: choose the Wi-Fi from your phone
- Bluetooth LE with the ESP32: the phone without a network
- The camera in your browser with the ESP32-S3
- A portable Bluetooth speaker you build yourself
- Bluetooth desktop speakers, 2 × 20 W
- Stereo MP3 player with two buttons
- The shelf that plays music: a Visaton exciter
- How to solder well
- How much does it draw? Current and power with the INA219
- Load-cell scale with the HX711
- CO2 traffic light: when to open the windows
- RFID card door opener
- GPS: track logger on microSD
- LoRa: how far does it go? A range test with two boards
- Battery weather sign with an e-paper display
- Web radio with an ESP32 and an I2S amplifier
- Getting started with the Raspberry Pi Pico 2 in MicroPython
- Your first amplifier: the LM386 and a speaker
- Talking Arduino: the DFR0760 speech synthesis module
- The spectrum of your music on an LED matrix
- Drawing with 64 LEDs: the 8×8 matrix with the MAX7219
- A real voltage: the 12-bit MCP4725 DAC
- The heartbeat on Arduino: an ECG with the AD8232