Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample: Send a message on Google Chat group with Python `requests`
"""A sample to send message on Google Chat group with Python requests.
Prerequisites:
- Google API v1
- A webhook URL taken
Usage:
```bash
WEBHOOK_URL='https://chat.googleapis.com/v1/spaces/AAAAdOUcFZM/messages?key=xxx&token=xxx' python send_message_on_google_chat.py
```
Ref:
- https://developers.google.com/hangouts/chat/quickstart/incoming-bot-python
- https://developers.google.com/hangouts/chat/reference/message-formats
"""
import os
from pprint import pprint
import requests
from requests.models import Response
# You need to pass WEBHOOK_URL as an environment variable.
WEBHOOK_URL = os.environ['WEBHOOK_URL']
def main():
# res = send_text(text='Hello!')
res = send_text_card(
text='Hey!',
subtitle='You!',
paragraph='<b>Roses</b> are <font color=\"#ff0000\">red</font>,<br><i>Violets</i> are <font color=\"#0000ff\">blue</font>',
)
pprint(res.json())
pass
def send_text(text: str) -> Response:
return requests.post(WEBHOOK_URL, json={'text': text})
def send_text_card(title: str, subtitle: str, paragraph: str) -> Response:
header = {
'title': title,
'subtitle': subtitle,
}
widget = {'textParagraph': {'text': paragraph}}
return requests.post(
WEBHOOK_URL,
json={
'cards': [
{
'header': header,
'sections': [{'widgets': [widget]}],
}
]
},
)
if __name__ == '__main__':
main()
@gh640

This comment has been minimized.

Copy link
Owner Author

@gh640 gh640 commented Apr 25, 2021

Simpler versions:

simple_text.py:

import os

import requests

WEBHOOK_URL = os.environ['WEBHOOK_URL']

text = 'Hello.'
res = requests.post(WEBHOOK_URL, json={'text': text})
print(res.json())

card.py:

import os

import requests

WEBHOOK_URL = os.environ['WEBHOOK_URL']

title = 'Hi'
subtitle = 'Hello'
paragraph = 'Hasta La Vista, Baby.'
widget = {'textParagraph': {'text': paragraph}}
res = requests.post(
    WEBHOOK_URL,
    json={
        'cards': [
            {
                'header': {
                    'title': title,
                    'subtitle': subtitle,
                },
                'sections': [{'widgets': [widget]}],
            }
        ]
    },
)
print(res.json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment