How to Create a Telegram Reminder Bot Using Node-RED

You probably wondered if it would be cool to set up reminders in the messenger about the need to drink water or feed your pet. In this article, we will look at how to easily and quickly create a Telegram chatbot in Node-RED, create reminder texts, and test it.

 

What is Node-RED and how does it work?

 

Node-RED is a browser-based data stream editor that allows you to easily combine data streams using various nodes that are collected in a palette (node-red palette).

Node – data node; the nodes of a decentralized network communicate via P2P protocols to exchange information about blocks and transactions. The node is the main building block of the flow.

Nodes are started by either receiving a message from a previous node in the thread or waiting for some external event, such as an incoming HTTP request or timer. They process this message or event and then can send the message to the next nodes in the stream.

The Node-RED palette includes a set of default nodes, which are the basic building blocks for creating threads.

Nodes can be added to the work area by dragging and dropping them from the palette using the quick add dialog or importing from the library or clipboard.

The nodes are connected by lines-wires through their ports. A node can have at most one input port and many output ports. If a node has unused changes, a blue circle appears above it. If there are errors in its configuration, it displays a red triangle.

The essence of the Node-RED editor is that instead of writing programs and commands based on the code, to build the logic for sending messages by the bot, the user just needs to drag and drop objects (nodes) in the visual editor. Since Node-RED provides objects with typical functions, it is easy and affordable for everyone to create projects using them. More complex JavaScript functions can be recreated using a text editor.

The built-in node library allows you to save useful functions, templates or streams for reuse.

Using Node-RED is free, in addition Node-RED can integrate with anything using the API.

 

Node-RED analogs

 

Chatfuel is a useful tool that lets you create chatbots on Facebook. In Chatfuel, you can access external data sources using plugins and create your own chatbots.

 

A chatbot can be configured to recognize specific words or phrases and send predefined responses to users. It can send automated responses to the most common and frequently asked questions. Also, Chatfuel can easily integrate with YouTube, Twitter, JSON, Messenger and others. Chatfuel is free to use, but there is a set of additional advanced paid functionality.

 

Botsify also gives you the ability to create chatbots on a website widget or Facebook messenger without any programming knowledge. Botsify is integrated with many services including WordPress, Shopify, Slack, Alexa, Google Sheets, RSS Feed, JSON API, ZenDesk. An easy-to-use interface allows you to build work logic using visual tools. Botsify is a paid tool and its cost depends on the number of bots you create and the number of bot subscribers.

 

Disadvantages of Node-RED analogues

 

The main disadvantages of Botsify and Chatfuel are these tools are intended either to work with only one messenger, or paid. Therefore, Node-RED is an indispensable tool for getting started and getting acquainted with the creation of bots, as it combines a user-friendly interface, functionality and does not require additional resources.

 

Create a chatbot in Telegram on Node-RED

 

To create a bot in Telegram, you need to go to the application and find @BotFather. Then call the / newbot command and name the bot.

After that, a token is generated, which is required to connect the bot to Node-RED.

 

Installing Node-RED

 

Next, you need to install Node-RED on your computer and start the server with Node-RED on your local machine. In Terminal on your Mac, run the following commands:

 node-red -u “./”

Next, in the browser line, you need to enter http: // localhost: 1880 and we will get access to the pure Node-RED flow, which will be used in further work.

For the setup of webhooks (custom callbacks over HTTPS) and the ability to send messages (logs) to the Node-RED server, you must use the HTTPS protocol, otherwise the messenger will not be able to send the body of the message to a URL that uses a secure connection.

To fix this problem, ngrok (secure tunnels for transferring information to localhost) or localtunnel are most often used. Below we will use the ngrok service. To do this, follow the link to the ngrok website and register. After entering all the required data, you need to download and unzip the file.

Next, open the file through the Terminal on your computer. When registering, each user is provided with an authorization token, and in order to use this service, run the following command in the Terminal command line:

[path to the place where ngrok is located] / ngrok authtoken [token received during registration]

