In this article, we will build an application using JavaScript and Node.js where a simple chatbot will be implemented using theĀ
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Ā
1.Ā Access the siteĀ
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.
The ngrok tool will create a tunnel for the application that is running locally providing a URL on the Internet.
1.Ā Access the siteĀ
2.Ā Extract and install the downloaded file. I'm using 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:
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:
1.Ā Access the siteĀ
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.
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:
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:
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:
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Ā
1.Ā Access the siteĀ
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.
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Ā
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Ā
This tutorial was first posted on myĀ