DEV Community

Cover image for How to build a weather chatbot in RCS channel using Node.js
Rodrigo Kamada
Rodrigo Kamada

Posted on • Edited on

How to build a weather chatbot in RCS channel using Node.js

Introduction

In this article, an application will be built using JavaScript and Node.js where a simple chatbot will be implemented using the Zenvia platform to integrate with RCS channel and the OpenWeatherMap platform to integrate with meteorological data in order to test some features of the RCS channel such as sending and receiving text and image messages and sharing 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 contents 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.

ngrok - Home page

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.

ngrok - Sign Up

3. Ready! Account created.

ngrok - Setup & Instalation

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.

ngrok - Download

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

ZENVIA - Sign in

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.

ZENVIA - Create your account

3. Check the registered email.

ZENVIA - Check email

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

ZENVIA - Activate account

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

ZENVIA - Sign in

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

ZENVIA - Sign in

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

ZENVIA - Secure your account

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

ZENVIA - Verify your identify

9. Ready! Account created.

ZENVIA - 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.

ZENVIA - Menu

2. Click on the button Create New.

ZENVIA - Sandbox - Keyworks

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

ZENVIA - Sandbox - Select the channel

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

ZENVIA - Sandbox - Add contacts

Notes:

  • This registration is require for the ZENVIA platform to register the number(s) you would like to test, making it impossible 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.

RCS - Accept message

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

RCS - Welcome message

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

ZENVIA - Sandbox - Added contacts

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.

ZENVIA - Sandbox - Test message text

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 selected number.

RCS - Test message text

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.

ZENVIA - Sandbox - Subscription

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.

OpenWeatherMap - Home page

2. Click on the link Create an Account.

OpenWeatherMap - Sign in

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.

OpenWeatherMap - Sign up

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

OpenWeatherMap - API usage

5. Check the registered email.

OpenWeatherMap - Check email

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

OpenWeatherMap - Activate account

7. Ready! Account created.

OpenWeatherMap - Account created

Search the API key on the OpenWeatherMap platform

1. Click on the link API keys.

OpenWeatherMap - New products

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.

OpenWeatherMap - keys

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

Create the Node.js application

Node.js is 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

3. Install the dependencies dotenv, express and got.

npm install dotenv express got
Enter fullscreen mode Exit fullscreen mode

4. Create the file .env.

touch .env
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

mkdir src
touch src/index.js
Enter fullscreen mode Exit fullscreen mode

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...');
Enter fullscreen mode Exit fullscreen mode

8. Run the application with the command below.

node src/index.js
Enter fullscreen mode Exit fullscreen mode

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.

RCS - Test

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}_w@4x.png`,
  };
};
Enter fullscreen mode Exit fullscreen mode

11. Run the application again with the command below.

node src/index.js
Enter fullscreen mode Exit fullscreen mode

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

RCS - Plus

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

RCS - Location

14. Click the button Send to share the location.

RCS - Share

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.

RCS - Test

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.

RCS - Settings

RCS - Chat resources

This tutorial was posted on my blog in portuguese.

Top comments (0)