Then start ngrok specifying the port of the local machine as well. In this case, we launch it using the following command:

/ ngrok http 1880

In the future, we set up hooks with the received ngrok secure address, in this case https://41b24bad1175.ngrok.io. Next, we will use the API documentation provided by Telegram.

 

Configuring bot logic

 

To connect and receive messages, you need to apply the following nodes. The inject block will be used to initiate the setup, the bunch of the bot and the Node-RED server is defined in the http request block.

In the http request block, set the following parameters: the POST method, after which we form the URL from the following parts

 

https://api.telegram.org/ [bot id ]/setWebhook?url= [used_ngrok ]/ [webhook_Node_red]

 

  • bot id is provided directly when registering a bot with @BotFather as a parameter in a token separated by a colon. In our case 1170972715: AAEntMHSaQEOD2ueLXb1VWmDoidnnbnEQCI)
  • used_ngrok – in this example https://41b24bad1175.ngrok.io
  • webhook_Node_red is a node that will directly “catch” user messages. We use the http in node, setting it the following parameters method POST, URL – / first_bot, (this url is our Node-RED hook)

Ultimately, our link looks like this:

https://api.telegram.org/bot1170972715:AAEntMHSaQEOD2ueLXb1VWmDoidnnbnEQCI/setWebhook?url=https://41b24bad1175.ngrok.io/first_bot

After filling in all the fields, click Done, and click on the Deploy button in the upper right corner. The Deploy button saves all changes that were made during the flow, so before each test, you must click it, if it is active.

All log messages that come to Node-RED can be found in the tab on the right side of the Debug messages flow. After opening the Debug messages tab, set up the hook by clicking on the node inject.

If all the steps described above are completed correctly, a successful connection response with a 200 status code will be displayed.

 

How to send the first message to a user in a Telegram bot

 

Sending a message to a bot is very simple, for this you need to know who to send what, that is, the text and chat_id parameters.

To find out the chat_id parameter, you can use the debug node and set the complete message object trapping in it. To do this, connect it to a node that catches all our messages and get the following:

Then go to the bot and send it the first message (by default – the / start command)

After that, we get an object that directly displays all the information sent to Telegram. To send a message, you need the id parameter, which can be found in the received log along this path payload.message.chat.id

The following URL is used to send the message:

https://api.telegram.org/bot<bottoken> / sendMessage

All information is transferred in the msg object, which has different levels of nesting and allows you to conveniently transport information. In general, the msg can be imagined as a box with folded data, with which we go to the post office to send as a parcel, parcel post or letter – depending on the complexity of the data object being sent.

 

By analogy, the algorithm below describes how to send an email message in a bot:

1. We indicate what exactly we send, but do not receive or update

   msg.method = “POST”

2. We indicate who will “transport” our letter (different tokens = different “carriers”, “carrier” = “bot”)

msg.url = “https://api.telegram.org/bot1170972715:AAEntMHSaQEOD2ueLXb1VWmDoidnnbnEQCI/sendMessage”

3. And of course, you need to write the message itself and to whom we will send it

msg.payload = {

  “text”: “Drink some water”,

  “chat_id”: msg.payload.message.from.id,

  }

4. Everything is ready, you don’t even need to specify a phone number in the sending template, just tell the node what text to send. To do this, use the command – return msg.

5. Next, you need to “transport” our letter. Since we have already indicated all the information, select – set by msg. method

6. Let’s test it, return to the bot and call the / start command again. The bot should immediately send us a message. It works! HOORAY 🙂

Frequency of sending messages

 

Now we will make the bot remind us every minute that we need to drink water (we take this value of the delay for tests, and later we will increase the time to an hour – we are not sadists).

But first, we need to save the value to whom we are sending the message. Since the object is saved and used only once, the value of this parameter is lost when resending. Therefore, it is necessary to preserve it from the very beginning.

To do this, we use the change node, which allows you to set values in parameters

Now the receiver, that is, the user’s chat_id, will not be lost anywhere and can be reused even if we do not receive a message from the user.

