forked from chalda/DiscordBot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdiscord_bot.js
More file actions
executable file
·454 lines (424 loc) · 13.3 KB
/
discord_bot.js
File metadata and controls
executable file
·454 lines (424 loc) · 13.3 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
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!"); // if there is an error, tell to install dependencies.
process.exit();
}
console.log("Starting DiscordBot\nNode version: " + process.version + "\nDiscord.js version: " + Discord.version); // send message notifying bot boot-up
// Get authentication data
try {
var AuthDetails = require("./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); // send message for error - no token
process.exit();
}
// Load custom permissions
var dangerousCommands = ["eval","pullanddeploy","setUsername","cmdauth"]; // set array if dangerous commands
var Permissions = {};
try{
Permissions = require("./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 (userid,permission){
//var usn = user.username + "#" + user.discriminator;
//console.log("Checking " + permission + " permission for " + usn);
try {
var allowed = true;
try{
if(Permissions.global.hasOwnProperty(permission)){
allowed = Permissions.global[permission] === true;
}
} catch(e){}
try{
if(Permissions.users[userid].hasOwnProperty("*")){
allowed = Permissions.users[userid]["*"] === true;
}
if(Permissions.users[userid].hasOwnProperty(permission)){
allowed = Permissions.users[userid][permission] === true;
}
} catch(e){}
return allowed;
} catch(e){}
return false;
}
fs.writeFile("./permissions.json",JSON.stringify(Permissions,null,2), (err) => {
if(err) console.error(err);
});
//load config data
var Config = {};
try{
Config = require("./config.json");
} catch(e){ //no config file, use defaults
Config.debug = false;
Config.commandPrefix = '!';
try{
if(fs.lstatSync("./config.json").isFile()){ // open config file
console.log("WARNING: config.json found but we couldn't read it!\n" + e.stack); // corrupted config file
}
} catch(e2){
fs.writeFile("./config.json",JSON.stringify(Config,null,2), (err) => {
if(err) console.error(err);
});
}
}
if(!Config.hasOwnProperty("commandPrefix")){
Config.commandPrefix = '!'; // set bots prefix
}
var messagebox;
var aliases;
try{
aliases = require("./alias.json");
} catch(e) {
//No aliases defined
aliases = {};
}
commands = { // all commands list below
"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("./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").then(console.log).catch(console.error);
}
},
"online": {
usage: "[status]",
description: "Sets bot status to online.",
process: function(bot,msg,suffix){
bot.user.setStatus("online").then(console.log).catch(console.error);
}
},
"say": {
usage: "<message>",
description: "Bot sends message",
process: function(bot,msg,suffix){ msg.channel.send(suffix);}
},
"announce": {
usage: "<message>",
description: "Bot sends message in text to speech.",
process: function(bot,msg,suffix){ msg.channel.send(suffix,{tts:true});}
},
"msg": {
usage: "<user> <message to send user>",
description: "Sends a message to 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) {
let result = eval(suffix,bot).toString();
if(result) {
msg.channel.send(result);
}
}
},
"cmdauth": {
usage: "<userid> <get/toggle> <command>",
description: "Gets/toggles command usage permissions for the specified user.",
process: function(bot,msg,suffix) {
var Permissions = require("./permissions.json");
var fs = require('fs');
var args = suffix.split(' ');
var userid = args.shift();
var action = args.shift();
var cmd = args.shift();
if(userid.startsWith('<@')){
userid = userid.substr(2,userid.length-3);
}
var target = msg.channel.guild.members.find("id",userid);
if(!target) {
msg.channel.send("Could not find user.");
} else {
if(commands[cmd] || cmd === "*") {
var canUse = Permissions.checkPermission(userid,cmd);
var strResult;
if(cmd === "*") {
strResult = "All commands"
} else {
strResult = 'Command "' + cmd + '"';
}
if(action.toUpperCase() === "GET") {
msg.channel.send("User permissions for " + strResult + " are " + canUse);
} else if(action.toUpperCase() === "TOGGLE") {
if(Permissions.users.hasOwnProperty(userid)) {
Permissions.users[userid][cmd] = !canUse;
}
else {
Permissions.users[userid].append({[cmd] : !canUse});
}
fs.writeFile("./permissions.json",JSON.stringify(Permissions,null,2));
msg.channel.send("User permission for " + strResult + " set to " + Permissions.users[userid][cmd]);
} else {
msg.channel.send('Requires "get" or "toggle" parameter.');
}
} else {
msg.channel.send("Invalid command.")
}
}
}
}
};
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"); // send link to invite bot into server.
}
}
}
try{
messagebox = require("./messagebox.json");
} catch(e) {
//no stored messages
messagebox = {};
}
function updateMessagebox(){
require("fs").writeFile("./messagebox.json",JSON.stringify(messagebox,null,2), null);
}
var bot = new Discord.Client();
var hooks = {
onMessage: []
}
bot.on("ready", function () {
console.log("Logged in! Currently serving " + bot.guilds.array().length + " servers.");
require("./plugins.js").init(hooks);
console.log("Type "+Config.commandPrefix+"help on Discord for a command list.");
bot.user.setPresence({
game: {
name: Config.commandPrefix+"help | " + bot.guilds.array().length +" Servers"
}
});
});
bot.on("disconnected", function () {
console.log("Disconnected!"); // send message that bot has 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 false;
}
}
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);
}
});
}
return true;
}
else if(cmd) {
if(Permissions.checkPermission(msg.author.id,cmdTxt)){
try{
cmd.process(bot,msg,suffix,isEdit);
} catch(e){
var msgTxt = "command " + cmdTxt + " failed :(";
if(Config.debug){
msgTxt += "\n" + e.stack;
console.log(msgTxt);
}
if(msgTxt.length > (1024 - 8)){ //Truncate the stack if it's too long for a discord message
msgTxt = msgTxt.substr(0,1024-8);
}
msg.channel.send(msgTxt);
}
} else {
msg.channel.send("You are not allowed to run " + cmdTxt + "!");
}
return true;
} else {
msg.channel.send(cmdTxt + " is not not recognized as a command!").then((message => message.delete(5000)))
return true;
}
} else {
//message is not a command or is from us
//drop our own messages to prevent feedback loops
if(msg.author == bot.user){
return true; //returning true to prevent feedback from commands
}
if (msg.author != bot.user && msg.isMentioned(bot.user)) {
//msg.channel.send("yes?"); //using a mention here can lead to looping
} else {
}
return false;
}
}
bot.on("message", (msg) => {
if(!checkMessageForCommand(msg, false)){
for(msgListener of hooks.onMessage){
msgListener(msg);
}
}
});
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.");
}