-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
445 lines (389 loc) · 11 KB
/
bot.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
require("dotenv").config();
const Discord = require("discord.js");
const ytdl = require("@distube/ytdl-core");
const client = new Discord.Client({
intents: [
Discord.GatewayIntentBits.Guilds,
Discord.GatewayIntentBits.GuildMessages,
Discord.GatewayIntentBits.MessageContent,
Discord.GatewayIntentBits.DirectMessages,
],
});
const ffmpeg = require("ffmpeg-static");
const fs = require("node:fs");
const path = require("node:path");
const cp = require("node:child_process");
const console = require("./services/console");
const { getAgents } = require("./services/agents");
client.once(Discord.Events.ClientReady, () => {
client.guilds.cache.forEach((guild) => {
console.debug(
'[INFO] Conected to guild "' +
guild.name +
'" (' +
guild.id +
") (" +
(guild.memberCount - 1) +
" members)."
);
});
client.commands = [];
const foldersPath = path.join(__dirname, "commands");
const commandFiles = fs
.readdirSync(foldersPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require("./commands/" + file);
if ("data" in command && "execute" in command) {
client.commands.push(command.data.toJSON());
} else {
console.warn(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
const rest = new Discord.REST().setToken(process.env.DISCORD_BOT_TOKEN);
(async () => {
try {
console.info(
`Started refreshing ${client.commands.length} application (/) commands.`
);
const data = await rest.put(
Discord.Routes.applicationCommands(client.application.id),
{ body: client.commands }
);
console.success(
`Successfully reloaded ${data.length} application (/) commands.`
);
} catch (error) {
console.error(error);
}
})();
setInterval(async () => {
let guildsCount = await client.shard.fetchClientValues("guilds.cache.size");
let usersCount = await client.shard.broadcastEval((c) =>
c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)
);
usersCount = usersCount.reduce((acc, memberCount) => acc + memberCount, 0);
usersCount -= guildsCount;
client.user.setActivity(
`${guildsCount.reduce(
(acc, guildCount) => acc + guildCount,
0
)} guilds and ${usersCount} users`,
{ type: Discord.ActivityType.Listening }
);
}, 5000);
});
client.on(Discord.Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.find(
(commandData) => commandData.name === interaction.commandName
);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await require("./commands/" + command.name).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,
});
}
}
});
client.on(Discord.Events.GuildCreate, async (guild) => {
console.info(
'[INFO] Adicionado ao servidor "' + guild.name + '" (' + guild.id + ")."
);
const webhook = await fetch(
`https://discord.com/api/webhooks/1301784003979776030/${process.env.DISCORD_WEBHOOK_TOKEN}`,
{
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({
content: `Adicionado ao servidor "${guild.name}" (${guild.id}).`,
username:
(process.env.IS_PRODUCTION.toString().toLowerCase() == "true"
? "CarlaDown [PROD]"
: "CarlaDown [DEV]") + " | GuildCreate",
}),
}
);
});
client.on("error", console.error);
client.on("warn", console.warn);
client.on("debug", console.info);
client.login(process.env.DISCORD_BOT_TOKEN);
// web server
const express = require("express");
const cors = require("cors");
const app = express();
const database = require("./database");
const { MongoClient, ServerApiVersion } = require("mongodb");
const { Webhook } = require("@top-gg/sdk");
const webhook = new Webhook(process.env.TOPGG_WEBHOOK_AUTH);
const dbClient = new MongoClient(
`mongodb+srv://admin:${process.env.MONGODB_PASSWORD}@carladown.d3xwq.mongodb.net/?retryWrites=true&w=majority&appName=CarlaDown`,
{
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
}
);
app.use(
cors({
origin: "*",
methods: ["GET"],
allowedHeaders: ["Content-Type"],
})
);
app.set("view engine", "ejs");
app.listen(8080, () => {});
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get("/download", (req, res) => {
res.json(req.query);
});
app.get("/api/download_mp4", async (req, res) => {
const agent = getAgents()[Math.floor(Math.random() * getAgents().length)];
await dbClient.connect();
const myDB = await dbClient.db(
`carladown_${
process.env.IS_PRODUCTION.toString() == "true" ? "prod" : "dev"
}`
);
const myColl = await myDB.collection("mp4");
const query = await myColl.findOne({
downloadID: req.query.id,
});
let data = {};
if (query !== null) {
data = {
error: null,
videoID: `${query.videoID}`,
};
} else {
data = {
error: {
message:
"No video has found. The download ID (" +
req.query.id +
") is correct?",
},
videoID: null,
};
return res.status(404).json(data);
}
try {
let url = "https://www.youtube.com/watch?v=" + data.videoID;
if (!ytdl.validateURL(url))
return res.sendStatus(400).json({
error: "Invalid URL",
});
const video = await ytdl.getInfo(url, { agent });
video.formats.filter(
(format) =>
format.container === "mp4" && format.hasVideo && format.hasAudio
);
let title = `${video.videoDetails.title} | ${video.videoDetails.author.name}`;
title = title.replace(/[^\x00-\x7F]/g, "");
let videoFile = ytdl(url, { filter: "videoonly" });
let audioFile = ytdl(url, { filter: "audioonly", highWaterMark: 1 << 25 });
const ffmpegProcess = cp.spawn(
ffmpeg,
[
"-i",
`pipe:3`,
"-i",
`pipe:4`,
"-map",
"0:v",
"-map",
"1:a",
"-c:v",
"copy",
"-c:a",
"libmp3lame",
"-crf",
"27",
"-preset",
"veryfast",
"-movflags",
"frag_keyframe+empty_moov",
"-f",
"mp4",
"-loglevel",
"error",
"-",
],
{
stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"],
}
);
videoFile.pipe(ffmpegProcess.stdio[3]);
audioFile.pipe(ffmpegProcess.stdio[4]);
res.header(
"Content-Disposition",
'attachment; filename="' + title + '.mp4"'
);
res.header("Content-Type", "video/mp4");
ffmpegProcess.stdio[1].pipe(res);
} catch (error) {
console.originalLog(error);
}
});
app.get("/api/download_mp3", async (req, res, next) => {
const agent = getAgents()[Math.floor(Math.random() * getAgents().length)];
await dbClient.connect();
const myDB = await dbClient.db(
`carladown_${
process.env.IS_PRODUCTION.toString() == "true" ? "prod" : "dev"
}`
);
const myColl = await myDB.collection("mp3");
const query = await myColl.findOne({
downloadID: req.query.id,
});
let data = {};
if (query !== null) {
data = {
error: null,
videoID: `${query.videoID}`,
};
} else {
return res.status(404).json({
error: {
message:
"No video has found. The download ID (" +
req.query.id +
") is correct?",
},
videoID: null,
});
}
try {
let url = "https://www.youtube.com/watch?v=" + data.videoID;
if (!ytdl.validateURL(url))
return res.json({
error: "Invalid URL",
});
const video = await ytdl.getInfo(url, { agent });
let title = `${video.videoDetails.title} | ${video.videoDetails.author.name}`;
title = title.replace(/[^\x00-\x7F]/g, "");
let audioFile = ytdl(url, {
agent,
filter: "audioonly",
highWaterMark: 1 << 25,
});
res.header(
"Content-Disposition",
'attachment; filename="' + title + '.mp3"'
);
res.header("Content-Type", "video/mp3");
audioFile.pipe(res);
} catch (error) {
console.originalLog(error);
}
});
app.get("/api/getVideoInfo", async (req, res) => {
try {
const agent = getAgents()[Math.floor(Math.random() * getAgents().length)];
await dbClient.connect();
const myDB = await dbClient.db(
`carladown_${
process.env.IS_PRODUCTION.toString() == "true" ? "prod" : "dev"
}`
);
if (!req.query.downloadType)
return res.status(400).json({
error: {
code: "MISSING_QUERY_PARAMETER",
message: 'The "downloadType" query parameter is required.',
},
result: null,
});
if (req.query.downloadType !== "mp3" && req.query.downloadType !== "mp4")
return res.status(400).json({
error: {
code: "INVALID_QUERY_PARAMETER",
message:
'The "downloadType" query parameter must be "mp3" for audio or "mp4" for video.',
},
result: null,
});
if (!req.query.id)
return res.status(400).json({
error: {
code: "MISSING_QUERY_PARAMETER",
message: 'The "id" query parameter is required.',
},
result: null,
});
const myColl = await myDB.collection(`${req.query.downloadType}`);
const query = await myColl.findOne({
downloadID: req.query.id,
});
if (query == null)
return res.status(404).json({
error: {
message:
"No video has found. The download ID (" +
req.query.id +
") is correct?",
},
videoID: null,
});
if (!ytdl.validateID(query.videoID)) {
return res.status(404).json({
error: {
message:
"No video has found. The download ID (" +
req.query.id +
") is correct?",
},
videoID: null,
});
}
const result = await ytdl.getBasicInfo(
`https://youtube.com/watch?v=${query.videoID}`,
{ agent }
);
return res.json({
error: null,
result: result.videoDetails,
});
} catch (error) {
console.originalLog(error);
return res.status(500).json({
error: {
code: "INTERNAL_SERVER_ERROR",
message: "An error occurred while processing this request.",
},
result: null,
});
}
});
app.post(
"/api/webhook/topgg",
webhook.listener((vote) => {
console.log(vote);
})
);
app.get("/download", (req, res) => {
res.render("./download.ejs");
});