paint-brush
How to Build a Weather Chatbot with RCS Services using Node.jsā€‚by@rodrigokamada
867 reads
867 reads

How to Build a Weather Chatbot with RCS Services using Node.js

by Rodrigo KamadaFebruary 5th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article, an application will be built using JavaScript and Node.js. The chatbot will be implemented using the ZENVIA platform to integrate with the RCS channel and the OpenWeatherMap platform. It will integrate with meteorological data in order to test some features of the channel such as sending and receiving text and image messages and sharing location. The app will be running locally on the Internet and will be able to send and receive texts and images from the channel. It is currently supported on Android devices and the.[Messages]

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - How to Build a Weather Chatbot with RCS Services using Node.js
Rodrigo Kamada HackerNoon profile picture

Introduction

In this article, we will build an application using JavaScript and Node.js where a simple chatbot will be implemented using theĀ ZENVIAĀ platform to integrate with a RCS channel and theĀ OpenWeatherMapĀ platform. We will retrieve meteorological data in order to test some features of the RCS channel such as sending and receiving text and image messages and share location.


RCS (Rich Communication Services) is a communication protocol that uses the carriers' infrastructure, as well as SMS (Short Message Service), with the purpose of having rich content such as image, video, button, card, among others.


This protocol can be implemented by any operating system or mobile application, however, it is currently supported on Android devices and theĀ MessagesĀ application.

Create an account on the ngrok platform

ngrokĀ is a service that exposes an application that is running locally on the Internet.


1.Ā Access the siteĀ https://ngrok.com/Ā and click on the buttonĀ Sign up.

2.Ā Fill in the fieldsĀ Name,Ā E-mail,Ā Password, click onĀ I'm not a robotĀ and click on the buttonĀ Sign Up. You can also login with GitHub or Google social login.

3.Ā Ready! Account created.

Install and configure the ngrok Platform Tool

The ngrok tool will create a tunnel for the application that is running locally providing a URL on the Internet.


1.Ā Access the siteĀ https://ngrok.com/downloadĀ and download the installation file for your operating system.

2.Ā Extract and install the downloaded file. I'm using theĀ openSUSE TumbleweedĀ operating system and I just extracted it in theĀ /usr/local/bin/Ā folder.


3.Ā Configure the authentication token. In my case, I ran the below command in terminal.

ngrok authtoken 1Rmotb9M3sa7Nw2Ox2w27hSY0c8_5ee3v6duPVT6Gfjb15omJ


Note:

  • Use your authentication token that was generated on the ngrok platform.


4.Ā Create the tunnel on portĀ 3000Ā that will be the application's port. In my case, I ran the below command in terminal.

ngrok http 3000


5.Ā Ready! The ngrok tool is configured and will display in the terminal the public URLĀ https://da3e845a1ceb.ngrok.ioĀ available to access on the Internet.

ngrok by @inconshreveable                                                                                                                                                                                                                                     (Ctrl+C to quit)

Session Status                online                                                                                                                                                                                                                                          
Session Expires               1 hour, 59 minutes                                                                                                                                                                                                                              
Update                        update available (version 2.3.40, Ctrl-U to update)                                                                                                                                                                                             
Version                       2.3.35                                                                                                                                                                                                                                          
Region                        United States (us)                                                                                                                                                                                                                              
Web Interface                 http://127.0.0.1:4040                                                                                                                                                                                                                           
Forwarding                    http://da3e845a1ceb.ngrok.io -> http://localhost:3000                                                                                                                                                                                           
Forwarding                    https://da3e845a1ceb.ngrok.io -> http://localhost:3000                                                                                                                                                                                          

Connections                   ttl     opn     rt1     rt5     p50     p90                                                                                                                                                                                                     
                              0       0       0.00    0.00    0.00    0.00


Note:

  • The tunnel has an expiration time of 2 hours as displayed inĀ Session Expires, and if it expires, run the command again to create the tunnel.

Create an account on the ZENVIA platform

ZENVIAĀ is a platform that empowers companies to create unique communication experiences for their customers through SMS, WhatsApp, Voice, Facebook Messenger, WEB Chat and RCS channels.


1.Ā Access the siteĀ https://app.zenvia.comĀ and click on the linkĀ Create your account.

2.Ā Fill in the fieldsĀ Name,Ā E-mail,Ā Password, click on the optionĀ I'm not a robotĀ and click on the buttonĀ Create account.

3.Ā Check the registered email.

4.Ā Click on the buttonĀ YES IT'S ME! CONFIRM IT :)Ā in the email sent.

5.Ā Fill in the fieldĀ E-mailĀ and click on the buttonĀ Next.

6.Ā Fill in the fieldĀ PasswordĀ and click on the buttonĀ Sign in.

7.Ā Fill in the fieldĀ Enter your phone numberĀ and click on the buttonĀ Continue.

