-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.js
2661 lines (2586 loc) · 103 KB
/
main.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
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2022 BadAimWeeb. All rights reserved. MIT license.
/* eslint-disable consistent-this */
/* eslint-disable no-loop-func */
/* eslint-disable require-atomic-updates */
/* eslint-disable class-methods-use-this */
/* eslint-disable no-process-env */
require("./ClassModifier.js");
global.nodemodule = {};
var os = require("os");
var FormData = require('form-data');
const fs = require('fs');
var path = require("path");
var syncrequest = require('sync-request');
var wait = require('wait-for-stuff');
var semver = require("semver");
var childProcess = require("child_process");
var streamBuffers = require("stream-buffers");
//var url = require("url");
//var net = require('net');
var zlib = require("zlib");
var tar = require("tar-stream");
const readline = require('readline');
var speakeasy = require("speakeasy"); //2FA
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: true,
prompt: ""
});
global.crl = rl;
var fetch = require("node-fetch");
var _checkPort = require("./checkPort.js");
var CPULoad = require("./CPULoad.js");
////var querystring = require('querystring');
////var delay = require('delay');
const StreamZip = require('node-stream-zip');
////var tf = require("@tensorflow/tfjs");
global.sshcurrsession = {};
global.sshstream = {};
//Cryptography
var crypto = require('crypto');
let aes = require("aes-js");
// Encrypted state feature (added in 0.8)
function encryptState(data, key) {
let hashEngine = crypto.createHash("sha256");
let hashKey = hashEngine.update(key).digest();
let bytes = aes.utils.utf8.toBytes(data);
let aesCtr = new aes.ModeOfOperation.ctr(hashKey);
let encryptedData = aesCtr.encrypt(bytes);
return aes.utils.hex.fromBytes(encryptedData);
}
function decryptState(data, key) {
let hashEngine = crypto.createHash("sha256");
let hashKey = hashEngine.update(key).digest();
let encryptedBytes = aes.utils.hex.toBytes(data);
let aesCtr = new aes.ModeOfOperation.ctr(hashKey);
let decryptedData = aesCtr.decrypt(encryptedBytes);
return aes.utils.utf8.fromBytes(decryptedData);
}
global.reload = () => {
unloadPlugin();
loadPlugin();
};
global.fbchat = (id, mess) => {
if (global.getType(facebook.api) === "Object") {
var isGroup = (id.toString().length == 16);
facebook.api.sendMessage(mess, id, () => { }, null, isGroup);
return `Sent message: ${mess} to ${isGroup ? "Thread" : "User"} ID ${id}`;
} else {
return "Error: Account not logged in!";
}
};
global.restart = () => {
setTimeout(function () {
process.exit(7378278);
}, 1000);
return "Restarting...";
};
/**
* Find every file in a directory
*
* @param {string} startPath A path specify where to start.
* @param {RegExp} filter Regex to filter results.
* @param {boolean} arrayOutput Options: Output array or send to callback?
* @param {boolean} recursive Options: Recursive or not?
* @param {function} [callback] Callback function.
*
* @return {(Array<String>|undefined)} An array contains path of every files match regex.
*/
function findFromDir(startPath, filter, arrayOutput, recursive, callback) {
var nocallback = false;
if (!callback) {
callback = function () { };
nocallback = true;
}
if (!fs.existsSync(startPath)) {
throw "No such dirror Unexpected newline before ')' function-paren-newlinerectory: " + startPath;
}
var files = fs.readdirSync(startPath);
var arrayFile = [];
for (var i = 0; i < files.length; i++) {
var filename = path.join(startPath, files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory() && recursive) {
var arrdata = findFromDir(filename, filter, true, true);
if (!nocallback && !arrayOutput) {
for (var n in arrdata) {
callback(path.join(filename, arrdata[n]));
}
} else {
arrayFile = arrayFile.concat(arrdata);
}
} else {
if (!arrayOutput && !nocallback) {
if (filter.test(filename)) callback(filename);
} else {
if (filter.test(filename)) arrayFile[arrayFile.length] = filename;
}
}
}
if (arrayOutput && !nocallback) {
callback(arrayFile);
} else if (arrayOutput) {
return arrayFile;
}
}
/**
* Ensure <path> exists.
*
* @param {string} path Path
* @param {number} mask Folder's mask
*
* @return {object} Error or nothing.
*/
function ensureExists(path, mask) {
if (typeof mask != 'number') {
mask = 0o777;
}
try {
fs.mkdirSync(path, {
mode: mask,
recursive: true
});
return;
} catch (ex) {
return {
err: ex
};
}
}
ensureExists(path.join(__dirname, "logs"));
var logFileList = findFromDir(path.join(__dirname, "logs"), /.*\.log$/, true, true);
logFileList.forEach(dir => {
var newdir = path.join(__dirname, "logs", path.parse(dir)
.name + ".tar.gz");
var file = fs.readFileSync(dir);
var pack = tar.pack();
pack.entry({
name: path.parse(dir)
.name + ".log"
}, file);
pack.finalize();
var tardata = Buffer.alloc(0);
pack.on("data", chunk => {
tardata = Buffer.concat([tardata, chunk]);
})
.on("end", () => {
zlib.gzip(tardata, (err, data) => {
if (err) throw err;
fs.writeFileSync(newdir, data, {
mode: 0o666
});
fs.unlinkSync(dir);
});
});
});
var log = require("./logger.js");
//Capturing STDERR
var _stderrold = process.stderr.write;
global.stderrdata = "";
process.stderr.write = function (chunk, encoding, callback) {
global.stderrdata += chunk;
if (typeof callback == "function") {
callback();
}
};
setInterval(() => {
if (global.stderrdata != "" && global.stderrdata.indexOf("Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.") == -1) {
var arr = global.stderrdata.split(/[\r\n]|\r|\n/g)
.filter((val) => val != "");
arr.splice(arr.length - 1, 1);
for (var n in arr) {
log("[STDERR]", arr[n]);
}
}
global.stderrdata = "";
}, 200);
//Handling rejected promise that are unhandled
process.on('unhandledRejection', (reason, promise) => {
log("[INTERNAL]", 'Warning: Rejected promise: ', promise, ', reason:', reason);
});
//Handling uncaught exception (without try/catch, usually in callback)
//! DEFINELY NOT SAFE AT ALL, BUT STILL ADDING IT.
process.on('uncaughtException', (err, origin) => {
log("[INTERNAL]", `Warning: ${origin}:`, err);
});
var autoUpdater = require("./autoUpdater.js");
var cUpdate = autoUpdater.checkForUpdate();
//Outputs version
var version = cUpdate.currVersion;
global.cVersion = version;
log("Starting C3CBot version", version, "...");
global.config = require("./getConfig.js")();
var testmode = global.config.testmode;
var prefix = "";
var availableLangFile = findFromDir(path.join(__dirname, "lang"), /.*\.yml$/, true, false);
var langMap = {};
var yamlParser = require('js-yaml');
availableLangFile.forEach(v => {
var lang = path.parse(v);
log("[INTERNAL]", "Loading language:", lang.name);
var ymlData = fs.readFileSync(v, { encoding: "utf8" });
langMap[lang.name] = yamlParser.load(ymlData);
});
var getLang = function (langVal, id, oLang) {
var lang = global.config.language;
if (id && global.data.userLanguage[id]) {
lang = global.data.userLanguage[id];
if (!langMap[lang]) {
log("[INTERNAL]", "Warning: Invalid language: ", lang, `; using ${global.config.language} as fallback...`);
lang = global.config.language;
}
}
if (oLang) {
lang = oLang;
if (!langMap[lang]) {
log("[INTERNAL]", "Warning: Invalid language: ", lang, `; using ${global.config.language} as fallback...`);
lang = global.config.language;
}
}
if (langMap[lang]) {
return String(langMap[lang][langVal]);
} else {
log("[INTERNAL]", "Warning: Invalid language: ", lang, "; using en_US as fallback...");
return String((langMap["en_US"] || {})[langVal]);
}
};
/**
* Resolves data received from base and return formatted UserID.
*
* @param {string} type Platform name
* @param {string} data Data to be resolved by plugins
*
* @return {string} Formatted UserID
*/
var resolveID = function (type, data) {
switch (type) {
case "Facebook":
return "FB-" + data.msgdata.senderID || data.msgdata.author;
case "Discord":
return "DC-" + data.msgdata.author.id;
default:
return "";
}
};
if (global.config.facebookProxyUseSOCKS) {
var ProxyServer = require("./SOCK2HTTP.js")(log);
var fS2HResolve = function () { };
var S2HPromise = new Promise(resolve => {
fS2HResolve = resolve;
});
var localSocksProxy = new ProxyServer({
socks: global.config.facebookProxy
})
.listen(global.config.portSOCK2HTTP, global.config.addressSOCK2HTTP || "0.0.0.0")
.on("listening", () => {
log("[SOCK2HTTP]", `Listening at ${localSocksProxy.address().address}:${localSocksProxy.address().port}`);
fS2HResolve({
address: localSocksProxy.address()
.address,
port: localSocksProxy.address()
.port
});
})
.on("error", err => {
log("[SOCK2HTTP]", err);
});
var S2HResponse = wait.for.promise(S2HPromise);
var sock2httpPort = S2HResponse.port;
var sock2httpAddress = S2HResponse.address;
}
/**
* Get a randomized number
*
* @param {number} min Minimum
* @param {number} max Maximum
*
* @returns {number} A randomized number.
*/
var random = function (min, max) {
if (min > max) {
var temp = min;
min = max;
max = temp;
}
var bnum = (max - min)
.toString(16)
.length / 2;
if (bnum < 1) bnum = 1;
return Math.round(parseInt(crypto.randomBytes(bnum)
.toString('hex'), 16) / Math.pow(16, bnum * 2) * (max - min)) + min;
};
/**
* Get some random bytes
*
* @param {number} numbytes Number of bytes.
* @returns {string} Random bytes.
*/
var _randomBytes = function (numbytes) {
numbytes = numbytes || 1;
return crypto.randomBytes(numbytes)
.toString('hex');
};
/**
* Get a HMAC hash.
*
* @param {string} publick Public key
* @param {string} privatek Private key
* @param {string} [algo=sha512] Algrorithim
* @param {string} [output=hex] Output type
*
* @return {string} HMAC hash
*/
function _HMAC(publick, privatek, algo, output) {
algo = algo || "sha512";
output = output || "hex";
var hmac = crypto.createHmac(algo, privatek);
hmac.update(publick);
var value = hmac.digest(output);
return value;
}
//* Load data
if (testmode) {
fs.existsSync(path.join(__dirname, "data-test.json")) ? global.data = JSON.parse(fs.readFileSync(path.join(
__dirname,
"data-test.json"
))) : (function () {
log("[INTERNAL]", "OwO, data file not found.");
global.data = {};
})();
} else {
fs.existsSync(path.join(__dirname, "data.json")) ? global.data = JSON.parse(fs.readFileSync(path.join(
__dirname,
"data.json"
))) : (function () {
log("[INTERNAL]", "OwO, data file not found.");
global.data = {};
})();
}
global.dataBackup = JSON.parse(JSON.stringify(global.data));
//*Auto-save global data clock
global.isDataSaving = false;
global.dataSavingTimes = 0;
var autosave = setInterval(function (testmode, log) {
if ((!global.isDataSaving || global.dataSavingTimes > 3) && JSON.stringify(global.data) !== JSON.stringify(global
.dataBackup)) {
if (global.dataSavingTimes > 3) {
log("[INTERNAL]", "Auto-save clock is executing over 30 seconds! (", global.dataSavingTimes, ")");
}
global.isDataSaving = true;
try {
if (testmode) {
fs.writeFileSync(path.join(__dirname, "data-test-temp.json"), JSON.stringify(global.data, null, 4), {
mode: 0o666
});
fs.renameSync(path.join(__dirname, "data-test-temp.json"), path.join(__dirname, "data-test.json"));
} else {
fs.writeFileSync(path.join(__dirname, "data-temp.json"), JSON.stringify(global.data, null, 4), {
mode: 0o666
});
fs.renameSync(path.join(__dirname, "data-temp.json"), path.join(__dirname, "data.json"));
}
} catch (err) {
log("[INTERNAL]", "Auto-save encounted an error:", err);
}
global.isDataSaving = false;
global.dataSavingTimes = 0;
global.dataBackup = JSON.parse(JSON.stringify(global.data));
} else {
if (JSON.stringify(global.data) != JSON.stringify(global.dataBackup)) {
global.dataSavingTimes++;
}
}
}, 10000, testmode, log);
var currentCPUPercentage = 0;
global.currentCPUPercentage = 0;
var _titleClocking = setInterval(async () => {
var titleescape1 = String.fromCharCode(27) + ']0;';
var titleescape2 = String.fromCharCode(7);
currentCPUPercentage = await (new CPULoad(1000));
global.currentCPUPercentage = currentCPUPercentage;
var title = global.config.botname + " v" + version + " | " + (currentCPUPercentage * 100)
.toFixed(0) + "% CPU" + " | " + ((os.totalmem() - os.freemem()) / 1024 / 1024)
.toFixed(0) + " MB" + "/" + (os.totalmem() / 1024 / 1024)
.toFixed(0) + " MB RAM" + " | BOT: " + (process.memoryUsage()
.rss / 1024 / 1024)
.toFixed(0) + " MB USED";
process.title = title;
if (global.sshcurrsession) {
if (typeof global.sshcurrsession == "object") {
for (var session in global.sshstream) {
try {
global.sshstream[session].stdout.write(titleescape1 + title + titleescape2);
} catch (ex) { }
}
}
}
}, 3000);
/**
* "require" with data as string
*
* @param {string} src Source code
* @param {string} filename File name
*
* @return {any} module.exports of source code
*/
function requireFromString(src, filename) {
var Module = module.constructor;
var m = new Module();
m._compile(src, filename);
return m.exports;
}
//Auto updater
function checkUpdate(silent, cUpdate) {
var newUpdate = cUpdate || autoUpdater.checkForUpdate();
if (!silent || newUpdate.newUpdate) {
log(
"[Updater]",
`You are using build ${newUpdate.currVersion}, and ${newUpdate.newUpdate ? "there is a new build (" + newUpdate.version + ")" : "there are no new build."}`
);
}
if (newUpdate.newUpdate && global.config.autoUpdate) {
log("[Updater]", `Downloading build ${newUpdate.version}...`);
autoUpdater.installUpdate()
.then(function (ret) {
var [success, value] = ret;
if (success) {
log("[Updater]", `Updated with ${value} entries extracted. Triggering restart...`);
process.exit(7378278);
} else {
log("[Updater]", "Failed to install new build:", value);
}
})
.catch(function (ex) {
log("[Updater]", "Failed to install new build:", ex);
});
}
}
checkUpdate(false, cUpdate);
if (global.config.autoUpdateTimer > 0 && global.config.autoUpdate) {
setInterval(checkUpdate, global.config.autoUpdateTimer * 60 * 1000, true);
}
//Plugin Load
ensureExists(path.join(__dirname, "plugins"));
ensureExists(path.join(__dirname, "plugins", "nodemodules"));
function checkPluginCompatibly(version) {
version = version.toString();
try {
//* Plugin complied with version 0.3.0 => 0.3.14 and 0.4.0 and 0.5.0 is allowed
var allowedVersion = "0.3.0 - 0.3.14 || 0.4.0 || 0.5.0";
return semver.intersects(semver.clean(version), allowedVersion);
} catch (ex) {
return false;
}
}
async function loadPlugin() {
let startLoading = Date.now();
var error = [];
global.plugins = {}; //Plugin Scope
var pltemp1 = {}; //Plugin Info
var pltemp2 = {}; //Plugin Executable
global.fileMap = {};
global.privateFileMap = {};
global.loadedPlugins = {};
global.chatHook = [];
!global.commandMapping ? global.commandMapping = {} : "";
log("[INTERNAL]", "Searching for plugins in ./plugins/ ...");
var pluginFileList = findFromDir(path.join(__dirname, "plugins/"), /.*\.(z3p|zip)$/, true, false);
for (var n in pluginFileList) {
let zip = null;
try {
zip = new StreamZip({
file: pluginFileList[n],
storeEntries: true
});
wait.for.event(zip, "ready");
try {
var plinfo = JSON.parse(zip.entryDataSync('plugins.json')
.toString('utf8'));
} catch (ex) {
throw "Invalid plugins.json file (Broken JSON)!";
}
if (!plinfo["plugin_name"] || !plinfo["plugin_scope"] || !plinfo["plugin_exec"]) {
throw "Invalid plugins.json file (Not enough data)!";
}
if (!plinfo["complied_for"]) {
throw "Plugin doesn't have complied_for (Complied for <=0.2.8?).";
} else {
if (!checkPluginCompatibly(plinfo["complied_for"])) {
throw "Plugin is complied for version {0}, but this version doesn't compatible with it.".replace(
"{0}",
plinfo["complied_for"]
);
}
}
try {
var plexec = zip.entryDataSync(plinfo["plugin_exec"])
.toString('utf8');
} catch (ex) {
throw "Executable file " + plinfo["plugin_exec"] + " not found.";
}
if (global.getType(plinfo["file_map"]) == "Object") {
for (let fd in plinfo["file_map"]) {
try {
global.fileMap[plinfo["file_map"][fd]] = zip.entryDataSync(fd);
} catch (ex) {
throw "File " + fd + " not found.";
}
}
}
if (global.getType(plinfo["private_file_map"]) == "Object") {
global.privateFileMap[plinfo["plugin_scope"]] = {};
for (let fd in plinfo["private_file_map"]) {
try {
global.privateFileMap[plinfo["plugin_scope"]][plinfo["private_file_map"][fd]] = zip.entryDataSync(fd);
} catch (ex) {
throw "File " + fd + " not found.";
}
}
}
if (typeof plinfo["node_depends"] == "object") {
for (var nid in plinfo["node_depends"]) {
var defaultmodule = require("module")
.builtinModules;
var moduledir = path.join(__dirname, "plugins", "nodemodules", "node_modules", nid);
try {
if (defaultmodule.indexOf(nid) != -1 || (["jimp", "wait-for-stuff", "deasync", "discord.js", "fca-unofficial", "ffmpeg-static"]).indexOf(nid) !== -1) {
try {
global.nodemodule[nid] = require(nid);
} catch (e) {
log("[INTERNAL]", nid, "failed to load using CommonJS require() method. Attempting to load using ES module import()...");
global.nodemodule[nid] = await import(nid);
}
} else {
global.nodemodule[nid] = require(moduledir);
}
} catch (ex) {
log(
"[INTERNAL]", pluginFileList[n], "is requiring node modules named", nid,
"but it isn't installed. Attempting to install it through npm package manager..."
);
childProcess.execSync(
"npm --loglevel error --package-lock false --save true -- install " + nid +
(
plinfo["node_depends"][nid] == "*" ||
plinfo["node_depends"][nid] == "" ? "" : ("@" + plinfo["node_depends"][nid])
),
{
stdio: "inherit",
cwd: path.join(__dirname, "plugins", "nodemodules"),
env: process.env,
shell: true
}
);
//Loading 3 more times before drop that plugins
var moduleLoadTime = 0;
var exception = "";
var success = false;
for (moduleLoadTime = 1; moduleLoadTime <= 3; moduleLoadTime++) {
require.cache = {};
try {
try {
global.nodemodule[nid] = require(nid);
} catch (e) {
log("[INTERNAL]", nid, "failed to load using CommonJS require() method. Attempting to load using ES module import()...");
global.nodemodule[nid] = await import(nid);
}
success = true;
break;
} catch (ex) {
exception = ex;
}
if (success) {
break;
}
}
if (!success) {
throw "Cannot load node module: " + nid + ". Additional info: " + exception;
}
}
}
}
pltemp1[plinfo["plugin_name"]] = plinfo;
pltemp1[plinfo["plugin_name"]].filename = pluginFileList[n];
pltemp2[plinfo["plugin_name"]] = plexec;
zip.close();
} catch (ex) {
log("[INTERNAL]", "Error while loading plugin at \"" + pluginFileList[n] + "\":", ex);
error.push(pluginFileList[n]);
delete pltemp1[plinfo["plugin_name"]];
delete pltemp2[plinfo["plugin_name"]];
if (zip) {
zip.close();
}
}
}
for (var plname in pltemp1) {
var passed = true;
if (pltemp1[plname]["dependents"]) {
for (var no in pltemp1[plname]["dependents"]) {
if (typeof pltemp1[pltemp1[plname]["dependents"][no]] != "object") {
passed = false;
log("[INTERNAL]", plname, "depend on plugin named", pltemp1[plname][
"dependents"][no] + ", but that plugin is not installed/loaded.");
}
}
}
if (passed) {
try {
global.plugins[pltemp1[plname]["plugin_scope"]] = requireFromString(pltemp2[plname], path.join(pltemp1[plname].filename, pltemp1[plname]["plugin_exec"]));
if (typeof global.plugins[pltemp1[plname]["plugin_scope"]].onLoad == "function") {
await (async function (plname) {
let ret = global.plugins[pltemp1[plname]["plugin_scope"]].onLoad({
// eslint-disable-next-line no-loop-func
log: function logPlugin(...message) {
log.apply(global, [
"[PLUGIN]",
"[" + plname + "]"
].concat(message));
}
});
if (global.getType(ret) == "Promise") {
ret = await ret;
}
if (global.getType(ret) == "Object") {
pltemp1[plname]["command_map"] = {
...pltemp1[plname]["command_map"],
...ret
};
}
})(String(plname));
}
for (var cmd in pltemp1[plname]["command_map"]) {
var cmdo = pltemp1[plname]["command_map"][cmd];
if (!cmdo["hdesc"] || !cmdo["fscope"] || isNaN(parseInt(cmdo["compatibly"]))) {
log("[INTERNAL]", plname, "has a command that isn't have enough information to define (/" + cmd + ")");
} else if (
global.getType(global.plugins[pltemp1[plname]["plugin_scope"]][cmdo.fscope]) != "Function" &&
global.getType(global.plugins[pltemp1[plname]["plugin_scope"]][cmdo.fscope]) != "AsyncFunction"
) {
log("[INTERNAL]", plname, "is missing a function for /" + cmd);
} else {
var oldstr;
if (typeof cmdo.hdesc != "object") {
oldstr = cmdo.hdesc;
cmdo.hdesc = {};
cmdo.hdesc[global.config.language] = oldstr;
}
if (cmdo.hargs) {
if (typeof cmdo.hargs != "object") {
oldstr = cmdo.hargs;
cmdo.hargs = {};
cmdo.hargs[global.config.language] = oldstr;
}
} else {
cmdo.hargs = {};
cmdo.hargs[global.config.language] = "";
}
global.commandMapping[cmd] = {
args: cmdo.hargs,
desc: cmdo.hdesc,
scope: global.plugins[pltemp1[plname]["plugin_scope"]][cmdo
.fscope],
compatibly: parseInt(cmdo.compatibly),
handler: plname
};
if (Object.prototype.hasOwnProperty.call(cmdo, "adminCmd")) {
global.commandMapping[cmd].adminCmd = true;
}
}
}
if (typeof pltemp1[plname]["chatHook"] == "string" &&
typeof pltemp1[plname]["chatHookType"] == "string" &&
!isNaN(parseInt(pltemp1[plname]["chatHookPlatform"])) &&
(
global.getType(global.plugins[pltemp1[plname]["plugin_scope"]][pltemp1[plname]["chatHook"]]) == "Function" ||
global.getType(global.plugins[pltemp1[plname]["plugin_scope"]][pltemp1[plname]["chatHook"]]) == "AsyncFunction"
)) {
global.chatHook.push({
resolverFunc: global.plugins[pltemp1[plname]["plugin_scope"]][pltemp1[plname]["chatHook"]],
listentype: pltemp1[plname]["chatHookType"],
listenplatform: parseInt(pltemp1[plname]["chatHookPlatform"]),
handler: plname
});
}
global.loadedPlugins[plname] = {
author: pltemp1[plname].author,
version: pltemp1[plname].version,
onUnload: global.plugins[pltemp1[plname]["plugin_scope"]].onUnload
};
log("[INTERNAL]", "Loaded", plname, pltemp1[plname].version, "by", pltemp1[plname].author);
} catch (ex) {
log(
"[INTERNAL]", plname,
"contains an malformed executable code and cannot be loaded. Plugin depend on this code may not work correctly. Additional information:",
ex
);
error.push(pltemp1[plname].filename);
}
}
}
global.commandMapping["systeminfo"] = {
args: {},
desc: "Show system info",
scope: function () {
var uptime = os.uptime();
var utdate = new Date(uptime);
return {
handler: "internal",
data: `System info:\r\n- CPU arch: ${os.arch()}\r\n- OS type: ${os.type()} (Platform: ${os.platform()})\r\n- OS version: ${os.release()}\r\n- Uptime: ${(uptime / 3600 / 24).floor(0).pad(2)}:${utdate.getUTCHours().pad(2)}:${utdate.getUTCMinutes().pad(2)}:${utdate.getUTCSeconds().pad(2)}\r\n- Total memory: ${os.totalmem() / 1048576} MB\r\n- Heroku: ${(!!process.env.PORT).toString()}`
};
},
compatibly: 0,
handler: "INTERNAL"
};
global.commandMapping["updatebot"] = {
args: {},
desc: {},
scope: function (type, data) {
if (data.admin) {
var newUpdate = autoUpdater.checkForUpdate();
log(
"[Updater]",
`You are using build ${newUpdate.currVersion}, and ${newUpdate.newUpdate ? "there is a new build (" + newUpdate.version + ")" : "there are no new build."}`
);
data.return({
data: `Current build: ${newUpdate.currVersion}\r\nLatest build: ${newUpdate.version}.${newUpdate.newUpdate ? "\r\nUpdating..." : ""}`,
handler: "internal"
});
if (newUpdate.newUpdate) {
log("[Updater]", `Downloading build ${newUpdate.version}...`);
autoUpdater.installUpdate()
.then(function (ret) {
var [success, value] = ret;
if (success) {
log("[Updater]", `Updated with ${value} entries extracted. Triggering restart...`);
data.return({
handler: "internal",
data: "Extracted files. Restarting..."
});
setTimeout(() => process.exit(7378278), 1000);
} else {
log("[Updater]", "Failed to install new build:", value);
data.return({
handler: "internal",
data: "Failed to install new build: " + value
});
}
})
.catch(function (ex) {
log("[Updater]", "Failed to install new build:", ex);
data.return({
handler: "internal",
data: "Failed to install new build: " + ex
});
});
}
} else {
return {
handler: "internal",
data: getLang("INSUFFICIENT_PERM", resolveID(type, data))
};
}
},
compatibly: 0,
handler: "INTERNAL",
adminCmd: true
};
global.commandMapping["version"] = {
args: {},
desc: {},
scope: function (_type, _data) {
var githubdata = JSON.parse(syncrequest("GET", "https://api.github.com/repos/c3cbot/legacy-c3cbot/git/refs/tags", {
headers: {
"User-Agent": global.config.fbuseragent
}
})
.body.toString());
var latestrelease = githubdata[githubdata.length - 1];
var latestgithubversion = latestrelease.ref.replace("refs/tags/", "");
var codedata = JSON.parse(syncrequest(
"GET",
"https://raw.githubusercontent.com/c3cbot/legacy-c3cbot/master/package.json", {
headers: {
"User-Agent": global.config.fbuseragent
}
}
)
.body.toString());
var latestcodeversion = codedata.version;
return {
handler: "internal",
data: "Currently running on version " + version + "\r\nLatest GitHub version: " + latestgithubversion +
"\r\nLatest code version: " + latestcodeversion
};
},
compatibly: 0,
handler: "INTERNAL"
};
global.commandMapping["version"].args[global.config.language] = "";
global.commandMapping["version"].desc[global.config.language] = getLang("VERSION_DESC");
global.commandMapping["help"] = {
args: Object.fromEntries(Object.entries(langMap).map(x => [x[0], x[1]["HELP_ARGS"]])),
desc: Object.fromEntries(Object.entries(langMap).map(x => [x[0], x[1]["HELP_DESC"]])),
scope: function (type, data) {
let ul = global.data.userLanguage[resolveID(type, data)] || global.config.language;
if (isNaN(parseInt(data.args[1])) && data.args.length != 1) {
var cmd = data.args[1];
if (Object.prototype.hasOwnProperty.call(global.commandMapping, cmd)) {
var mts = global.config.commandPrefix + cmd;
if (typeof global.commandMapping[cmd].args == "object") {
let ha = global.commandMapping[cmd].args;
if (typeof ha[ul] == "string") {
ha = ha[ul];
} else {
ha = ha[global.config.language];
typeof ha == "undefined" ? ha = "" : "";
}
if (ha.replace(/ /g).length != 0) {
mts += ` ${ha}`;
}
}
mts += "\r\n" + global.commandMapping[cmd].desc[ul] || global.commandMapping[cmd].desc[global.config.language];
mts += "\r\n" + getLang("HELP_ARG_INFO", resolveID(type, data));
return {
handler: "internal",
data: mts
};
} else {
return {
handler: "internal",
data: global.config.commandPrefix + cmd + "\r\n" + getLang("HELP_CMD_NOT_FOUND", resolveID(type, data))
};
}
} else {
var page = 1;
page = parseInt(data.args[1]) || 1;
if (page < 1) page = 1;
let mts = "";
mts += getLang("HELP_OUTPUT_PREFIX", resolveID(type, data));
var helpobj = global.commandMapping["help"];
helpobj.command = "help";
helpobj.args[ul] = getLang("HELP_ARGS", resolveID(type, data));
helpobj.desc[ul] = getLang("HELP_DESC", resolveID(type, data));
var hl = [helpobj];
for (var no in global.commandMapping) {
if (no !== "help") {
var tempx = global.commandMapping[no];
tempx.command = no;
hl.push(tempx);
}
}
if (type == "Discord") {
mts += "\r\n```HTTP";
}
var compatiblyFlag = 0;
switch (type) {
case "Facebook":
compatiblyFlag = 1;
break;
case "Discord":
compatiblyFlag = 2;
break;
}
for (var i = 15 * (page - 1); i < 15 * (page - 1) + 15; i++) {
if (i < hl.length) {
if (hl[i].compatibly == 0 || (hl[i].compatibly & compatiblyFlag)) {
if (data.admin) {
mts += `\n${i + 1}. ${global.config.commandPrefix}${hl[i].command}`;
if (typeof hl[i].args == "object") {
let ha = hl[i].args;
if (typeof ha[ul] == "string") {
ha = ha[ul];
} else {
ha = ha[global.config.language];
typeof ha == "undefined" ? ha = "" : "";
}
if (ha.replace(/ /g).length != 0) {
mts += ` ${ha}`;
}
} else if (typeof hl[i].args == "string") {
mts += ` ${hl[i].args}`;
}
} else if (!hl[i].adminCmd) {
mts += `\n${i + 1}. ${global.config.commandPrefix}${hl[i].command}`;
if (typeof hl[i].args == "object") {
let ha = hl[i].args;
if (typeof ha[ul] == "string") {
ha = ha[ul];
} else {
ha = ha[global.config.language];
typeof ha == "undefined" ? ha = "" : "";
}
if (ha.replace(/ /g).length != 0) {
mts += ` ${ha}`;
}
}
}
}
}
}
if (type == "Discord") {
mts += "\n```";
}
mts += `\n(${getLang("PAGE", resolveID(type, data))} ${page}/${(hl.length / 15).ceil()})`;
mts += `\n${getLang("HELP_MORE_INFO", resolveID(type, data)).replace("{0}", global.config.commandPrefix)}`;
return {
handler: "internal",
data: mts
};
}
},
compatibly: 0,
handler: "INTERNAL"
};
global.commandMapping["restart"] = {
desc: Object.fromEntries(Object.entries(langMap).map(x => [x[0], x[1]["RESTART_DESC"]])),
scope: function (type, data) {
if (data.admin && global.config.allowAdminUseRestartCommand) {
setTimeout(function () {
process.exit(7378278);
}, 1000);
return {
handler: "internal",
data: "Restarting..."
};
} else {
return {
handler: "internal",
data: getLang("INSUFFICIENT_PERM", resolveID(type, data))
};
}
},
compatibly: 0,
handler: "INTERNAL",
adminCmd: true
};
global.commandMapping["shutdown"] = {
desc: Object.fromEntries(Object.entries(langMap).map(x => [x[0], x[1]["SHUTDOWN_DESC"]])),
scope: function (type, data) {
if (data.admin && global.config.allowAdminUseShutdownCommand) {
setTimeout(function () {
process.exit(74883696);