やりたかった事
GASでGoogleChatに投稿、そのスレッドにインラインスレッドへの返信の形で追加情報をPOSTしたかった。
しかし、いくらやっても新しいスレッドへの投稿になってしまい悩んでいました。
解決方法
インラインスレッドへの返信はMessageReplyOptionを指定しないとデフォルトで無効になっていました。
webhook URLに下記の様にオプションを加える必要がありました。
&messageReplyOption=REPLY_MESSAGE_OR_FAIL
サンプルGAS
下記、サンプルのロジックです。参考になれば幸いです。
function postGoogleChat(url, message) {
var msg_json = JSON.stringify(message);
var options = {
"method" : "POST",
"contentType" : "application/json; charset=utf-8",
"payload" : msg_json
}
return UrlFetchApp.fetch(url , options);
}
function main() {
// スペースのWebhook URL
var url = "https://chat.googleapis.com/v1/spaces/xxxxxxxxxx";
// https://developers.google.com/chat/api/reference/rest/v1/spaces.messages/create?hl=ja#MessageReplyOption
// 指定しないとdefaultで新しいThreadが生成される
// インラインスレッドへの返信の場合は指定が必須
var res_swith = "&messageReplyOption=REPLY_MESSAGE_OR_FAIL";
//Googlechat投稿用のMessageを作成
var msg = {
"text" : new Date(),
}
var response = postGoogleChat(url , msg);
//Threadを取得する
var response_json = JSON.parse(response.getContentText());
var thread_name = response_json["thread"]["name"];
//インラインスレッドへの返信のMessageを作成
var thread_msg = {
"text" : "Hello!",
"thread": {
"name" : thread_name
},
}
//res_swithを付与し、Thread返信を有効化する
var thread_response = postGoogleChat(url + res_swith, thread_msg);
Logger.log(thread_response);
}