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

Written by rodrigokamada | Published 2022/02/05
Tech Story Tags: chatbot | rcs | nodejs | weather | javascript | bot | rich-communication-services | software-development | web-monetization

TLDRIn 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]via the TL;DR App

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 NameE-mailPassword, 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 NameE-mailPassword, 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 UsernameEnter emailPasswordRepeat 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 dotenvexpress 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.


Written by rodrigokamada | 👨‍💻 Software Developer | ✍️ Technical Content Creator | 🤝 Open Source Contributor | 🎙️ Speaker | 🙌 Ambassador
Published by HackerNoon on 2022/02/05