Last active
October 16, 2024 10:33
-
-
Save gh640/4df1cf28bf2e1b8544487213e3fbd4fe to your computer and use it in GitHub Desktop.
Sample: Send a message on Google Chat group with Python `requests`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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() |
We need Requests PyPI package:
python -m pip install requests==2.31.0
is it possible to send an interactive message in the google chat space using the python requests module, I know there's a google chat API to do the same but my requirement isn't that much, just a very little one where I can send an interactive message to the google chat space and later retrieve the details user has submitted.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simpler versions:
simple_text.py
:card.py
: