-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathslack-bot.js
More file actions
191 lines (164 loc) · 5.67 KB
/
slack-bot.js
File metadata and controls
191 lines (164 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
* Free Crypto News Slack Bot
*
* Posts crypto news to a Slack channel.
* 100% FREE - no API keys required for the news API!
*
* Setup:
* 1. Create a Slack App at https://api.slack.com/apps
* 2. Enable "Incoming Webhooks" and create a webhook URL
* 3. Set SLACK_WEBHOOK_URL environment variable
* 4. Run: node slack-bot.js
*
* For scheduled posts, use cron or a cloud scheduler.
*/
const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;
const NEWS_API = 'https://free-crypto-news.vercel.app';
if (!SLACK_WEBHOOK_URL) {
console.error('❌ Missing SLACK_WEBHOOK_URL environment variable');
console.log('Set it with: export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."');
process.exit(1);
}
async function fetchNews(endpoint = '/api/news', limit = 5) {
const url = `${NEWS_API}${endpoint}?limit=${limit}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`API error: ${response.status}`);
return response.json();
}
async function fetchTrending() {
const response = await fetch(`${NEWS_API}/api/trending?limit=5&hours=24`);
if (!response.ok) throw new Error(`API error: ${response.status}`);
return response.json();
}
function formatNewsMessage(articles, title = '📰 Latest Crypto News') {
const blocks = [
{
type: 'header',
text: { type: 'plain_text', text: title, emoji: true }
},
{ type: 'divider' }
];
for (const article of articles) {
blocks.push({
type: 'section',
text: {
type: 'mrkdwn',
text: `*<${article.link}|${article.title}>*\n_${article.source}_ • ${article.timeAgo}`
}
});
}
blocks.push(
{ type: 'divider' },
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: '🆓 Powered by <https://github.com/nirholas/free-crypto-news|Free Crypto News API>'
}
]
}
);
return { blocks };
}
function formatTrendingMessage(trending) {
const sentimentEmoji = { bullish: '🟢', bearish: '🔴', neutral: '⚪' };
const blocks = [
{
type: 'header',
text: { type: 'plain_text', text: '📊 Trending in Crypto (24h)', emoji: true }
},
{ type: 'divider' }
];
const topicsText = trending.trending
.slice(0, 10)
.map((t, i) => `${i + 1}. ${sentimentEmoji[t.sentiment]} *${t.topic}* (${t.count} mentions)`)
.join('\n');
blocks.push({
type: 'section',
text: { type: 'mrkdwn', text: topicsText }
});
blocks.push(
{ type: 'divider' },
{
type: 'context',
elements: [
{ type: 'mrkdwn', text: `_Based on ${trending.articlesAnalyzed} articles analyzed_` }
]
}
);
return { blocks };
}
async function postToSlack(message) {
const response = await fetch(SLACK_WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message)
});
if (!response.ok) {
throw new Error(`Slack error: ${response.status}`);
}
return true;
}
// ═══════════════════════════════════════════════════════════════
// COMMANDS
// ═══════════════════════════════════════════════════════════════
async function postLatestNews() {
console.log('📰 Fetching latest news...');
const data = await fetchNews('/api/news', 5);
const message = formatNewsMessage(data.articles, '📰 Latest Crypto News');
await postToSlack(message);
console.log('✅ Posted latest news to Slack');
}
async function postBreakingNews() {
console.log('🚨 Fetching breaking news...');
const data = await fetchNews('/api/breaking', 5);
if (data.articles.length === 0) {
console.log('ℹ️ No breaking news right now');
return;
}
const message = formatNewsMessage(data.articles, '🚨 Breaking Crypto News');
await postToSlack(message);
console.log('✅ Posted breaking news to Slack');
}
async function postDefiNews() {
console.log('💰 Fetching DeFi news...');
const data = await fetchNews('/api/defi', 5);
const message = formatNewsMessage(data.articles, '💰 DeFi News');
await postToSlack(message);
console.log('✅ Posted DeFi news to Slack');
}
async function postBitcoinNews() {
console.log('₿ Fetching Bitcoin news...');
const data = await fetchNews('/api/bitcoin', 5);
const message = formatNewsMessage(data.articles, '₿ Bitcoin News');
await postToSlack(message);
console.log('✅ Posted Bitcoin news to Slack');
}
async function postTrending() {
console.log('📊 Fetching trending topics...');
const data = await fetchTrending();
const message = formatTrendingMessage(data);
await postToSlack(message);
console.log('✅ Posted trending topics to Slack');
}
// ═══════════════════════════════════════════════════════════════
// MAIN
// ═══════════════════════════════════════════════════════════════
const command = process.argv[2] || 'latest';
const commands = {
latest: postLatestNews,
breaking: postBreakingNews,
defi: postDefiNews,
bitcoin: postBitcoinNews,
trending: postTrending,
};
if (!commands[command]) {
console.log('Usage: node slack-bot.js [command]');
console.log('Commands: latest, breaking, defi, bitcoin, trending');
process.exit(1);
}
commands[command]().catch(err => {
console.error('❌ Error:', err.message);
process.exit(1);
});