Zbotic Logo Zbotic Logo
  • Home
  • Shop
  • Sale
  • 3D Print Service
  • PCB Service
  • B2B
  • Blogs
  • Contact Us
0 0

View Wishlist Add all to cart

0 0
0 Shopping Cart
Shopping cart (0)
Subtotal: ₹0.00

View cartCheckout

  • Shop
  • About Us
  • Contact Us
  • Reseller
  • Blogs
020 69134444
1800 209 0998
[email protected]
Help Desk
Facebook Twitter Instagram Linkedin YouTube
Zbotic Logo Zbotic Logo
0 0

View Wishlist Add all to cart

0 0
0 Shopping Cart
Shopping cart (0)
Subtotal: ₹0.00

View cartCheckout

All departments
  • 3D Print Service
  • 3D Printer
  • Batteries & Chargers
  • Development Boards
  • Drone Parts
  • EBike parts
  • Sensor Modules
  • Electronic Components
  • Electronic Modules
  • IoT and Wireless
  • Mechanical Parts and Workbench Tools
  • Motors & Drivers & Pumps & Actuators
  • DIY and Robot Kits
  • Show more
  • Home
  • Shop
  • Sale
  • 3D Print Service
  • PCB Service
  • B2B
  • Blogs
  • Contact Us
Return to previous page
Home IoT & Smart Home

Telegram Bot with ESP32: Remote Control via Messaging App

Telegram Bot with ESP32: Remote Control via Messaging App

March 11, 2026 /Posted byJayesh Jain / 0

Building a Telegram bot with ESP32 for remote control via a messaging app is one of the most practical and satisfying IoT projects you can complete in a weekend. Instead of building a custom mobile app or dealing with complex cloud dashboards, you get a secure, free, and globally accessible control interface right inside Telegram — an app most Indian smartphone users already have. In this tutorial, you will learn how to set up a Telegram bot, connect it to an ESP32, and use it to control relays, read sensor data, and even stream status updates, all from your phone.

Table of Contents

  1. Why Telegram for ESP32 Remote Control?
  2. Step 1: Creating Your Telegram Bot with BotFather
  3. Step 2: Hardware Setup and Required Components
  4. Step 3: Installing the Universal Telegram Bot Library
  5. Step 4: Writing the Firmware — Commands, Relays, and Sensors
  6. Step 5: Advanced Features — Keyboards, Alerts, and Groups
  7. Step 6: Security Considerations for Production Use
  8. Frequently Asked Questions
  9. Conclusion

Why Telegram for ESP32 Remote Control?

India has over 100 million active Telegram users, and the platform has one of the most developer-friendly bot APIs in the world. Unlike WhatsApp (which requires a business account and charges per message), Telegram bots are completely free, support unlimited messages, and work over both mobile data and Wi-Fi. For ESP32-based remote control systems, this makes Telegram an ideal choice for several reasons:

  • No port forwarding needed: The ESP32 polls Telegram’s servers (outbound HTTPS), so it works behind NAT, CGNAT (common with Indian ISPs like Jio and Airtel broadband), and even behind mobile data.
  • End-to-end SSL: All communication is encrypted by default. No custom SSL certificates needed on your ESP32.
  • Rich interface: Telegram supports custom keyboards, inline buttons, photos, and formatted text — far richer than SMS or simple HTTP endpoints.
  • Multi-user support: You can control your device from multiple phones, or create a group bot that multiple family members can use.
  • Free for life: No subscriptions, no tiers, no rate limit concerns for typical home automation use.

Step 1: Creating Your Telegram Bot with BotFather

Before writing a single line of ESP32 code, you need to register a bot with Telegram. The process takes about two minutes:

  1. Open Telegram and search for @BotFather (the official Telegram bot for creating bots).
  2. Send the command /newbot.
  3. BotFather will ask for a display name (e.g., “Home Controller”) and a username (must end in “bot”, e.g., “myhomecontrollerbot”).
  4. BotFather will reply with your bot’s HTTP API token — a long string like 1234567890:ABCDEF.... Save this securely; it is your bot’s password.
  5. Next, you need your personal chat ID. Search for @userinfobot on Telegram, send it any message, and it will reply with your numeric chat ID (e.g., 987654321).

You will embed both the token and your chat ID into the ESP32 firmware. The chat ID acts as an authorisation filter — the bot will only respond to commands coming from your specific account.

