Skip to content

Instantly share code, notes, and snippets.

@alazycoder101
Created July 11, 2024 12:33
Show Gist options
  • Save alazycoder101/74c7a890223237a53c21bcb1b9e4ef01 to your computer and use it in GitHub Desktop.
Save alazycoder101/74c7a890223237a53c21bcb1b9e4ef01 to your computer and use it in GitHub Desktop.
const { IncomingWebhook } = require('@slack/webhook');
const url = process.env.SLACK_WEBHOOK_URL;
const webhook = new IncomingWebhook(url);
// Optionally filter what notification types to forward to Slack.
// If empty, all types will be allowed.
const allowedTypeURLs = [];
// slackNotifier is the main function called by Cloud Functions
module.exports.slackNotifier = (pubSubEvent, context) => {
const data = decode(pubSubEvent.data);
// Send message to Slack.
if (isAllowedType(pubSubEvent.attributes)) {
const message = createSlackMessage(data, pubSubEvent.attributes);
webhook.send(message);
}
};
// decode decodes a pubsub event message from base64.
const decode = (data) => {
return Buffer.from(data, 'base64').toString();
}
// isAllowedType can be used to filter out messages that don't match the
// allowed type URLs. If allowedTypeURLs is empty, it allows all types.
const isAllowedType = (attributes) => {
if (allowedTypeURLs.length == 0) {
return true;
}
for (var x in allowedTypeURLs) {
if (attributes['type_url'] == allowedTypeURLs[x]) {
return true;
}
}
return false;
}
// createSlackMessage creates a message from a data object.
const createSlackMessage = (data, attributes) => {
// Write the message data and attributes.
text = `${data}`
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) {
text = text + `\n\t\`${key}: ${attributes[key]}\``
}
}
const message = {
text: text,
mrkdwn: true,
};
return message;
}
{
"name": "gke-slack",
"version": "0.0.1",
"description": "Slack integration for GKE, using Cloud Functions",
"main": "index.js",
"dependencies": {
"@slack/webhook": "5.0.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment