Node-RED

Node-RED Telegram Bot for MQTT Devices: Alerts, Status Queries and Remote Commands

Turn Telegram into a pocket control panel for your MQTT devices. This tutorial builds a Node-RED Telegram bot that forwards alerts, answers /status, switches a relay with /on and /off, and only listens to approved chat IDs.

Node-RED Telegram bot exchanging alerts and commands with MQTT devices through a cloud broker
Run this on your own MQTT brokerGet a private, managed MQTT broker on the Free plan and start from ready-made code samples.
Try it free Code samples No card required

Combining Node-RED and Telegram gives you a free, instant way to receive alerts from MQTT devices and to send them commands from your phone. In this tutorial you will create a Telegram bot, connect it to Node-RED, forward threshold alerts from an MQTT topic, answer a /status command with the latest reading, and switch a relay with /on and /off, while ignoring everyone who is not on your allow list.

Why Telegram Works Well for IoT Notifications

Email is fine for reports, but it is slow to notice and easy to filter away. Telegram bots are free to create, push notifications reach the phone quickly, and the Bot API is two-way: the same chat that receives an alert can reply with a command. For a home lab, a greenhouse, a small workshop or an on-call maintenance team, that is often exactly the right amount of tooling.

Node-RED is a good host for the bot because it already speaks MQTT natively. The bot never talks to your devices directly. It talks to Node-RED, and Node-RED publishes and subscribes on the broker, which keeps your devices simple and unaware of Telegram entirely.

What You Need

  1. A running Node-RED instance (local, Raspberry Pi or Docker).
  2. A Telegram account.
  3. An MQTT broker. This guide uses ConnectMQ; for testing we use the public MQTT test broker at broker.connectmq.com with the prefix connectmq/demo/tg42x9. Replace tg42x9 with your own random string.
  4. The node-red-contrib-telegrambot package.

Because anything under the public demo area can be read by other users, do not publish real commands for real equipment there. Move to private credentials before you connect anything that matters.

Step 1: Create the Bot with BotFather

In Telegram, open a chat with @BotFather and send /newbot. Choose a display name and a username ending in bot. BotFather replies with an API token that looks like 123456789:AA.... Treat it like a password: anyone with the token can control the bot.

Optionally send /setcommands to BotFather and register the command list so Telegram shows suggestions:

status - Show the latest sensor values
on - Switch the relay on
off - Switch the relay off

Step 2: Install and Configure the Telegram Nodes

Install node-red-contrib-telegrambot from Menu → Manage palette. It adds three nodes we will use:

Node Purpose
Telegram receiver Emits every message sent to the bot
Telegram command Emits only when a specific command such as /status is received
Telegram sender Sends a message, photo or other content to a chat

Create a bot configuration node, paste the token, and use the default polling mode. Polling works behind NAT and home routers because Node-RED fetches updates from Telegram rather than waiting for incoming connections. The configuration node also lets you restrict the bot to specific usernames or chat IDs. Use that, and add your own check in the flow as a second layer.

Find your chat ID

Wire a Telegram receiver node to a debug node set to show the complete message, deploy, and send any text to your bot. The debug sidebar shows msg.payload.chatId. Note it down; you will use it for the allow list and for sending unsolicited alerts.

Step 3: Forward MQTT Alerts to Telegram

