forked from ScamBaiterDev/ScamBaiter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
602 lines (567 loc) · 17 KB
/
bot.js
File metadata and controls
602 lines (567 loc) · 17 KB
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
process.on("message", (msg) => {
if (!msg.type) return false;
if (msg.type === "activity") {
console.info(msg);
bot.user.setPresence(msg.data);
}
});
const urlRegex = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g);
const DiscordInviteLinkRegex = /(?:^|\b)discord(?:(?:app)?\.com\/invite|\.gg(?:\/invite)?)\/(?<code>[\w-]{2,255})(?:$|\b)/gi;
let serverdb = [];
const os = require("os");
const xbytes = require("xbytes");
const Discord = require("discord.js");
const {
REST
} = require("@discordjs/rest");
const {
Routes
} = require('discord-api-types/v10');
const axios = require("axios");
const fs = require("fs/promises");
const WebSocket = require("ws");
const config = require("./config.json");
const path = require("path");
const revision = require("child_process")
.execSync("git rev-parse HEAD")
.toString()
.trim()
.slice(0, 6);
const startup = new Date();
const urlDBPath = path.join(__dirname, ".", "db.json");
const serverDBPath = path.join(__dirname, ".", "server_db.json");
const bot = new Discord.Client({
intents: [
"GuildMessages",
"GuildBans",
"GuildMembers",
"GuildInvites",
"Guilds",
"MessageContent"
],
partials: ["MESSAGE", "CHANNEL", "GUILD_MEMBER", "USER"],
});
const reportHook = new Discord.WebhookClient({"url": config.discord.reportHook})
const Jimp = require('jimp');
const jsQR = require("jsqr");
let lastUpdate = null;
let lastIdPerGuild = [];
let db = [];
setInterval(() => {
updateDb();
}, 1000 * 30 * 60);
const sock = new WebSocket(config.scams.scamSocket, {
headers: {
"User-Agent": "ScamBaiter/1.0; Chris Chrome#9158",
"X-Identity": "ScamBaiter/1.0; Chris Chrome#9158",
},
});
sock.onopen = () => {
console.log("Connected to WS");
};
sock.onmessage = (message) => {
const data = JSON.parse(message.data);
if (data.type === "add") {
// Get all the entries in "data.domains" array and push to db
db.push(...data.domains);
} else if (data.type === "delete") {
// Get all the entries in "data.domains" array and remove from db
db = db.filter(item => !data.domains.includes(item));
}
};
bot.once("ready", async () => {
console.info(`Logged in as ${bot.user.tag}`);
await updateDb();
const commands = [];
const everySlashiesData = [
new Discord.SlashCommandBuilder()
.setName('botinfo')
.setDescription('Shows information about the bot.'),
new Discord.SlashCommandBuilder()
.setName('check')
.setDescription('Checks a provided scam URL against the database.')
.addStringOption((option) =>
option.setName("scam_url").setDescription("The domain to check.").setRequired(true)
),
new Discord.SlashCommandBuilder()
.setName('invite')
.setDescription('Gives the bot invite link.'),
new Discord.SlashCommandBuilder()
.setName('update_db')
.setDescription('Updates database')
];
everySlashiesData.forEach((slashies) => {
commands.push(slashies.toJSON());
});
const rest = new REST().setToken(config.discord.token);
rest.put(Routes.applicationCommands(config.discord.client_id), {
body: commands
})
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
});
bot.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
switch (interaction.commandName) {
case "botinfo":
bot.shard.fetchClientValues("guilds.cache.size").then((guildSizes) => {
const hostname = config.owners.includes(interaction.user.id) === true ? os.hostname() : os.hostname().replace(/./g, "•");
const systemInformationButReadable = `
Hostname: ${hostname}
CPU: ${os.cpus()[0].model}
Total RAM: ${Math.round(os.totalmem() / 1024 / 1024 / 1024)} GB
Free RAM: ${Math.round(os.freemem() / 1024 / 1024 / 1024)} GB
Uptime: <t:${Math.floor(
new Date() / 1000 - os.uptime()
)}:R>
`;
const botInfoButReadable = `
Bot Name: "${bot.user.tag}"
Guild Count: ${guildSizes.reduce((a, b) => a + b, 0)}
Shard Count: ${bot.shard.count}
Shard Latency: ${Math.round(bot.ws.ping)}ms
Startup Time: <t:${Math.floor(
startup.getTime() / 1000
)}:D> <t:${Math.floor(
startup.getTime() / 1000
)}:T>
Current DB size: ${db.length.toString()}
Last Database Update: <t:${Math.floor(
lastUpdate.getTime() / 1000
)}:R>
`;
interaction
.reply({
embeds: [{
"title": "Bot Info",
"timestamp": new Date(),
"fields": [{
"name": "System Information",
"value": systemInformationButReadable
},
{
"name": "Bot Info",
"value": botInfoButReadable
}
],
"footer": {
"text": `Commit ${revision}`
}
}],
})
.catch((err) => {
console.error(err);
});
});
break;
case "update_db":
if (!config.owners.includes(interaction.user.id)) return;
interaction.reply("Updating...").then(() => {
updateDb()
.then(() => interaction.editReply("Updated Database"))
.catch(() => interaction.editReply("Failed to Update Database"));
});
break;
case "invite":
await interaction.reply(config.inviteMsg);
break;
case "check":
const scamUrl = interaction.options.getString("scam_url", true);
const matchedREgexThing = urlRegex.exec(scamUrl);
if (matchedREgexThing) {
const removeEndingSlash = matchedREgexThing[0].split("/")[2];
if (removeEndingSlash === undefined) return interaction.reply("Please provide a valid URL");
const splited = removeEndingSlash.split(".");
const domain =
splited[splited.length - 2] + "." + splited[splited.length - 1];
await interaction.reply("Checking...").then(() =>
interaction
.editReply(`${domain} is ${db.includes(domain) ? "" : "not "}a scam.`)
.catch(() => {
interaction.editReply(
"An error occurred while checking that domain name!\nTry again later"
);
})
);
return;
}
await interaction.reply("Checking...").then(() =>
interaction
.editReply(`${scamUrl} is ${db.includes(scamUrl) ? "" : "not "}a scam.`)
.catch(() => {
interaction.editReply(
"An error occurred while checking that domain name!\nTry again later"
);
})
);
break;
}
})
bot.on("messageCreate", async (message) => {
if (message.author.id == bot.user.id) return;
const prefix = "$";
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
const invites = DiscordInviteLinkRegex.exec(message.content);
if (invites !== null) {
const inviteCode = invites.groups.code;
const serverID = await bot.fetchInvite(inviteCode).then((invite) => invite.guild.id)
serverdb.forEach(async (invite) => {
if(serverID !== invite.serverID) return;
try {
if (message.deletable) await message.delete();
await reportHook.send({
embeds: [{
"timestamp": new Date(),
"author": {
"name": message.guild.name,
"icon_url": message.guild.iconURL(),
},
"thumbnail": {
"url": message.author.avatarURL()
},
"footer": {
"text": `${message.id}${message.member.bannable &&
!message.member.permissions.has("KickMembers")
? " | Softbanned"
: " | Not Softbanned"
}`
},
"fields": [{
name: "User",
value: `${message.author} (${message.author.tag})\nID: ${message.author.id}`,
},
{
name: "Message",
value: message.content,
},
{
name: "Invite",
value: invites[0],
}
]
}]
})
} catch (err) {
console.error(err);
}
if (
message.member.bannable &&
!message.member.permissions.has("KickMembers")
) {
try {
await message.author.send(
config.discord.banMsg.replace("{guild}", message.guild.name)
);
await message.member.ban({
reason: "Scam detected",
days: 1
});
await message.guild.bans.remove(message.author.id, "AntiScam - Softban");
return;
} catch (e) {
console.error(e);
}
}
});
}
const scamUrls = urlRegex.exec(message.content);
let isScam = false;
let scamDomain = "";
if (scamUrls !== null && cmd !== "check") {
for (const potscamurl of scamUrls) {
// Somtimes potscamurl would be undefined causing a crash
if (potscamurl === undefined) break;
// remove everything after the third slash
const removeEndingSlash = potscamurl.split("/")[2];
if (removeEndingSlash === undefined) continue;
const splited = removeEndingSlash.split(".");
const domain =
splited[splited.length - 2] + "." + splited[splited.length - 1];
// check if domain is in db
if (db.includes(domain) || db.includes(removeEndingSlash)) {
isScam = true;
scamDomain = domain;
break;
}
}
}
if (isScam) {
if (message.deletable) await message.delete();
// Check if any of the elements in lastIdPerGuild matches the message id and guild id
if (
lastIdPerGuild.find(
(data) =>
data.userId === message.member.id && data.guildId === message.guild.id
)
) {
// Remove the element from the array
lastIdPerGuild = lastIdPerGuild.filter((data) => data.messageId !== message.id);
return;
} else {
// If the message is not in the array, add it
lastIdPerGuild.push({
messageId: message.id,
userId: message.author.id,
guildId: message.guild.id,
});
}
await reportHook.send({
embeds: [{
"timestamp": new Date(),
"author": {
"name": message.guild.name,
"icon_url": message.guild.iconURL(),
},
"thumbnail": {
"url": message.author.avatarURL()
},
"footer": {
"text": `${message.id}${message.member.bannable &&
!message.member.permissions.has("KickMembers")
? " | Softbanned"
: " | Not Softbanned"
}`
},
"fields": [{
name: "User",
value: `${message.author} (${message.author.tag})\nID: ${message.author.id}`,
},
{
name: "Message",
value: message.content,
},
{
name: "URL",
value: scamDomain,
}
]
}]
}).then((reportMsg) => {
if (config.discord.reportCrosspost) {
reportMsg.id
bot.channels.cache.get(config.discord.reportChannel).lastMessage.crosspost()
}
});
if (
message.member.bannable &&
!message.member.permissions.has("KickMembers")
) {
try {
await message.author.send(
config.discord.banMsg.replace("{guild}", message.guild.name)
);
await message.member.ban({
reason: "Scam detected",
days: 1
});
await message.guild.bans.remove(message.author.id, "AntiScam - Softban");
return;
} catch (e) {
console.error(e);
}
}
}
message.attachments.forEach((att) => {
if (att.contentType.startsWith("image")) {
Jimp.read(att.attachment).then(img => {
code = jsQR(img.bitmap.data, img.bitmap.width, img.bitmap.height);
if (code) {
if (code.data.startsWith("https://discord.com/ra/") || code.data.startsWith("https://discordapp.com/ra/")) {
// Do ban stuff
try {
message.reply({
"embeds": [{
"description": ":warning: POSSIBLE SCAM DETECTED :warning:\n\nThe image above contains a Discord Login QR code.\nScanning this code with the Discord app will give whoever made the code FULL ACCESS to your account",
"color": null
}]
})
} catch (error) {
if(error) message.delete();
}
}
}
})
}
})
// This is broken af right now, if someone knows what I'm doing wrong feel free to open a PR!
/*message.embeds.forEach(embed => {
if (() => {
Jimp.read(embed.thumbnail.url).then(img => {
code = jsQR(img.bitmap.data, img.bitmap.width, img.bitmap.height);
if (code) {
if (code.data.startsWith("https://discord.com/ra/")) return true;
}
})
Jimp.read(embed.image.url).then(img => {
code = jsQR(img.bitmap.data, img.bitmap.width, img.bitmap.height);
if (code) {
if (code.data.startsWith("https://discord.com/ra/")) return true;
}
})
Jimp.read(embed.footer.iconURL).then(img => {
code = jsQR(img.bitmap.data, img.bitmap.width, img.bitmap.height);
if (code) {
if (code.data.startsWith("https://discord.com/ra/")) return true;
}
})
Jimp.read(embed.author.iconURL).then(img => {
code = jsQR(img.bitmap.data, img.bitmap.width, img.bitmap.height);
if (code) {
if (code.data.startsWith("https://discord.com/ra/")) return true;
}
})
return false;
}) {
try {
message.reply({
"embeds": [{
"description": ":warning: POSSIBLE SCAM DETECTED :warning:\n\nThe image above contains a Discord Login QR code.\nScanning this code with the Discord app will give whoever made the code FULL ACCESS to your account",
"color": null
}]
})
} catch (error) {
if(error) message.delete();
}
}
})*/
// Funky debug commands
if (message.content.toLowerCase().startsWith(prefix)) {
switch (cmd) {
case "botinfo":
bot.shard.fetchClientValues("guilds.cache.size").then((guildSizes) => {
const hostname = config.owners.includes(message.author.id) === true ? os.hostname() : os.hostname().replace(/./g, "•");
const systemInformationButReadable = `
Hostname: ${hostname}
CPU: ${os.cpus()[0].model}
Total RAM: ${Math.round(os.totalmem() / 1024 / 1024 / 1024)} GB
Free RAM: ${Math.round(os.freemem() / 1024 / 1024 / 1024)} GB
Uptime: <t:${Math.floor(
new Date() / 1000 - os.uptime()
)}:R>
`;
const botInfoButReadable = `
Bot Name: "${bot.user.tag}"
Guild Count: ${guildSizes.reduce((a, b) => a + b, 0)}
Shard Count: ${bot.shard.count}
Shard Latency: ${Math.round(bot.ws.ping)}ms
Startup Time: <t:${Math.floor(
startup.getTime() / 1000
)}:D> <t:${Math.floor(
startup.getTime() / 1000
)}:T>
Current DB size: ${db.length.toString()}
Last Database Update: <t:${Math.floor(
lastUpdate.getTime() / 1000
)}:R>
`;
message.channel
.send({
embeds: [{
"title": "Bot Info",
"timestamp": new Date(),
"fields": [{
"name": "System Information",
"value": systemInformationButReadable
},
{
"name": "Bot Info",
"value": botInfoButReadable
}
],
"footer": {
"text": `Commit ${revision}`
}
}],
})
.catch((err) => {
console.error(err);
});
});
break;
case "update":
if (!config.owners.includes(message.author.id)) return;
message.channel.send("Updating...").then((msg1) => {
updateDb()
.then(() => msg1.edit("Updated Database"))
.catch(() => msg1.edit("Failed to Update Database"));
});
break;
case "invite":
await message.reply(config.inviteMsg);
break;
case "check":
const urls = args[0];
if (!urls)
return message.reply(
`Please provide a domain name to check, not the full URL please\nExample: \`${prefix}check discordapp.com\``
);
const matchedREgexThing = urlRegex.exec(urls);
if (matchedREgexThing) {
const removeEndingSlash = matchedREgexThing[0].split("/")[2];
if (removeEndingSlash === undefined) return interaction.reply("Please provide a valid URL");
const splited = removeEndingSlash.split(".");
const domain =
splited[splited.length - 2] + "." + splited[splited.length - 1];
await message.reply("Checking...").then(() =>
message
.edit(`${domain} is ${db.includes(domain) ? "" : "not "}a scam.`)
.catch(() => {
message.edit(
"An error occurred while checking that domain name!\nTry again later"
);
})
);
return;
}
await message.reply("Checking...").then((msg1) =>
msg1
.edit(`${urls} is ${db.includes(urls) ? "" : "not "}a scam.`)
.catch(() => {
msg1.edit(
"An error occurred while checking that domain name!\nTry again later"
);
})
);
break;
}
}
});
bot.login(config.discord.token);
const updateDb = () => {
return new Promise(async (resolve, reject) => {
try {
let scamAPIRESP = await axios.get(config.scams.scamApi, {
headers: {
"User-Agent": "ScamBaiter/1.0; Chris Chrome#9158",
// Mozilla/5.0 (compatible; <botname>/<botversion>; +<boturl>)
},
});
await fs.writeFile(urlDBPath, JSON.stringify(scamAPIRESP.data));
scamdb = scamAPIRESP.data;
lastUpdate = new Date();
console.info("Updated scam DB!");
resolve();
} catch (e) {
scamdb = require(urlDBPath);
console.error("Failed To Update the scam DB: " + e);
reject();
}
try {
let serverAPIRESP = await axios.get(config.scams.serverApi, {
headers: {
"User-Agent": "ScamBaiter/1.0; Chris Chrome#9158",
}
});
await fs.writeFile(serverDBPath, JSON.stringify(serverAPIRESP.data))
serverdb = serverAPIRESP.data;
lastUpdate = new Date();
console.info("Updated server DB!");
resolve();
} catch (e) {
serverdb = require(serverDBPath)
console.error("Failed To Update the server DB: " + e);
reject();
}
});
};