Step 2: Hardware Setup and Required Components

For this tutorial, we will build a system that:

  • Controls a relay (simulating a light or appliance) via Telegram commands
  • Reads temperature and humidity from a DHT11 sensor and reports it on demand
  • Sends an automatic alert when temperature exceeds a threshold

Components needed:

  • ESP32 development board (NodeMCU-32S or similar)
  • DHT11 or DHT22 temperature/humidity sensor
  • 1-channel 5V relay module
  • LED (for visual feedback during testing)
  • Jumper wires and breadboard
  • USB cable and computer for flashing

Wiring:

  • DHT11 DATA pin → ESP32 GPIO4, VCC → 3.3V, GND → GND
  • Relay IN pin → ESP32 GPIO26, VCC → 5V (from VIN if USB-powered), GND → GND
  • LED (with 220Ω resistor) → GPIO2, GND → GND
Ai Thinker NodeMCU-32S ESP32 Development Board

Ai Thinker NodeMCU-32S ESP32 Development Board – IPEX Version

A reliable ESP32 dev board with IPEX connector for optional external antenna — great for installations where the ESP32 is inside a metal enclosure or far from the router.

View on Zbotic

DHT11 Digital Relative Humidity and Temperature Sensor Module

DHT11 Digital Relative Humidity and Temperature Sensor Module

The DHT11 is the classic beginner-friendly sensor for temperature and humidity readings — easy to wire and supported by the widely-used DHT library for Arduino/ESP32.

View on Zbotic

Step 3: Installing the Universal Telegram Bot Library

The easiest way to use Telegram with ESP32 is via Brian Lough’s Universal Telegram Bot library, which abstracts the Telegram Bot API into simple C++ methods. Install it via the Arduino Library Manager:

  1. Open Arduino IDE → Sketch → Include Library → Manage Libraries
  2. Search for “Universal Telegram Bot” and install it (by Brian Lough)
  3. Also install ArduinoJson (version 6.x) which the Telegram library depends on
  4. Install DHT sensor library by Adafruit

If you are using ESP-IDF or PlatformIO, you can add the library as a dependency in your platformio.ini or use the ESP-IDF component manager. The library handles HTTPS by using the ESP32’s built-in SSL stack with Telegram’s root certificate — no additional certificate files needed.

Step 4: Writing the Firmware — Commands, Relays, and Sensors

Below is a complete, production-ready sketch. Read it carefully — comments explain every important section.

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <DHT.h>

// ----- Configuration -----
const char* WIFI_SSID     = "YourWiFiSSID";
const char* WIFI_PASSWORD = "YourWiFiPassword";
const char* BOT_TOKEN     = "1234567890:ABCDEF...";
const long  CHAT_ID       = 987654321LL; // Your Telegram chat ID

#define RELAY_PIN   26
#define DHT_PIN     4
#define DHT_TYPE    DHT11
#define TEMP_ALERT  35.0  // Alert if temperature > 35°C

// ----- Globals -----
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
DHT dht(DHT_PIN, DHT_TYPE);

bool relayState = false;
unsigned long lastBotCheck = 0;
const unsigned long BOT_INTERVAL = 1500; // Poll every 1.5 seconds
unsigned long lastTempCheck = 0;
bool alertSent = false;

// ----- Setup -----
void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
  dht.begin();

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
  Serial.println("nConnected: " + WiFi.localIP().toString());

  // Use Telegram's root CA (included in ESP32 core)
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT);

  bot.sendMessage(CHAT_ID, "ESP32 is online! Send /help for commands.", "");
}

// ----- Handle incoming messages -----
void handleMessages(int numMsg) {
  for (int i = 0; i < numMsg; i++) {
    String chatId = bot.messages[i].chat_id;
    if (chatId.toInt() != CHAT_ID) {
      bot.sendMessage(chatId, "Unauthorised access.", "");
      continue;
    }
    String text = bot.messages[i].text;
    if (text == "/on") {
      relayState = true;
      digitalWrite(RELAY_PIN, HIGH);
      bot.sendMessage(CHAT_ID, "Relay is ON", "");
    } else if (text == "/off") {
      relayState = false;
      digitalWrite(RELAY_PIN, LOW);
      bot.sendMessage(CHAT_ID, "Relay is OFF", "");
    } else if (text == "/status") {
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      String msg = "Relay: " + String(relayState ? "ON" : "OFF") +
                   "nTemperature: " + String(t, 1) + "°C" +
                   "nHumidity: " + String(h, 1) + "%";
      bot.sendMessage(CHAT_ID, msg, "");
    } else if (text == "/help") {
      bot.sendMessage(CHAT_ID,
        "/on - Turn relay ONn/off - Turn relay OFFn/status - Read sensor datan/help - Show this menu", "");
    }
  }
}

