Tag Archives: Hangouts Chat API

Hangouts Chat alerts & notifications… with asynchronous messages

Posted by Wesley Chun (@wescpy), Developer Advocate, G Suite

While most chatbots respond to user requests in a synchronous way, there are scenarios when bots don't perform actions based on an explicit user request, such as for alerts or notifications. In today's DevByte video, I'm going to show you how to send messages asynchronously to rooms or direct messages (DMs) in Hangouts Chat, the team collaboration and communication tool in G Suite.

What comes to mind when you think of a bot in a chat room? Perhaps a user wants the last quarter's European sales numbers, or maybe, they want to look up local weather or the next movie showtime. Assuming there's a bot for whatever the request is, a user will either send a direct message (DM) to that bot or @mention the bot from within a chat room. The bot then fields the request (sent to it by the Hangouts Chat service), performs any necessary magic, and responds back to the user in that "space," the generic nomenclature for a room or DM.

Our previous DevByte video for the Hangouts Chat bot framework shows developers what bots and the framework are all about as well as how to build one of these types of bots, in both Python and JavaScript. However, recognize that these bots are responding synchronously to a user request. This doesn't suffice when users want to be notified when a long-running background job has completed, when a late bus or train will be arriving soon, or when one of their servers has just gone down. Recognize that such alerts can come from a bot but also perhaps a monitoring application. In the latest episode of the G Suite Dev Show, learn how to integrate this functionality in either type of application.

From the video, you can see that alerts and notifications are "out-of-band" messages, meaning they can come in at any time. The Hangouts Chat bot framework provides several ways to send asynchronous messages to a room or DM, generically referred to as a "space." The first is the HTTP-based REST API. The other way is using what are known as "incoming webhooks."

The REST API is used by bots to send messages into a space. Since a bot will never be a human user, a Google service account is required. Once you create a service account for your Hangouts Chat bot in the developers console, you can download its credentials needed to communicate with the API. Below is a short Python sample snippet that uses the API to send a message asynchronously to a space.

from apiclient import discovery
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = 'https://www.googleapis.com/auth/chat.bot'
creds = ServiceAccountCredentials.from_json_keyfile_name(
'svc_acct.json', SCOPES)
CHAT = discovery.build('chat', 'v1', http=creds.authorize(Http()))

room = 'spaces/<ROOM-or-DM>'
message = {'text': 'Hello world!'}
CHAT.spaces().messages().create(parent=room, body=message).execute()

The alternative to using the API with services accounts is the concept of incoming webhooks. Webhooks are a quick and easy way to send messages into any room or DM without configuring a full bot, i.e., monitoring apps. Webhooks also allow you to integrate your custom workflows, such as when a new customer is added to the corporate CRM (customer relationship management system), as well as others mentioned above. Below is a Python snippet that uses an incoming webhook to communicate into a space asynchronously.

import requests
import json

URL = 'https://chat.googleapis.com/...&thread_key=T12345'
message = {'text': 'Hello world!'}
requests.post(URL, data = json.dumps(message))

Since incoming webhooks are merely endpoints you HTTP POST to, you can even use curl to send a message to a Hangouts Chat space from the command-line:

curl \
-X POST \
-H 'Content-Type: application/json' \
'https://chat.googleapis.com/...&thread_key=T12345' \
-d '{"text": "Hello!"}'

To get started, take a look at the Hangouts Chat developer documentation, especially the specific pages linked to above. We hope this video helps you take your bot development skills to the next level by showing you how to send messages to the Hangouts Chat service asynchronously.

Develop bot integrations with the Hangouts Chat platform and API

Posted by Mike Sorvillo, Product Manager, Hangouts Chat and Wesley Chun (@wescpy), Developer Advocate, G Suite

You might have seen that we announced new features in G Suite to help teams transform how they work, including Hangouts Chat, a new messaging platform for enterprise collaboration on web and mobile. Perhaps more interesting is that starting today you'll be able to craft your own bot integrations using the Hangouts Chat developer platform and API.

Now, you can create bots to streamline work—automate manual tasks or give your users new ways to connect with your application, all with commands issued from chat rooms or direct messages (DMs). Here are some ideas you might consider:

  • Create a bot that can complete simple tasks or query for information
  • Create a bot that can post asynchronous notifications in any room or DM
  • Use interactive UI cards to bring your message responses to life
  • Use Google Apps Script to create custom bots for your colleagues or organization

For example, a bot can take a location from a user, look it up using the Google Maps API, and display the resulting map right within the same message thread in Hangouts Chat. The bot output you see in the image below is generated from the Apps Script bot integration. It returns the JSON payload just below the same image shown on this page in the documentation.

When messages are sent to an Apps Script bot, the onMessage() function is called and passed an event object. The code below extracts the bot name as well as the location requested by the user. The location is then passed to Google Maps to create the static map as well as an openLink URL that takes the user directly to Google Maps if either the map or "Open in Google Maps" link is clicked.

function onMessage(e) {
var bot = e.message.annotations[0].userMention.user.displayName;
var loc = encodeURI(e.message.text.substring(bot.length+2));
var mapClick = {
"openLink": {
"url": "https://google.com/maps/search/?api=1&query=" + loc
}
};

return {
// see JSON payload in the documentation link above
};
}

Finally, this function returns everything Hangouts Chat needs to render a UI card assuming the appropriate links, data and Google Maps API key were added to the response JSON payload. It may be surprising, but this is the entire bot and follows this common formula: get the user request, collate the results and respond back to the user.

When results are returned immediately like this, it's known as a synchronous bot. Using the API isn't necessary because you're just responding to the HTTP request. If your bot requires additional processing time or must execute a workflow out-of-band, return immediately then post an asynchronous response when the background jobs have completed with data to return. Learn more about bot implementation, its workflow, as well as synchronous vs. asynchronous responses.

Developers are not constrained to using Apps Script, although it is perhaps one of the easiest ways to create and deploy bots. Overall, you can write and host bots on a variety of platforms:

No longer are chat rooms just for conversations. With feature-rich, intelligent bots, users can automate tasks, get critical information or do other heavy-lifting with a simple message. We're excited at the possibilities that await both developers and G Suite users on the new Hangouts Chat platform and API.

Develop bot integrations with the Hangouts Chat platform and API



You might have seen that we announced new features in G Suite to help teams transform how they work, including Hangouts Chat, a new messaging platform for enterprise collaboration on web and mobile. Perhaps more interesting is that starting today you’ll be able to craft your own bot integrations using the Hangouts Chat developer platform and API.

Now, you can create bots to streamline work—automate manual tasks or give your users new ways to connect with your application, all with commands issued from chat rooms or direct messages (DMs). Here are some ideas you might consider:
  • Create a bot that can complete simple tasks or query for information 
  • Create a bot that can post asynchronous notifications in any room or DM 
  • Use interactive UI cards to bring your message responses to life 
  • Use Google Apps Script to create custom bots for your colleagues or organization 
For example, a bot can take a location from a user, look it up using the Google Maps API, and display the resulting map right within the same message thread in Hangouts Chat. The bot output you see in the image below is generated from the Apps Script bot integration. It returns the JSON payload just below the same image shown on this page in the documentation.


When messages are sent to an Apps Script bot, the onMessage() function is called and passed an event object. The code below extracts the bot name as well as the location requested by the user. The location is then passed to Google Maps to create the static map as well as an openLink URL that takes the user directly to Google Maps if either the map or "Open in Google Maps" link is clicked.

function onMessage(e) {
var bot = e.message.annotations[0].userMention.user.displayName;
var loc = encodeURI(e.message.text.substring(bot.length+2));
var mapClick = {
"openLink": {
"url": "https://google.com/maps/search/?api=1&query=" + loc
}
};

return {
// see JSON payload in the documentation link above
};
}

Finally, this function returns everything Hangouts Chat needs to render a UI card assuming the appropriate links, data and Google Maps API key were added to the response JSON payload. It may be surprising, but this is the entire bot and follows this common formula: get the user request, collate the results and respond back to the user.

When results are returned immediately like this, it's known as a synchronous bot. Using the API isn't necessary because you're just responding to the HTTP request. If your bot requires additional processing time or must execute a workflow out-of-band, return immediately then post an asynchronous response when the background jobs have completed with data to return. Learn more about bot implementation, its workflow, as well as synchronous vs. asynchronous responses.

Developers are not constrained to using Apps Script, although it is perhaps one of the easiest ways to create and deploy bots. Overall, you can write and host bots on a variety of platforms:
No longer are chat rooms just for conversations. With feature-rich, intelligent bots, users can automate tasks, get critical information or do other heavy-lifting with a simple message. We're excited at the possibilities that await both developers and G Suite users on the new Hangouts Chat platform and API.