This repository has been archived by the owner on Nov 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
710 lines (664 loc) · 24.6 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
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
require("dotenv").config();
const Discord = require("discord.js");
const intents = new Discord.Intents([Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES, Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS]);
const client = new Discord.Client({ autoReconnect: true, intents: intents });
const fs = require("fs");
const snoowrap = require("snoowrap");
const weather = require("weather-js");
const UrbanDictionary = require("easyurban");
const dictionary = new UrbanDictionary();
const wiki = require("wikijs").default;
const archiver = require("archiver");
const imagedownloader = require("image-downloader");
const shoutBackRegEx = /^[A-Z ]+$/;
let intervalCount = 0;
/**
* Load server settings
*/
let serversJSON = fs.readFileSync("./servers.json");
serversJSON = JSON.parse(serversJSON);
let servers = {}; //server classes dict
/** Server Class */
const server = function (id) {
this.id = id;
this.memeChannel = "";
this.shoutback = true;
this.nsfw = false;
};
let r = new snoowrap({
userAgent: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9b5pre) Gecko/2008030706 Firefox/3.0b5pre",
clientId: process.env.REDDIT_APP_ID,
clientSecret: process.env.REDDIT_APP_SECRET,
username: process.env.REDDIT_APP_USERNAME,
password: process.env.REDDIT_APP_PASSWORD,
});
const oof = [
"https://www.myinstants.com/media/sounds/roblox-death-sound_1.mp3",
"https://www.myinstants.com/media/sounds/sm64_mario_oof.mp3",
"https://www.myinstants.com/media/sounds/classic_hurt.mp3",
];
const options_8ball = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
];
const spasten = ["s", "p", "a", "s", "t", "e", "n"];
const commands = [
"!help",
"!ping",
"!hmmm",
"!dafuq",
"!vid",
"!meirl",
"!dank",
"!deepfry",
"!kitty",
"!doggo",
"!nicememe",
"!oof",
"!bruh",
"!sus",
"!ohshit",
"!8ball",
"!yikes",
"!wann",
"!source",
"!mama",
"!yeet",
"!poll <question>",
"!weather <location>",
"!r (!reddit) <subreddit>",
"!define <term>",
"!wiki <term>",
];
let commandsString = "List of commands:";
for (let cmd of commands) {
commandsString += "\n``" + cmd + "``";
}
commandsString += `
----------------
Admin commands:
\`!dumpemoji\` - dumps all server emoji to a zip file
\`!setmemechannel\` - turns hourly posts on and sets the bots 'auto meme' channel (off by default)
\`!resetmemechannel\` - turns hourly posts off (why)
\`!shoutback\` - turns 'shoutback' on/off (on by default)
\`!nsfw\` - allows NSFW posts from !reddit command (off by default, works only in NSFW channels)
Bot by awieandy#4205 & Weazel#0293`;
let lastMeme = ""; //prevent posting the same picture for hours
/** On bot start up */
client.on("ready", () => {
console.log(`Bot started.`);
console.log(`Logged in as ${client.user.tag}!`);
loadServers();
for (const guild of client.guilds.cache) {
if (!servers[guild[0]]) {
let newServer = new server(guild[0]);
servers["" + guild[0]] = newServer;
serversToJson();
}
}
setPresenceText(`ayy lmao`);
});
/**
* Bot joins a Discord server
*/
client.on("guildCreate", (guild) => {
//create new server instance
let newServer = new server(guild.id);
servers["" + guild.id] = newServer;
serversToJson();
console.log(`Bot added to ${guild.name}`);
//Send help text into default text channel
let defaultChannel = guild.channels.find((e) => {
return e.type === "text" && e.permissionsFor(guild.me).has(`SEND_MESSAGES`);
});
if (defaultChannel != null) {
defaultChannel.send(commandsString);
}
});
/**
* Bot gets kicked from Discord server
*/
client.on("guildDelete", (guild) => {
delete servers["" + guild.id];
serversToJson();
console.log(`Bot kicked from ${guild.name}`);
});
/**
* Respond to incoming messages f.e. commands
*/
client.on("messageCreate", (msg) => {
if (msg.author.bot) return false;
//commands - messages that start with '!'
if (msg.content[0] == "!") {
if (msg.content === "!ping") {
msg.channel.send("Pong 🏓");
} else if (msg.content === "!help") {
msg.reply(commandsString);
} else if (msg.content === "!hmmm") {
r.getSubreddit("hmmm")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("🤔");
});
});
} else if (msg.content === "!dafuq") {
r.getSubreddit("cursedimages")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("✝");
});
});
} else if (msg.content === "!meirl") {
r.getSubreddit("me_irl")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("👀");
});
});
} else if (msg.content === "!vid") {
r.getSubreddit("youtubehaiku")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(data).then((m) => {
m.react("📼");
});
});
} else if (msg.content === "!deepfry") {
r.getSubreddit("DeepFriedMemes")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("🍤");
});
});
} else if (msg.content === "!dank") {
r.getSubreddit("dankmemes")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("💯");
});
});
} else if (msg.content === "!kitty") {
r.getSubreddit("kitty")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("🐱");
});
});
} else if (msg.content === "!doggo") {
r.getSubreddit("woof_irl")
.getRandomSubmission()
.url.then((data) => {
msg.channel.send(isImage(data) ? { files: [data] } : data).then((m) => {
m.react("🐶");
});
});
} else if (msg.content === "!joke") {
r.getSubreddit("jokes")
.getRandomSubmission()
.then((data) => {
msg.channel.send(`*${data.title}*\n\n${data.selftext}`);
});
} else if (msg.content == "!source") {
msg.reply("dankbot sourcecode: https://github.com/Andyyyyyy/discordbot");
} else if (msg.content.split(" ")[0] === "!8ball") {
let rand = Math.floor(Math.random() * options_8ball.length);
msg.reply(options_8ball[rand]);
} else if (msg.content.split(" ")[0] === "!weather") {
let location = msg.content.substring(9);
if (location === "") {
msg.channel.send("Usage: !weather <location>");
return;
}
getWeather(location, msg);
} else if (msg.content.split(" ")[0] === "!reddit" || msg.content.split(" ")[0] === "!r") {
let subreddit = msg.content.split(" ")[1];
if (subreddit === undefined) {
msg.channel.send("Usage: !reddit <subreddit>");
return;
}
getRandomSubmission(subreddit, msg);
} else if (msg.content.split(" ")[0] === "!define") {
let term = msg.content.substring(8);
if (term == "") {
msg.channel.send("Usage: !define <term>");
return;
}
udDefine(term, msg);
} else if (msg.content == "!wann") {
msg.channel.send(calculateWhen());
return;
} else if (msg.content.split(" ")[0] === "!wiki") {
let term = msg.content.substring(6);
if (term == "") {
msg.channel.send("Usage: !wiki <term>");
return;
}
wiki()
.page(term)
.then((data) => msg.channel.send(data.raw.fullurl))
.catch((err) => {
msg.channel.send("⚠ Error. No article found.");
});
} else if (msg.content.split(" ")[0] === "!poll") {
let question = msg.content.substring(6);
if (question == "") {
msg.channel.send("Usage: !poll <question>");
return;
}
msg.channel.send(`**Poll:** ${question}`).then((m) => {
m.react("👍");
m.react("👎");
});
} else if (msg.content === "!joke") {
r.getSubreddit("jokes")
.getRandomSubmission()
.then((data) => {
msg.channel.send(`*${data.title}*\n\n${data.selftext}`);
});
} else if (msg.content === "!yikes") {
msg.channel.send({
files: ["https://i.redd.it/ut6yjuo9pkc21.jpg"],
});
} else if (msg.content == "!spasten2") {
let members = msg.guild.members.array();
let list = "Alle Spasten hier:\n";
for (let i = 0; i < members.length; i++) {
list += `:regional_indicator_${spasten[i % spasten.length]}: ${members[i].displayName}\n`;
}
msg.channel.send(list);
} else if (msg.content == "!oof") {
/* Sound commands */
let rand = Math.floor(Math.random() * oof.length);
msg.channel.send("***OOF***");
msg.channel.send({
files: [oof[rand]],
});
} else if (msg.content == "!nicememe") {
msg.channel.send("***Nice Meme!***");
msg.channel.send({
files: ["./sounds/nicememe.mp3"],
});
} else if (msg.content == "!sus") {
msg.channel.send({
files: ["./sounds/sus.mp3"],
});
} else if (msg.content == "!mama") {
msg.channel.send({
files: ["./sounds/mama-uwu.mp3"],
});
} else if (msg.content == "!yeet") {
msg.channel.send({
files: ["./sounds/yeet.mp3"],
});
} else if (msg.content == "!bruh") {
msg.channel.send("***BRUH***");
msg.channel.send({
files: ["./sounds/movie_1.mp3"],
});
} else if (msg.content == "!ohshit") {
msg.channel.send("***OH SHIT***");
msg.channel.send({
files: ["./sounds/oh-shit_4.mp3"],
});
} else if (msg.content == "!lachs") {
msg.channel.send({
files: ["./sounds/den_lachs_ins_arschloch.mp3"],
});
} else if (msg.content == "!behinderung") {
msg.channel.send({
files: ["./sounds/rivaa_behinderung.ogg"],
});
} else if (msg.content == "!spasten") {
msg.channel.send({
files: ["./sounds/foggel_weazel_sind_spasten.ogg"],
});
} else if (msg.content == "!poyo") {
msg.channel.send({
files: ["./sounds/kirby-poyo.mp3"],
});
} else if (msg.content === "!dumpemoji") {
/**
* Admin Commands
*/
if (!msg.member.permissions.has(Discord.Permissions.FLAGS.ADMINISTRATOR)) {
msg.channel.send("You don't have permissions for this action");
return;
}
msg.channel.send("Dumping all server emoji. Please wait...");
let emojiMap = msg.guild.emojis;
let dir = `./${msg.guild.id}`;
prepareEmojiDump(dir);
downloadEmojis(emojiMap, dir).then(() => {
msg.channel.send("Creating zip archive...");
let files = fs.readdirSync(dir);
let output = fs.createWriteStream(`${dir}/${msg.guild.name}.zip`);
let archive = archiver("zip");
archive.on("error", function (err) {
msg.channel.send("Error.");
});
archive.pipe(output);
for (let file of files) {
// console.log(file);
archive.file(`${dir}/${file}`, { name: file });
}
archive.finalize().then(() => {
msg.channel
.send({
files: [`${dir}/${msg.guild.name}.zip`],
})
.then(() => {
deleteFolderRecursive(dir);
});
});
});
} else if (msg.content === "!setmemechannel") {
if (!msg.member.permissions.has(Discord.Permissions.FLAGS.ADMINISTRATOR)) {
msg.channel.send("You don't have permissions for this action");
return;
}
let currentServer = getServer(msg.guild.id);
currentServer.memeChannel = msg.channel.id;
serversToJson();
msg.channel.send("Meme channel set to this one.");
} else if (msg.content === "!resetmemechannel") {
if (!msg.member.permissions.has(Discord.Permissions.FLAGS.ADMINISTRATOR)) {
msg.channel.send("You don't have permissions for this action");
return;
}
let currentServer = getServer(msg.guild.id);
currentServer.memeChannel = "";
serversToJson();
msg.channel.send("Hourly memes turned off (why tho).");
} else if (msg.content === "!shoutback") {
if (!msg.member.permissions.has(Discord.Permissions.FLAGS.ADMINISTRATOR)) {
msg.channel.send("You don't have permissions for this action");
return;
}
let currentServer = getServer(msg.guild.id);
currentServer.shoutback = !currentServer.shoutback;
serversToJson();
msg.channel.send(`Shoutback has been turned ${currentServer.shoutback ? "on" : "off"}.`);
} else if (msg.content === "!nsfw") {
if (!msg.member.permissions.has(Discord.Permissions.FLAGS.ADMINISTRATOR)) {
msg.channel.send("You don't have permissions for this action");
return;
}
let currentServer = getServer(msg.guild.id);
currentServer.nsfw = !currentServer.nsfw;
serversToJson();
msg.channel.send(`NSFW Posts are now ${currentServer.nsfw ? "allowed" : "forbidden"}.`);
}
// else if (msg.content === "!hmTest") {
// sendHourlyMemes("DEBUG");
// }
} else if (msg.content === "ayy") {
//Actions without command
msg.channel.send("lmao😂");
} else if (msg.content === "nice") {
msg.react("🇳").then(() => {
msg.react("🇮").then(() => {
msg.react("🇨").then(() => {
msg.react("🇪");
});
});
});
} else if (msg.content === "lmao") {
msg.react("🇱").then(() => {
msg.react("🇲").then(() => {
msg.react("🇦").then(() => {
msg.react("🇵");
});
});
});
} else if (msg.content.length > 3 && shoutBackRegEx.test(msg.content)) {
//Shoutback
let currentServer = getServer(msg.guild.id);
if (currentServer.shoutback) {
msg.channel.send(textToRegionalIndicator(msg.content));
}
}
});
client.on("error", (err) => {
console.log("Error! " + err.message);
});
client.on("disconnect", (e) => {
console.log("disconnected.");
});
function sendHourlyMemes(text) {
console.log("Sending out dem memes...");
for (let s of Object.keys(servers)) {
s = servers[s];
if (s.memeChannel === "") continue;
let thisServer = client.guilds.cache.get(s.id);
if (!thisServer) continue;
let thisChannel = thisServer.channels.cache.get(s.memeChannel);
console.log(`Send meme to ${thisServer.name}`);
trySendAsImage(text, {channel: thisChannel}) //hacky lol
// thisChannel.send(isImage(text) ? { files: [text] } : text);
}
}
let minuteInterval = setInterval(() => {
intervalCount++;
if (intervalCount === 60) {
r.getTop("hmmm", { time: "hour" })[0].url.then(function (data) {
if (lastMeme !== data) {
sendHourlyMemes(data);
lastMeme = data;
} else {
r.getRandomSubmission("hmmm").url.then((data) => {
sendHourlyMemes(data);
});
}
});
intervalCount = 0;
}
if (intervalCount % 9 === 0) {
setPresenceText(`Use !help for commands`);
} else {
setPresenceText(`Shitpost incoming in ${60 - intervalCount} minutes`);
}
}, 60 * 1000);
function loadServers() {
for (let s of Object.keys(serversJSON)) {
s = serversJSON[s];
let newServer = new server(s.id);
newServer.memeChannel = s.memeChannel;
newServer.shoutback = s.shoutback;
newServer.nsfw = s.nsfw;
servers["" + s.id] = newServer;
}
}
function textToRegionalIndicator(text) {
let lower = text.toLowerCase();
let output = "";
for (let i = 0; i < lower.length; i++) {
let char = lower.charAt(i);
if (char === " ") {
output += char;
} else {
output += ":regional_indicator_" + char + ": ";
}
}
return output;
}
function setPresenceText(text) {
client.user.setPresence({
activities: [{ name: text, type: "WATCHING" }],
status: "online",
});
}
function getWeather(location, msg) {
let output = "";
weather.find({ search: location, degreeType: "C" }, function (err, result) {
if (err) {
console.log(err);
output = "Error";
} else {
result = result[0];
if (result === undefined) {
msg.channel.send("? Unknown location.");
return;
}
output = `In **${result.location.name}** it's **${result.current.temperature} °C** and ${result.current.skytext}.`;
output += "\n__Forecast:__";
for (let i = 2; i < 5; i++) {
output += `\n**${result.forecast[i].day}:** ${result.forecast[i].skytextday} at **${result.forecast[i].low}** to **${result.forecast[i].high} °C**`;
}
}
msg.channel.send(output);
});
}
function udDefine(term, msg) {
dictionary
.lookup(term)
.then((result) => {
if (result.list.length == 0) {
msg.channel.send("Couldn't find definition for " + term);
return;
}
let definition = `**${result.list[0].word}**:
${result.list[0].definition}
Example: *${result.list[0].example}*`;
definition = definition.replace(/\[/g, "");
definition = definition.replace(/\]/g, "");
if (definition.length > 1999) {
msg.channel.send(`${definition.substring(0, 1900)}... (Message too long)`);
} else {
msg.channel.send(definition);
}
})
.catch(console.error);
}
/* Server aus Settings lesen und wenn keiner gefunden ist, einen neuen anlegen */
function getServer(id) {
let serv = servers["" + id];
if (serv === undefined) {
let serv = new server(id);
servers["" + id] = serv;
serversToJson();
console.log(`Bot added to ${id}`);
}
return serv;
}
function serversToJson() {
fs.writeFileSync("servers.json", JSON.stringify(servers));
serversJSON = servers;
}
function getRandomSubmission(subreddit, msg) {
const sr = r.getSubreddit(subreddit);
if (!sr) {
msg.channel.send("Error. 😞 (Subreddit not found.)");
return;
}
sr.getRandomSubmission()
.then((data) => {
if (data.url === undefined) {
msg.channel.send("Subreddit does not exist or Reddit API fucks around");
return;
}
if (msg.channel.type == "GUILD_TEXT") {
if (data.over_18) {
if (!getServer(msg.guild.id).nsfw) {
msg.channel.send("⚠ Post is NSFW. Use !nsfw to allow NSFW posts.");
return;
}
if (!msg.channel.nsfw) {
msg.channel.send("⚠ Post is NSFW. This isn't a NSFW channel.");
return;
}
trySendAsImage(data.url, msg)
} else {
trySendAsImage(data.url, msg)
}
} else if (msg.channel.type == "dm" || msg.type == "group") {
trySendAsImage(data.url, msg)
}
})
.catch((e) => {
msg.channel.send("Error. 😞 (Reddit might be fucking around.)");
console.log(e);
});
}
function isImage(url) {
let regex = /\.(jpg|png|gif)$/;
return regex.test(url);
}
function trySendAsImage(url, msg) {
let image = isImage(url);
if (image) {
try {
msg.channel.send(url, image ? { files: [url] } : url);
} catch (e) {
console.log("Catched a post likely larger than 8 MB.");
msg.channel.send(url);
}
} else msg.channel.send(url);
}
const deleteFolderRecursive = function (path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file, index) {
var curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) {
// recurse
deleteFolderRecursive(curPath);
} else {
// delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
function prepareEmojiDump(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file, index) {
let curPath = path + "/" + file;
fs.unlinkSync(curPath);
});
} else {
fs.mkdirSync(path);
}
}
function calculateWhen() {
let releaseDate = new Date("June 10, 2022 00:00:00");
let delta = releaseDate - new Date();
if (delta > 0) {
return `***⚽ Noch ${Math.floor(delta / 1000 / 60 / 60 / 24).toLocaleString()} Tage bis Mario Strikers Battle League Football kommt!***`;
} else {
return "Ja nie";
}
}
async function downloadEmojis(emojiMap, dir) {
return new Promise(async function (resolve, reject) {
for (let emoji of emojiMap) {
emoji = emoji[1];
let { filename, image } = await imagedownloader.image({
url: emoji.url,
dest: `${dir}/${emoji.name}${emoji.animated ? ".gif" : ".png"}`,
});
// console.log(filename);
}
resolve(true);
});
}
/** Log into Discord */
client.login(process.env.DISCORD_BOT_TOKEN);