Tuesday, 3 April, 2018 UTC


Summary

Chat bots became very popular with a Slack’s massive success, then Facebook introduced their Messenger platform with Chat bots. Now Google is doing the same with the most recent release of their Hangouts Chat, which also supports bots.
Hangouts, primarily released as Google Talk service, XMPP (Jabber) compatible service, been very popular in the past. Now with Messenger and WhatsApp leading in the private messaging sector and Slack as a no. 1 choice for teams messaging, Google needs to take some steps to get their part of the market back.
So they released refreshed version of Hangouts Chat. With standalone app, more features (including chatrooms) and support for custom bots!
Chat bots are software written to listen to some type of messages in private chats or chat rooms and when they recognise a known command they do some task and send appropriate response.
Bots in Hangouts Chat
  • Can respond to direct messages
  • Can be participant in a public discussion (in a chat room)
Bots communicate with Hangouts Chat through specific endpoints: either HTTP or Google Cloud Pub/Sub endpoints. The choice is up to you – choose the one that you’re the most comfortable with.
https://developers.google.com/hangouts/chat/concepts/bots
I assume you already have node.js and yarn properly installed in your system. Let’s now use Yarn to bootstrap our project:
mkdir hangout-chat-bot && cd hangout-chat-bot/
yarn init -y
Let’s now add express which we will use as our HTTP server:
yarn add express
and nodemon, to dynamically reload our app after code changes:
yarn add --dev nodemon
And add script targets to our package.json file, to tell yarn witch command to run:
{
"name":"hangout-chat-bot",
"version":"1.0.0",
"main":"index.js",
"license":"MIT",
"scripts":{
"dev":"nodemon index.js",
"start":"node index.js"
},
"dependencies":{
"express":"^4.16.3"
},
"devDependencies":{
"nodemon":"^1.17.2"
}
}
After this setup you will be able to run the app:
yarn dev
Then create file named index.js and put the following content there:
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
res.send("Hello World");
});

app.listen(PORT, () => {
console.log(`listening on ${PORT}`);
});
Now open the url http://localhost:3000 in your browser and you should see the Hello World text:
Let’s now configure Heroku to deploy our app. Download heroku-cli client for your platform.
Let’s now do some initial setup:
heroku login
You will be asked about your login and password. To be able to deploy to Heroku we need to have our project in git repository so let’s do it now:
git init .
git add .
git commit -am"Initial commit."
Okay, let’s create heroku app:
heroku create
You will be given now with a unique URL to your app. To see it in the browser the last step is to assign a dyno worker to the app:
heroku ps:scale web=1
And finally you can push to heroku:
git push heroku master
After successful push you will be able to see your app at the URL you were given in the previous step. If there’s something wrong, you see an “Application error” message use the command heroku logs to see what happened to your app.
Once your app is published you’ll see your deployment URL. Write it down, we’ll need that later when registering the bot:
Responding to POST requests
Express itself doesn’t parse incoming POST request to JSON documents. In order to achieve that we need to add a plugin called body-parser:
yarn add body-parser
And we need to add it as an express middleware:
const bodyParser = require('body-parser')
app.use(bodyParser.json());
Let’s add a POST route called /top-secret-bot. The name is for the sake of simplicity in this article, but in the production environment it should be random string.
app.post("/top-secret-bot", (req, res) => {
const { space, type, message } = req.body || {};

if (type === "ADDED_TO_SPACE" && space.type === "ROOM") {
res.send({ text: `Thanks for adding me to ${space.displayName}` });
}
});
Gif for every occasion
To make the example more practical we’ll use GIPHY API to search gifs library and display appropriate gif for the given query.
First, you need to register in the GIPHY Developers portal on developers.giphy.com.
Once you complete the registration the next step will be create an application and obtaining API credentials. Whey you register your App, copy the API key and we’ll use it soon after preparing the application.
For performing requests we’ll use node-fetch, a node equivalent of in-browser’s fetch module:
yarn add node-fetch
const fetch = require('node-fetch');
Registering our bot
The bot we’ve created is now ready to use and all we need to do to make it working is enablind Chat API and registering the bot in the Google API Console. Detailed instruction on how to register the bot and enable API access you’ll find in the Google Developer Docs here. Once you do that you can go to next step.
Bear in mind that in the configuration section of our bot you’ll need to put the full URL including our route name, in the case of this article it is /top-secret-bot. As mentioned earlier, for security reasons it’s recommended that you’ll use a random string here.
Talking to the bot
When our app is deployed, bot register it’s time to test if it works. So to do that I’d suggest creating a new chat room and invite the bot using it’s given name (during configuration). When you’re in the same room with the bot just use its handle with @ and you should see a giphy response:
Full source code is available here on the Github Gist. Remember to replace string YOUR_GIPHY_API_KEY with the API key obtained from the Giphy website. Enjoy!
The post How to write Hangouts Chat Bot with Node.js appeared first on matwrites.com.