Skip to content

Instantly share code, notes, and snippets.

@hiroy
Last active June 12, 2019 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroy/92caabd9d7358bdfbca14dc984bc65ac to your computer and use it in GitHub Desktop.
Save hiroy/92caabd9d7358bdfbca14dc984bc65ac to your computer and use it in GitHub Desktop.
SendGridのEvent Notificationの内容をGoogle Cloud Functionsで受け取ってSlackに通知するサンプル
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);
};
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"@slack/client": "^4.12.0",
"moment": "^2.24.0"
}
}
@hiroy
Copy link
Author

hiroy commented Jun 12, 2019

あ、ランタイムは「Node.js 10(ベータ版)」で動かしてます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment