forked from roydejong/timbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
631 lines (525 loc) · 23.6 KB
/
index.js
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
const fs = require('fs');
const path = require('path');
const { Client, GatewayIntentBits, REST, Routes, Collection, EmbedBuilder } = require('discord.js');
const config = require('./config.json');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMembers,
]
});
global.discordJsClient = client;
const TwitchMonitor = require("./twitch-monitor");
const DiscordChannelSync = require("./discord-channel-sync");
const LiveEmbed = require('./live-embed');
const MiniDb = require('./minidb');
const commands = [
{
name: 'setup',
description: 'Setup your bot configuration',
options: [
{
type: 3, // STRING
name: 'twitch_channels',
description: 'Comma-separated list of Twitch channels',
required: true,
},
{
type: 3, // STRING
name: 'discord_announce_channel',
description: 'Discord channel for announcements',
required: true,
},
{
type: 3, // STRING
name: 'twitch_client_id',
description: 'Twitch client ID',
required: true,
},
{
type: 3, // STRING
name: 'twitch_oauth_token',
description: 'Twitch OAuth token',
required: true,
},
{
type: 4, // INTEGER
name: 'twitch_check_interval_ms',
description: 'Twitch check interval in milliseconds',
required: true,
},
{
type: 5, // BOOLEAN
name: 'twitch_use_boxart',
description: 'Whether to use Twitch box art',
required: true,
}
],
},
{
name: 'help',
description: 'Get information about available commands',
},
{
name: 'gettokens',
description: 'Get instructions on how to obtain your Twitch tokens',
},
{
name: 'addchannel',
description: 'Add a new channel ID to the announcement list',
options: [
{
type: 3, // STRING
name: 'channel_id',
description: 'The ID of the Discord channel to add',
required: true,
}
],
},
{
name: 'listchannel',
description: 'List all announcement channel IDs',
},
{
name: 'deletechannel',
description: 'Remove a channel ID from the announcement list',
options: [
{
type: 3, // STRING
name: 'channel_id',
description: 'The ID of the Discord channel to remove',
required: true,
}
],
},
{
name: 'setservermention',
description: 'Set server-specific mention for a Twitch channel',
options: [
{
type: 3, // STRING
name: 'twitch_channel',
description: 'The Twitch channel name',
required: true,
},
{
type: 3, // STRING
name: 'role_name',
description: 'The role name to mention (or "none" for no mention)',
required: true,
}
],
},
];
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN || config.discord_bot_token);
client.once('ready', async () => {
console.log(`[Discord] Bot is ready; logged in as ${client.user.tag}.`);
// Register slash commands
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(client.user.id), {
body: commands,
});
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error('Error registering commands:', error);
}
await syncServerList(true);
StreamActivity.init(client);
TwitchMonitor.start();
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
const { commandName, options } = interaction;
if (commandName === 'setup') {
try {
const twitchChannels = options.getString('twitch_channels');
const discordAnnounceChannels = options.getString('discord_announce_channel').split(',');
const twitchClientId = options.getString('twitch_client_id');
const twitchOauthToken = options.getString('twitch_oauth_token');
const twitchCheckIntervalMs = options.getInteger('twitch_check_interval_ms');
const twitchUseBoxart = options.getBoolean('twitch_use_boxart');
const newConfig = {
...config,
twitch_channels: twitchChannels,
discord_announce_channel: discordAnnounceChannels,
twitch_client_id: twitchClientId,
twitch_oauth_token: twitchOauthToken,
twitch_check_interval_ms: twitchCheckIntervalMs,
twitch_use_boxart: twitchUseBoxart,
};
fs.writeFileSync(path.join(__dirname, 'config.json'), JSON.stringify(newConfig, null, 2));
// Reload config
Object.assign(config, newConfig);
// Trigger refresh
TwitchMonitor.start(); // Restart TwitchMonitor with new config
await syncServerList(true); // Refresh Discord channels list
await interaction.reply('Configuration updated and refreshed successfully!');
} catch (error) {
console.error('Error updating configuration:', error.message);
await interaction.reply(`Failed to update configuration. ${error.message}`);
}
}else if (commandName === 'addchannel') {
try {
const channelId = options.getString('channel_id');
if (!channelId) {
throw new Error('Channel ID is required.');
}
if (config.discord_announce_channel.includes(channelId)) {
await interaction.reply('Channel ID is already in the announcement list.');
return;
}
config.discord_announce_channel.push(channelId);
fs.writeFileSync(path.join(__dirname, 'config.json'), JSON.stringify(config, null, 2));
// Reload config
Object.assign(config, { discord_announce_channel: config.discord_announce_channel });
// Trigger refresh
await syncServerList(true); // Refresh Discord channels list
await interaction.reply('Channel ID added and configuration refreshed successfully!');
} catch (error) {
console.error('Error adding channel:', error.message);
await interaction.reply(`Failed to add channel. ${error.message}`);
}
} else if (commandName === 'listchannel') {
try {
const guilds = client.guilds.cache;
let description = '';
for (const [guildId, guild] of guilds) {
const channels = guild.channels.cache.filter(channel => config.discord_announce_channel.includes(channel.id));
if (channels.size > 0) {
description += `**Server:** ${guild.name}\n`;
channels.forEach(channel => {
description += `- **Channel(s):** ${channel.name} (ID: ${channel.id})\n`;
});
description += '\n';
}
}
if (description === '') {
description = 'No announcement channels set.';
}
const listEmbed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Announcement Channels')
.setDescription(description);
await interaction.reply({ embeds: [listEmbed], ephemeral: true });
} catch (error) {
console.error('Error listing channels:', error.message);
await interaction.reply(`Failed to list channels. ${error.message}`);
}
} else if (commandName === 'deletechannel') {
try {
const channelId = options.getString('channel_id');
if (!channelId) {
throw new Error('Channel ID is required.');
}
const index = config.discord_announce_channel.indexOf(channelId);
if (index === -1) {
await interaction.reply('Channel ID is not in the announcement list.');
return;
}
config.discord_announce_channel.splice(index, 1);
fs.writeFileSync(path.join(__dirname, 'config.json'), JSON.stringify(config, null, 2));
// Reload config
Object.assign(config, { discord_announce_channel: config.discord_announce_channel });
// Trigger refresh
await syncServerList(true); // Refresh Discord channels list
await interaction.reply('Channel ID removed and configuration refreshed successfully!');
} catch (error) {
console.error('Error removing channel:', error.message);
await interaction.reply(`Failed to remove channel. ${error.message}`);
}
} else if (commandName === 'help') {
const helpEmbed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Help - Setup Command')
.addFields(
{ name: '**/setup**', value: 'Setup your bot configuration.' },
{ name: '**twitch_channels**', value: 'Comma-separated list of Twitch channels to monitor. You can add as little or as many as you want. Syntax: `channel1,channel2`' },
{ name: '**discord_announce_channel**', value: 'The name of the Discord channel where announcements will be made (e.g., `announcements`).' },
{ name: '**discord_mentions**', value: 'JSON string for Discord mentions, used for notifying users when a stream goes live.' },
{ name: '**twitch_client_id**', value: 'Your Twitch client ID for OAuth2 authentication.' },
{ name: '**twitch_oauth_token**', value: 'Your Twitch OAuth token for authentication.' },
{ name: '**twitch_check_interval_ms**', value: 'Interval in milliseconds to check Twitch status.' },
{ name: '**twitch_use_boxart**', value: 'Whether to use Twitch box art in the announcement messages.' }
);
await interaction.reply({ embeds: [helpEmbed] });
} else if (commandName === 'gettokens') {
const tokensEmbed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Obtaining Twitch Tokens')
.setDescription('To get your Twitch tokens, follow these instructions: [Twitch OAuth Documentation](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth)');
await interaction.reply({ embeds: [tokensEmbed] });
}
else if (commandName === 'setservermention') {
try {
const twitchChannel = options.getString('twitch_channel');
const roleName = options.getString('role_name');
if (!config.discord_mentions[twitchChannel]) {
config.discord_mentions[twitchChannel] = {
default: '',
server_specific: {}
};
}
config.discord_mentions[twitchChannel].server_specific = {
...config.discord_mentions[twitchChannel].server_specific,
[interaction.guild.id]: roleName
};
fs.writeFileSync(path.join(__dirname, 'config.json'), JSON.stringify(config, null, 2));
await interaction.reply(`Server-specific mention for ${twitchChannel} updated to ${roleName}.`);
} catch (error) {
console.error('Error updating server-specific mention:', error.message);
await interaction.reply(`Failed to update server-specific mention. ${error.message}`);
}
}
});
// --- Startup ---------------------------------------------------------------------------------------------------------
console.log('Timbot is starting.');
// --- Discord ---------------------------------------------------------------------------------------------------------
console.log('Connecting to Discord...');
let targetChannels = [];
let syncServerList = async (logMembership) => {
try {
console.log('[Discord] Syncing server list...');
const channelIds = config.discord_announce_channel;
targetChannels = await DiscordChannelSync.getChannelList(client, channelIds, logMembership);
console.log(`[Discord] Synced ${targetChannels.length} channels`);
targetChannels.forEach(channel => console.log(`Channel ID: ${channel.id}, Name: ${channel.name}`));
} catch (error) {
console.error('[Discord] Error syncing server list:', error);
}
};
client.once('ready', async () => {
console.log(`[Discord] Bot is ready; logged in as ${client.user.tag}.`);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(client.user.id), {
body: commands,
});
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error('Error registering commands:', error);
}
// Init list of connected servers, and determine which channels we are announcing to
await syncServerList(true);
// Keep our activity in the user list in sync
StreamActivity.init(client);
// Begin Twitch API polling
TwitchMonitor.start();
});
client.on('guildCreate', guild => {
console.log(`[Discord]`, `Joined new server: ${guild.name}`);
syncServerList(false);
});
client.on('guildDelete', guild => {
console.log(`[Discord]`, `Removed from a server: ${guild.name}`);
syncServerList(false);
});
console.log('[Discord]', 'Logging in...');
client.login(process.env.DISCORD_BOT_TOKEN || config.discord_bot_token);
// Activity updater
class StreamActivity {
static onlineChannels = {};
static discordClient = null;
static setChannelOnline(stream) {
this.onlineChannels[stream.user_name] = stream;
console.log('[StreamActivity]', `Channel online: ${stream.user_name}`);
this.updateActivity();
}
static setChannelOffline(stream) {
delete this.onlineChannels[stream.user_name];
console.log('[StreamActivity]', `Channel offline: ${stream.user_name}`);
this.updateActivity();
}
static clearAllChannels() {
this.onlineChannels = {};
console.log('[StreamActivity]', 'Cleared all channels');
this.updateActivity();
}
static getMostRecentStreamInfo() {
let lastChannel = null;
for (let channelName in this.onlineChannels) {
if (typeof channelName !== "undefined" && channelName) {
lastChannel = this.onlineChannels[channelName];
}
}
return lastChannel;
}
static updateActivity() {
let streamInfo = this.getMostRecentStreamInfo();
if (streamInfo) {
this.discordClient.user.setActivity({
name: streamInfo.user_name,
type: 1, // 1 is 'STREAMING'
url: `https://twitch.tv/${streamInfo.user_name.toLowerCase()}`
});
console.log('[StreamActivity]', `Update current activity: streaming ${streamInfo.user_name}.`);
} else {
console.log('[StreamActivity]', 'Cleared current activity.');
this.discordClient.user.setActivity(null);
}
}
static init(discordClient) {
this.discordClient = discordClient;
this.onlineChannels = {};
this.updateActivity();
setInterval(() => this.updateActivity(), 5 * 60 * 1000);
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Live events
let liveMessageDb = new MiniDb('live-messages');
let messageHistory = liveMessageDb.get("history") || {};
TwitchMonitor.onChannelLiveUpdate(async (streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
await syncServerList(false);
// Update activity
if (isLive) {
StreamActivity.setChannelOnline(streamData);
} else {
StreamActivity.setChannelOffline(streamData);
}
// Generate message
const msgFormatted = isLive
? `${streamData.user_name} went live on Twitch!`
: `${streamData.user_name} was live on Twitch.`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (const discordChannel of targetChannels) {
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.user_name.toLowerCase()}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgData = messageHistory[liveMsgDiscrim];
let existingMsgId = existingMsgData && !existingMsgData.offline ? existingMsgData.id : null; // Only use the message if it's still live
let mentionMode = null;
if (isLive) { // Only include mention if the stream is live
const streamerName = streamData.user_name.toLowerCase();
if (config.discord_mentions && config.discord_mentions[streamerName]) {
const serverSpecificMentions = config.discord_mentions[streamerName].server_specific;
if (serverSpecificMentions && serverSpecificMentions[discordChannel.guild.id]) {
mentionMode = serverSpecificMentions[discordChannel.guild.id];
} else {
mentionMode = config.discord_mentions[streamerName].default;
}
}
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "none") {
mentionMode = "";
} else if (mentionMode === "everyone" || mentionMode === "here") {
mentionMode = `@${mentionMode}`;
} else {
let roleData = discordChannel.guild.roles.cache.find(role => role.name.toLowerCase() === mentionMode);
if (roleData) {
mentionMode = `<@&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}, (does not exist on server ${discordChannel.guild.name})`);
mentionMode = "";
}
}
}
}
let msgToSend = mentionMode ? `${msgFormatted} ${mentionMode}` : msgFormatted;
if (existingMsgId) {
// Fetch existing message
try {
const existingMsg = await discordChannel.messages.fetch(existingMsgId);
await existingMsg.edit({
content: msgToSend,
embeds: [msgEmbed] // Update the embed
});
// Update entry if no longer live
messageHistory[liveMsgDiscrim] = { id: existingMsg.id, offline: false };
liveMessageDb.put('history', messageHistory);
} catch (e) {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
} else {
console.warn('[Discord] Error editing message:', e);
}
}
} else if (isLive) {
// Sending a new message only if the stream is live
try {
const message = await discordChannel.send({
content: msgToSend,
embeds: [msgEmbed]
});
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`);
messageHistory[liveMsgDiscrim] = { id: message.id, offline: false };
liveMessageDb.put('history', messageHistory);
} catch (err) {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}: ${err.message}`);
}
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
TwitchMonitor.onChannelOffline(async (streamData) => {
console.log('[TwitchMonitor]', `Channel offline: ${streamData.user_name}`);
// Refresh channel list
await syncServerList(false);
// Update activity
StreamActivity.clearAllChannels();
StreamActivity.setChannelOffline(streamData);
// Reset message state
for (const discordChannel of targetChannels) {
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.user_name.toLowerCase()}`;
if (messageHistory[liveMsgDiscrim]) {
// Update the message to indicate the stream is offline
try {
const existingMsg = await discordChannel.messages.fetch(messageHistory[liveMsgDiscrim].id);
await existingMsg.edit({
content: `${streamData.user_name} was live on Twitch.`,
embeds: [LiveEmbed.createForStream(streamData)] // Update the embed for offline state
});
messageHistory[liveMsgDiscrim].offline = true;
liveMessageDb.put('history', messageHistory);
} catch (e) {
console.warn('[Discord]', `Error updating offline message in #${discordChannel.name} on ${discordChannel.guild.name}:`, e);
}
}
}
});
// --- Common functions ------------------------------------------------------------------------------------------------
String.prototype.replaceAll = function(search, replacement) {
return this.split(search).join(replacement);
};
String.prototype.spacifyCamels = function () {
return this.replace(/([a-z](?=[A-Z]))/g, '$1 ');
};
Array.prototype.joinEnglishList = function () {
return [this.slice(0, -1).join(', '), this.slice(-1)[0]].join(this.length < 2 ? '' : ' and ');
};
String.prototype.lowercaseFirstChar = function () {
return this.charAt(0).toUpperCase() + this.slice(1);
};
Array.prototype.hasEqualValues = function (b) {
if (this.length !== b.length) {
return false;
}
this.sort();
b.sort();
for (let i = 0; i < this.length; i++) {
if (this[i] !== b[i]) {
return false;
}
}
return true;
};