// ----- Loop -----
void loop() {
  unsigned long now = millis();
  if (now - lastBotCheck > BOT_INTERVAL) {
    lastBotCheck = now;
    int msgCount = bot.getUpdates(bot.last_message_received + 1);
    handleMessages(msgCount);
  }
  // Temperature alert every 60 seconds
  if (now - lastTempCheck > 60000) {
    lastTempCheck = now;
    float t = dht.readTemperature();
    if (t > TEMP_ALERT && !alertSent) {
      bot.sendMessage(CHAT_ID, "ALERT: Temperature " + String(t,1) + "°C exceeded threshold!", "");
      alertSent = true;
    } else if (t <= TEMP_ALERT) {
      alertSent = false; // Reset so alert fires again if it rises again
    }
  }
}

Flash this to your ESP32, open the Serial Monitor, and within a few seconds you should see “Connected” and receive a “ESP32 is online!” message on Telegram. Send /on and your relay will click. Send /status and you will get live temperature and humidity readings.

Step 5: Advanced Features — Keyboards, Alerts, and Groups

Custom Inline Keyboards: Instead of typing text commands, you can send a keyboard with buttons. Use bot.sendMessageWithInlineKeyboard() to send a JSON-formatted keyboard. For example, two buttons “ON” and “OFF” that send callback data. This makes the bot much more user-friendly on mobile.

Sending Photos: If you add an ESP32-CAM to your setup, you can send JPEG images directly to your Telegram chat using bot.sendPhoto(). This is perfect for a doorbell camera or a garden monitoring system — motion detected, photo sent instantly to your phone.

Group Bots: Add your bot to a Telegram group so multiple family members can control the same device. Use a whitelist of chat IDs (each person’s ID) instead of a single ID. The bot checks if the sender’s chat ID is in the whitelist before executing any command.

Scheduled Reports: Use millis()-based timers to send hourly or daily summary messages automatically. This is excellent for greenhouse monitoring, server room temperature tracking, or water tank level alerts.

2 x 18650 Lithium Battery Shield for ESP32

2 x 18650 Lithium Battery Shield for Arduino/ESP32/ESP8266

Power your Telegram-controlled ESP32 node from 18650 batteries with built-in charging and 5V/3.3V output — ideal for untethered installations.

View on Zbotic

Ai Thinker ESP32 CAM Development Board

Ai Thinker ESP32 CAM Development Board WiFi+Bluetooth with AF2569 Camera

Combine this ESP32-CAM with the Telegram bot to build a remote camera that sends photos on command or on motion detection — no cloud subscription needed.

View on Zbotic

Step 6: Security Considerations for Production Use

For a home hobby project, storing your Telegram token in plaintext firmware is acceptable. For any device deployed in a business or accessible to the public, follow these hardening steps:

  • Store credentials in NVS: Use the ESP32’s Non-Volatile Storage (NVS) to store the Wi-Fi password and bot token, provisioned via BLE during first setup. Never hardcode secrets in production firmware.
  • Whitelist chat IDs: Always verify the sender’s chat ID against a whitelist. Never process commands from unknown senders.
  • Rate limiting: Implement a per-sender command rate limit (e.g., max 10 commands per minute) to prevent flooding.
  • OTA updates: Use ESP32’s built-in OTA (Over-the-Air) update mechanism to push firmware patches without physical access. Sign your firmware images using Secure Boot.
  • Avoid relaying dangerous commands remotely: For safety-critical actuators (gas valves, high-voltage relays), add a confirmation step — the bot asks “Are you sure? Reply /confirm” before executing.

Frequently Asked Questions

Does the Telegram bot work when the ESP32 is on mobile data (hotspot)?

Yes, since the ESP32 initiates outbound HTTPS connections to Telegram’s servers, it works on any internet-connected network including mobile hotspots. There is no need for a static IP or port forwarding — this is one of the biggest advantages over raw TCP socket servers.

What is the polling delay and can it be reduced?

