Incoming webhook with Python

Complete the steps described in the rest of this page, and in about fifteen minutes you'll have created a Hangouts Chat bot that sends messages to a Hangouts Chat room. This quickstart uses a simple Python script that sends HTTP requests to an incoming webhook registered to a Hangouts Chat room.

Prerequisites

To run this quickstart, you need:

  • Python 2.6 or greater.
  • A Google account.
  • An existing Hangouts Chat room.

Step 1: Register the incoming webhook

  1. Open Hangouts Chat in your browser.
  2. Go to the room to which you want to add a bot.
  3. From the menu at the top of the page, select Configure webhooks.
  4. Under Incoming Webhooks, click ADD WEBHOOK.
  5. Name the new webhook 'Quickstart Webhook' and click SAVE.
  6. Copy the URL listed next to your new webhook in the Webhook Url column.
  7. Click outside the dialog box to close.

Step 2: Create the Python script

Create a file named quickstart.py in your working directory and copy the following code:

from httplib2 import Http
from json import dumps

#
# Hangouts Chat incoming webhook quickstart
#
def main():
    url = '<INCOMING-WEBHOOK-URL>'
    bot_message = {
        'text' : 'Hello from Python script!'}

    message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}

    http_obj = Http()

    response = http_obj.request(
        uri=url,
        method='POST',
        headers=message_headers,
        body=dumps(bot_message),
    )

    print(response)

if __name__ == '__main__':
    main()

Be sure to replace the value for the url variable in the code snippet with the URL provided to you by Hangouts Chat when you registered the incoming webhook. (If you need to find the URL again, go to the Hangouts Chat room, select Configure webhooks, and then copy the URL associated with your new incoming webhook in the Webhook Url column.)

Step 3: Run the sample

Run the sample by running the following command from your working directory:

$ python3 quickstart.py

Further reading

Troubleshooting

403: The caller does not have permission

Incoming webhooks for rooms will fail with this error if not all users in your domain have bots enabled. See the webhooks documentation for more information.

Send feedback about...

Hangouts Chat API
Hangouts Chat API
Need help? Visit our support page.