Skip to content

Instantly share code, notes, and snippets.

@gh640
Last active July 5, 2024 06:24
Show Gist options
  • Save gh640/4df1cf28bf2e1b8544487213e3fbd4fe to your computer and use it in GitHub Desktop.
Save gh640/4df1cf28bf2e1b8544487213e3fbd4fe to your computer and use it in GitHub Desktop.
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
- Python 3
- Requests (last tested with 2.31.0)
Usage:
```bash
WEBHOOK_URL='https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN' 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.
# You can generate a webhok URL in the "Apps & integrations" page of a chat space.
WEBHOOK_URL = os.environ["WEBHOOK_URL"]
def main():
# Sample 1) Send a simple text.
res = send_text(text="Hello!")
pprint(res.json())
# Sample 2) Send a card.
res = send_text_card(
title="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())
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}}
cards = [
{
"header": header,
"sections": [{"widgets": [widget]}],
},
]
return requests.post(WEBHOOK_URL, json={"cards": cards})
if __name__ == "__main__":
main()
@gh640
Copy link
Author

gh640 commented Feb 10, 2024

We need Requests PyPI package:

python -m pip install requests==2.31.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment