Why should you read this?

You have been playing with Node RED for a while, installing nodes, connecting IoT products, your TV, home made sensors, lights? Want to have a telegram interface for your connected things?

In this article, I’m going to try to reproduce the path I take whenever I create a new bot running on my raspberry pi at home to control my lights, tv, query sensors and interact with other “connected” things.

In order to keep it as short as possible, I am going to assume that you have already installed at least once Node RED, installed custom nodes and wrote basic javascript functions to access and act upon data.

If you want to follow along, you would need at least Node RED v0.17, a telegram client on your phone or computer and a google account.

The technical stuff

Architecture

Click the image for more
  1. Telegram Client (mobile or desktop Telegram app) sends message to server
  2. In Node-RED import a Telegram Receiver. This node polls (asks on an interval) the Telegram server for messages. If message is received, see next steps below
  3. Telegram message is passed to your Node-RED flow for processing. If you pass it to a debug node you can see in payload properties like chatId and content. In originalMessage you can see even more info, like user name etc. Using a function node, you can save any data you need from the telegram message to be passed further in the flow. You can add a new property to the msg object, call it telegram and also make it have it’s own properties.
  4. Import a Telegram Sender node and pass to it’s input a specific payload format. Using a function node you can create the message by adding properties to the msg.payload. You need to pass the chatId, type and content.
  5. The message is sent to Telegram server
  6. User gets the message in the client app.

The flow described in the steps above starts with a message from the user. However, the flow can also start from step 4, if you want to send a message from your Node-RED flow to your Telegram app, without user’s input. For example, you may have a PIR sensor and you want to send a message to Telegram, whenever the PIR is sensing motion. (You may want to restrict messages to a certain interval, so you won’t get messages every 1 second - depending on how you configured your PIR sensor)

For the PIR sensor example, you must send at least one message from Telegram while implementing the flow, and save the chatId somewhere. If you need only one user to chat with the bot, you could just hardcode the chatId in the message to Telegram. For example in a function node you can create a message like below and pass it to Telegram Sender input:

Below is what your Telegram Message builder function node could look like:

msg.payload = {
	chatId:"123456789", //your chatId
	type:"message",
	content: "PIR detected motion"
};
return msg;

Telegram

First, install Telegram on your device (smartphone or computer).

Use the device you installed Telegram on and browse Bot Father. This page gives you a link to start chatting with Bot Father in your Telegram app. It is a Telegram bot that you can use to create and manage your own bots.

Click the image for more

Once you have created your new bot using BotFather, you will see a message in your chat with BotFather. It gives you a link to start chat with the bot and an access token for the Telegram HTTP API. Copy the token and save it in a note or text document. You will use this to configure the Telegram bot for your Telegram Receiver and Telegram Sender nodes in Node-RED. Click the link provided to add your bot to your Telegram chats list.

Install the telegrambot node in Node-RED.

Your conversation with the bot will be private (like chatting with only one other person). I didn’t look yet into adding a bot to a group. However, if you want to allow other users to chat with the bot, give them the link you got from BotFather and, connecting the second output of the Telegram Receiver to a debug node, you can see their chatIds. Add those in the list of allowed chatIds (in the bot configuration in Node-RED).

Below is what a message from a Telegram chat looks like:

{"payload":{"chatId":"your_chatId","type":"message","content":"Hi F. This is a message from Node RED.","options":{"chat_id":"your_chatId","text":"Hi F. This is a message from Node RED."},"sentMessageId":34},"originalMessage":{"message_id":33,"from":{"id":"your_chatId","is_bot":false,"first_name":"F","last_name":"B","language_code":"en-US"},"chat":{"id":"your_chatId","first_name":"F","last_name":"B","type":"private"},"date":1521964778,"text":"hi"},"_msgid":"7c0275e5.89c40n","telegram":{"payload":{"chatId":"your_chatId","messageId":33,"type":"message","content":"hi"},"data":{"message_id":33,"from":{"id":"your_chatId","is_bot":false,"first_name":"F","last_name":"B","language_code":"en-US"},"chat":{"id":"your_chatId","first_name":"F","last_name":"B","type":"private"},"date":1521964778,"text":"hi"}}}

Allow Telegram messages from only specific chatId