With getUpdates() polling every 1.5 seconds, command response latency is typically 1.5–3 seconds. You can reduce the polling interval to 500ms for faster response, but this uses more power and hits the Telegram API more frequently. For near-instantaneous response, you would need to set up a webhook on a public server — not feasible directly on ESP32 without port forwarding, but achievable via an MQTT bridge.

Can multiple ESPs be controlled from the same Telegram bot?

Yes. Each ESP32 can use the same bot token but respond to different commands. Alternatively, create separate bots for each device for cleaner separation. A more scalable approach is to use MQTT as a backbone and have a single Telegram-to-MQTT gateway that routes commands to many ESP32 nodes.

What happens if the internet goes down?

The ESP32 will keep retrying Wi-Fi connections and Telegram polls. Commands sent during the outage will be delivered once connectivity is restored (Telegram queues messages on its servers). For critical systems, always include a local fallback (physical button or local HTTP endpoint) in case internet is unavailable.

Conclusion

Building a Telegram bot with ESP32 for remote control via a messaging app is genuinely one of the most practical IoT projects for Indian hobbyists and professionals. It requires no cloud subscription, no custom app development, and no port forwarding — just a Telegram account, an ESP32, and a few sensors. The code is simple enough to understand in an afternoon yet powerful enough to form the backbone of a real home automation system. Start with the relay and DHT11 example above, then expand to cameras, door sensors, water tank monitors, and beyond.

Shop ESP32 Boards and Sensors at Zbotic

Tags: ESP32 messaging, ESP32 Remote Control, IoT home automation, Telegram API Arduino, Telegram Bot
Share Post
  • Facebook
  • Linkedin
  • Whatsapp
Firebase Realtime Database wit...
blog firebase realtime database with esp32 iot data storage 595519
blog home assistant integration esp32 sensor with esphome 595521
Home Assistant Integration: ES...

Related posts

Svg%3E
Read more

IoT Home Insurance Sensor Kit: Leak, Smoke, and Motion

April 1, 2026 0
Table of Contents IoT and Home Insurance Water Leak Detection Smoke and Fire Detection Motion and Intrusion Sensing Building the... Continue reading
Svg%3E
Read more

IoT Pet Tracker: GPS Collar with Geofencing Alerts

April 1, 2026 0
Table of Contents Introduction and Overview Hardware Components Required GPS Module Integration with ESP32 Cloud Platform Setup Real-Time Tracking Dashboard... Continue reading
Svg%3E
Read more

IoT Aquaponics Controller: Fish and Plant Automation

April 1, 2026 0
Table of Contents The Water Monitoring Challenge in India Sensor Technologies for Water Building the Sensor Node Data Transmission and... Continue reading
Svg%3E
Read more

IoT Composting Monitor: Temperature and Moisture Tracking

April 1, 2026 0
Table of Contents Why Temperature Monitoring Matters Sensor Selection Guide Hardware Assembly and Wiring Firmware Development Cloud Data Logging Alert... Continue reading
Svg%3E
Read more

IoT Beehive Monitor: Weight, Temperature, and Humidity

April 1, 2026 0
Table of Contents Why Monitor Beehives Weight Measurement System Temperature and Humidity Sensing Building the Monitor Data Analysis for Bee... Continue reading

Add comment Cancel reply

Your email address will not be published. Required fields are marked

Facebook Twitter Instagram Pinterest Linkedin Youtube

Get the latest deals and more.

Download on Google Play Download on the App Store

Call us: 020 69134444 / 1800 209 0998

Monday - Saturday 09:30 AM - 06:00 PM
For Technical Supports Email: [email protected]
For Sales / Enquiries Email: [email protected]

  • My Account

    • Cart

    • Wishlist

    • Checkout

    • My Orders

    • Track Order

    • My Account

  • Information

    • FAQs

    • Blogs

    • Career

    • About Us

    • Contact Us

    • Payment Options

  • Policies

    • Privacy Policy

    • Terms & Conditions

    • GST Input Tax Credit

    • Shipping Return Policy

    • E-Waste Collection Points

    • Our Sitemap

© Zbotic.in is registered trademark of Moxie Supply Pvt Ltd – All Rights Reserved
Login
Use Phone Number
Use Email Address
Not a member yet? Register Now
Reset Password
Use Phone Number
Use Email Address
Register
Already a member? Login Now