Alex
Alex

Reputation: 44305

How to send a message to google hangouts with python?

I am trying to create a simple "chat bot" for google hangouts that sends regular messages on a chat. I found this documentation but I find it tremendously complicated.

It contains a "Complete example" but I am not sure about how to find the "space" ID for an existing google hangout chat. This is nowhere explained. How do I find the "space" ID for an existing google chat?

And in addition: Is there a SIMPLE (!!!) documentation somewhere how to just simply post a message to an existing chat?

Upvotes: 2

Views: 15687

Answers (1)

Rafa Guillermo
Rafa Guillermo

Reputation: 15357

Answer:

You can either use spaces.list to get a list of spaces the bot is a member of followed by spaces.get for additional information on the space, or alternatively set up a room-specific Webhook.

Additional Information:

  • To send messages to a room without a respond trigger, you must use a service account
  • Bot-initiated message documentation can be found here.

Important Note: You can only use the Google Hangouts Chat API if you have a Google Workspace account - it will not work with Gmail alone. The second solution, which uses a Webhook, requires access to https://chat.google.com which is only available to Google Workspace domains. Unfortunately this is not at all possible using a consumer @gmail.com account.

Using the Hangouts Chat API:

Once you have a service account set up as per Step 1 on this page, you can download the credentials for the service account from the Google Cloud Project UI, by clicking on the button to the right of the service account name, and following the Create key button and selecting JSON as the key type. Make sure to save this file well as there is only one copy of this key.

With this JSON file downloaded, you can use it in your python code as the credentials when setting up your service object:

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

scopes = 'https://www.googleapis.com/auth/chat.bot'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'credentials.json', scopes)

chat_service = build('chat', 'v1', http=credentials.authorize(Http()))

To make the spaces.list request, you can use this newly built chat_service, and extract hte list of spaces from the response:

def extract(n):
    return n['name']

spaces_list = chat_service.spaces().list().execute()
all_spaces = map(extract, spaces_list['spaces'])

You can then use one of these spaces to send a message from the python program:

response = chat_service.spaces().messages().create(
    parent=all_spaces[0],
    body={'text': 'Test message'}).execute()
print(response)

Things to Remember:

  • Make sure the Hangouts Chat API is enabled for your project at https://console.cloud.google.com
  • Once enabled, make sure the bot is configured with a name, logo and description.
  • The Connection settings for the bot must also be set up; the method is not so important; you can for example choose Apps Script project and enter the deployment ID for an empty deployed project.

Using a Webhook:

Instead of directly using the API, you can instead set up a webhook for a specific chat and with a hardcoded URL, you can send messages to a room from an external script.

The full steps are set out on this page but I'll go through it here also.

Go to the room to which you wish to send a message at https://chat.google.com, and from the dropdown menu next to the room's name, select Manage Webhooks.

Enter a name and an optional avatar for your bot, and press SAVE. This will give you a webhook URL to use in your python script.

Locally, make sure you have httplib2 installed in your environment, and copy the following script into a new .py file:

from json import dumps
from httplib2 import Http

def main():
    """Hangouts Chat incoming webhook quickstart."""
    url = 'webhook-url'
    bot_message = {
        'text' : 'Hello from a 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()

Manking sure to replace the webhook-url string with the webhook provided in the Chat UI in the previous step.

Now you can just save the file and run it - this will send a message automatically to the aforementioned chat space:

enter image description here

References:

Upvotes: 8

Related Questions