|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +# [START chat_webhook_thread] |
| 17 | +from json import dumps |
| 18 | +from httplib2 import Http |
| 19 | + |
| 20 | +# Copy the webhook URL from the Chat space where the webhook is registered. |
| 21 | +# The values for SPACE_ID, KEY, and TOKEN are set by Chat, and are included |
| 22 | +# when you copy the webhook URL. |
| 23 | +# |
| 24 | +# Then, append messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD to the |
| 25 | +# webhook URL. |
| 26 | + |
| 27 | + |
| 28 | +def main(): |
| 29 | + """Google Chat incoming webhook that starts or replies to a message thread.""" |
| 30 | + url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD" |
| 31 | + app_message = { |
| 32 | + "text": "Hello from a Python script!", |
| 33 | + # To start a thread, set threadKey to an arbitratry string. |
| 34 | + # To reply to a thread, specify that thread's threadKey value. |
| 35 | + "thread": { |
| 36 | + "threadKey": "THREAD_KEY_VALUE" |
| 37 | + }, |
| 38 | + } |
| 39 | + message_headers = {"Content-Type": "application/json; charset=UTF-8"} |
| 40 | + http_obj = Http() |
| 41 | + response = http_obj.request( |
| 42 | + uri=url, |
| 43 | + method="POST", |
| 44 | + headers=message_headers, |
| 45 | + body=dumps(app_message), |
| 46 | + ) |
| 47 | + print(response) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + main() |
| 52 | +# [END chat_webhook_thread] |
0 commit comments