Created
February 28, 2020 09:19
-
-
Save Code-Hex/d692295ce8a2cfe4eb356848994e23c9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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/webhook'); | |
| const url = process.env.SLACK_WEBHOOK_URL; | |
| const webhook = new IncomingWebhook(url); | |
| // subscribeSlack is the main function called by Cloud Functions. | |
| module.exports.subscribeSlack = (pubSubEvent, context) => { | |
| const build = eventToBuild(pubSubEvent.data); | |
| // Skip if the current status is not in the status list. | |
| // Add additional statuses to list if you'd like: | |
| // QUEUED, WORKING, SUCCESS, FAILURE, | |
| // INTERNAL_ERROR, TIMEOUT, CANCELLED | |
| const status = ['SUCCESS', 'FAILURE', 'INTERNAL_ERROR', 'TIMEOUT']; | |
| if (status.indexOf(build.status) === -1) { | |
| return; | |
| } | |
| // Send message to Slack. | |
| const message = createSlackMessage(build); | |
| webhook.send(message); | |
| }; | |
| // eventToBuild transforms pubsub event message to a build object. | |
| const eventToBuild = (data) => { | |
| return JSON.parse(Buffer.from(data, 'base64').toString()); | |
| } | |
| // createSlackMessage creates a message from a build object. | |
| const createSlackMessage = (build) => { | |
| const STATUS_COLOR = { | |
| SUCCESS: '#34A853', // green | |
| FAILURE: '#EA4335', // red | |
| TIMEOUT: '#FBBC05', // yellow | |
| INTERNAL_ERROR: '#EA4335', // red | |
| } | |
| const message = { | |
| text: 'Build logs', | |
| mrkdwn: true, | |
| attachments: [ | |
| { | |
| color: STATUS_COLOR[build.status], | |
| title: 'Build logs', | |
| title_link: build.logUrl, | |
| fields: [{ | |
| title: 'Status', | |
| value: build.status | |
| }] | |
| } | |
| ] | |
| } | |
| // Add image(s) to the message. | |
| const images = build.images || []; | |
| if (images.length) { | |
| message.attachments[0].fields.push({ | |
| title: `Image${(images.length > 1) ? 's' : ''}`, | |
| value: images.join('\n'), | |
| }); | |
| } | |
| return message; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment