How to create a simple Hangouts Chat bot in Python

Jason Jurotich
May 27, 2020 · 6 min read

So, right off the bat, I just want to clarify that in order to do follow the instructions below, you will need to have some experience with Google Cloud Platform, or have read my previous story here about using gcloud and Google Cloud Platform if you don’t have experience in using it yet.

The reason for this is because we will be using App Engine (a Google Cloud Platform option) to set it up and a service account.

The other thing I want to underline is that, we will only be following Google’s set-up example for now (to some degree) just to get basics ready, because in later stories, we’ll see how to change the code below to do more of what we want (everything will remain the same, and we will just edit the main.py file to make the bot do other things). So this is basically an intro to doing more complex bots in the future.

Now that we have clarified those two points, presupposing that you have everything ready in your project in Google Cloud Platform, let’s jump into a local terminal, or ssh into the terminal in your VM instance within the Compute Engine in your GCP project) where you have gcloud set up, and create a folder (name it whatever you want), then cd into it.

mkdir folhapp && cd folhapp

Now, we are going to create three files: app.yaml, requirements.txt, and main.py. All of these can be made with Vim. (If you need to see how Vim works, just take a look at my story here.)

So, starting off with vim requirements.txt , we’ll add the following and save with :x

Flask==1.1.1                                                                                                           
google-api-python-client==1.7.11
google-auth==1.6.3

Then, in vim app.yaml , we’ll add the following:

runtime: python37                                                                                                      
env_variables:
GOOGLE_APPLICATION_CREDENTIALS: KEYS.json

Where is says “KEYS”, that should be the name of the json file you got when you downloaded the json file after having created the service account and the keys in the Google Cloud Platform (see the previous story on GCP).

In this case, after we save this, we need to copy the json file that was downloaded previously into this file (or move it, whatever you like). You can use the following to do this.

cp ~/KEYS.json ~/folhapp/KEYS.json

So, in the end, we will actually have four files in this folder, not three. The reason why we did this is because we want to be able to do something with the bot which might take a bit of time (more than 5 minutes), and this will allow us to receive a message telling us it’s done, but we can only do that by using a service account, which requires us to add the json file to the folder to authenticate.

Finally, we need to create and set up the main.py file. (vim main.py). In that file we will put the following which comes from Google’s example:

import logging 
from googleapiclient.discovery import build
from flask import Flask, render_template, request, json
import google.auth
app = Flask(__name__) scopes = ['https://www.googleapis.com/auth/chat.bot']
credentials, project_id = google.auth.default()
credentials = credentials.with_scopes(scopes=scopes)
chat = build('chat', 'v1', credentials=credentials)
@app.route('/', methods=['POST'])
def home_post():
event_data = request.get_json()
resp = None
if event_data['type'] == 'REMOVED_FROM_SPACE':
logging.info('Bot removed from %s',
event_data['space']['name'])
return json.jsonify({})
resp = format_response(event_data)
space_name = event_data['space']['name']
send_async_response(resp, space_name)
return json.jsonify({})
def send_async_response(response, space_name):
chat.spaces().messages().create(
parent=space_name,
body=response).execute()
def format_response(event):
event_type = event['type']
text = ""
sender_name = event['user']['displayName']
if event_type == 'ADDED_TO_SPACE' and event['space']['type'] == 'ROOM':
text = 'Thanks for adding me to {}!'.format(event['space']['displayName'])

elif event_type == 'ADDED_TO_SPACE' and event['space']['type'] == 'DM':
text = 'Thanks for adding me to a DM, {}!'.format(sender_name)

elif event_type == 'MESSAGE':
text = 'Your message, {}: "{}"'.format(sender_name, event['message']['text'])

response = {'text': text}
if event_type == 'MESSAGE' and event['message']['thread'] is not None:
thread_id = event['message']['thread']
response['thread'] = thread_id
return response@app.route('/', methods=['GET'])
def home_get():
return render_template('home.html')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)

Once that is in the main.py file and we have saved it, we can send this up to the App Engine. I just want to underline that the code in main.py is just to make sure that this is working, because later on, we will put other code here to do some more interesting things.

After those four files are in that folder, we can now run the following (making sure we are in the folder still):

gcloud app deploy

It will ask if you want to continue, and we’ll type “y” for yes. Once you type “y” it will give you some info on the App Engine, and we need to copy the link under “target url” which we will need later.

With that all done, we now have to set up the hangouts Chat API in the project we have in GCP. For this we have to go to APIs and Services, then to Dashboard, and then scroll down and click on Hangouts Chat API (previously activated from our story on GCP).

When we are there, we need to go down and click Configuration, and then fill out the information (Bot name, Avatar URL, Description, and choose Bot URL).

(Remember, Hangouts Chat API is only available to G Suite users. those with gmail.com cannot access this.)

You can put what you want for Bot name and Description. For the Avatar URL, you will get an error if you put anything, so you’ll have to play around with that, but you can use the link https://i.imgur.com/5LvguzT.png to have something generic.

Check everything under Functionality.

Then, finally we need to put something under Bot URL:

This URL is the “target url” from the photo in black above. You can also get that from the App Engine section, under Dashboard:

Once that is pasted into the Bot URL box above, we only have one last thing to do, which is to put your email address in the section called Permissions, and then we click on SAVE.

With that, we have finished and you should be able to find your bot in the Hangouts Chat app. (https://chat.google.com/)

Now that this is active, if we want to update it, we only have to edit the main.py and then run the command gcloud app deploy again. We will play around with some other G Suite APIs in later stories, but first, we will see how to set up a Telegram Bot so we can use either one in the future.

If you want to see a video on this process, you can take a look here. Cheers.

JJ INNOVATIVE RESULTS

Tech tutorials, reviews, and reflections on innovation

Jason Jurotich

Written by

Masters in Philosophy, Author, Professor, Consultant, Tech Promoter and Programming Novice. www.jjir.org

JJ INNOVATIVE RESULTS

How can we use tech better? We’ll offer ways to hack what you use today to work better and smarter.

Jason Jurotich

Written by

Masters in Philosophy, Author, Professor, Consultant, Tech Promoter and Programming Novice. www.jjir.org

JJ INNOVATIVE RESULTS

How can we use tech better? We’ll offer ways to hack what you use today to work better and smarter.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store