Cloud Functions 实战 – Slack Slash Command
这篇文章将带您探讨如何使用Cloud Functions 实践Slack Slash Command,并与Google Knowledge Graph API 做整合。
流程解说
1.使用者在Slack频道当中执行/kg <想要搜寻的内容> Slash command
2. Slack发送带有payload的讯息至Cloud Functions endpoint 3. Cloud Functions发送带有使用者Query的请求至Knowledge Graph API 4 . Knowledge Graph API回传请求之讯息5. Cloud Functions把要回传之讯息打包成Slack的格式6. Cloud Functions回传讯息以及图片7.使用者看到回传结果
准备(API密钥+松弛令牌)
1.进入到APIs & Services
2.点选Create Credentials的API Key,创建一个API Key
3.创建完API KEY之后到Dashborad启用Knowledge Graph API Key
4.进入到所属Slack的Custom Integration页面https://xxxxx .slack.com/apps/manage/custom-integrations并点选Slash Commands
5.点选左边的Add Configuration
6. Choose a command栏位当中填入/kg后送出
7.送出后,请至页面下方的URL填入以下讯息(或是可以部署完Cloud Functions再填写)
//[YOUR_REGION]為使用者部署 Cloud Functions 的 Region
//[YOUR_PROJECT_ID]為使用者的 Project ID
https://[YOUR_REGION]-[YOUR_PROJECT_ID].cloudfunctions.net/kgSearch
8. 回到终端机并创建一个资料夹
$ mkdir ~/gcf_slack
$ cd ~/gcf_slack
部署到 Cloud Functions
- 下载GCP的Node.js sample
- 进到/nodejs-docs-samples/functions/helloworld/,把index.js 跟package.json 复制到刚刚的资料夹
- 创建一个档案config.json,并填入以下资讯
{ "SLACK_TOKEN": "[YOUR_SLACK_TOKEN]", //[YOUR_SLACK_TOKEN] 在創立完 Slash command 之後,頁面下方產生的 Token "KG_API_KEY": "[YOUR_KG_API_KEY]" //[YOUR_KG_API_KEY] APIs & Service 裡剛剛創立的 Key value } - 进到index.js,删除所有内容并加入以下程式
const config = require('./config.json'); const googleapis = require('googleapis'); const kgsearch = googleapis.kgsearch('v1'); //當發一個 HTTP POST請求給 Cloud Functions 時會觸發 exports.kgSearch = (req, res) => { return Promise.resolve() .then(() => { if (req.method !== 'POST') { const 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 return makeSearchRequest(req.body.text); }) .then((response) => { // Send the formatted message back to Slack res.json(response); }) .catch((err) => { console.error(err); res.status(err.code || 500).send(err); return Promise.reject(err); }); }; // 驗證 Slack token function verifyWebhook (body) { if (!body || body.token !== config.SLACK_TOKEN) { const error = new Error('Invalid credentials'); error.code = 401; throw error; } } //把使用者的請求發送給 Knowledge Graph API function makeSearchRequest (query) { return new Promise((resolve, reject) => { kgsearch.entities.search({ auth: config.KG_API_KEY, query: query, limit: 1 }, (err, response) => { console.log(err); if (err) { reject(err); return; } // Return a formatted message resolve(formatSlackMessage(query, response)); }); }); } //把資料轉換成 Slack 可以顯示的格式 function formatSlackMessage (query, response) { let entity; // Extract the first entity from the result list, if any if (response && response.itemListElement && response.itemListElement.length > 0) { entity = response.itemListElement[0].result; } // Prepare a rich Slack message // See https://api.slack.com/docs/message-formatting const slackMessage = { response_type: 'in_channel', text: `Query: ${query}`, attachments: [] }; if (entity) { const 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; } - 进入到package.json,在dependencies 区块加入以下内容
"googleapis": "^19.0.0", -
$ gcloud beta functions deploy kgSearch --trigger-http测试
1. 执行以下指令进行测试
//[YOUR_REGION]為使用者部署 Cloud Functions 的 Region
//[YOUR_PROJECT_ID]為使用者的 Project ID
//[YOUR_SLACK_TOKEN]為Slack的使用 Token
$ curl -X POST "https://[YOUR_REGION]-[YOUR_PROJECT_ID].cloudfunctions.net/kgSearch" -H "Content-Type: application/json" --data '{"token":"[YOUR_SLACK_TOKEN]","text":"giraffe"}' -k
2. 查看Log 是否成功执行
$ gcloud beta functions logs read --limit 20
3. 在Slack 的任一频道送出以下内容,成功送出会显示长颈鹿的图片
/kg giraffe
清空资讯
1. 删除Cloud Functions 上的资讯
$ gcloud beta functions delete kgSearch
2. Disable 或是删除刚刚的Slash command
( 原文翻译Google Cloud。)

QQ咨询
旺旺咨询