8.Ā Fill in the fieldĀ Enter the 6-digit codeĀ with the code you received on your mobile phone and click on the buttonĀ Continue.

9.Ā Ready! Account created.

Create the Sandbox on the ZENVIA Platform

SandboxĀ is a very popular concept among developers, where it is possible to test some functionality of a platform without hiring the service. Therefore, it needs to be intuitive and without bureaucracy.


1.Ā Click on the menuĀ SolutionsĀ andĀ Sandbox.

2.Ā Click on the buttonĀ Create New.

3.Ā Select the optionĀ RCSĀ and click on the buttonĀ Next.

4.Ā Fill in the field with your mobile phone and click on the buttonĀ Send message.

Notes:

  • This registration is required for the ZENVIA platform to register the number(s) you would like to test, making it possible to send the message to any mobile phone.
  • It is possible to register other numbers using the same procedure.


5.Ā You will receive a message on your mobile phone confirming the registration of the number. Click on the buttonĀ AcceptĀ to confirm your registration.

6.Ā You will receive a message on your mobile phone confirming that your number has been registered.

7.Ā The registered number(s) will be displayed on the screen, as well as the limit of 200 messages in a 24-hour period.

Note:

  • When the 24 hour period is reached, register the number(s) again to start a new cycle of 200 messages in the 24 hour period. If you use the 200 messages, you will have to wait a period of 24 hours.


8.Ā You can test sending a text message. Select the number you want to send in the fieldĀ To, fill in the message in the fieldĀ MessageĀ and click on the buttonĀ Send message. Copy the token in the parameterĀ X-API-TOKENĀ and, in my case, the tokenĀ gSTuqxR2rsXY-UJGzdXFMWv-uvp7DKPtGLzqĀ was generated because this token will be configured in the Node.js application. Click on the buttonĀ Next.

Notes:

  • In the fieldĀ From, as it is a Sandbox, a random word is createdIn the From field, as it is a Sandbox, a random word is created that corresponds to the integration identifier when the service is contracted.
  • In the fieldĀ Request, an example of a request using theĀ curlĀ tool is displayed. You can simulate this same request using other tools likeĀ PostmanĀ orĀ Insomnia.


9.Ā Test message sent to the selected number.

10.Ā Let's create a subscription to the webhook using the URL that was created on the ngrok platform. Fill in the fieldsĀ Message Webhook URLĀ with the URLĀ https://da3e845a1ceb.ngrok.io/messageĀ andĀ Status Webhook URLĀ with the URLĀ https://da3e845a1ceb.ngrok.io/statusĀ and click on the buttonsĀ SaveĀ andĀ Finish.

11.Ā Ready! Sandbox created for the RCS channel, number and webhook URL configured. API documentation is available atĀ https://zenvia.github.io/zenvia-openapi-spec/.

Create an account on the OpenWeatherMap platform

OpenWeatherMapĀ is a service that allows you to get weather data using APIs.


1.Ā Access the siteĀ https://openweathermap.orgĀ and click on the linkĀ Sign In.

2.Ā Click on the linkĀ Create an Account.

3.Ā Fill in the fieldsĀ Username,Ā Enter email,Ā Password,Ā Repeat Password, click onĀ I am 16 years...,Ā I agree with...,Ā I'm not a robotĀ and click on the buttonĀ Create Account.

4.Ā Select an option in the fieldĀ PurposeĀ and click on the buttonĀ Save.

5.Ā Check the registered email.

6.Ā Click on the buttonĀ Verify your emailĀ in the email sent.

7.Ā Ready! Account created.

Search the API key on the OpenWeatherMap platform

1.Ā Click on the linkĀ API keys.

2.Ā Copy the key in the parameterĀ KeyĀ and, in my case, the keyĀ 311207449541d9dbd7f7bc9a52680e57Ā was generated because this key will be configured in the Node.js application.

3.Ā Ready! API key created. API documentation is available atĀ https://openweathermap.org/current.

Create the Node.js application

Node.jsĀ is an open-source, cross-platform software that runs JavaScript code on the server. It is based on Google's V8 JavaScript interpreter.


1.Ā Create the application folder.

mkdir chatbot-rcs
cd chatbot-rcs


2.Ā Create the fileĀ package.json. The optionĀ -yĀ allows the file to be created without the questions, such as application name, version, among others.

npm init -y


3.Ā Install the dependenciesĀ dotenv,Ā expressĀ andĀ got.

npm install dotenv express got


4.Ā Create the fileĀ .env.

touch .env


5.Ā Add the tokens created on the platforms ZENVIA and OpenWeatherMap in the fileĀ .envĀ as below.

ZENVIA_TOKEN=gSTuqxR2rsXY-UJGzdXFMWv-uvp7DKPtGLzq
OPENWEATHERMAP_TOKEN=311207449541d9dbd7f7bc9a52680e57


