Googleフォームに回答があった場合、Chatworkに回答内容を送信するGAS(Google Apps Script)の作り方です。
送信元のGoogleフォームにスクリプトを書く
Googleフォームの設定からスクリプトエディタを開きます。
最初のコードを消して、以下のスクリプトをコピペします。
/** ChatworkのAPIトークン */
const CHATWORK_API_TOKEN = "ChatworkのAPIトークンを設定します";
/** ChatworkのルームID */
const CHATWORK_ROOM_ID = "送信したいChatworkのルームIDを設定します";
/**
* Googleフォームの回答があったときに実行される関数
*/
function onFormSubmit() {
const message = buildChatworkMessage();
sendToChatwork(message);
}
/**
* 最新のフォーム回答からChatwork用のメッセージを作成する
* @return {string} Chatwork用のメッセージ
*/
function buildChatworkMessage() {
const form = FormApp.getActiveForm();
const latestResponse = form.getResponses().pop(); // 最後の回答のみ取得
const items = latestResponse.getItemResponses();
let message = "[info][title]Googleフォームに回答が届きました[/title]\n";
items.forEach((item) => {
const response = item.getResponse();
const responseText = Array.isArray(response)
? response.join(", ")
: String(response);
message += `${item.getItem().getTitle()}:${responseText}\n`;
});
message += "[/info]";
return message;
}
/**
* Chatworkにメッセージを送信する
*
* @param {string} message 送信するメッセージ
*/
function sendToChatwork(message) {
Logger.log(`Chatworkに送信するメッセージ:${message}`);
const url = `https://api.chatwork.com/v2/rooms/${CHATWORK_ROOM_ID}/messages`;
const options = {
method: "POST",
headers: { "X-ChatWorkToken": CHATWORK_API_TOKEN },
payload: { body: message },
};
try {
const response = UrlFetchApp.fetch(url, options);
const statusCode = response.getResponseCode();
const responseText = response.getContentText();
Logger.log(`Chatwork APIのレスポンス:${statusCode} ${responseText}`);
} catch (error) {
Logger.log(`Chatwork APIの送信に失敗しました:${error}`);
}
}
ついでにプロジェクト名やファイル名を変更しておくと後から分かりやすいです。
スクリプトの設定を行う
- ChatworkのAPIトークン
- 送信するCahtworkのルームID
Chatwork APIトークンの取得
ルームIDを取得
送信したいチャットを開いて、ルームIDを取得します。
画面右上の設定マーク>グループチャットの設定>ルームIDから確認できます。
トリガーの設定
Googleフォーム送信時にスクリプトが動くようにトリガーを設定します。
以下の設定で保存します。
イベントの種類は「フォーム送信時」に変更します。
Googleフォームを送信すると、Chatworkに内容が送信される
ここまでの設定をすると、フォームに回答があった場合にChatworkへ内容が送信されるようになります。