Last active
June 12, 2019 12:45
-
-
Save hiroy/92caabd9d7358bdfbca14dc984bc65ac to your computer and use it in GitHub Desktop.
SendGridのEvent Notificationの内容をGoogle Cloud Functionsで受け取ってSlackに通知するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { IncomingWebhook } = require('@slack/client'); | |
const moment = require('moment'); | |
// SLACK_INCOMING_WEBHOOK_URL と | |
// SECRET_QUERY_TOKEN を環境変数で設定、 | |
// SendGrid の HTTP POST URL には | |
// ?token= で SECRET_QUERY_TOKEN に設定した値を | |
// トリガーのURLに付けたものを設定すること | |
async function sendNotification(message) { | |
const url = process.env.SLACK_INCOMING_WEBHOOK_URL; | |
const slackIncomingWebhook = new IncomingWebhook(url); | |
return await slackIncomingWebhook.send({ | |
text: message | |
}); | |
} | |
exports.receiveAndNotify = async (req, res) => { | |
if (req.query.token !== process.env.SECRET_QUERY_TOKEN) { | |
res.status(200).send('Invalid token.'); | |
return; | |
} | |
let message = ''; | |
for (const data of req.body) { | |
const dt = moment(data.timestamp * 1000).toISOString(); | |
message = message | |
+ `[${data.event}]\n` | |
+ `- email: ${data.email}\n` | |
+ `- category: ${data.category}\n`; | |
if (data.event === 'bounce' || data.event === 'dropped') { | |
message += `- reason: ${data.reason}\n`; | |
} | |
message = message | |
+ `- sg_event_id: ${data.sg_event_id}\n` | |
+ `- timestamp: ${dt}\n\n`; | |
} | |
await sendNotification(message); | |
res.status(200).send(message); | |
}; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "sample-http", | |
"version": "0.0.1", | |
"dependencies": { | |
"@slack/client": "^4.12.0", | |
"moment": "^2.24.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
あ、ランタイムは「Node.js 10(ベータ版)」で動かしてます。