-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
911 lines (890 loc) · 40.1 KB
/
app.js
File metadata and controls
911 lines (890 loc) · 40.1 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
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
#!/usr/bin/env node
'use strict';
var io = require("socket.io-client");
var entities = require("entities");
var request = require("sync-request");
var commander = require("commander");
var EventEmitter = require("events");
var storage = require("node-persist");
var picarto = require("./modules/picarto.js");
var http = require('http');
var jade = require('jade');
var config = require("./config.json") || {};
var socket;
var plugin_loader;
var api = {};
var socket = {};
var store = storage.create({ dir: process.cwd() + "/storage/main_app" });
var inputLog = [];
store.initSync();
api.version = "1.2.1";
api.Events = new EventEmitter;
api.Events.setMaxListeners(0);
api.readOnly = {};
api.jade = jade;
api.sharedStorage = storage.create({ dir: process.cwd() + "/storage/shared_storage" });
api.sharedStorage.initSync();
api.mute_manager = {
__channels: [],
isMuted: function(channel){
return this.__channels.indexOf(channel.toLowerCase()) > -1;
},
mute: function(channel){
if(this.__channels.indexOf(channel.toLowerCase()) === -1){
this.__channels.push(channel.toLowerCase());
}
},
unmute: function(channel){
var index = this.__channels.indexOf(channel.toLowerCase());
if(index > -1){
this.__channels.splice(index,1);
}
}
};
api.permissions_manager = {
PERMISSION_USER: 1,
PERMISSION_ADMIN: 2,
PERMISSION_MOD: 4,
PERMISSION_PTVADMIN: 8,
__permsCache: {},
__defaultLevel: 6,
getPerm: function (channel, pId, defaultPermLevel) {
channel = channel.toLowerCase();
this.__permsCache = store.getItem("permissions") || {};
this.__permsCache[channel] = this.__permsCache[channel] || {};
return this.__permsCache[channel][pId] = (typeof this.__permsCache[channel][pId] !== 'undefined') ? this.__permsCache[channel][pId] : {id: pId, level: (typeof defaultPermLevel !== 'undefined' ? defaultPermLevel : this.PERMISSION_ADMIN | this.PERMISSION_MOD), whitelist: [], blacklist: []};
},
savePerms: function () {
store.setItem("permissions", this.__permsCache);
},
isOwner: function (userData) {
return (userData.username.toLowerCase() === userData.channel.toLowerCase()) || this.isGlobalAdmin(userData);
},
isGlobalAdmin: function (userData){
var globalAdmins = store.getItem("admins") || [];
return globalAdmins.indexOf(userData.username.toLowerCase()) > -1;
},
addGlobalAdmin: function(username){
var globalAdmins = store.getItem("admins") || [];
if(globalAdmins.indexOf(username.toLowerCase()) === -1){
globalAdmins.push(username.toLowerCase());
store.setItem("admins",globalAdmins);
}
},
removeGlobalAdmin: function(username){
var globalAdmins = store.getItem("admins") || [];
var index = globalAdmins.indexOf(username.toLowerCase());
if(index > -1){
globalAdmins.splice(index,1);
store.setItem("admins",globalAdmins);
}
},
getGlobalAdmins: function(){
return store.getItem("admins") || [];
},
userHasPermission: function (user, pId, defaultPermLevel) { // !onblacklist && (permLevelCheck || (onwhitelist && registered))
var p = this.getPerm(user.channel.toLowerCase(), pId, defaultPermLevel);
return !(p.blacklist.indexOf(user.username) !== -1) && ((p.level & this.getUserPermissionLevel(user) !== 0) || ((p.whitelist.indexOf(user.username) !== -1) && user.registered));
},
getUserPermissionLevel: function (userData) {
return (!(userData.admin || userData.mod || userData.ptvadmin) * this.PERMISSION_USER) +
(userData.admin * this.PERMISSION_ADMIN) +
(userData.mod * this.PERMISSION_MOD) +
(userData.ptvadmin * this.PERMISSION_PTVADMIN);
},
addPermissionLevel: function (channel, permissionId, level) {
var perm = this.getPerm(channel, permissionId);
perm.level = perm.level | level;
this.savePerms();
},
removePermissionLevel: function (channel, permissionId, level) {
var perm = this.getPerm(channel, permissionId);
perm.level = perm.level ^ (perm.level & level);
this.savePerms();
},
whitelistUser: function (channel, permissionId, username) {
var perm = this.getPerm(channel, permissionId);
if (perm.whitelist.indexOf(username.toLowerCase()) === -1) {
perm.whitelist.push(username.toLowerCase());
}
this.savePerms();
},
unwhitelistUser: function (channel, permissionId, username) {
var perm = this.getPerm(channel, permissionId);
if ((index = perm.whitelist.indexOf(username.toLowerCase())) === -1) {
perm.whitelist.splice(index, 1);
}
this.savePerms();
},
blacklistUser: function (channel, permissionId, username) {
var perm = this.getPerm(channel, permissionId);
if (perm.blacklist.indexOf(username.toLowerCase()) === -1) {
perm.blacklist.push(username.toLowerCase());
}
this.savePerms();
},
unblacklistUser: function (channel, permissionId, username) {
var perm = this.getPerm(channel, permissionId);
if ((index = perm.blacklist.indexOf(username.toLowerCase())) === -1) {
perm.blacklist.splice(index, 1);
}
this.savePerms();
}
};
api.user_manager = {
__currentUserData: {},
updateUserData: function (data) {
var channel = data.channel.toLowerCase();
this.__currentUserData[channel.toLowerCase()] = this.__currentUserData[channel.toLowerCase()] || {};
var un = data.username.toLowerCase();
return this.__currentUserData[channel.toLowerCase()][un] = (typeof this.__currentUserData[channel.toLowerCase()][un] !== 'undefined') ? this.mergeUserData(this.__currentUserData[channel.toLowerCase()][un], data) : data;
},
updateUserList: function (channel, data) {
var fud = {};
for (var i = 0; i < data.length; ++i) {
var un = data[i].username.toLowerCase();
this.__currentUserData[channel.toLowerCase()] = this.__currentUserData[channel.toLowerCase()] || {};
fud[data.username] = (typeof this.__currentUserData[channel.toLowerCase()][un] !== 'undefined') ? this.mergeUserData(this.__currentUserData[channel.toLowerCase()][un], data[i]) : data[i];
}
this.__currentUserData[channel.toLowerCase()] = fud;
},
mergeUserData: function (sourceData, additionalData) {
for (var attrname in additionalData) {
sourceData[attrname] = additionalData[attrname];
}
return sourceData;
},
getUserByName: function (channel, username) {
this.__currentUserData[channel.toLowerCase()] = this.__currentUserData[channel.toLowerCase()] || {};
return this.__currentUserData[channel.toLowerCase()][username.toLowerCase()];
}
};
api.timeout_manager = {
__timeoutMsCache: {},
__currentTimeoutsTimes: {},
__defaultMs: 15000,
getTimeoutTime: function (channel, id) {
this.__currentTimeoutsTimes[channel.toLowerCase()] = this.__currentTimeoutsTimes[channel.toLowerCase()] || {};
return this.__currentTimeoutsTimes[channel.toLowerCase()][id] = (typeof this.__currentTimeoutsTimes[channel.toLowerCase()][id] !== 'undefined') ? this.__currentTimeoutsTimes[channel.toLowerCase()][id] : 0;
},
checkTimeout: function (channel, id, defaultMs) {
this.__currentTimeoutsTimes[channel.toLowerCase()] = this.__currentTimeoutsTimes[channel.toLowerCase()] || {};
if (Date.now() - this.getTimeoutTime(channel, id) > this.getTimeoutMs(channel, id, defaultMs)) {
this.__currentTimeoutsTimes[channel.toLowerCase()][id] = Date.now();
return true;
}
return false;
},
getTimeRemaining: function (channel, id, defaultMs) {
return Math.max(0, (this.getTimeoutMs(channel, id, defaultMs) - (Date.now() - this.getTimeoutTime(channel, id))));
},
setTimeout: function (channel, id, ms) {
this.__timeoutMsCache[channel.toLowerCase()] = this.__timeoutMsCache[channel.toLowerCase()] || {};
this.__timeoutMsCache[channel.toLowerCase()][id] = ms;
this.saveTimeoutMs();
},
clearTimeout: function(channel, id) {
this.__currentTimeoutsTimes[channel.toLowerCase()] = this.__currentTimeoutsTimes[channel.toLowerCase()] || {};
this.__currentTimeoutsTimes[channel.toLowerCase()][id] = 0;
},
getTimeoutMs: function (channel, id, defaultMs) {
this.__timeoutMsCache = store.getItem("timeouts") || {};
this.__timeoutMsCache[channel.toLowerCase()] = this.__timeoutMsCache[channel.toLowerCase()] || {};
return (typeof this.__timeoutMsCache[channel.toLowerCase()][id] !== 'undefined') ? this.__timeoutMsCache[channel.toLowerCase()][id] : (typeof defaultMs !== 'undefined' ? defaultMs : this.__defaultMs);
},
saveTimeoutMs: function () {
store.setItem("timeouts", this.__timeoutMsCache);
}
};
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);
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.create(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();
}
}
}
function initServer(url) {
var server = http.createServer(function (req, res) {
res.writeHead(200);
api.Events.emit("http", req, res);
var path = req.url.split('/');
if (path.length < 3 && path[1] == '') {
api.jade.renderFile(process.cwd() + '/views/index.jade', {
urls: req.collection.sort(function (a, b) {
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
})
}, function (err, html) {
res.write(html);
});
}
res.end();
});
server.listen(url.port, function (error) {
function waitToPost() {
if (!SET_PICARTO_LOGIN) {
if (error) {
console.error("Unable to listen on port", url.port, error);
return;
} else {
console.log("Enter " + url.url + ":" + url.port + " in a browser to access web functions.");
}
} else {
setTimeout(waitToPost, 1000);
}
}
waitToPost();
});
}
function initSocket(token,channel) {
if(!channel) return;
// Connect all the socket events with the EventEmitter of the API
socket[channel.toLowerCase()] = io.connect("https://nd1.picarto.tv:443", {
secure: true,
forceNew: true,
query: "token=" + token
}).on("connect", function () {
console.log("Connected to " + channel);
api.Events.emit("connected");
}).on("disconnect", function (reason) {
console.log("Disconnected from " + channel);
api.Events.emit("disconnected", reason);
}).on("reconnect", function () {
api.Events.emit("reconnected");
}).on("reconnect_attempt", function () {
api.Events.emit("reconnect_attempt");
}).on("chatMode", function (data) {
api.Events.emit("chatMode", data);
}).on("srvMsg", function (data) {
api.Events.emit("srvMsg", data);
}).on("channelUsers", function (data) {
api.user_manager.updateUserList(channel, data);
api.Events.emit("channelUsers", data, channel);
}).on("userMsg", function (data) {
if(inputLog.indexOf(data.id) == -1){
inputLog.push(data.id);
if(inputLog.length > 50) inputLog.shift();
data.msg = entities.decode(data.msg);
data.channel = channel;
data.whisper = false;
api.Events.emit("userMsg", api.user_manager.updateUserData(data));
} else {
api.Events.emit("userMsgDuplicate", api.user_manager.updateUserData(data));
}
}).on("meMsg", function (data) {
api.Events.emit("meMsg", data);
}).on("globalMsg", function (data) {
api.Events.emit("globalMsg", data);
}).on("clearChat", function () {
api.Events.emit("clearChat");
}).on("commandHelp", function () {
api.Events.emit("commandHelp");
}).on("modToolsVisible", function (modToolsEnabled) {
api.Events.emit("modToolsVisible", modToolsEnabled);
}).on("modList", function (data) {
api.Events.emit("modList", data);
}).on("whisper", function (data) {
if(inputLog.indexOf(data.id) == -1){
inputLog.push(data.id);
if(inputLog.length > 50) inputLog.shift();
data.msg = entities.decode(data.msg);
data.channel = channel;
data.whisper = true;
api.Events.emit("whisper", api.user_manager.updateUserData(data));
} else {
api.Events.emit("whisperDuplicate", api.user_manager.updateUserData(data));
}
}).on("color", function (data) {
api.Events.emit("color", data);
}).on("onlineState", function (data) {
api.Events.emit("onlineState", data);
}).on("raffleUsers", function (data) {
api.Events.emit("raffleUsers", data);
}).on("wonRaffle", function (data) {
api.Events.emit("wonRaffle", data);
}).on("runPoll", function () {
api.Events.emit("runPoll");
}).on("showPoll", function (data) {
api.Events.emit("showPoll", data);
}).on("pollVotes", function (data) {
api.Events.emit("pollVotes", data)
}).on("voteResponse", function () {
api.Events.emit("voteResponse");
}).on("finishPoll", function (data) {
api.Events.emit("finishPoll", data);
}).on("gameMode", function (data) {
api.Events.emit("gameMode", data);
}).on("adultMode", function (data) {
api.Events.emit("adultMode", data);
}).on("commissionsAvailable", function (data) {
api.Events.emit("commissionsAvailable", data);
}).on("clearUser", function (data) {
api.Events.emit("clearUser", data);
}).on("removeMsg", function (data) {
api.Events.emit("removeMsg", data);
}).on("warnAdult", function () {
api.Events.emit("warnAdult");
}).on("warnGaming", function () {
api.Events.emit("warnGaming");
}).on("warnMovies", function () {
api.Events.emit("warnMovies");
}).on("multiStatus", function (data) {
api.Events.emit("multiStatus", data);
});
api.Messages = {
send: function (message,channel) {
if(typeof channel == 'undefined'){
channel = Object.keys(socket)[0];
} else if(typeof socket[channel.toLowerCase()] === 'undefined' || socket[channel.toLowerCase()].disconnected) {
console.log("Failed to send, channel is not connected");
return;
}
if (api.readOnly[channel.toLowerCase()]) {
console.log("Bot runs in ReadOnly Mode. Messages can not be sent");
return;
}
if(api.mute_manager.isMuted(channel)){
return;
}
if (message.length > 255) {
socket[channel.toLowerCase()].emit("chatMsg", {
msg: "This message was too long for Picarto: " + message.length + " characters. Sorry."
});
console.log("This message was too long for Picarto: " + message.length + " characters. Sorry.");
return;
}
socket[channel.toLowerCase()].emit("chatMsg", {
msg: message.toString()
});
},
whisper: function (to, message,channel) {
if(typeof channel == 'undefined'){
channel = Object.keys(socket)[0];
} else if(typeof socket[channel.toLowerCase()] === 'undefined' || socket[channel.toLowerCase()].disconnected) {
console.log("Failed to send, channel is not connected");
return;
}
if (api.readOnly[channel.toLowerCase()]) {
console.log("Bot runs in ReadOnly Mode. Messages can not be sent");
return;
}
if(api.mute_manager.isMuted(channel)){
return;
}
if ((message.length + 4 + to.length) > 255) {
socket[channel.toLowerCase()].emit("chatMsg", {
msg: "/w " + to + " This message was too long for Picarto: " + message.length + " characters. Sorry."
});
console.log("This message was too long for Picarto: " + message.length + " characters. Sorry.");
return;
}
socket[channel.toLowerCase()].emit("chatMsg", {
msg: "/w " + to + " " + message.toString()
});
}
}
api.setColor = function (color,channel) {
if(typeof channel == 'undefined'){
channel = Object.keys(socket)[0];
}
if (color.startsWith("#")) {
color = color.substring(1);
}
socket[channel.toLowerCase()].emit("setColor", color.toUpperCase());
}
}
initPluginLoader();
// 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);
}
});
var token;
var name;
var channel;
config.http = config.http || {};
if (process.env.PICARTO_TOKEN) token = process.env.PICARTO_TOKEN;
if (process.env.PICARTO_CHANNEL) channel = process.env.PICARTO_CHANNEL;
if (process.env.PICARTO_NAME) name = process.env.PICARTO_NAME;
if (process.env.PICARTO_PORT) config.http.port = process.env.PICARTO_PORT;
if (process.env.PICARTO_URL) config.http.url = process.env.PICARTO_URL;
// Load commandline args as env variables
commander.version(api.version).usage("[options]")
.option("-c, --channel <Picarto Channel>", "Set channel to connect to.")
.option("-n, --botname <Bot name>", "Set the bot's name.")
.option("-t, --token <Token>", "Use an already existing token to login")
.option("-p, --port <Port>","Set a custom port")
.option("-u, --url <URL>","Set a custom URL")
.parse(process.argv);
if (commander.token) token = commander.token;
if (commander.botname) name = commander.botname;
if (commander.channel) channel = commander.channel;
if (commander.port) config.http.port = commander.port;
if (commander.url) config.http.url = commander.url;
if(config.http){
if(config.http.enabled){
initServer(config.http);
}
} else {
initServer({url:"http://localhost",port:10001});
}
var SET_PICARTO_LOGIN = 0;
if (token) {
console.log("Attempting token based connection, please be patient...");
initSocket(token);
} else if (channel && name) {
console.log("Attempting to connect, this might take a moment. Please be patient...");
picarto.getToken(channel, name).then(function (res) {
initSocket(res.token,channel);
api.readOnly[channel.toLowerCase()] = res.readOnly;
if (res.readOnly) console.log("Chat disabled guest login! Establishing ReadOnly Connection.");
}).catch(function (reason) { console.log("Token acquisition failed: " + reason);});
} else if (channel) {
console.log("Attempting ReadOnly connection, please be patient...");
picarto.getROToken(channel).then(function (res) { api.readOnly[channel.toLowerCase()] = res.readOnly; initSocket(res.token,channel); }).catch(function (reason) { console.log("Token acquisition failed: " + reason); });
} else if(config.channels.length === 0 || (config.channels.length === 1 && config.channels[0].channel === "ExampleChannel")) {
SET_PICARTO_LOGIN = 1;
console.log("No login information given.");
process.stdout.write("Channel: ");
}
if(config.channels && config.channels.length && !(config.channels.length === 1 && config.channels[0].channel === "ExampleChannel")){
config.channels.forEach(function(channel){
if(channel.enabled && channel.channel){
picarto.getToken(channel.channel, channel.name).then(function (res) {
initSocket(res.token,channel.channel);
api.readOnly[channel.channel.toLowerCase()] = res.readOnly;
if(channel.muted){
api.mute_manager.mute(channel.channel);
}
if (res.readOnly) console.log(channel + ": Chat disabled guest login! Establishing ReadOnly Connection.");
}).catch(function (reason) { console.log(channel.channel + ": Token acquisition failed: " + reason);});
}
});
}
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) {
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(/\.pbot\.js/, ""),
});
data.push(column_divider);
}
console.log(
"\n" +
columnify(data, {
columnSplitter: " | ",
showHeaders: false,
maxLineWidth: "auto",
config: {
plugin_description: { maxWidth: 20, align: "center" },
plugin_author: { maxWidth: 10, align: "center" },
plugin_name: { maxWidth: 10 }
}
})
);
break;
default:
console.log("Unknown subcommand. Type plugins 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",
"clear|cls": "Clears the screen",
"exit|quit": "Shuts the bot down",
"say <channel> <message>": "Say something as the bot",
"whisper <channel> <to> <message>": "Whisper to someone as the bot",
"disconnect <channel>": "Disconnect from Picarto",
"connect <channel> <name>": "Connect to Picarto again or create a new connection",
"reconnect <channel>": "Close and re-establish connection",
"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) {
if (SET_PICARTO_LOGIN) {
if (SET_PICARTO_LOGIN === 1) {
if (!chunk.toString().trim()) { process.stdout.write("Channel: "); return; }
process.env.PICARTO_CHANNEL = chunk.toString().trim();
process.stdout.write("Name (Leave blank for ReadOnly): ");
SET_PICARTO_LOGIN = 2;
} else if (SET_PICARTO_LOGIN === 2) {
if (!chunk.toString().trim()) {
console.log("Attempting ReadOnly connection, please be patient...");
picarto.getROToken(process.env.PICARTO_CHANNEL).then(function (res) { initSocket(res.token,process.env.PICARTO_CHANNEL); api.readOnly[process.env.PICARTO_CHANNEL.toLowerCase()] = res.readOnly; }).catch(function (reason) { console.log("Token acquisition failed: " + reason); });
SET_PICARTO_LOGIN = 0;
return;
}
process.env.PICARTO_NAME = chunk.toString().trim();
SET_PICARTO_LOGIN = 0;
console.log("Attempting to connect, this might take a moment. Please be patient...");
picarto.getToken(process.env.PICARTO_CHANNEL, process.env.PICARTO_NAME).then(function (res) {
initSocket(res.token,process.env.PICARTO_CHANNEL);
api.readOnly[process.env.PICARTO_CHANNEL.toLowerCase()] = res.readOnly;
if (res.readOnly) console.log("Chat disabled guest login! Establishing ReadOnly Connection.");
}).catch(function (reason) { console.log("Token acquisition failed: " + reason); });
}
return;
}
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 "clear":
case "cls":
require("cli-clear")();
break;
case "exit":
case "quit":
process.exit();
break;
case "say":
channel = args.shift();
api.Messages.send(args.join(" "),channel);
break;
case "admin":
var subcmd = args.splice(0, 1)[0];
switch(subcmd){
case "add":
if(args[0]){
api.permissions_manager.addGlobalAdmin(args[0]);
console.log("Added " + args[0] + " as a global admin");
}
break;
case "delete":
case "del":
if(args[0]){
api.permissions_manager.removeGlobalAdmin(args[0]);
console.log("Deleted " + args[0] + " from the global admin list");
}
break;
case "list":
api.permissions_manager.getGlobalAdmins().forEach(function(admin){
console.log(admin);
});
break;
default:
console.log("Usage: admin <add|del|list> <username>");
}
break;
case "mute":
if(args[0]){
api.mute_manager.mute(args[0]);
console.log("Channel " + args[0] + " is muted");
} else {
console.log("Usage: mute <channel>");
}
break;
case "unmute":
if(args[0]){
api.mute_manager.unmute(args[0]);
console.log("Channel " + args[0] + " is not muted");
} else {
console.log("Usage: mute <channel>");
}
break;
case "whisper":
case "w":
var channel = args.shift();
var user = args.shift();
api.Messages.whisper(user, args.join(" "),channel);
break;
case "connect":
if(args[0] && typeof socket[args[0].toLowerCase()] !== 'undefined'){
socket[args[0].toLowerCase()].connect();
} else if(args[0] && args[1]){
picarto.getToken(args[0], args[1]).then(function (res) {
initSocket(res.token,args[0]);
api.readOnly[args[0].toLowerCase()] = res.readOnly;
if (res.readOnly) console.log("Chat disabled guest login! Establishing ReadOnly Connection.");
}).catch(function (reason) { console.log("Token acquisition failed: " + reason);});
} else if(args[0]){
process.stdout.write("Name (Leave blank for ReadOnly): ");
process.env.PICARTO_CHANNEL = args[0];
SET_PICARTO_LOGIN = 2;
} else {
process.stdout.write("Channel: ");
SET_PICARTO_LOGIN = 1;
}
break;
case "disconnect":
if(args[0] && typeof socket[args[0].toLowerCase()] !== 'undefined'){
socket[args[0].toLowerCase()].disconnect();
break;
}
case "reconnect":
if(args[0] && typeof socket[args[0].toLowerCase()] !== 'undefined'){
socket[args[0].toLowerCase()].disconnect();
socket[args[0].toLowerCase()].connect();
break;
} else if(!args[0]){
console.log("Please specify channel");
} else {
console.log("Socket does not exist, please connect first");
}
break;
case "status":
case "stat":
console.log("Current Sockets");
for(var key in socket){
if (socket.hasOwnProperty(key)) {
console.log("Channel " + key + " is " + (socket[key].connected ? "connected" : "disconnected") + " and " + (api.mute_manager.isMuted(key) ? "muted" : "unmuted"));
}
}
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;
}
}
});