Python - Send a message to Google chat space

Steps

  1. End result. A message on chat space.

  2. Open chat https://mail.google.com/chat/u/0/ and create a new space.

  3. Enter a new space name. eg) Demo

  4. Click dropdown arrow on the space. eg) Demo and select Manage webhooks

  5. Copy a webhook address.

  6. Create a new python file and paste below code. Update url to the webhook. eg) demo.py

    #  https://developers.google.com/chat/quickstart/incoming-bot-python
    from json import dumps
    
    from httplib2 import Http
    
    
    def main():
        """Hangouts Chat incoming webhook quickstart."""
        url = '<INCOMING-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()
    
  7. Run demo.py. Ctrl + F5 or Right click >> "Run Python File in Terminal" within VS Code.

Github

taeheechoi © 2023