Send Google Form notification to Slack via GoogleAppScript
2022-04-15
GASThis post aims to describe how to integrate Google Form and Slack through Google App Script. The goal is that when a user submits a response to a form, the result shows up in Slack immediately.
Setup Slack App
First of all, create a Slack App and let it authorized to be allowed to send chat messages to your Slack workspace.
In this post, I'm going to use incoming-webhook, but you can use chat:write.
Activate Incoming Webhooks in https://api.slack.com/apps/
If an error message like This app is requesting permission to install a bot on your workspace, but it’s not currently configured with a bot
shows up ,you should provision a bot user into your workspace.
Presumably, Display Information
at https://api.slack.com/apps/
GAS
To send results of form submitted to Slack, use Google App Script(GAS) as I described above. For that, only Slack webhook url is needed. Besides, if you'd like to see fancy message, Block-Kit maybe the best way.
const SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/aaa/bbb/ccc"
const SPREAD_SHEET_URL = "https://docs.google.com/spreadsheets/d/xxx/";
// this function gets called every after a user submits google form
function onFormSubmit(e) {
const message = buildSlackMessageBlock(e.response.getRespondentEmail(), e.response.getItemResponses())
sendToSlack(message);
}
const sendToSlack = (body) => {
const payload = JSON.stringify(body);
const options = {
method: "POST",
contentType: "application/json",
payload,
};
return UrlFetchApp.fetch(SLACK_WEBHOOK_URL, options);
}
// using Block Kit to build message structure
const buildSlackMessageBlock = (sender, responses) => {
const text = responses.reduce((acc, input) => {
return acc.concat([`*${input.getItem().getTitle()}*: ${input.getResponse()}`])
}, []).join("\n")
return {
text: "New form submitted",
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: `from <${sender}>`
},
accessory: {
type: "button",
text: {
type: "plain_text",
text: "Open SpreadSheet",
emoji: true
},
value: "click_me_123",
url: SPREAD_SHEET_URL,
action_id: "button-action"
}
},
{
type: "section",
text: {
type: "mrkdwn",
text: text,
},
}
]
}
}
After saving the script, create a trigger to enable the script after a form submitted.
That's it!
When a user submits a form, the result should show up in Slack immediately like below.