Lambda API GatewayでSlack webhookを分岐させる
Slack通知先が1個しか設定できないけれど、通知したいチャネルが別の時ありますよね?
こんな感じでLambdaとAPI Gatewayをつなげます
Lambdaのサンプルコードはこんな具合で、中身を見てチャンネルを振り分けるだけをやってる。
// MEMO:このwebhookはSaaS => Slackの通知のチャンネル分岐をする
const https = require('https');
const CHANNEL_1 = '/services/XXXXXX/YYYYYY/1';
const CHANNEL_2 = '/services/XXXXXX/YYYYYY/2';
const getWebhookPath = (body) => {
try {
// MEMO:payloadの細かいフィールド定義はドキュメント参照
// https://api.slack.com/reference/messaging/payload
return (JSON.parse(body).attachments[0].footer.includes('LINE')) ? CHANNEL_1 : CHANNEL_2;
} catch (e) {
console.log(e);
return CHANNEL_1;
}
}
const doPostRequest = (body) => {
return new Promise((resolve, reject) => {
const path = getWebhookPath(body);
const options = {
host: 'hooks.slack.com',
path: path,
port: 443,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
const req = https.request(options, (res) => {
resolve(JSON.stringify(res.statusCode));
});
req.on('error', (e) => {
reject(e.message);
});
req.write(body);
req.end();
});
};
exports.handler = async (event) => {
await doPostRequest(event.body)
.then(result => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*"
}
};
return response;
})
.catch(err => console.error(`Error doing the request for the event: ${JSON.stringify(event)} => ${err}`));
};
webhookはPOSTなので、CORSの設定が必要だからそこだけ注意
この記事が気に入ったらサポートをしてみませんか?