From 53a3f185e589fad05a6a107f68d177426a41e21e Mon Sep 17 00:00:00 2001 From: Brayden Wilmoth Date: Tue, 4 Feb 2025 12:55:38 -0500 Subject: [PATCH] Slack plugin for sending messages to webhooks --- plugins/slack/README.md | 43 +++++++++++++++++++++++++++++++++++++++++ plugins/slack/index.ts | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 plugins/slack/README.md create mode 100644 plugins/slack/index.ts diff --git a/plugins/slack/README.md b/plugins/slack/README.md new file mode 100644 index 0000000..6c287fb --- /dev/null +++ b/plugins/slack/README.md @@ -0,0 +1,43 @@ +## Usage + +````typescript +const slackPlugin = new SlackPlugin({ + webhookUrl: 'https://hooks.slack.com/services/SCRIBBLESCRIBBLESCRIBBLE', +}) +const cdcPlugin = new ChangeDataCapturePlugin({ + stub, + broadcastAllEvents: true, + events: [], +}) + +cdcPlugin.onEvent(({ action, schema, table, data }) => { + ctx.waitUntil( + slackPlugin.sendMessage({ + blocks: [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: `${action} detected on ${table}`, + }, + }, + { + type: 'section', + text: { + type: 'mrkdwn', + text: 'The following data was associated with this action:', + }, + }, + { + type: 'section', + block_id: 'section_1', + text: { + type: 'mrkdwn', + text: '```' + `${JSON.stringify(data)}` + '```', + }, + }, + ], + }) + ) +}) +```` diff --git a/plugins/slack/index.ts b/plugins/slack/index.ts new file mode 100644 index 0000000..ea3b986 --- /dev/null +++ b/plugins/slack/index.ts @@ -0,0 +1,43 @@ +import { StarbasePlugin } from '../../src/plugin' + +export class SlackPlugin extends StarbasePlugin { + // Prefix route + prefix: string = '/slack' + // Webhook URL to call to Slack + webhookUrl?: string + + constructor(opts?: { webhookUrl: string }) { + super('starbasedb:slack', { + requiresAuth: true, + }) + + this.webhookUrl = opts?.webhookUrl + } + + public async sendMessage(message: { text?: string; blocks?: any[] }) { + if (!this.webhookUrl) { + throw new Error(`Slack webhook URL was not provided.`) + } + + try { + const response = await fetch(this.webhookUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(message), + }) + + if (!response.ok) { + throw new Error( + `Failed to send Slack message: ${response.statusText}` + ) + } + + return response + } catch (error) { + console.error('Error sending Slack message:', error) + throw error + } + } +}