-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
304 lines (287 loc) · 13.9 KB
/
app.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
require("dotenv").config();
const axios = require("axios").default;
const { readFileSync, writeFileSync, existsSync } = require("fs");
const Discord = require("discord.js");
const { schedule } = require("node-cron");
const client = new Discord.Client({ intents: [Discord.GatewayIntentBits.DirectMessages, Discord.GatewayIntentBits.GuildMessages, Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.MessageContent], partials: [Discord.Partials.Channel, Discord.Partials.Message] });
let tokenData = null;
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity("n!help", { type: Discord.ActivityType.Listening });
if (!existsSync("notifiers.json")) {
writeFileSync("notifiers.json", "{}");
}
});
client.on("messageCreate", async (msg) => {
if (msg.author.bot) return;
if (!msg.content.startsWith("n!")) return;
const args = msg.content.split(" ");
const command = args.shift().replace("n!", "").toLowerCase();
switch (command) {
case "ping":
msg.reply("Pong!");
break;
case "notify":
case "notifyme": {
const username = args.shift();
const user = msg.author;
const data = JSON.parse(readFileSync("notifiers.json"));
if (data[username.toLowerCase()]) {
if (data[username.toLowerCase()].users.includes(user.id)) {
msg.reply("You are already being notified when " + username + " goes live!");
return;
}
data[username.toLowerCase()].users.push(user.id);
msg.reply("You will now be notified when " + username + " goes live!");
} else {
if ((await doesTwitchUserExist(username)) === false) return msg.reply("That user does not exist on Twitch!");
data[username.toLowerCase()] = {
users: [user.id],
isLive: false,
};
msg.reply("You will now be notified when " + username + " goes live!");
}
writeFileSync("notifiers.json", JSON.stringify(data, null, 4));
break;
}
case "unnotify":
case "unnotifyme": {
const username = args.shift();
const user = msg.author;
const data = JSON.parse(readFileSync("notifiers.json"));
if (data[username.toLowerCase()]) {
if (data[username.toLowerCase()].users.includes(user.id)) {
data[username.toLowerCase()].users.splice(data[username.toLowerCase()].users.indexOf(user.id), 1);
msg.reply("You will no longer be notified when " + username + " goes live!");
if (data[username.toLowerCase()].users.length === 0) delete data[username.toLowerCase()];
} else {
msg.reply("You are not being notified when " + username + " goes live!");
}
} else {
msg.reply("You are not being notified when " + username + " goes live!");
}
writeFileSync("notifiers.json", JSON.stringify(data, null, 4));
break;
}
case "list": {
const data = JSON.parse(readFileSync("notifiers.json"));
const streamers = Object.keys(data);
if (streamers.length === 0) return msg.reply("You are not being notified when anyone goes live!");
const streamersList = streamers.filter((streamer) => data[streamer].users.includes(msg.author.id));
if (streamersList.length === 0) return msg.reply("You are not being notified when anyone goes live!");
msg.reply("You are being notified when the following streamers go live:\n```\n" + streamersList.join("\n") + "```");
break;
}
case "islive":
case "live": {
const username = args.shift();
getToken()
.then((token) => {
axios({
url: `https://api.twitch.tv/helix/streams?user_login=${username.toLowerCase()}`,
method: "GET",
headers: {
"Client-ID": process.env.CLIENT_ID,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
})
.then((res) => {
const stream = res.data.data[0];
if (stream) {
msg.reply(stream.user_name + " is live!");
} else {
msg.reply(username + " is not live!");
}
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
break;
}
case "help":
msg.reply({
embeds: [
{
author: {
name: `Twitch Notifier`,
icon_url: client.user.displayAvatarURL(),
},
title: "Commands",
description: "Here are the commands you can use with the Twitch Notifier bot!",
color: 0x9146ff,
fields: [
{
name: "n!notify <username>",
value: "Use this command to start receiving notifications when a streamer goes live!",
},
{
name: "n!unnotify <username>",
value: "Use this command to stop receiving notifications when a streamer goes live!",
},
{
name: "n!list",
value: "Use this command to see the list of streamers you are currently receiving notifications for!",
},
{
name: "n!islive <username>",
value: "Use this command to check if a streamer is currently live!",
},
{
name: "n!help",
value: "Use this command to see this message again!",
},
],
timestamp: new Date(),
},
],
});
break;
default:
break;
}
});
client.login(process.env.TOKEN);
schedule("*/5 * * * *", () => {
console.log("Checking for live streams...");
const data = JSON.parse(readFileSync("notifiers.json"));
const streamers = Object.keys(data);
if (streamers.length === 0) return;
getToken()
.then((token) => {
axios({
url: `https://api.twitch.tv/helix/streams?user_login=${streamers.join("&user_login=")}`,
method: "GET",
headers: {
"Client-ID": process.env.CLIENT_ID,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
})
.then((res) => {
const streams = res.data.data;
if (streams.length === 0) {
for (const streamer of streamers) {
if (data[streamer.toLowerCase()].isLive) {
console.log(streamer + " is no longer live!");
data[streamer.toLowerCase()].isLive = false;
}
}
writeFileSync("notifiers.json", JSON.stringify(data, null, 4));
return;
}
console.log("Live:", streams.map((stream) => stream.user_name).join(", "));
axios({
url: `https://api.twitch.tv/helix/users?id=${streams.map((stream) => stream.user_id).join("&id=")}`,
method: "GET",
headers: {
"Client-ID": process.env.CLIENT_ID,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
})
.then((res) => {
const users = res.data.data;
for (const stream of streams) {
if (data[stream.user_login.toLowerCase()]) {
if (!data[stream.user_login.toLowerCase()].isLive) {
data[stream.user_login.toLowerCase()].isLive = true;
for (const user of data[stream.user_login.toLowerCase()].users) {
client.users.fetch(user).then((user) => {
user.send({
content: `<@${user.id}>\nYou are receiving this message because you have told me to notify you when \`${stream.user_name}\` goes live!\nIf you want to stop receiving these messages, use \`n!unnotify ${stream.user_login}\``,
embeds: [
{
author: {
name: `${stream.user_name} is now live on Twitch!`,
icon_url: users.find((user) => user.id === stream.user_id).profile_image_url,
url: "https://twitch.tv/" + stream.user_login,
},
title: stream.title,
description: `Playing ${stream.game_name}\n\nPress [here](<https://twitch.tv/${stream.user_login}>) to watch the stream!`,
url: "https://twitch.tv/" + stream.user_login,
color: 0x9146ff,
image: {
url: stream.thumbnail_url.replace("{width}", "1280").replace("{height}", "720"),
},
timestamp: new Date(stream.started_at),
},
],
});
});
}
writeFileSync("notifiers.json", JSON.stringify(data, null, 4));
}
}
}
for (const streamer of streamers) {
if (!streams.find((stream) => stream.user_login.toLowerCase() === streamer.toLowerCase()) && data[streamer.toLowerCase()].isLive) {
data[streamer.toLowerCase()].isLive = false;
}
}
writeFileSync("notifiers.json", JSON.stringify(data, null, 4));
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
});
function getToken() {
return new Promise((resolve, reject) => {
if (tokenData && tokenData.expires_at > Date.now()) return resolve(tokenData.access_token);
axios({
url: `https://id.twitch.tv/oauth2/token`,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: `client_id=${process.env.CLIENT_ID}&client_secret=${process.env.CLIENT_SECRET}&grant_type=client_credentials`,
})
.then((res) => {
tokenData = {
access_token: res.data.access_token,
expires_at: Date.now() + res.data.expires_in * 1000,
};
return resolve(res.data.access_token);
})
.catch((err) => {
return reject(err);
});
});
}
function doesTwitchUserExist(username) {
return new Promise((resolve, reject) => {
getToken()
.then((token) => {
axios({
url: `https://api.twitch.tv/helix/users?login=${username}`,
method: "GET",
headers: {
"Client-ID": process.env.CLIENT_ID,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
})
.then((res) => {
return resolve(true);
})
.catch((err) => {
return resolve(false);
});
})
.catch((err) => {
return reject(err);
});
});
}