Projects / Control devices with a Telegram bot

Control devices with a Telegram bot

Intermediate2 hGuided buildReviewed

Build it step by step

0 of 8 done
  1. ESP32

    Create the bot

    Talk to BotFather and note the token.

  2. ESP32

    Find your chat ID

    Use a chat ID bot.

  3. ESP32

    Fill in the placeholders

    Add the Wi-Fi details, token and chat ID.

  4. ESP32ON

    Wire the relay and sensor

    Test them with a simple sketch first.

  5. ESP32

    Upload

    Send /status to the bot.

  6. ESP32ON

    Switch the relay

    Send /on and /off.

  7. ESP32

    Test the alert

    Warm the sensor above the limit.

  8. ESP32

    Test a stranger

    Message it from another account and see it refuse.

In short

How do you build a control devices with a Telegram bot?

Send /on, /off or /status to a Telegram bot and an ESP32 switches a relay and replies with readings. You need ESP32 DevKit V1, Relay Module 5V, DHT22 Sensor, Resistor 10 kΩ and 5 V 2 A USB adapter. It takes 8 steps and about 120 minutes.

Level
Intermediate
Time
About 120 min
Parts
5

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Relay module VCCESP32 VIN (5 V)Coil power
Relay module GNDESP32 GNDGround
Relay module INESP32 GPIO26Control signal
DHT22 VCCESP32 3V3Power
DHT22 GNDESP32 GNDGround
DHT22 dataESP32 GPIO27 and 10 kΩ resistor to 3V3Sensor signal
5 V adapterESP32 USBPower
Load on the relayA 12 V lamp or fan on COM and NO from a separate low-voltage supplySwitched load

Code

Create a bot by chatting to BotFather in Telegram, which gives you a token, and find your own chat ID with a bot such as userinfobot. The token acts like a password for the bot, so keep it out of shared code and repositories, and replace the placeholders in the sketch yourself. The sketch obeys only messages from your chat ID and tells everyone else they are not allowed. setInsecure() skips the certificate check, which is fine for a learning project but means the server is not verified; a better design loads Telegram's root certificate. Switch only low-voltage loads from the relay. Arduino IDE with the ESP32 boards package, board "ESP32 Dev Module".

Runs on a virtual ESP32 Dev Module in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

// Libraries: UniversalTelegramBot (Brian Lough), ArduinoJson, Adafruit DHT.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <DHT.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* BOT_TOKEN = "YOUR_BOT_TOKEN";        // from BotFather, never share or upload it
const char* MY_CHAT_ID = "YOUR_CHAT_ID";         // only this chat may control the device
const byte RELAY = 26;
const bool ACTIVE_LOW = true;
const float ALERT_C = 35.0;

WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
DHT dht(27, DHT22);
unsigned long lastPoll = 0, lastAlert = 0;
bool relayOn = false;

void setRelay(bool on) { relayOn = on; digitalWrite(RELAY, (on == ACTIVE_LOW) ? LOW : HIGH); }

void setup() {
  pinMode(RELAY, OUTPUT); setRelay(false);
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  client.setInsecure();   // skips certificate checking: simple for learning, but the server is not verified
}

void loop() {
  if (millis() - lastPoll > 2000) {
    lastPoll = millis();
    int n = bot.getUpdates(bot.last_message_received + 1);
    while (n) {
      for (int i = 0; i < n; i++) {
        String chat = bot.messages[i].chat_id;
        String text = bot.messages[i].text;
        if (chat != MY_CHAT_ID) { bot.sendMessage(chat, "Not allowed", ""); continue; }   // ignore strangers
        if (text == "/on") { setRelay(true); bot.sendMessage(chat, "Relay is ON", ""); }
        else if (text == "/off") { setRelay(false); bot.sendMessage(chat, "Relay is OFF", ""); }
        else if (text == "/status") {
          String s = "Relay " + String(relayOn ? "ON" : "OFF") + ", " + String(dht.readTemperature(), 1) + " C, " + String(dht.readHumidity(), 0) + " %";
          bot.sendMessage(chat, s, "");
        } else bot.sendMessage(chat, "Commands: /on /off /status", "");
      }
      n = bot.getUpdates(bot.last_message_received + 1);
    }
  }
  float t = dht.readTemperature();
  if (!isnan(t) && t > ALERT_C && millis() - lastAlert > 600000UL) {   // alert at most every 10 minutes
    lastAlert = millis();
    bot.sendMessage(MY_CHAT_ID, "Alert: temperature " + String(t, 1) + " C", "");
  }
}

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
/statusReply with relay state and readings
/on and /offRelay clicks and replies
Message from another chatNot allowed
Temperature above the limitOne alert in ten minutes

If it does not work

No replies

Check the token and Wi-Fi.

Always not allowed

Check the chat ID, which is a number.

Relay works backwards

Change ACTIVE_LOW.

Temperature NaN

Check the DHT22 pull-up and wiring.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the control devices with a Telegram bot?

ESP32 DevKit V1, Relay Module 5V, DHT22 Sensor, Resistor 10 kΩ and 5 V 2 A USB adapter.

How long does the control devices with a Telegram bot take to build?

About 120 minutes for a intermediate maker, in 8 steps.

How do I know the control devices with a Telegram bot works?

/status: Reply with relay state and readings. /on and /off: Relay clicks and replies. Message from another chat: Not allowed.

No replies: what should I check?

Check the token and Wi-Fi.

Always not allowed: what should I check?

Check the chat ID, which is a number.

Relay works backwards: what should I check?

Change ACTIVE_LOW.

Temperature NaN: what should I check?

Check the DHT22 pull-up and wiring.