This repository has been archived by the owner on Sep 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscord_bot.js
377 lines (352 loc) · 10.8 KB
/
discord_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
var fs = require('fs');
process.on('unhandledRejection', (reason) => {
console.error(reason);
process.exit(1);
});
try {
var Discord = require("discord.js");
} catch (e) {
console.log(e.stack);
console.log(process.version);
console.log("Please run npm install and ensure it passes with no errors!");
process.exit();
}
console.log("Starting DiscordBot\nNode version: " + process.version + "\nDiscord.js version: " + Discord.version);
// Get authentication data
try {
var AuthDetails = require(__dirname + "/auth.json");
} catch (e) {
console.log("Please create an auth.json like auth.json.example with a bot token or an email and password.\n" + e.stack);
process.exit();
}
// Load custom permissions
var dangerousCommands = [ "eval", "update", "setUsername" ];
var Permissions = {};
try {
Permissions = require(__dirname + "/permissions.json");
} catch (e) {
Permissions.global = {};
Permissions.users = {};
}
for (var i = 0; i < dangerousCommands.length; i++) {
var cmd = dangerousCommands[ i ];
if (!Permissions.global.hasOwnProperty(cmd)) {
Permissions.global[ cmd ] = false;
}
}
Permissions.checkPermission = function (user, permission) {
try {
var allowed = true;
try {
if (Permissions.global.hasOwnProperty(permission)) {
allowed = Permissions.global[ permission ] === true;
}
} catch (e) { }
try {
if (Permissions.users[ user.id ].hasOwnProperty(permission)) {
allowed = Permissions.users[ user.id ][ permission ] === true;
}
} catch (e) { }
return allowed;
} catch (e) { }
return false;
}
fs.writeFile(__dirname + "/permissions.json", JSON.stringify(Permissions, null, 2));
//load config data
var Config = {};
try {
Config = require(__dirname + "/config.json");
} catch (e) { //no config file, use defaults
Config.debug = false;
Config.commandPrefix = '!';
try {
if (fs.lstatSync(__dirname + "/config.json").isFile()) {
console.log("WARNING: config.json found but we couldn't read it!\n" + e.stack);
}
} catch (e2) {
fs.writeFile(__dirname + "/config.json", JSON.stringify(Config, null, 2));
}
}
if (!Config.hasOwnProperty("commandPrefix")) {
Config.commandPrefix = '!';
}
var messagebox;
var aliases;
try {
aliases = require(__dirname + "/alias.json");
} catch (e) {
//No aliases defined
aliases = {};
}
var commands = {
"alias": {
usage: "<name> <actual command>",
description: "Creates command aliases. Useful for making simple commands on the fly",
process: function (bot, msg, suffix) {
var args = suffix.split(" ");
var name = args.shift();
if (!name) {
msg.channel.send(Config.commandPrefix + "alias " + this.usage + "\n" + this.description);
} else if (commands[ name ] || name === "help") {
msg.channel.send("overwriting commands with aliases is not allowed!");
} else {
var command = args.shift();
aliases[ name ] = [ command, args.join(" ") ];
//now save the new alias
require("fs").writeFile(__dirname + "/alias.json", JSON.stringify(aliases, null, 2), null);
msg.channel.send("created alias " + name);
}
}
},
"aliases": {
description: "lists all recorded aliases",
process: function (bot, msg, suffix) {
var text = "current aliases:\n";
for (var a in aliases) {
if (typeof a === 'string')
text += a + " ";
}
msg.channel.send(text);
}
},
"ping": {
description: "responds pong, useful for checking if bot is alive",
process: function (bot, msg, suffix) {
msg.channel.send(msg.author + " pong!");
if (suffix) {
msg.channel.send("note that !ping takes no arguments!");
}
}
},
"idle": {
usage: "[status]",
description: "sets bot status to idle",
process: function (bot, msg, suffix) {
bot.user.setStatus("idle");
bot.user.setGame(suffix);
}
},
"online": {
usage: "[status]",
description: "sets bot status to online",
process: function (bot, msg, suffix) {
bot.user.setStatus("online");
bot.user.setGame(suffix);
}
},
"say": {
usage: "<message>",
description: "bot says message",
process: function (bot, msg, suffix) { msg.channel.send(suffix); }
},
"announce": {
usage: "<message>",
description: "bot says message with text to speech",
process: function (bot, msg, suffix) { msg.channel.send(suffix, { tts: true }); }
},
"msg": {
usage: "<user> <message to leave user>",
description: "leaves a message for a user the next time they come online",
process: function (bot, msg, suffix) {
var args = suffix.split(' ');
var user = args.shift();
var message = args.join(' ');
if (user.startsWith('<@')) {
user = user.substr(2, user.length - 3);
}
var target = msg.channel.guild.members.find("id", user);
if (!target) {
target = msg.channel.guild.members.find("username", user);
}
messagebox[ target.id ] = {
channel: msg.channel.id,
content: target + ", " + msg.author + " said: " + message
};
updateMessagebox();
msg.channel.send("message saved.")
}
},
"eval": {
usage: "<command>",
description: 'Executes arbitrary javascript in the bot process. User must have "eval" permission',
process: function (bot, msg, suffix) {
if (Permissions.checkPermission(msg.author, "eval")) {
msg.channel.send(eval(suffix, bot));
} else {
msg.channel.send(msg.author + " doesn't have permission to execute eval!");
}
}
}
};
if (AuthDetails.hasOwnProperty("client_id")) {
commands[ "invite" ] = {
description: "generates an invite link you can use to invite the bot to your server",
process: function (bot, msg, suffix) {
msg.channel.send("invite link: https://discordapp.com/oauth2/authorize?&client_id=" + AuthDetails.client_id + "&scope=bot&permissions=470019135");
}
}
}
try {
messagebox = require(__dirname + "/messagebox.json");
} catch (e) {
//no stored messages
messagebox = {};
}
function updateMessagebox() {
require("fs").writeFile(__dirname + "/messagebox.json", JSON.stringify(messagebox, null, 2), null);
}
var bot = new Discord.Client();
bot.on("ready", function () {
console.log("Logged in! Serving in " + bot.guilds.array().length + " servers");
require(__dirname + "/plugins.js").init();
console.log("type " + Config.commandPrefix + "help in Discord for a commands list.");
bot.user.setGame(Config.commandPrefix + "help | " + bot.guilds.array().length + " Servers");
});
bot.on("disconnected", function () {
console.log("Disconnected!");
process.exit(1); //exit node.js with an error
});
function checkMessageForCommand(msg, isEdit) {
//check if message is a command
if (msg.author.id != bot.user.id && (msg.content.startsWith(Config.commandPrefix))) {
console.log("treating " + msg.content + " from " + msg.author + " as command");
var cmdTxt = msg.content.split(" ")[ 0 ].substring(Config.commandPrefix.length);
var suffix = msg.content.substring(cmdTxt.length + Config.commandPrefix.length + 1);//add one for the ! and one for the space
if (msg.isMentioned(bot.user)) {
try {
cmdTxt = msg.content.split(" ")[ 1 ];
suffix = msg.content.substring(bot.user.mention().length + cmdTxt.length + Config.commandPrefix.length + 1);
} catch (e) { //no command
msg.channel.send("Yes?");
return;
}
}
alias = aliases[ cmdTxt ];
if (alias) {
console.log(cmdTxt + " is an alias, constructed command is " + alias.join(" ") + " " + suffix);
cmdTxt = alias[ 0 ];
suffix = alias[ 1 ] + " " + suffix;
}
var cmd = commands[ cmdTxt ];
if (cmdTxt === "help") {
//help is special since it iterates over the other commands
if (suffix) {
var cmds = suffix.split(" ").filter(function (cmd) { return commands[ cmd ] });
var info = "";
for (var i = 0; i < cmds.length; i++) {
var cmd = cmds[ i ];
info += "**" + Config.commandPrefix + cmd + "**";
var usage = commands[ cmd ].usage;
if (usage) {
info += " " + usage;
}
var description = commands[ cmd ].description;
if (description instanceof Function) {
description = description();
}
if (description) {
info += "\n\t" + description;
}
info += "\n"
}
msg.channel.send(info);
} else {
msg.author.send("**Available Commands:**").then(function () {
var batch = "";
var sortedCommands = Object.keys(commands).sort();
for (var i in sortedCommands) {
var cmd = sortedCommands[ i ];
var info = "**" + Config.commandPrefix + cmd + "**";
var usage = commands[ cmd ].usage;
if (usage) {
info += " " + usage;
}
var description = commands[ cmd ].description;
if (description instanceof Function) {
description = description();
}
if (description) {
info += "\n\t" + description;
}
var newBatch = batch + "\n" + info;
if (newBatch.length > (1024 - 8)) { //limit message length
msg.author.send(batch);
batch = info;
} else {
batch = newBatch
}
}
if (batch.length > 0) {
msg.author.send(batch);
}
});
}
}
else if (cmd) {
if (Permissions.checkPermission(msg.author, cmdTxt)) {
try {
cmd.process(bot, msg, suffix, isEdit);
} catch (e) {
var msgTxt = "command " + cmdTxt + " failed :(";
if (Config.debug) {
msgTxt += "\n" + e.stack;
}
msg.channel.send(msgTxt);
}
} else {
msg.channel.send("You are not allowed to run " + cmdTxt + "!");
}
} else {
msg.channel.send(cmdTxt + " not recognized as a command!").then((message => message.delete(5000)))
}
} else {
//message isn't a command or is from us
//drop our own messages to prevent feedback loops
if (msg.author == bot.user) {
return;
}
if (msg.author != bot.user && msg.isMentioned(bot.user)) {
msg.channel.send("yes?"); //using a mention here can lead to looping
} else {
}
}
}
bot.on("message", (msg) => checkMessageForCommand(msg, false));
bot.on("messageUpdate", (oldMessage, newMessage) => {
checkMessageForCommand(newMessage, true);
});
//Log user status changes
bot.on("presence", function (user, status, gameId) {
//if(status === "online"){
//console.log("presence update");
console.log(user + " went " + status);
//}
try {
if (status != 'offline') {
if (messagebox.hasOwnProperty(user.id)) {
console.log("found message for " + user.id);
var message = messagebox[ user.id ];
var channel = bot.channels.get("id", message.channel);
delete messagebox[ user.id ];
updateMessagebox();
bot.send(channel, message.content);
}
}
} catch (e) { }
});
exports.addCommand = function (commandName, commandObject) {
try {
commands[ commandName ] = commandObject;
} catch (err) {
console.log(err);
}
}
exports.commandCount = function () {
return Object.keys(commands).length;
}
if (AuthDetails.bot_token) {
console.log("logging in with token");
bot.login(AuthDetails.bot_token);
} else {
console.log("Logging in with user credentials is no longer supported!\nYou can use token based log in with a user account, see\nhttps://discord.js.org/#/docs/main/master/general/updating");
}