6.Ā Create the folderĀ srcĀ and create the fileĀ index.jsĀ inside the folderĀ src.

mkdir src
touch src/index.js


7.Ā Add the content below in the fileĀ src/index.js, where when receiving a message, the application will send a message with the contentĀ Tested.

const dotenv = require('dotenv');
const express = require('express');
const got = require('got');

dotenv.config();

const app = express();
app.use(express.json());

app.post('*', async (req, res) => {
  const contentReceived = req.body;
  console.log(`Content Received [${JSON.stringify(contentReceived)}]`);

  res.sendStatus(200);

  if (!contentReceived || !contentReceived.message || !contentReceived.message.contents) {
    return;
  }

  if (contentReceived.type === 'MESSAGE') {
    await got.post('https://api.zenvia.com/v2/channels/rcs/messages', {
      responseType: 'json',
      resolveBodyOnly: true,
      json: {
        from: contentReceived.message.to,
        to: contentReceived.message.from,
        contents: [{
          type: 'text',
          text: 'Tested',
        }],
      },
      headers: {
        'X-API-TOKEN': process.env.ZENVIA_TOKEN,
      },
    });
  }
});

app.listen(3000);

console.log('Listening...');


8.Ā Run the application with the command below.

node src/index.js


9.Ā Test the integration with the ZENVIA platform. Send a test message using the registered mobile phone. You should get the message with the contentĀ Tested.

10.Ā After creating and testing the sending and receiving of text messages, we will change the content of the fileĀ src/index.jsĀ to improve the application, search the weather data and send the content of the card type.

const dotenv = require('dotenv');
const express = require('express');
const got = require('got');

dotenv.config();

const app = express();
app.use(express.json());

app.post('*', async (req, res) => {
  const contentReceived = req.body;
  console.log(`Content Received [${JSON.stringify(contentReceived)}]`);

  res.sendStatus(200);

  if (!contentReceived || !contentReceived.message || !contentReceived.message.contents) {
    return;
  }

  if (contentReceived.type === 'MESSAGE') {
    let content = {
      type: 'text',
      text: 'Tested',
    };

    if (contentReceived.message.contents[0].type === 'location') {
      const weather = await getWeather(contentReceived.message.contents[0].latitude, contentReceived.message.contents[0].longitude);
      content = {
        type: 'card',
        text: `šŸ“ Weather for ${weather.name}\n\nTemperature: ${weather.temperature}Āŗ\nMinimum Temperature: ${weather.temperatureMinimum}Āŗ\nMaximum Temperature: ${weather.temperatureMaximum}Āŗ\nHumidity: ${weather.humidity}%`,
        media: {
          url: weather.url,
          disposition: 'ON_THE_LEFT',
        },
      };
    }

    await got.post('https://api.zenvia.com/v2/channels/rcs/messages', {
      responseType: 'json',
      resolveBodyOnly: true,
      json: {
        from: contentReceived.message.to,
        to: contentReceived.message.from,
        contents: [{...content}],
      },
      headers: {
        'X-API-TOKEN': process.env.ZENVIA_TOKEN,
      },
    });

    console.log(`Content Sent [${JSON.stringify(content)}]`);
  }
});

app.listen(3000);

console.log('Listening...');

const getWeather = async (latitude, longitude) => {
  const response = await got.post(`https://api.openweathermap.org/data/2.5/weather?appid=${process.env.OPENWEATHERMAP_TOKEN}&units=metric&lat=${latitude}&lon=${longitude}`, {
    responseType: 'json',
    resolveBodyOnly: true,
  });

  return {
    name: response.name,
    temperature: response.main.temp,
    temperatureMinimum: response.main.temp_min,
    temperatureMaximum: response.main.temp_max,
    humidity: response.main.humidity,
    url: `https://rodrigokamada.github.io/openweathermap/images/${response.weather[0].icon}[email protected]`,
  };
};


11.Ā Run the application again with the command below.

node src/index.js


12.Ā Test integration with ZENVIA and OpenWeatherMap platforms. Let's share the location. Click on the buttonĀ PlusĀ to display the options.

13.Ā Click the buttonĀ LocationĀ to display the location sharing.

14.Ā Click the buttonĀ SendĀ to share the location.

15.Ā After sharing the location, the application will receive the message containing the latitude and longitude information, search the weather data and send a card type content with the weather data.

16.Ā Ready! Application tested and running using a mobile phone.


The application repository is available atĀ https://github.com/rodrigokamada/chatbot-rcs.

Extras

  • Carriers available in Brazil: Claro, Oi, Tim and Vivo.
  • If you have problems with the Google Messages application, enable the optionĀ Enable chat featuresĀ available within the menuĀ SettingsĀ and then underĀ Chat features.


This tutorial was first posted on myĀ blogĀ in Portuguese.