-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitch2.js
307 lines (274 loc) · 11.3 KB
/
twitch2.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
const Discord = require('discord.js');
const { ApiClient } = require('twitch');
const { ClientCredentialsAuthProvider } = require('twitch-auth');
const fs = require('fs');
const config = require('./config.json'); // Load config file
const client = new Discord.Client();
let twitchChannels = [];
let twitchAuth;
let twitchClient;
let lastNotificationTimes = {};
let liveMessageIds = {};
let live = []
client.once('ready', () => {
console.log('Bot is online!');
initializeTwitchClient();
});
client.on('message', message => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'setnotifychannel') {
if (message.member.hasPermission('ADMINISTRATOR')) {
const channelId = message.content.slice(`${config.prefix}setnotifychannel`.length).trim();
if (isValidChannelId(channelId)) {
config.discordChannelId = channelId;
fs.writeFileSync('./config.json', JSON.stringify(config, null, 2), 'utf-8');
message.channel.send(`Notify channel has been updated to <#${channelId}>.`);
} else {
message.channel.send('Invalid channel ID format. Please provide a valid channel ID.');
}
} else {
message.channel.send('You need to have administrator permission to use this command.');
}
}
if (command === 'setprefix') {
if (message.member.hasPermission('ADMINISTRATOR')) {
const newPrefix = message.content.slice(`${config.prefix}setprefix`.length).trim();
if (newPrefix) {
config.prefix = newPrefix;
fs.writeFileSync('./config.json', JSON.stringify(config, null, 2), 'utf-8');
message.channel.send(`Prefix has been updated to \`${newPrefix}\`.`);
} else {
message.channel.send('Please provide a new prefix.');
}
} else {
message.channel.send('You need to have administrator permission to use this command.');
}
}
if (command === 'addchannel') {
const channelName = message.content.slice('*addchannel'.length).trim().toLowerCase();
if (addChannel(channelName)) {
message.channel.send(`Added ${channelName} to the Twitch channel list.`)
.then(() => {
console.log(`Added ${channelName} to the Twitch channel list.`);
})
.catch((error) => {
console.error(`Error adding ${channelName} to the Twitch channel list:`, error);
});
} else {
message.channel.send('That Twitch channel is already in the list.')
.then(() => {
console.log(`Twitch Channel ${channelName} is already in the list.`);
})
.catch((error) => {
console.error(`Error sending message for existing Twitch channel ${channelName}:`, error);
});
}
}
if (command === 'removechannel') {
const channelName = message.content.slice('*removechannel'.length).trim().toLowerCase();
if (removeChannel(channelName)) {
message.channel.send(`Removed ${channelName} from the Twitch channel list.`)
.then(() => {
console.log(`Removed ${channelName} from the Twitch channel list.`);
})
.catch((error) => {
console.error(`Error removing ${channelName} from the Twitch channel list:`, error);
});
} else {
message.channel.send('That Twitch channel is not in the list.')
.then(() => {
console.log(`Channel ${channelName} is not in the list.`);
})
.catch((error) => {
console.error(`Error sending message for non-existing channel ${channelName}:`, error);
});
}
}
if (command === 'listchannels') {
if (twitchChannels.length === 0) {
message.channel.send('The Twitch channel list is empty.')
.then(() => {
console.log('The Twitch channel list is empty.');
})
.catch((error) => {
console.error('Error sending empty Twitch channel list message:', error);
});
} else {
const channels = twitchChannels.join(', ');
message.channel.send(`Twitch Channels in the list: ${channels}`)
.then(() => {
console.log(`Listed Twitch channels: ${channels}`);
})
.catch((error) => {
console.error('Error sending Twitch channel list message:', error);
});
}
}
if (command === 'live') {
if (live.length === 0) {
message.channel.send('No channels are currently live.')
.then(() => {
console.log('No channels are currently live.');
})
.catch((error) => {
console.error('Error sending empty live channel list message:', error);
});
} else {
const liveChannels = live.join(', ');
message.channel.send(`Currently live channels: ${liveChannels}`)
.then(() => {
console.log(`Listed live channels: ${liveChannels}`);
})
.catch((error) => {
console.error('Error sending live channel list message:', error);
});
}
}
});
client.login(config.discordToken);
async function initializeTwitchClient() {
try {
const clientId = config.twitchClientId;
const clientSecret = config.twitchClientSecret;
twitchAuth = new ClientCredentialsAuthProvider(clientId, clientSecret);
twitchClient = new ApiClient({ authProvider: twitchAuth });
const channelData = fs.readFileSync('./channels.json', 'utf-8');
twitchChannels = JSON.parse(channelData);
setInterval(checkStreams, 10 * 1000);
} catch (error) {
console.error('Error initializing Twitch client:', error);
}
}
async function checkStreams() {
try {
for (const channel of twitchChannels) {
const user = await twitchClient.helix.users.getUserByName(channel);
if (user) {
const stream = await twitchClient.helix.streams.getStreamByUserId(user.id);
if (stream) {
const channelName = stream.userDisplayName;
const streamTitle = stream.title;
const streamURL = `https://twitch.tv/${channelName}`;
const profilePictureURL = user.profilePictureUrl;
const game = stream.gameName;
const gameID = stream.gameId;
const gameDetails = await twitchClient.helix.games.getGameById(gameID);
const boxArtURL = gameDetails ? gameDetails.boxArtUrl.replace('{width}', '285').replace('{height}', '380') : '';
const currentTime = Date.now();
const lastNotificationTime = lastNotificationTimes[channel] || 0;
const notificationCooldown = 60 * 1000;
if (currentTime - lastNotificationTime > notificationCooldown) {
const embed = new Discord.MessageEmbed()
.setColor('#6441A4')
.setTitle(`${channelName} is now live!`)
.setDescription(`Title: ${streamTitle}`)
.setURL(streamURL)
.setAuthor(channelName, profilePictureURL)
.setThumbnail(boxArtURL)
.setImage(stream.thumbnailUrl.replace('{width}', '1280').replace('{height}', '720'))
.addField('Game', game)
.setTimestamp();
const channelToPost = client.channels.cache.get(config.discordChannelId);
const lastMessageId = liveMessageIds[channel];
if (lastMessageId) {
const lastMessage = await channelToPost.messages.fetch(lastMessageId);
if (lastMessage && lastMessage.author.id === client.user.id) {
lastMessage.edit('', embed)
.then(() => {
console.log(`Updated stream notification for ${channel}`);
})
.catch((error) => {
console.error(`Error updating stream notification for ${channel}:`, error);
});
}
} else {
channelToPost.send(embed)
.then((sentMessage) => {
liveMessageIds[channel] = sentMessage.id;
console.log(`Posted new stream notification for ${channel}`);
if (!live.includes(channel)) {
live.push(channel);
}
})
.catch((error) => {
console.error(`Error posting stream notification for ${channel}:`, error);
});
}
lastNotificationTimes[channel] = currentTime;
}
} else {
const lastNotificationTime = lastNotificationTimes[channel];
if (lastNotificationTime) {
const channelToPost = client.channels.cache.get(config.discordChannelId);
const lastMessageId = liveMessageIds[channel];
if (lastMessageId) {
const lastMessage = await channelToPost.messages.fetch(lastMessageId);
if (lastMessage && lastMessage.author.id === client.user.id) {
const embed = new Discord.MessageEmbed()
.setColor('#6441A4')
.setTitle(`${channel} stream ended`)
.setDescription('The stream has ended.')
.setTimestamp();
lastMessage.edit('', embed)
.then(() => {
console.log(`Updated stream end notification for ${channel}`);
})
.catch((error) => {
console.error(`Error updating stream end notification for ${channel}:`, error);
});
}
} else {
const embed = new Discord.MessageEmbed()
.setColor('#6441A4')
.setTitle(`${channel} stream ended`)
.setDescription('The stream has ended.')
.setTimestamp();
channelToPost.send(embed)
.then((sentMessage) => {
liveMessageIds[channel] = sentMessage.id;
console.log(`Posted new stream end notification for ${channel}`);
const index = live.indexOf(channel);
if (index !== -1) {
live.splice(index, 1);
}
})
.catch((error) => {
console.error(`Error posting stream end notification for ${channel}:`, error);
});
}
delete lastNotificationTimes[channel];
delete liveMessageIds[channel];
}
}
}
}
} catch (error) {
console.error('Error checking Twitch streams:', error);
}
}
function addChannel(channelName) {
if (!twitchChannels.includes(channelName)) {
twitchChannels.push(channelName);
saveChannels();
return true;
}
return false;
}
function removeChannel(channelName) {
const channelIndex = twitchChannels.indexOf(channelName);
if (channelIndex !== -1) {
twitchChannels.splice(channelIndex, 1);
saveChannels();
return true;
}
return false;
}
function saveChannels() {
const channelData = JSON.stringify(twitchChannels, null, 2);
fs.writeFileSync('./channels.json', channelData, 'utf-8');
}
function isValidChannelId(channelId) {
return channelId && /^\d+$/.test(channelId);
}