-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathdiscord-bot.js
More file actions
563 lines (468 loc) · 18.2 KB
/
discord-bot.js
File metadata and controls
563 lines (468 loc) · 18.2 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/**
* @copyright 2024-2026 nirholas. All rights reserved.
* @license SPDX-License-Identifier: SEE LICENSE IN LICENSE
* @see https://github.com/nirholas/free-crypto-news
*
* This file is part of free-crypto-news.
* Unauthorized copying, modification, or distribution is strictly prohibited.
* For licensing inquiries: nirholas@users.noreply.github.com
*/
/**
* Discord Bot Example — Crypto News Bot
*
* A full-featured Discord bot that provides crypto news, market data,
* sentiment analysis, and AI-powered insights.
*
* Setup:
* npm install discord.js
* DISCORD_TOKEN=your_token DISCORD_CHANNEL_ID=your_channel node discord-bot.js
*
* Slash Commands:
* /news — Latest crypto news
* /breaking — Breaking news (last 2 hours)
* /bitcoin — Bitcoin-specific news
* /defi — DeFi news
* /market — Market overview (prices + Fear & Greed)
* /sentiment — AI sentiment for an asset
* /ask — Ask AI a crypto question
* /whale — Recent whale alerts
* /trending — Trending topics
* /signals — Trading signals
* /defisummary — DeFi TVL, yield & protocol summary
* /stablecoins — Stablecoin market overview
* /l2 — Layer 2 project stats
* /gas — Ethereum/chain gas prices
* /briefing — AI flash briefing
* /oracle — AI oracle prediction
* /macro — Macro indicators & Fed data
* /funding — Funding rate dashboard
* /nft — NFT market overview
* /unlocks — Upcoming token unlocks
*/
const { Client, GatewayIntentBits, EmbedBuilder, SlashCommandBuilder } = require('discord.js');
const API_BASE = 'https://cryptocurrency.cv';
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const CHANNEL_ID = process.env.DISCORD_CHANNEL_ID;
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// ── Helpers ──────────────────────────────────────────────
async function apiFetch(endpoint, params = {}) {
try {
const url = new URL(`${API_BASE}${endpoint}`);
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
const res = await fetch(url.toString());
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error(`API error (${endpoint}):`, err.message);
return null;
}
}
function truncate(str, len = 256) {
return str && str.length > len ? str.slice(0, len - 3) + '...' : str || '';
}
// ── News Embed Builder ──────────────────────────────────
function buildNewsEmbed(title, color, articles) {
const embed = new EmbedBuilder()
.setTitle(title)
.setColor(color)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv — Free Crypto News API' });
for (const article of (articles || []).slice(0, 10)) {
embed.addFields({
name: `${article.source}`,
value: `[${truncate(article.title, 200)}](${article.link})\n*${article.timeAgo || ''}*`,
});
}
if (!articles || articles.length === 0) {
embed.setDescription('No articles found.');
}
return embed;
}
// ── Command Handlers ─────────────────────────────────────
const commands = {
async news(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/news', { limit: '8' });
const embed = buildNewsEmbed('📰 Latest Crypto News', 0x0099ff, data?.articles);
await interaction.editReply({ embeds: [embed] });
},
async breaking(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/breaking', { limit: '8' });
const embed = buildNewsEmbed('🚨 Breaking News', 0xff0000, data?.articles);
await interaction.editReply({ embeds: [embed] });
},
async bitcoin(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/bitcoin', { limit: '8' });
const embed = buildNewsEmbed('₿ Bitcoin News', 0xf7931a, data?.articles);
await interaction.editReply({ embeds: [embed] });
},
async defi(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/defi', { limit: '8' });
const embed = buildNewsEmbed('💰 DeFi News', 0x00ff88, data?.articles);
await interaction.editReply({ embeds: [embed] });
},
async market(interaction) {
await interaction.deferReply();
const [prices, fearGreed, global] = await Promise.all([
apiFetch('/api/prices', { ids: 'bitcoin,ethereum,solana', vs_currencies: 'usd' }),
apiFetch('/api/fear-greed'),
apiFetch('/api/global'),
]);
const embed = new EmbedBuilder()
.setTitle('💹 Market Overview')
.setColor(0x00ff00)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (prices) {
const fmt = (id) => {
const p = prices[id]?.usd || prices?.prices?.[id]?.usd;
return p ? `$${Number(p).toLocaleString()}` : 'N/A';
};
embed.addFields(
{ name: '₿ Bitcoin', value: fmt('bitcoin'), inline: true },
{ name: 'Ξ Ethereum', value: fmt('ethereum'), inline: true },
{ name: '◎ Solana', value: fmt('solana'), inline: true },
);
}
if (fearGreed) {
embed.addFields({
name: '😱 Fear & Greed',
value: `${fearGreed.value || 'N/A'} — ${fearGreed.classification || ''}`,
inline: true,
});
}
await interaction.editReply({ embeds: [embed] });
},
async sentiment(interaction) {
await interaction.deferReply();
const asset = interaction.options?.getString('asset') || 'bitcoin';
const data = await apiFetch('/api/sentiment', { asset, period: '24h' });
const embed = new EmbedBuilder()
.setTitle(`📊 Sentiment: ${asset}`)
.setColor(0x9b59b6)
.setTimestamp();
if (data) {
embed.setDescription(JSON.stringify(data, null, 2).slice(0, 2000));
} else {
embed.setDescription('Could not fetch sentiment data.');
}
await interaction.editReply({ embeds: [embed] });
},
async ask(interaction) {
await interaction.deferReply();
const question = interaction.options?.getString('question') || 'What is happening in crypto?';
const data = await apiFetch('/api/ask', { q: question });
const embed = new EmbedBuilder()
.setTitle('🤖 AI Answer')
.setColor(0x3498db)
.setTimestamp();
if (data?.answer) {
embed.setDescription(truncate(data.answer, 2000));
} else if (data) {
embed.setDescription(truncate(JSON.stringify(data), 2000));
} else {
embed.setDescription('Could not get an answer.');
}
await interaction.editReply({ embeds: [embed] });
},
async whale(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/whale-alerts');
const embed = new EmbedBuilder()
.setTitle('🐋 Whale Alerts')
.setColor(0x1abc9c)
.setTimestamp();
if (data?.alerts) {
for (const alert of data.alerts.slice(0, 8)) {
embed.addFields({
name: alert.asset || alert.symbol || 'Unknown',
value: truncate(`${alert.amount || ''} — ${alert.description || alert.type || ''}`, 200),
});
}
} else {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No whale alerts.');
}
await interaction.editReply({ embeds: [embed] });
},
async trending(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/trending', { limit: '10', period: '24h' });
const embed = new EmbedBuilder()
.setTitle('🔥 Trending Topics')
.setColor(0xe74c3c)
.setTimestamp();
if (data?.topics) {
for (const topic of data.topics.slice(0, 10)) {
embed.addFields({
name: topic.name || topic.topic || 'Topic',
value: truncate(topic.description || topic.sentiment || `Score: ${topic.score || 'N/A'}`, 200),
});
}
} else {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No trending data.');
}
await interaction.editReply({ embeds: [embed] });
},
async signals(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/signals');
const embed = new EmbedBuilder()
.setTitle('📡 Trading Signals')
.setColor(0xf39c12)
.setTimestamp();
if (data?.signals) {
for (const signal of data.signals.slice(0, 8)) {
embed.addFields({
name: `${signal.asset || signal.symbol || 'N/A'} — ${signal.action || signal.type || ''}`,
value: truncate(signal.reason || signal.description || `Confidence: ${signal.confidence || 'N/A'}`, 200),
});
}
} else {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No signals available.');
}
await interaction.editReply({ embeds: [embed] });
},
async defisummary(interaction) {
await interaction.deferReply();
const [summary, yields] = await Promise.all([
apiFetch('/api/defi/summary'),
apiFetch('/api/yields/stats'),
]);
const embed = new EmbedBuilder()
.setTitle('🏦 DeFi Summary')
.setColor(0x00ff88)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (summary) {
embed.addFields(
{ name: 'Total TVL', value: `$${((summary.totalTvl || 0) / 1e9).toFixed(2)}B`, inline: true },
{ name: 'Protocols', value: `${summary.protocolCount || 'N/A'}`, inline: true },
{ name: '24h Change', value: `${(summary.tvlChange24h || 0).toFixed(2)}%`, inline: true },
);
}
if (yields) {
embed.addFields(
{ name: 'Avg Yield', value: `${(yields.avgApy || 0).toFixed(2)}%`, inline: true },
{ name: 'Median Yield', value: `${(yields.medianApy || 0).toFixed(2)}%`, inline: true },
);
}
await interaction.editReply({ embeds: [embed] });
},
async stablecoins(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/stablecoins');
const embed = new EmbedBuilder()
.setTitle('💵 Stablecoin Market')
.setColor(0x2ecc71)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
const coins = Array.isArray(data) ? data : data?.stablecoins || [];
for (const coin of coins.slice(0, 10)) {
embed.addFields({
name: coin.name || coin.symbol || 'Unknown',
value: `Mkt Cap: $${((coin.marketCap || 0) / 1e9).toFixed(2)}B | Price: $${(coin.price || 1).toFixed(4)}`,
});
}
if (coins.length === 0) {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No stablecoin data.');
}
await interaction.editReply({ embeds: [embed] });
},
async l2(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/l2/projects');
const embed = new EmbedBuilder()
.setTitle('🔗 Layer 2 Projects')
.setColor(0x3498db)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
const projects = Array.isArray(data) ? data : data?.projects || [];
for (const p of projects.slice(0, 10)) {
embed.addFields({
name: p.name || 'Unknown',
value: `TVL: $${((p.tvl || 0) / 1e9).toFixed(2)}B | Type: ${p.type || 'N/A'} | TPS: ${(p.tps || 0).toFixed(1)}`,
});
}
if (projects.length === 0) {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No L2 data.');
}
await interaction.editReply({ embeds: [embed] });
},
async gas(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/gas');
const embed = new EmbedBuilder()
.setTitle('⛽ Gas Prices')
.setColor(0xe67e22)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (data) {
embed.addFields(
{ name: '🐢 Slow', value: `${data.slow || 'N/A'} Gwei`, inline: true },
{ name: '🚶 Standard', value: `${data.standard || 'N/A'} Gwei`, inline: true },
{ name: '🏃 Fast', value: `${data.fast || 'N/A'} Gwei`, inline: true },
{ name: '⚡ Instant', value: `${data.instant || 'N/A'} Gwei`, inline: true },
);
} else {
embed.setDescription('Could not fetch gas data.');
}
await interaction.editReply({ embeds: [embed] });
},
async briefing(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/ai/flash-briefing');
const embed = new EmbedBuilder()
.setTitle('⚡ AI Flash Briefing')
.setColor(0x9b59b6)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (data?.briefing) {
embed.setDescription(truncate(data.briefing, 2000));
} else if (data?.summary) {
embed.setDescription(truncate(data.summary, 2000));
} else {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No briefing available.');
}
await interaction.editReply({ embeds: [embed] });
},
async oracle(interaction) {
await interaction.deferReply();
const asset = interaction.options?.getString('asset') || 'bitcoin';
const data = await apiFetch('/api/ai/oracle', { asset });
const embed = new EmbedBuilder()
.setTitle(`🔮 AI Oracle: ${asset}`)
.setColor(0x8e44ad)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (data?.prediction) {
embed.setDescription(truncate(data.prediction, 2000));
if (data.confidence) {
embed.addFields({ name: 'Confidence', value: `${data.confidence}`, inline: true });
}
if (data.timeframe) {
embed.addFields({ name: 'Timeframe', value: data.timeframe, inline: true });
}
} else {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No oracle data.');
}
await interaction.editReply({ embeds: [embed] });
},
async macro(interaction) {
await interaction.deferReply();
const [indicators, fearGreed] = await Promise.all([
apiFetch('/api/macro/indicators'),
apiFetch('/api/fear-greed'),
]);
const embed = new EmbedBuilder()
.setTitle('🌐 Macro Overview')
.setColor(0x2c3e50)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (indicators) {
embed.setDescription(truncate(JSON.stringify(indicators, null, 2), 2000));
}
if (fearGreed) {
embed.addFields({
name: '😱 Fear & Greed',
value: `${fearGreed.value || 'N/A'} — ${fearGreed.classification || ''}`,
inline: true,
});
}
await interaction.editReply({ embeds: [embed] });
},
async funding(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/funding/dashboard');
const embed = new EmbedBuilder()
.setTitle('📈 Funding Rate Dashboard')
.setColor(0x27ae60)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (data) {
embed.setDescription(truncate(JSON.stringify(data, null, 2), 2000));
} else {
embed.setDescription('No funding rate data available.');
}
await interaction.editReply({ embeds: [embed] });
},
async nft(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/nft/market');
const embed = new EmbedBuilder()
.setTitle('🎨 NFT Market')
.setColor(0xe91e63)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
if (data) {
embed.addFields(
{ name: '24h Volume', value: `$${((data.totalVolume24h || 0) / 1e6).toFixed(1)}M`, inline: true },
{ name: 'Sales', value: `${(data.totalSales24h || 0).toLocaleString()}`, inline: true },
{ name: 'Avg Price', value: `$${(data.averagePrice || 0).toFixed(2)}`, inline: true },
);
} else {
embed.setDescription('No NFT market data.');
}
await interaction.editReply({ embeds: [embed] });
},
async unlocks(interaction) {
await interaction.deferReply();
const data = await apiFetch('/api/token-unlocks');
const embed = new EmbedBuilder()
.setTitle('🔓 Upcoming Token Unlocks')
.setColor(0xf1c40f)
.setTimestamp()
.setFooter({ text: 'cryptocurrency.cv' });
const unlocks = Array.isArray(data) ? data : data?.unlocks || [];
for (const u of unlocks.slice(0, 8)) {
embed.addFields({
name: u.token || u.symbol || 'Unknown',
value: `Value: $${((u.valueUsd || 0) / 1e6).toFixed(1)}M | Date: ${u.date || 'N/A'} | Tokens: ${(u.amount || 0).toLocaleString()}`,
});
}
if (unlocks.length === 0) {
embed.setDescription(data ? JSON.stringify(data).slice(0, 2000) : 'No upcoming unlocks.');
}
await interaction.editReply({ embeds: [embed] });
},
};
// ── Hourly Auto-Post ─────────────────────────────────────
async function autoPostBreaking(channel) {
const data = await apiFetch('/api/breaking', { limit: '5' });
if (!data?.articles?.length) return;
const embed = buildNewsEmbed('🚨 Breaking Crypto News', 0xff0000, data.articles);
await channel.send({ embeds: [embed] });
}
// ── Bot Events ───────────────────────────────────────────
client.on('ready', () => {
console.log(`✅ Logged in as ${client.user.tag}`);
// Post breaking news every hour
if (CHANNEL_ID) {
setInterval(async () => {
try {
const channel = await client.channels.fetch(CHANNEL_ID);
if (channel) await autoPostBreaking(channel);
} catch (err) {
console.error('Auto-post error:', err.message);
}
}, 60 * 60 * 1000);
}
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const handler = commands[interaction.commandName];
if (handler) {
try {
await handler(interaction);
} catch (err) {
console.error(`Command error (${interaction.commandName}):`, err.message);
const reply = interaction.deferred
? interaction.editReply.bind(interaction)
: interaction.reply.bind(interaction);
await reply({ content: '❌ Something went wrong. Try again later.', ephemeral: true });
}
}
});
client.login(DISCORD_TOKEN);