-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
801 lines (786 loc) · 32.7 KB
/
app.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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
#!/usr/bin/env node
'use strict';
var appDir = require("path").dirname(require.main.filename);
process.chdir(appDir);
var CURRENT_VERSION = require('./package.json').version;
var commander = require("commander");
var EventEmitter = require("events");
var storage = require("node-persist");
var discord_io = require("discord.io");
var read = require("read");
var plugin_loader;
var discord;
var api = {};
var store = storage.create({ dir: process.cwd() + "/storage/main_app" });
store.initSync();
require("request").get("https://registry.npmjs.org/extendable-discord-bot", function (err, response, body) {
if (err) return;
var LATEST_VERSION = CURRENT_VERSION;
try { LATEST_VERSION = JSON.parse(body)['dist-tags'].latest; } catch (e) { return; }
if (require("semver").lt(CURRENT_VERSION, LATEST_VERSION)) {
console.log("[WARNING]: Your bot is out of date! Your version is " + CURRENT_VERSION + ", but the latest version is " + LATEST_VERSION + ". Consider updating!");
api.UPDATE_AVAILABLE = true;
api.LATEST_VERSION = LATEST_VERSION;
} else {
api.UPDATE_AVAILABLE = false;
}
});
api.Events = new EventEmitter;
api.Events.setMaxListeners(0);
api.sharedStorage = storage.create({ dir: process.cwd() + "/storage/shared_storage" });
api.sharedStorage.initSync();
api.VERSION = CURRENT_VERSION;
function initPluginLoader() {
var loader_storage = storage.create({ dir: process.cwd() + "/storage/plugin_loader" });
loader_storage.initSync();
plugin_loader = require("./modules/plugin_loader.js"); plugin_loader = new plugin_loader(api, loader_storage, CURRENT_VERSION);
api.plugin_manager = {
load: function (file_id, quiet) {
console.log("[Plugin]Plugin requests loading of " + file_id);
return plugin_loader.loadPlugin(file_id, quiet);
},
unload: function (file_id, quiet) {
console.log("[Plugin]Plugin requests unloading of " + file_id);
return plugin_loader.unloadPlugin(file_id, quiet);
},
start: function (file_id, quiet) {
console.log("[Plugin]Plugin requests starting of " + file_id);
return plugin_loader.startedPlugins(file_id, quiet);
},
stop: function (file_id, quiet) {
console.log("[Plugin]Plugin requests stopping of " + file_id);
return plugin_loader.stopPlugin(file_id, quiet);
},
listPlugins: function () {
return plugin_loader.listPlugins();
},
getPlugin: function (fileID) {
var plugin = Object.assign({}, plugin_loader.getPlugin(fileID));
plugin.start = function () { console.log("Plugins are not allowed to call another plugin's start function!"); }
plugin.stop = function () { console.log("Plugins are not allowed to call another plugin's stop function!"); }
plugin.load = function () { console.log("Plugins are not allowed to call another plugin's load function!"); }
plugin.unload = function () { console.log("Plugins are not allowed to call another plugin's unload function!"); }
return plugin;
},
getPluginInfo: function (fileID) {
return plugin_loader.getPluginInfo(fileID);
},
isPluginLoaded: function (fileID) {
return plugin_loader.isPluginLoaded(fileID);
},
listLoadedPlugins: function () {
return plugin_loader.getLoadedPlugins()
},
isPluginRunning: function (fileID) {
return plugin_loader.isPluginRunning(fileID);
},
getStartedPlugins: function () {
return plugin_loader.getStartedPlugins();
}
}
}
var manual_disconnect = false;
function retryConnection(nextTry) {
if (!api.connected) api.connection.connect();
api.connected = discord.connected;
if (!api.connected) {
setTimeout(retryConnection.bind(this, nextTry * 2), nextTry);
}
}
function connectToDiscord() {
discord = new discord_io({
autorun: true,
token: process.env.DISCORD_TOKEN,
email: process.env.DISCORD_EMAIL,
password: process.env.DISCORD_PASSWORD
}).on("ready", function (rawEvent) {
api.voiceChannel = null;
api.client = {};
api.client.username = discord.username;
api.username = api.client.username;
api.client.id = discord.id;
api.client.email = discord.email;
api.client.avatar_hash = discord.avatar;
api.client.avatar = "https://cdn.discordapp.com/avatars/" + api.client.id + "/" + api.client.avatar_hash + ".jpg";
api.client.presence = discord.presenceStatus;
api.presence = api.client.presence;
api.connected = discord.connected;
api.client.directMessages = discord.directMessages;
api.client.servers = discord.servers;
api.servers = api.client.servers;
api.Events.emit("ready");
api.Events.emit("ready_raw", rawEvent);
try {
require.resolve("node-opus");
api.canSendSound = true;
} catch (e) {
api.canSendSound = false;
}
api.connection = {
connect: function () {
discord.connect();
api.connected = discord.connected;
},
disconnect: function () {
manual_disconnect = true;
discord.disconnect();
api.connected = discord.connected;
}
};
api.status = {
setPresence: discord.setPresence,
userInfo: {
changeEmail: function (new_mail) {
discord.editUserInfo({
email: new_mail,
password: process.env.DISCORD_PASSWORD
});
},
changeUsername: function (new_name) {
discord.editUserInfo({
password: process.env.DISCORD_PASSWORD,
username: new_name
});
},
changeAvatar: function (icon) {
discord.editUserInfo({
avatar: icon,
password: process.env.DISCORD_PASSWORD
});
},
changeAvatarFromFile: function (file_path) {
discord.editUserInfo({
avatar: require("fs").readFileSync(file_path, "base64"),
password: process.env.DISCORD_PASSWORD
});
}
}
};
api.content = {
sendMessage: discord.sendMessage,
uploadFile: discord.uploadFile,
getMessages: discord.getMessages,
editMessage: discord.editMessage,
simulateTyping: discord.simulateTyping,
deleteMessage: discord.deleteMessage,
fixMessage: discord.fixMessage
};
api.Messages = {
sendMessage: discord.sendMessage,
send: function (_to, _message) {
var msg = _message;
if (msg.length > 2000) {
console.log("Message exceeds character limit. Message length: " + msg.length);
msg = "Message exceeds Discord character limit.";
}
discord.sendMessage({
to: _to,
message: msg,
tts: false,
typing: false
});
api.Events.emit("sendMessage", _to, _message);
},
sendTTS: function (_to, _message) {
var msg = _message;
if (msg.length > 2000) {
console.log("Message exceeds character limit. Message length: " + msg.length);
msg = "Message exceeds Discord character limit.";
}
discord.sendMessage({
to: _to,
message: msg,
tts: true,
typing: false
});
api.Events.emit("sendTTSMessage", _to, _message);
},
uploadFile: api.content.uploadFile
}
api.sendMessage = api.Messages.send;
api.sendTTSMessage = api.Messages.sendTTS;
api.management = {
createServer: function (options, callback) {
discord.createServer(options, function (error, response) {
if (!error) api.Events.emit("createdDiscordServer", response);
if (callback) callback(error, response);
});
},
deleteServer: function (options, callback) {
discord.deleteServer(options, function (error, response) {
if (!error) api.Events.emit("deletedDiscordServer", options.server, response);
if (callback) callback(error, response);
});
},
createChannel: function (options, callback) {
discord.createChannel(options, function (error, response) {
if (!error) api.Events.emit("createdDiscordChannel", response);
if (callback) callback(error, response);
});
},
deleteChannel: function (options, callback) {
discord.deleteChannel(options, function (error, response) {
if (!error) api.Events.emit("deletedDiscordChannel", options.channel, response);
if (callback) callback(error, response);
});
},
editChannelInfo: discord.editChannelInfo,
acceptInvite: function (inviteCode, callback) {
if (inviteCode.indexOf("/") !== -1) {
inviteCode = inviteCode.substring(inviteCode.lastIndexOf("/") + 1);
}
discord.acceptInvite(inviteCode, function (error, response) {
if (!error) api.Events.emit("joinedServer", response);
if (callback) callback(error, response);
});
},
createInvite: discord.createInvite,
roles: {
createRole: discord.createRole,
editRole: discord.editRole,
deleteRole: discord.deleteRole,
addToRole: discord.addToRole,
removeFromRole: discord.removeFromRole
},
moderation: {
kick: discord.kick,
ban: discord.ban,
unban: discord.unban,
mute: discord.mute,
unmute: discord.unmute,
deafen: discord.deafen,
undeafen: discord.undeafen
}
}
api.roles = api.management.roles;
api.moderation = api.management.moderation;
api.voice = {
joinChannel: function (channelID, callback) {
discord.joinVoiceChannel(channelID, function () {
api.voiceChannel = channelID;
api.Events.emit("voiceChannelJoined", channelID);
if (callback) callback();
});
},
leaveChannel: function (channelID, callback) {
discord.leaveVoiceChannel(channelID, function () {
api.voiceChannel = null;
api.Events.emit("voiceChannelLeft", channelID);
if (callback) callback();
});
},
getAudioContext: discord.getAudioContext
}
api.misc = {
serverFromChannel: discord.serverFromChannel
};
// Load all Plugins in the ./plugins directory
var quiet_loading = true;
plugin_loader.listPlugins().forEach(function (item) {
var plugin_state = plugin_loader.getInitialPluginState(item);
if (plugin_state === "running" || plugin_state === "loaded") {
plugin_loader.loadPlugin(item, quiet_loading);
}
if (plugin_state === "running") {
plugin_loader.startPlugin(item, quiet_loading);
}
});
}).on("message", function (_username, _userID, _channelID, _message, _rawEvent) {
api.Events.emit("message_raw", _rawEvent);
if (_userID === api.client.id) {
api.Events.emit("selfMessage", {
username: _username,
userID: _userID,
channelID: _channelID,
message: discord.fixMessage(_message),
msg: discord.fixMessage(_message),
message_raw: _message,
rawEvent: _rawEvent
});
} else {
api.Events.emit("otherMessage", {
username: _username,
userID: _userID,
channelID: _channelID,
message: discord.fixMessage(_message),
msg: discord.fixMessage(_message),
message_raw: _message,
rawEvent: _rawEvent
});
}
if (_message.indexOf("<@" + api.client.id + ">") !== -1) {
api.Events.emit("botMention", {
username: _username,
userID: _userID,
channelID: _channelID,
message: discord.fixMessage(_message),
msg: discord.fixMessage(_message),
message_raw: _message,
rawEvent: _rawEvent
});
api.Events.emit("botMention_raw", _rawEvent);
}
if (_channelID === _userID) {
api.Events.emit("directMessage", {
username: _username,
userID: _userID,
channelID: _channelID,
message: discord.fixMessage(_message),
msg: discord.fixMessage(_message),
message_raw: _message,
rawEvent: _rawEvent
});
}
api.Events.emit("message", {
username: _username,
userID: _userID,
channelID: _channelID,
message: discord.fixMessage(_message),
msg: discord.fixMessage(_message),
message_raw: _message,
rawEvent: _rawEvent
});
var cmd_prefix = store.getItemSync("chat_command_prefix") || "!";
if (_message.startsWith(cmd_prefix)) {
var cmd_args = _message.split(" ");
var cmd = cmd_args.splice(0, 1)[0].substring(1).toLowerCase();
api.Events.emit("chatCmd", {
cmd: cmd,
args: cmd_args,
channelID: _channelID,
username: _username,
userID: _userID,
});
api.Events.emit("chatCmd#" + cmd, {
args: cmd_args,
channelID: _channelID,
username: _username,
userID: _userID,
});
api.Events.emit("chatCmd_raw", _rawEvent);
api.Events.emit("chatCmd#" + cmd + "_raw", _rawEvent);
}
}).on("presence", function (_username, _userID, _status, _gameName, _rawEvent) {
api.Events.emit("presence", {
username: _username,
userID: _userID,
status: _status,
game: _gameName,
rawEvent: _rawEvent
});
api.Events.emit("presence_raw", _rawEvent);
}).on("disconnected", function () {
api.connected = discord.connected;
api.Events.emit("disconnected");
if (!manual_disconnect) {
retryConnection(5000);
} else {
manual_disconnect = false;
}
}).on("debug", function (rawEvent) {
api.Events.emit("debug", rawEvent);
});
}
initPluginLoader();
// Load commandline args as env variables
commander.version(CURRENT_VERSION).usage("[options]")
.option("-e, --email <Picarto Channel>", "Set the bots Login Username.")
.option("-p, --password <Bot name>", "Set the bot's Login Password.")
.option("-t, --token <Token>", "Use an already existing token to login.")
.parse(process.argv);
if (commander.token) process.env.DISCORD_TOKEN = commander.token;
if (commander.email) process.env.DISCORD_EMAIL = commander.email;
if (commander.password) process.env.DISCORD_PASSWORD = commander.password;
if (process.env.DISCORD_TOKEN) {
console.log("Attempting token based connection, please be patient...");
connectToDiscord();
} else if (process.env.DISCORD_PASSWORD && process.env.DISCORD_EMAIL) {
console.log("Attempting to connect, this might take a moment. Please be patient...");
connectToDiscord();
} else {
console.log("No login information given.");
function readEmail() {
read({ prompt: "EMail: " }, function (err, email, isDefault) {
if (!email) {
readEmail();
return;
}
process.env.DISCORD_EMAIL = email;
readPassword();
});
}
function readPassword() {
read({ prompt: "Password: ", replace: "*", silent: true }, function (err, password, isDefault) {
if (!password) {
readPassword();
return;
}
process.env.DISCORD_PASSWORD = password;
connectToDiscord();
});
}
readEmail();
}
function plugin_cmd(args) {
var columnify = require("columnify");
function printHelp() {
var commands = {
"list": "List status of all plugins",
"load <filename>": "Load a plugin from the /plugins directory",
"start <filename>": "Start a previously loaded plugin",
"enable <filename>": "Loads and starts a plugin from the /plugins directory",
"stop <filename>": "Stop a previously loaded plugin",
"unload <filename>": "Unload a previously loaded plugin",
"disable <filename>": "Stops and unloads a previously loaded plugin",
"reload <filename>": "Fully reload a plugin (Stop->Unload->Load->Start)",
"clearstorage <filename>": "Clear the Plugins storage. Plugin restarts in the process"
}
console.log(
"\n" +
"Plugin Loader Commands\n\n" +
"\tUsage: plugins <subcommand> [arguments]\n\nSubcommands:\n" +
columnify(commands, {
columnSplitter: " - ",
showHeaders: false
})
);
}
var subcmd = args.splice(0, 1)[0];
if (subcmd) {
switch (subcmd.toLowerCase()) {
case "help":
printHelp();
break;
case "load":
var file_id = args.splice(0, 1)[0];
if (file_id) {
plugin_loader.loadPlugin(file_id);
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins load <File Name>\n");
}
break;
case "unload":
var file_id = args.splice(0, 1)[0];
if (file_id) {
plugin_loader.unloadPlugin(file_id);
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins unload <File Name>\n");
}
break;
case "start":
var file_id = args.splice(0, 1)[0];
if (file_id) {
plugin_loader.startPlugin(file_id);
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins start <File Name>\n");
}
break;
case "stop":
var file_id = args.splice(0, 1)[0];
if (file_id) {
plugin_loader.stopPlugin(file_id);
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins stop <File Name>\n");
}
break;
case "enable":
var file_id = args.splice(0, 1)[0];
if (file_id) {
if (plugin_loader.isPluginLoaded(file_id) && !plugin_loader.isPluginRunning(file_id)) {
if (plugin_loader.startPlugin(file_id, true)) {
console.log("[PluginLoader]Successfully started Plugin " + file_id);
} else {
console.log("[PluginLoader]Failed to start Plugin " + file_id + ". Please try 'plugins start " + file_id + "'.");
}
} else if (!plugin_loader.isPluginLoaded(file_id)) {
if (
plugin_loader.loadPlugin(file_id, true) &&
plugin_loader.startPlugin(file_id, true)
) {
console.log("[PluginLoader]Successfully loaded and started Plugin " + file_id);
} else {
console.log("[PluginLoader]Failed to load or start Plugin " + file_id + ". Please try 'plugins load " + file_id + "' and then 'plugins start " + file_id + "'.");
}
} else {
console.log("[PluginLoader]Plugin " + file_id + " is already running.");
}
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins enable <File Name>\n");
}
break;
case "disable":
var file_id = args.splice(0, 1)[0];
if (file_id) {
if (plugin_loader.isPluginLoaded(file_id) && !plugin_loader.isPluginRunning(file_id)) {
if (plugin_loader.unloadPlugin(file_id, true)) {
console.log("[PluginLoader]Successfully unloaded Plugin " + file_id);
} else {
console.log("[PluginLoader]Failed to unload Plugin " + file_id + ". Please try 'plugins unload " + file_id + "'.");
}
} else if (plugin_loader.isPluginRunning(file_id)) {
if (
plugin_loader.stopPlugin(file_id, true) &&
plugin_loader.unloadPlugin(file_id, true)
) {
console.log("[PluginLoader]Successfully stopped and unloaded Plugin " + file_id);
} else {
console.log("[PluginLoader]Failed to load or start Plugin " + file_id + ". Please try 'plugins stop " + file_id + "' and then 'plugins unload " + file_id + "'.");
}
} else {
console.log("[PluginLoader]Plugin " + file_id + " is already disabled.");
}
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins enable <File Name>\n");
}
break;
case "reload":
var file_id = args.splice(0, 1)[0];
if (file_id) {
var isRunning = plugin_loader.isPluginRunning(file_id);
if (
(!isRunning || plugin_loader.stopPlugin(file_id, true)) &&
(!plugin_loader.isPluginLoaded(file_id) || plugin_loader.unloadPlugin(file_id, true)) &&
plugin_loader.loadPlugin(file_id, true) &&
isRunning ? plugin_loader.startPlugin(file_id, true) : true
) {
console.log("[PluginLoader]Plugin " + file_id + " reloaded successfully");
} else {
console.log("[PluginLoader]Plugin " + file_id + " reload failed! Please reload manually (Stop -> Unload -> Load -> Start).");
}
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins reload <File Name>");
}
break;
case "clearstorage":
var file_id = args.splice(0, 1)[0];
if (file_id) {
plugin_loader.deleteStorage(file_id);
} else {
console.log("No Plugin File specified!\n\n\tUsage: plugins clearstorage <File Name>");
}
break;
case "list":
var column_divider = {
plugin_name: "------",
plugin_version: "-------",
plugin_author: "------",
plugin_description: "-----------",
plugin_state: "-----",
plugin_file: "----"
}
var data = [
{
plugin_name: "Plugin",
plugin_version: "Version",
plugin_author: "Author",
plugin_description: "Description",
plugin_state: "State",
plugin_file: "File"
},
column_divider
]
var plugin_info; var plugin_state; var plugin;
var list = plugin_loader.listPlugins();
for (var plugin_index in list) {
try {
plugin = list[plugin_index];
plugin_info = plugin_loader.getPluginInfo(plugin);
if (plugin_loader.isPluginRunning(plugin)) {
plugin_state = "Running";
} else if (plugin_loader.isPluginLoaded(plugin)) {
plugin_state = "Stopped";
} else {
plugin_state = "Unloaded"
}
data.push({
plugin_name: plugin_info.Name,
plugin_version: plugin_info.Version,
plugin_author: plugin_info.Author,
plugin_description: plugin_info.Description,
plugin_state: plugin_state,
plugin_file: plugin.replace(/\.dbot\.js/, ""),
});
} catch (ex) {
data.push({
plugin_name: "ERROR",
plugin_version: "ERROR",
plugin_author: "ERROR",
plugin_description: ex,
plugin_state: "errored",
plugin_file: plugin.replace(/\.dbot\.js/, ""),
});
}
data.push(column_divider);
}
console.log(
"\n" +
columnify(data, {
columnSplitter: " | ",
showHeaders: false,
maxLineWidth: "auto",
config: {
plugin_description: { maxWidth: 20, align: "center" },
plugin_name: { maxWidth: 10 }
}
})
);
break;
default:
console.log("Unknown subcommand. Type 'plugins help' for a full list of commands");
break;
}
} else {
printHelp();
}
}
function bot_cmd(args) {
var columnify = require("columnify");
function printHelp() {
var commands = {
"disconnect": "Disconnect from Discord",
"connect": "Connect to Discord",
"reconnect": "Close and re-establish connection to Discord",
"join <Invitation Code>": "Join a Server with an invite code",
"exit": "Shuts the bot down"
}
console.log(
"\n" +
"Bot Commands\n\n" +
"\tUsage: bot <subcommand> [arguments]\n\nSubcommands:\n" +
columnify(commands, {
columnSplitter: " - ",
showHeaders: false
})
);
}
var subcmd = args.splice(0, 1)[0];
if (subcmd) {
switch (subcmd.toLowerCase()) {
case "help":
printHelp();
break;
case "disconnect":
if (api.connected) {
api.connection.disconnect();
api.connected = discord.connected;
} else {
console.log("Not connected to Discord!");
}
break;
case "connect":
if (!api.connected) {
api.connection.connect();
api.connected = discord.connected;
} else {
console.log("Already connected to Discord as '" + api.client.username + "'!");
}
break;
case "reconnect":
if (api.connected) api.connection.disconnect();
api.connection.connect();
break;
case "exit":
case "quit":
process.exit();
break;
case "join":
var inviteCode = args.splice(0, 1)[0];
if (!inviteCode) {
console.log("No Invitation Code specified!\n\n\tUsage: bot join <Invitation Code>\n");
break;
}
api.management.acceptInvite(inviteCode, function (error, resp) {
if (!error) {
console.log("Successfully joined Server! " + resp);
} else {
console.log("Error occured while joining Server: " + error);
}
});
break;
case "say":
var channelID = args.splice(0, 1)[0];
if (isNaN(parseInt(channelID))) {
console.log("No Channel ID specified!\n\n\tUsage: bot say <Invitation Code> <message>\n");
break;
}
api.Messages.send(channelID, args.join(" "));
break;
case "list":
for (var server in api.client.servers) {
console.log(api.client.servers[server].name + " (" + api.client.servers[server].id + "):");
for (var channel in api.client.servers[server].channels) {
console.log("\t" + api.client.servers[server].channels[channel].name + " (" + api.client.servers[server].channels[channel].id + "): " + api.client.servers[server].channels[channel].type)
}
}
break;
default:
if (api.Events.listenerCount("botCommand") || api.Events.listenerCount("botCommand#" + subcmd.toLowerCase())) {
api.Events.emit("botCommand", subcmd.toLowerCase(), args);
api.Events.emit("botCommand#" + subcmd.toLowerCase(), args);
} else {
console.log("Unknown subcommand. Type 'bot help' for a full list of commands");
}
break;
}
} else {
printHelp();
}
}
process.stdin.on('readable', function () {
function printHelp() {
var columnify = require("columnify");
var commands = {
"plugins|pl <subcommand>": "Everything related with plugins can be done here",
"bot|discord <subcommand>": "All discord backend related functions",
"clear|cls": "Clears the screen",
"exit|quit": "Shuts the bot down",
"help": "Show this help"
}
console.log(
"\n" +
"Bot Commands\n\n" +
"\tUsage: <command> <subcommand> [arguments]\n\n" +
columnify(commands, {
columnSplitter: " - ",
showHeaders: false
}) + "\n\n" +
"All Commands that accept subcommands come with a help subcommand\n\n"
);
}
var chunk = process.stdin.read();
if (chunk !== null) {
var input = chunk.toString().trim();
var args = input.split(" ");
var cmd = args.splice(0, 1)[0];
switch (cmd.toLowerCase()) {
case "plugins":
case "pl":
case "plugin":
plugin_cmd(args);
break;
case "bot":
case "discord":
bot_cmd(args);
break;
case "clear":
case "cls":
require("cli-clear")();
break;
case "exit":
case "quit":
process.exit();
break;
case "help":
printHelp();
break;
default:
if (api.Events.listenerCount("command") || api.Events.listenerCount("command#" + cmd.toLowerCase())) {
api.Events.emit("command", cmd.toLowerCase(), args);
api.Events.emit("command#" + cmd.toLowerCase(), args);
} else {
console.log("\n\nInvalid Command. Use 'help' to get a list of commands.");
}
break;
}
}
});