Skip to content

Instantly share code, notes, and snippets.

@kyouheicf
Last active September 11, 2024 14:23
Show Gist options
  • Save kyouheicf/99bde6e3d43355245cc7b2636a65ce30 to your computer and use it in GitHub Desktop.
Save kyouheicf/99bde6e3d43355245cc7b2636a65ce30 to your computer and use it in GitHub Desktop.
// 権限を付与するために一度だけ実行する。
function test_Google_Chatに通知() {
notify('テストです。');
}
//Misc
function getRows_(item, type) {
if (type === 'GRID') return item.asGridItem().getRows();
if (type === 'CHECKBOX_GRID') return item.asCheckboxGridItem().getRows();
throw 'invalid type: ' + type;
}
// Google Chat Webhook URL を定義
const URL = 'https://chat.googleapis.com/v1/spaces/xx/messages?key=xx-xx&token=xx';
// Google Chat に通知するための関数定義
function notify(text) {
const response = UrlFetchApp.fetch(URL, {
method: 'post',
contentType: 'application/json; charset=UTF-8',
payload: JSON.stringify({ text }),
});
}
// フォーム送信時のトリガーにこの関数を設定する
function onFormSubmit(e) {
const items = {};
e.response.getItemResponses().forEach(itemResponse => {
const item = itemResponse.getItem();
const response = itemResponse.getResponse();
const type = item.getType().toString();
if (type.includes('GRID')) {
const rows = getRows_(item, type);
const grid = {};
for (let i = 0; i < rows.length; i++) {
grid[rows[i]] = response[i];
}
items[item.getTitle()] = grid;
} else {
items[item.getTitle()] = response;
}
});
// Google Workspace だとフォームを送信した人のメールアドレスを取得できる。
handleResponse_(items, e.response.getEditResponseUrl(), e.response.getRespondentEmail());
}
// メイン処理。ログ出力 + フォーム送信イベントを処理(Google Chatに通知)
function handleResponse_(items, url, email) {
console.log(JSON.stringify(items, null, 2));
console.log(url);
console.log(email);
const text = JSON.stringify(items, null, 2);
notify(text);
}
// フォーム送信イベントを処理(Google Chatに通知)
function handleResponse2_(items) {
const text2 = JSON.stringify(items, null, 2);
console.log(text2);
notify(text2);
}
// Google Chatへ通知するテスト
function testNotify() {
const items = {
"email": "[email protected]",
"氏名": "ほげほげ ふがふが",
"種別": "業務開始",
"時刻": "9:00"
};
handleResponse2_(items);
}
// Ref.
// Googleフォームで送信されたデータを使いやすいJSONに変換する #GoogleAppsScript - Qiita
//https://qiita.com/takatama/items/d5ae76811ff96f34114b
// GoogleフォームからApps Scriptを呼び出す方法は2つある #GoogleAppsScript - Qiita
//https://qiita.com/takatama/items/0d67609b9332c550b9d2
//GoogleフォームからGoogle Chatに通知!動かして学ぶApps Scriptの使い方 - BIGLOBE Style | BIGLOBEの「はたらく人」と「トガッた技術」
//https://style.biglobe.co.jp/entry/2024/05/29/100000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment