|
import os |
|
import json |
|
import requests |
|
from google.oauth2 import service_account |
|
from google.auth.transport.requests import Request |
|
from googleapiclient.discovery import build |
|
|
|
|
|
service_account_info = os.getenv('GOOGLE_APPLICATION_CREDENTIALS_CONTENT') |
|
|
|
if service_account_info is None: |
|
raise ValueError("サービスアカウントのJSON内容が設定されていません。") |
|
|
|
|
|
service_account_info_dict = json.loads(service_account_info) |
|
|
|
|
|
credentials = service_account.Credentials.from_service_account_info( |
|
service_account_info_dict, |
|
scopes=['https://www.googleapis.com/auth/chat.bot'] |
|
) |
|
|
|
|
|
chat_service = build('chat', 'v1', credentials=credentials) |
|
|
|
|
|
space_name = 'spaces/AAAAv_S3Bco' |
|
|
|
|
|
initial_message = { |
|
'text': 'スレッドへ返信に変更テスト' |
|
} |
|
|
|
initial_response = chat_service.spaces().messages().create( |
|
parent=space_name, |
|
body=initial_message |
|
).execute() |
|
|
|
|
|
thread_name = initial_response['thread']['name'] |
|
print('Initial message sent. Thread name:', thread_name) |
|
|
|
return thread_name |
|
|
|
|
|
|
|
url = f'https://chat.googleapis.com/v1/{space_name}/messages?messageReplyOption=REPLY_MESSAGE_OR_FAIL' |
|
|
|
|
|
follow_up_message = { |
|
'text': 'スレッドへ返信.', |
|
'thread': { |
|
'name': thread_name |
|
} |
|
} |
|
|
|
|
|
credentials.refresh(Request()) |
|
access_token = credentials.token |
|
|
|
headers = { |
|
'Authorization': f'Bearer {access_token}', |
|
'Content-Type': 'application/json' |
|
} |
|
|
|
response = requests.post(url, headers=headers, data=json.dumps(follow_up_message)) |
|
|
|
print('Follow-up message sent:', response.json()) |
|
|