Telegram receiver node has two outputs: first is for authorized users, second for anonymous. If you only want to respond to specific chats, add the chatId for each one in the Node-RED Telegram Bot configuration (comma separated).

Node RED

Click the image for more

PIR simulator flow

Import the json below to create a flow that simulates a PIR sensor using an inject node, and sends messages to Telegram on a 10 seconds interval.

[{"id":"724850de.33c8a","type":"tab","label":"Flow 3"},{"id":"fd6092c6.787bd","type":"inject","z":"724850de.33c8a","name":"PIR simulator ","topic":"","payload":"PIR motion detected","payloadType":"str","repeat":"10","crontab":"","once":true,"x":107,"y":121,"wires":[["cebad29d.a8396"]]},{"id":"cebad29d.a8396","type":"function","z":"724850de.33c8a","name":"Telegram Message Builder","func":"var content = msg.payload;\nmsg.payload = {\n    chatId:'your_chatId',\n    type: \"message\",\n    content:content\n};\nreturn msg;","outputs":1,"noerr":0,"x":380.5,"y":128,"wires":[["f9afe5de.f94398"]]},{"id":"f9afe5de.f94398","type":"telegram sender","z":"724850de.33c8a","name":"","bot":"80782252.33e6d","x":671,"y":124,"wires":[[]]},{"id":"80782252.33e6d","type":"telegram bot","z":"","botname":"HomeAssistantBlogBot","usernames":"","chatids":""}]

Respond to Telegram message with text

Import json below in Node-RED to create a flow that receives a message from Telegram and sends back a text response.

[{"id":"3edf956e.0a4d9a","type":"tab","label":"Flow 1"},{"id":"d40462c2.16f4f","type":"telegram receiver","z":"3edf956e.0a4d9a","name":"","bot":"80782252.33e6d","saveDataDir":"","x":137,"y":130,"wires":[["1581efb1.f2a2a"],["1581efb1.f2a2a"]]},{"id":"a3b6e39b.a79cd","type":"function","z":"3edf956e.0a4d9a","name":"BuildTelegramResponse","func":"var userFirstName = msg.telegram.data.from.first_name;\n\nmsg.payload = {};\nmsg.payload.chatId = msg.telegram.payload.chatId;\nmsg.payload.type = \"message\";\nmsg.payload.content = `Hi ${userFirstName}. This is a message from Node RED.`;\n\nreturn msg;","outputs":1,"noerr":0,"x":258.5,"y":229,"wires":[["954e7368.f52dd"]]},{"id":"954e7368.f52dd","type":"telegram sender","z":"3edf956e.0a4d9a","name":"","bot":"80782252.33e6d","x":499,"y":227,"wires":[["bacea26d.6cbd1"]]},{"id":"bacea26d.6cbd1","type":"debug","z":"3edf956e.0a4d9a","name":"","active":true,"console":"false","complete":"true","x":683,"y":228,"wires":[]},{"id":"1581efb1.f2a2a","type":"function","z":"3edf956e.0a4d9a","name":"TelegramData","func":"// this function is appending data from telegram\n// to the msg object so it doesn't get lost when the message\n// is flowing trough other nodes\nmsg.telegram = {};\nmsg.telegram.payload = msg.payload; // basic data, like chatId, msg text, msg type\nmsg.telegram.data = msg.originalMessage; // more info, like user name, chat info etc\n\nreturn msg;","outputs":1,"noerr":0,"x":388.5,"y":132,"wires":[["1d92007d.c7bd4","a3b6e39b.a79cd"]]},{"id":"1d92007d.c7bd4","type":"debug","z":"3edf956e.0a4d9a","name":"","active":true,"console":"false","complete":"true","x":594.5,"y":133,"wires":[]},{"id":"80782252.33e6d","type":"telegram bot","z":"","botname":"HomeAssistantBlogBot","usernames":"","chatids":""}]

Conclusion

Node-RED is a great tool for connecting software components like your code and all kinds of services (APIs): Azure (storage and cognitive services), AWS, IBM, IFTTT and others. Just go to Manage palette in Node-RED menu and see how many possibilities are at your hand. Have fun creating your own software tools that are now able to interact with real world objects.