forked from GoogleCloudPlatform/nodejs-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
162 lines (147 loc) · 4.62 KB
/
index.js
File metadata and controls
162 lines (147 loc) · 4.62 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
// [START setup]
var config = require('./config.json');
var googleapis = require('googleapis');
// Get a reference to the Knowledge Graph Search component
var kgsearch = googleapis.kgsearch('v1');
// [END setup]
// [START formatSlackMessage]
/**
* Format the Knowledge Graph API response into a richly formatted Slack message.
*
* @param {string} query The user's search query.
* @param {Object} response The response from the Knowledge Graph API.
* @returns {Object} The formatted message.
*/
function formatSlackMessage (query, response) {
var entity;
// Extract the first entity from the result list, if any
if (response && response.itemListElement &&
response.itemListElement.length) {
entity = response.itemListElement[0].result;
}
// Prepare a rich Slack message
// See https://api.slack.com/docs/message-formatting
var slackMessage = {
response_type: 'in_channel',
text: 'Query: ' + query,
attachments: []
};
if (entity) {
var attachment = {
color: '#3367d6'
};
if (entity.name) {
attachment.title = entity.name;
if (entity.description) {
attachment.title = attachment.title + ': ' + entity.description;
}
}
if (entity.detailedDescription) {
if (entity.detailedDescription.url) {
attachment.title_link = entity.detailedDescription.url;
}
if (entity.detailedDescription.articleBody) {
attachment.text = entity.detailedDescription.articleBody;
}
}
if (entity.image && entity.image.contentUrl) {
attachment.image_url = entity.image.contentUrl;
}
slackMessage.attachments.push(attachment);
} else {
slackMessage.attachments.push({
text: 'No results match your query...'
});
}
return slackMessage;
}
// [END formatSlackMessage]
// [START verifyWebhook]
/**
* Verify that the webhook request came from Slack.
*
* @param {Object} body The body of the request.
* @param {string} body.token The Slack token to be verified.
*/
function verifyWebhook (body) {
if (!body || body.token !== config.SLACK_TOKEN) {
var error = new Error('Invalid credentials');
error.code = 401;
throw error;
}
}
// [END verifyWebhook]
// [START makeSearchRequest]
/**
* Send the user's search query to the Knowledge Graph API.
*
* @param {string} query The user's search query.
* @param {Function} callback Callback function.
*/
function makeSearchRequest (query, callback) {
kgsearch.entities.search({
auth: config.KG_API_KEY,
query: query,
limit: 1
}, function (err, response) {
if (err) {
return callback(err);
}
// Return a formatted message
return callback(null, formatSlackMessage(query, response));
});
}
// [END makeSearchRequest]
// [START kgSearch]
/**
* Receive a Slash Command request from Slack.
*
* Trigger this function by making a POST request with a payload to:
* https://[YOUR_REGION].[YOUR_PROJECT_ID].cloudfunctions.net/kgsearch
*
* @example
* curl -X POST "https://us-central1.your-project-id.cloudfunctions.net/kgSearch" --data '{"token":"[YOUR_SLACK_TOKEN]","text":"giraffe"}'
*
* @param {Object} req Cloud Function request object.
* @param {Object} req.body The request payload.
* @param {string} req.body.token Slack's verification token.
* @param {string} req.body.text The user's search query.
* @param {Object} res Cloud Function response object.
*/
exports.kgSearch = function kgSearch (req, res) {
try {
if (req.method !== 'POST') {
var error = new Error('Only POST requests are accepted');
error.code = 405;
throw error;
}
// Verify that this request came from Slack
verifyWebhook(req.body);
// Make the request to the Knowledge Graph Search API
makeSearchRequest(req.body.text, function (err, response) {
if (err) {
console.error(err);
return res.status(500);
}
// Send the formatted message back to Slack
return res.json(response);
});
} catch (err) {
console.error(err);
return res.status(err.code || 500).send(err.message);
}
};
// [END kgSearch]