Skip to content

Instantly share code, notes, and snippets.

@Gromina
Created December 3, 2021 12:07
Show Gist options
  • Save Gromina/ea1dd51024abeaa72b94945b48cd285d to your computer and use it in GitHub Desktop.
Save Gromina/ea1dd51024abeaa72b94945b48cd285d to your computer and use it in GitHub Desktop.
// Original Source: https://github.com/markfguerra/google-forms-to-slack
/////////////////////////
// Begin customization //
/////////////////////////
// Alter this to match the incoming webhook url provided by Slack
var slackIncomingWebhookUrl = 'Put your webhook url here';
// In the Script Editor, run initialize() at least once to make your code execute on form submit
function initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("submitValuesToSlack")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
var attachments = constructAttachments(e.values);
var payload = {
"fields": attachments["fields"][2]["value"], // put your field here
};
var options = {
'method': 'post',
'payload': JSON.stringify(payload),
'contentType': 'application/json',
};
console.log(attachments);
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
// Creates Slack message attachments which contain the data from the Google Form
// submission, which is passed in as a parameter
// https://api.slack.com/docs/message-attachments
var constructAttachments = function(values) {
var fields = makeFields(values);
var attachments = {
"fields" : fields
}
return attachments;
}
// Creates an array of Slack fields containing the questions and answers
var makeFields = function(values) {
var fields = [];
var columnNames = getColumnNames();
for (var i = 0; i < columnNames.length; i++) {
var colName = columnNames[i];
var val = values[i];
fields.push(makeField(colName, val));
}
return fields;
}
// Creates a Slack field for your message
// https://api.slack.com/docs/message-attachments#fields
var makeField = function(question, answer) {
var field = {
"title" : question,
"value" : answer,
"short" : false
};
return field;
}
// Extracts the column names from the first row of the spreadsheet
var getColumnNames = function() {
var sheet = SpreadsheetApp.getActiveSheet();
// Get the header row using A1 notation
var headerRow = sheet.getRange("1:1");
// Extract the values from it
var headerRowValues = headerRow.getValues()[0];
return headerRowValues;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment