The project I’m going to describe today it’s a sort of proof of concept that will demonstrate the possibility to remote control sensors and actuators (for example a couple of relays) via Telegram.
Telegram is an instant messaging application, similar to the famous Whatsapp. Last June, the Telegram developers announced that a new set of APIs were available to develop bots.My idea was to develop a bot, running on my Raspberry Pi, that receives commands via Telegram chats. I connected to the Raspberry a temperature/humidity sensor and a module with two relays. Here’s a short video that describes the project:
The user, through the Telegram app installed on his smartphone, starts a chat with the “bot” account; the messages are delivered to the Telegram servers. The program running on the Raspberry can get the messages in two ways:
- polling, every tot seconds the program verifies if there are new messages and fetches them
- webhook, the program configures Telegram to dispatch the new messages to a web URL
The second solution requires a public IP address (static or a dyndns service) and some configuration (NAT) on your Internet router, I therefore chose to implement the simpler polling.
Let’s create the bot
The first step in developing your own bot, is to create it in Telegram. You create new bots or configure existing ones sending the right commands to a “built-in” bot, the BotFather:Start the process to create a new bot sending to the BotFather the command /newbot. You’ll be prompted for the name (display name) of your new bot and for its username. If the process is successful, you’ll receive an authorization token, that is the “password” you must specify in your program to “impersonate” the botThe library installation is super simple thanks to the NPM (Node Package Manager). Create a new folder to save the bot code and, within that folder, type the following command.
For more detail: Home automation with Telegram BOT