The sender node expects msg.payload to be an object with a chat ID, a type and the content. Subscribe to an alert topic with an mqtt in node (connectmq/demo/tg42x9/alerts/#) and convert each message with a function node:

const CHAT_ID = 123456789;   // your chat ID from the debug sidebar

let text = msg.payload;
if (typeof text === "object") text = JSON.stringify(text);

// Topic like connectmq/demo/tg42x9/alerts/freezer -> "freezer"
const source = msg.topic.split("/").pop();

msg.payload = {
    chatId: CHAT_ID,
    type: "message",
    content: `Alert from ${source}: ${text}`
};
return msg;

Wire it to a Telegram sender node. If your alerts come from raw sensor values rather than a dedicated alerts topic, put the hysteresis and cooldown logic from our Node-RED email alert tutorial in front of this function so the bot does not message you on every reading.

Step 4: Answer /status with the Latest Values

Keep the last value of each sensor in flow context. Subscribe to connectmq/demo/tg42x9/sensors/# and store each reading:

const name = msg.topic.split("/").pop();
const latest = flow.get("latest") || {};
latest[name] = { value: msg.payload, at: new Date().toISOString() };
flow.set("latest", latest);
return null;

Then add a Telegram command node with the command /status, followed by this function and a Telegram sender:

const ALLOWED = [123456789];   // allowed chat IDs

const chatId = msg.payload.chatId;
if (!ALLOWED.includes(chatId)) {
    node.warn("Ignored /status from chat " + chatId);
    return null;
}

const latest = flow.get("latest") || {};
const names = Object.keys(latest);

let text;
if (names.length === 0) {
    text = "No sensor data received yet.";
} else {
    text = names
        .map(n => `${n}: ${JSON.stringify(latest[n].value)} (at ${latest[n].at.substring(11, 19)} UTC)`)
        .join("\n");
}

msg.payload = { chatId, type: "message", content: text };
return msg;

Including the time of the last reading matters. A value that looks normal but is two hours old is usually a sign that the device is offline.

Step 5: Send Commands to MQTT Devices

Add Telegram command nodes for /on and /off. Both feed one function node that checks the sender and builds two messages: a command for the device and a confirmation for the chat.

const ALLOWED = [123456789];
const chatId = msg.payload.chatId;
if (!ALLOWED.includes(chatId)) return [null, null];

// The command node's configured command tells us which one fired
const text = (msg.payload.content || "").toString().toLowerCase();
const state = text.includes("off") ? "OFF" : "ON";

const mqttMsg = {
    topic: "connectmq/demo/tg42x9/relay1/set",
    payload: JSON.stringify({ state, by: "telegram", chatId }),
    qos: 1,
    retain: false
};

const reply = {
    payload: { chatId, type: "message", content: `Relay 1 command sent: ${state}` }
};

return [mqttMsg, reply];

Set the function to two outputs, wire the first to an mqtt out node and the second to a Telegram sender. If the content field does not contain the command text in your version of the node, use two separate function nodes, one per command, with the state hard-coded. That is less clever and more robust.

A better reply waits for the device to confirm. Have the device publish its actual state to connectmq/demo/tg42x9/relay1/state and forward that topic to Telegram with the alert function from Step 3. You then know the relay switched, not just that a command left Node-RED. Our Node-RED HTTP to MQTT guide uses the same command-and-confirm pattern for HTTP callers.

Test the Whole Loop

# Watch the command topic
mosquitto_sub -h broker.connectmq.com -p 1883 -i watch-tg42x9 -v -t "connectmq/demo/tg42x9/#"

# Simulate a sensor and an alert
mosquitto_pub -h broker.connectmq.com -p 1883 -i sim-tg42x9 -t "connectmq/demo/tg42x9/sensors/freezer" -m "-17.5"
mosquitto_pub -h broker.connectmq.com -p 1883 -i sim-tg42x9 -t "connectmq/demo/tg42x9/alerts/freezer" -m "Door open for 5 minutes"

Then send /status, /on and /off to the bot and watch the command messages appear in the subscriber terminal.

Security Checklist for a Node-RED Telegram Bot

A bot that can switch equipment is a remote control, so treat it like one:

  1. Allow list chat IDs in the bot config node and again in every function that acts on a command.
  2. Keep the token secret. It lives in the configuration node credentials, not in flow JSON you export or commit.
  3. Use private ConnectMQ credentials and TLS (port 8883) for anything beyond a demo. On the public broker, anyone can read and publish under any demo topic.
  4. Make commands idempotent. Sending /on twice should leave the relay on, not toggle it.
  5. Log every command with chat ID and time, for example to a database or a retained audit topic.
  6. Protect the editor. Enable adminAuth in settings.js so nobody can change the flow and the allow list.

Troubleshooting

Symptom Fix
Bot does not respond at all Only one process can poll a bot token; stop other Node-RED instances or scripts using the same token
Error 401 Unauthorized Token copied incorrectly or revoked via BotFather
Command node never fires in a group Group privacy mode is on; address the bot as /status@yourbot or disable privacy with BotFather
Alerts arrive minutes late Check the MQTT connection status on the mqtt in node and use QoS 1
Relay switches twice Two command nodes wired to the same function, or a retained command on the set topic

Run Your Node-RED Telegram Bot on ConnectMQ

Once the bot works on the demo broker, switch the Node-RED broker config to a private ConnectMQ broker: port 8883 with TLS, and the username, password and client ID generated in the portal. The portal's in-browser MQTT client and live topic explorer are handy for watching the command and state topics while you test from your phone. Sign up for the free Serverless plan at app.connectmq.com with no credit card. If you are still deciding where your broker should live, our overview of the MQTT broker in the cloud explains the options, and the Node-RED MQTT tutorial covers the rest of the Node-RED basics.

Frequently Asked Questions

Which Node-RED package should I use for Telegram?

node-red-contrib-telegrambot is the most widely used option. It provides receiver, command and sender nodes, supports polling and webhook modes, and can restrict access to known users or chats.

Do I need a public IP or port forwarding?

No. In polling mode Node-RED makes outbound requests to Telegram, and MQTT is also an outbound connection to the broker, so both work behind a home router.

Can several people use the same bot?

Yes. Add each person's chat ID to the allow list, or add the bot to a group and use the group chat ID for alerts.

Is it safe to control devices from Telegram?

It can be, if you restrict chat IDs, keep the token secret, use private broker credentials with TLS and log every command. Avoid it for safety-critical equipment that needs local interlocks.

Related articles

Node-RED OPC UA Client to MQTT with ISA-95 Topics

Use node-red-contrib-opcua to subscribe to OPC UA variables on a PLC or simulation server, map node IDs to ISA-95 style MQTT topics, and publish values with quality and timestamps.

9 min read

All articles →

Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.