Shell
/**
* Slack Alert Integration
* Sends notifications when high-value threads or insights are found
*/
import { execFileNoThrow } from '../utils/execFileNoThrow.js';
import type { GoldmineScore, MarketInsight } from '../types.js';
export interface SlackConfig {
webhookUrl: string;
channel?: string;
username?: string;
iconEmoji?: string;
minGoldmineScore?: number;
}
interface SlackMessage {
text?: string;
blocks?: SlackBlock[];
channel?: string;
username?: string;
icon_emoji?: string;
}
interface SlackBlock {
type: string;
text?: { type: string; text: string; emoji?: boolean };
fields?: Array<{ type: string; text: string }>;
elements?: Array<{ type: string; text: string }>;
}
/**
* Send a message to Slack
*/
async function sendSlackMessage(webhookUrl: string, message: SlackMessage): Promise<boolean> {
const result = await execFileNoThrow('curl', [
'-s',
'-X', 'POST',
'-H', 'Content-Type: application/json',
'-d', JSON.stringify(message),
webhookUrl
]);
return result.status === 'success' && result.stdout === 'ok';
}
/**
* Format a goldmine thread for Slack
*/
function formatThreadAlert(thread: GoldmineScore): SlackMessage {
return {
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: 'π High-Value Thread Found!',
emoji: true
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*<${thread.url}|${thread.title.slice(0, 100)}${thread.title.length > 100 ? '...' : ''}>*`
}
},
{
type: 'section',
fields: [
{ type: 'mrkdwn', text: `*Subreddit:*\nr/${thread.subreddit}` },
{ type: 'mrkdwn', text: `*Goldmine Score:*\n${thread.goldmineScore}` },
{ type: 'mrkdwn', text: `*Post Score:*\n${thread.score} pts` },
{ type: 'mrkdwn', text: `*Comments:*\n${thread.numComments}` }
]
},
{
type: 'context',
elements: [
{ type: 'mrkdwn', text: `Upvote ratio: ${Math.round(thread.upvoteRatio * 100)}%` }
]
}
]
};
}
/**
* Format market insights for Slack
*/
function formatInsightAlert(insight: MarketInsight, threadTitle: string): SlackMessage {
const blocks: SlackBlock[] = [
{
type: 'header',
text: {
type: 'plain_text',
text: 'π New Market Insights Extracted!',
emoji: true
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*Thread:* <${insight.threadUrl}|${threadTitle.slice(0, 80)}...>\n*Summary:* ${insight.summary}`
}
}
];
// Pain points
if (insight.painPoints.length > 0) {
blocks.push({
type: 'section',
text: {
type: 'mrkdwn',
text: `*π΄ Pain Points (${insight.painPoints.length}):*\n${insight.painPoints.slice(0, 3).map(p => `β’ ${p.description}`).join('\n')}`
}
});
}
// Opportunities
if (insight.opportunities.length > 0) {
blocks.push({
type: 'section',
text: {
type: 'mrkdwn',
text: `*π‘ Opportunities (${insight.opportunities.length}):*\n${insight.opportunities.slice(0, 3).map(o => `β’ [${o.confidence}] ${o.description}`).join('\n')}`
}
});
}
// Buying signals
if (insight.buyingSignals.length > 0) {
blocks.push({
type: 'section',
text: {
type: 'mrkdwn',
text: `*π° Buying Signals (${insight.buyingSignals.length}):*\n${insight.buyingSignals.slice(0, 2).map(s => `β’ "${s.quote.slice(0, 100)}..."`).join('\n')}`
}
});
}
return { blocks };
}
/**
* Format scan summary for Slack
*/
function formatScanSummary(stats: {
threadsScanned: number;
insightsFound: number;
topThreads: GoldmineScore[];
duration: number;
}): SlackMessage {
return {
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: 'β
Scan Cycle Complete',
emoji: true
}
},
{
type: 'section',
fields: [
{ type: 'mrkdwn', text: `*Threads Scanned:*\n${stats.threadsScanned}` },
{ type: 'mrkdwn', text: `*Insights Found:*\n${stats.insightsFound}` },
{ type: 'mrkdwn', text: `*Duration:*\n${Math.round(stats.duration / 1000)}s` },
{ type: 'mrkdwn', text: `*Top Score:*\n${stats.topThreads[0]?.goldmineScore || 'N/A'}` }
]
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*Top Threads:*\n${stats.topThreads.slice(0, 3).map((t, i) => `${i + 1}. <${t.url}|${t.title.slice(0, 50)}...>`).join('\n')}`
}
}
]
};
}
/**
* Slack Alert Manager
*/
export class SlackAlerts {
private config: SlackConfig;
constructor(config: SlackConfig) {
this.config = {
minGoldmineScore: 25,
username: 'Reddit Research Agent',
iconEmoji: ':mag:',
...config
};
}
/**
* Alert on high-value thread
*/
async alertThread(thread: GoldmineScore): Promise<boolean> {
if (thread.goldmineScore < (this.config.minGoldmineScore || 25)) {
return false;
}
const message = formatThreadAlert(thread);
message.username = this.config.username;
message.icon_emoji = this.config.iconEmoji;
if (this.config.channel) {
message.channel = this.config.channel;
}
return sendSlackMessage(this.config.webhookUrl, message);
}
/**
* Alert on new insights
*/
async alertInsights(insight: MarketInsight, threadTitle: string): Promise<boolean> {
const message = formatInsightAlert(insight, threadTitle);
message.username = this.config.username;
message.icon_emoji = this.config.iconEmoji;
if (this.config.channel) {
message.channel = this.config.channel;
}
return sendSlackMessage(this.config.webhookUrl, message);
}
/**
* Alert scan summary
*/
async alertScanSummary(stats: {
threadsScanned: number;
insightsFound: number;
topThreads: GoldmineScore[];
duration: number;
}): Promise<boolean> {
const message = formatScanSummary(stats);
message.username = this.config.username;
message.icon_emoji = this.config.iconEmoji;
if (this.config.channel) {
message.channel = this.config.channel;
}
return sendSlackMessage(this.config.webhookUrl, message);
}
/**
* Send custom message
*/
async sendMessage(text: string): Promise<boolean> {
return sendSlackMessage(this.config.webhookUrl, {
text,
username: this.config.username,
icon_emoji: this.config.iconEmoji,
channel: this.config.channel
});
}
}
/**
* Create Slack alerts from environment
*/
export function createSlackAlerts(): SlackAlerts | null {
const webhookUrl = process.env.SLACK_WEBHOOK_URL;
if (!webhookUrl) {
return null;
}
return new SlackAlerts({
webhookUrl,
channel: process.env.SLACK_CHANNEL,
minGoldmineScore: parseInt(process.env.SLACK_MIN_SCORE || '25', 10)
});
}