forked from markfguerra/google-forms-to-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.js
100 lines (78 loc) · 2.48 KB
/
code.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// This Google Sheets script will post to a slack channel when a user submits data to a Google Forms Spreadsheet
// View the README for installation instructions. Don't forget to add the required slack information below.
// Source: https://github.com/markfguerra/google-forms-to-slack
/////////////////////////
// Begin customization //
/////////////////////////
// Alter this to match the incoming webhook url provided by Slack
var slackIncomingWebhookUrl = 'https://hooks.slack.com/services/YOUR-URL-HERE';
// Include # for public channels, omit it for private channels
var postChannel = "YOUR-CHANNEL-HERE";
var postIcon = ":mailbox_with_mail:";
var postUser = "Form Response";
var postColor = "#0000DD";
var messageFallback = "The attachment must be viewed as plain text.";
var messagePretext = "A user submitted a response to the form.";
///////////////////////
// End customization //
///////////////////////
// TODO Set up triggers programmatically
// Trigger this on Form Submit
function submitValuesToSlack(e) {
// Test code. uncomment to debug in Google Script editor
// if (typeof e === "undefined") {
// e = {namedValues: {"Question1": ["answer1"], "Question2" : ["answer2"]}};
// messagePretext = "Debugging our Sheets to Slack integration";
// }
var attachments = constructAttachments(e.namedValues);
var payload = {
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"attachments": attachments
};
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
var constructAttachments = function(namedValues) {
var fields = makeFields(namedValues);
var attachments = [{
"fallback" : messageFallback,
"pretext" : messagePretext,
"mrkdwn_in" : ["pretext"],
"color" : postColor,
"fields" : fields
}]
return attachments;
}
var makeFields = function(namedValues) {
var fields = [];
var keys = getKeys(namedValues);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = namedValues[key][0];
fields.push(makeField(key, value));
}
return fields;
}
var makeField = function(question, answer) {
var field = {
"title" : question,
"value" : answer,
"short" : false
};
return field;
}
var getKeys = function(namedValues) {
var keys = [];
for (var key in namedValues) {
if (namedValues.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}