-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
342 lines (303 loc) · 10.7 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
require("dotenv").config();
const { StaticAuthProvider } = require("@twurple/auth");
const { ApiClient } = require("@twurple/api");
const { EventSubWsListener } = require("@twurple/eventsub-ws");
const { ActivityType, Client, Collection, Events, GatewayIntentBits, IntentsBitField, } = require("discord.js");
const fs = require("node:fs");
const path = require("node:path");
/* TWITCH APP TOKENS */
const ttv_app_id = process.env.TWITCH_CLIENT_ID;
const ttv_app_secret = process.env.TWITCH_CLIENT_SECRET;
/* TWITCH USERS */
const ttv_id_lucian = process.env.TTV_STLUCIAN_ID;
const ttv_id_nekosoul = process.env.TTV_NEKOSOUL_ID;
/* DISCORD APP TOKENS */
const dc_app_lucia_token = process.env.DC_APP_TOKEN;
/* const dc_app_lucia_id = process.env.DC_APP_ID; */
const dc_app_lucia_log = process.env.DC_CHANNEL_LUCIALOG;
/* DISCORD STREAM ALERT CHANNELS */
const dc_alert_lucian = process.env.DC_CHANNEL_STLUCIAN;
const dc_alert_nekosoul = process.env.DC_CHANNEL_NEKOSOUL;
/* ALERT MESSAGES */
const msg_lucian = `**Lucian nii-san just went live!**\nLet's go visit the penthouse! <a:LuciaCaughtIn4K:1214998758295601232>\nhttps://twitch.tv/stlucian`;
const msg_nekosoul = `**Soul-chan just went live!**\nLet's go visit the rabbit house! :heart:\nhttps://twitch.tv/nekoso_ul`;
const lucia = new Client({
intents: [
IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMembers,
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent,
GatewayIntentBits.Guilds
],
});
let isStreaming = false;
let tokens = {
access_token: undefined,
refresh_token: process.env.TWITCH_REFRESH_TOKEN
};
let listeners = null;
let listeners_lucian = [];
let listeners_nekosoul = [];
function initCommands() {
lucia.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
lucia.commands.set(command.data.name, command);
} else {
console.warn(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
lucia.on(Events.InteractionCreate, async (interaction) => {
const command = await interaction.client.commands.get(interaction.commandName);
if (!command) {
luciaLog('No command matching '+interaction.commandName+' was found.');
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: "There was an error while executing this command!",
ephemeral: true,
});
} else {
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
}
});
}
function luciaLog(msg) {
lucia.channels.cache.get(dc_app_lucia_log).send(msg);
}
async function luciaLogin() {
await lucia.login(dc_app_lucia_token);
return 'Lucia is now online on Discord!';
}
async function luciaStart() {
const msg = await luciaLogin();
setLuciaPresence('standby');
return msg ? true : false;
}
function luciaError(error = 'Lucia is now confused!') {
setLuciaPresence();
luciaLog(error);
}
function announceOnDiscord(twitchID = null) {
switch (twitchID) {
case getTwitchID('stlucian'):
lucia.channels.cache.get(dc_alert_lucian).send(msg_lucian);
break;
case getTwitchID('nekoso_ul'):
lucia.channels.cache.get(dc_alert_nekosoul).send(msg_nekosoul);
break;
default:
luciaLog('Twitch user invalid, cannot annouce on Discord');
}
}
function setLuciaPresence(status = 'error') {
switch (status) {
case 'standby':
lucia.user.setPresence({
activities: [
{
name: "น้องมาแอบฟัง",
type: ActivityType.Listening,
},
],
status: "online",
});
break;
case 'streaming':
lucia.user.setPresence({
activities: [
{
name: "Lucian nii-san's penthouse",
type: ActivityType.Streaming,
url: `https://twitch.tv/stlucian`,
},
],
status: "online",
});
break;
case 'busy':
lucia.user.setPresence({
activities: [
{
name: "with the code!",
type: ActivityType.Playing,
},
],
status: "dnd",
});
break;
case 'error':
default:
lucia.user.setPresence({
activities: [
{
name: "Lucia is now confused!",
type: ActivityType.Listening,
},
],
status: "dnd",
});
}
}
function getTwitchID(username) {
switch (username) {
case 'stlucian':
return ttv_id_lucian;
case 'nekoso_ul':
return ttv_id_nekosoul;
default:
return null;
}
}
/* Validate Tokens */
async function isTwitchTokenValid(access_token) {
let headers = new Headers();
headers.append(`Authorization`, `OAuth ${access_token}`);
const response = await fetch(`https://id.twitch.tv/oauth2/validate`, {
method: "GET",
headers: headers,
redirect: "follow",
});
let valid = response.status === 200 ? true : false;
luciaLog('**[Get]** ValidatedToken');
luciaLog(valid.toString());
return valid;
}
/* Initialize Listeners */
async function createListener(access_token) {
const authProvider = new StaticAuthProvider(ttv_app_id, access_token);
const apiClient = new ApiClient({ authProvider });
listeners = new EventSubWsListener({ apiClient });
listeners.start();
luciaLog('Lucia is listening!');
/* STREAM START */
try {
listeners_lucian[0] = listeners.onStreamOnline(ttv_id_lucian, () => {
announceOnDiscord(ttv_id_lucian);
luciaLog('StLucian started streaming');
setLuciaPresence('streaming');
isStreaming = true;
});
luciaLog(`**[Created]** StLucian's online listener`);
listeners_nekosoul[0] = listeners.onStreamOnline(ttv_id_nekosoul, () => {
announceOnDiscord(ttv_id_nekosoul);
luciaLog('NeKoSo_UL started streaming');
});
luciaLog(`**[Created]** NeKoSo_UL's online listener`);
} catch (error) {
throw new luciaError(error);
}
/* STREAM STOP */
try {
listeners_lucian[1] = listeners.onStreamOffline(ttv_id_lucian, () => {
luciaLog('StLucian went offline');
setLuciaPresence('standby');
isStreaming = false;
});
luciaLog(`**[Created]** StLucian's offline listener`);
listeners_nekosoul[1] = listeners.onStreamOffline(ttv_id_nekosoul, () => {
announceOnDiscord(dc_alert_nekosoul);
luciaLog('NeKoSo_UL went offline');
});
luciaLog(`**[Created]** NeKoSo_UL's offline listener`);
} catch (error) {
throw new luciaError(error);
}
}
async function refreshToken(tokensData) {
luciaLog('Renewing Access Token...');
setLuciaPresence('busy');
let headers = new Headers();
headers.append(`Content-Type`, `application/json`);
let body = {
client_id: ttv_app_id,
client_secret: ttv_app_secret,
grant_type: "refresh_token",
refresh_token: encodeURIComponent(tokensData.refresh_token),
};
const request = new Request("https://id.twitch.tv/oauth2/token", {
method: "POST",
headers: headers,
body: JSON.stringify(body),
});
const response = await fetch(request);
const response_json = await response.json();
const newAccessToken = response_json.access_token;
const newRefreshToken = response_json.refresh_token;
luciaLog('**[Get]** Access Token');
luciaLog(`${newAccessToken ? true : false}`);
luciaLog('**[Get]** Refresh Token');
luciaLog(`${newRefreshToken ? true : false}`);
if (!newAccessToken || !newRefreshToken) {
throw new luciaError(`**[Error]** No Tokens!`);
} else {
const tokens = {
access_token: newAccessToken,
refresh_token: newRefreshToken,
};
if (isStreaming) {
setLuciaPresence('streaming');
} else {
setLuciaPresence('standby');
}
return tokens;
}
}
/* Auto cycle */
async function performMaintenance() {
luciaLog(`**[Maintenance]** Starting...`);
try {
await listeners_lucian[0].stop();
luciaLog(`**[Stopped]** StLucian's online listener`);
await listeners_lucian[1].stop();
luciaLog(`**[Stopped]** StLucian's offline listener`);
await listeners_nekosoul[0].stop();
luciaLog(`**[Stopped]** NeKoSo_UL's online listener`);
await listeners_nekosoul[1].stop();
luciaLog(`**[Stopped]** NeKoSo_UL's offline listener`);
await listeners.stop();
luciaLog(`**[Stopped]** All listeners`);
listeners.removeListener();
luciaLog('Deleted Listeners');
} catch (error) {
throw new luciaError(error);
}
tokens = await refreshToken(tokens);
await createListener(tokens.access_token);
luciaLog('Resuming Listeners...');
luciaLog(`**[Maintenance]** Ended`);
}
/* First Time Run */
async function initializeSequence() {
const response = await refreshToken(tokens);
if (await isTwitchTokenValid(response.access_token)) {
createListener(response.access_token);
} else {
throw new luciaError(`Initializing Failed`);
}
return response;
}
/* ---- APP STARTS HERE ---- */
const startSuccess = luciaStart();
if (startSuccess) {
lucia.on("ready", async () => {
luciaLog('**Lucia** is being initialized...');
tokens = await initializeSequence();
initCommands();
setInterval(performMaintenance, 1000 * 60 * 60 * 3); // Maintenance every 3 hours
});
}