We will also add a timer and set a value of 1 min – a delay 1m block. Let’s connect it to the message sending block. Thus, after the first message is sent, it will take 1 minute and the message will be sent again.

Let’s test it out.

Next, we will increase the frequency of sending messages by 1 hour or any other value – in the delay block.

Bot for reminders in Telegram – ready

 

Without programming skills, anyone can create a bot for reminders to drink water (every minute, hour, or any other period of time).

Let’s complicate the bot a little by adding the ability to independently select reminder hours. To do this, we need to configure the sequence of messages – this will not be difficult, since the first message is displayed after the / start command, and the second command, namely, the start of the timer to receive notifications in all other cases. To do this, we will analyze the text that we receive from the user, we will get 2 options in total.

 

After that, if the user has called the / start command, we will display the message “Hello! Choose how often to remind you about water? 😏 ”, as well as buttons for choosing the frequency – 30 minutes, 1 hour, 2 hours.

Buttons with text in Telegram are announced as follows:

“text”: “Hello! Choose how often to remind you about water? 😏”,

        “reply_markup”: {

            “keyboard”: [[‘Every half hour’], [‘Every hour’], [‘Every two hours’]],

                  ‘resize_keyboard’: true,

      ‘one_time_keyboard’: false

each with [] in the keyboard, reads a new button, and the text in [] is responsible for the inscription that will be displayed on the button. Place buttons and text in msg.payload, add msg.method i msg.url to the function.

 

 msg.method = “POST”

msg.url = “https://api.telegram.org/bot1170972715:AAEntMHSaQEOD2ueLXb1VWmDoidnnbnEQCI/sendMessage”

msg.payload = {

        

        “text”: “Hello! Choose how often to remind you about water? 😏”,

        “reply_markup”: {

            “keyboard”: [[‘Every half hour’], [‘Every hour’], [‘Every two hours’]],

                  ‘resize_keyboard’: true,

      ‘one_time_keyboard’: false

        },

“chat_id”: msg.receiver

}

 

 return msg;

Let’s connect to http request. If this message is not the first, then it must contain one of the text values ​​that we previously displayed on the buttons. All actions that lead from these three conditions are similar, but have different delays in sending messages.

In each of the functions we will display a message, only in “text” – we will display different texts, such as (Great! I will remind you every half hour😌. Great! I will remind you every hour😉, Great! I will remind you every two hours😎)

msg.method = “POST”

msg.url = “https://api.telegram.org/bot1170972715:AAEntMHSaQEOD2ueLXb1VWmDoidnnbnEQCI/sendMessage”

 

msg.payload = {

“text”: “Great! I will remind you every hour😌”,

“chat_id”: msg.receiver}

return msg;

 

 

After displaying the message, add the corresponding delay in sending the next message and the message itself.

msg.method = “POST”

msg.url = “https://api.telegram.org/bot1170972715:AAEntMHSaQEOD2ueLXb1VWmDoidnnbnEQCI/sendMessage”

msg.payload = {

“text”: “Drink some water”,

“chat_id”: msg.receiver}

return msg;

After sending the message, we return to the timer to repeat the sending of the message.

Let’s test

Let’s choose, for example, the first option – Every half hour

Summing up

In this article, we figured out how Node-RED works and how to create a bot in Node-RED Telegram chatbot for reminders.

 

The Chatbots.Studio team develops chat bots in instant messengers – Apple Business Chat, WhatsApp, Telegram, FB Messenger and Viber. If you are interested in articles about using Node-RED in other messengers, subscribe to our Facebook and stay tuned for new articles.

 

Are you interested in creating chatbots?

 

Build your career with Chatbots.Studio! Chatbots.Studio is a place for engineers looking for effective and creative ways to solve complex problems and constantly improving existing approaches to creating new products.

 

Do you need to create a bot with complex functionality?

 

If you need to create a complex solution based on Node-RED, the Chatbots.Studio team will develop a bot of any complexity (our portfolio). To do this, leave a request in the form below.