forked from ntkhang03/Goat-Bot-V2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
1067 lines (981 loc) · 28.5 KB
/
utils.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
const axios = require("axios");
const fs = require("fs-extra");
const path = require("path");
const cheerio = require("cheerio");
const https = require("https");
const agent = new https.Agent({
rejectUnauthorized: false
});
const moment = require("moment-timezone");
const mimeDB = require("mime-db");
const _ = require("lodash");
const { google } = require("googleapis");
const ora = require("ora");
const log = require("./logger/log.js");
const { isHexColor, colors } = require("./func/colors.js");
const Prism = require("./func/prism.js");
const { config } = global.GoatBot;
const { gmailAccount } = config.credentials;
const { clientId, clientSecret, refreshToken, apiKey: googleApiKey } = gmailAccount;
if (!clientId) {
log.err("CREDENTIALS", `Please provide a valid clientId in file ${path.normalize(global.client.dirConfig)}`);
process.exit();
}
if (!clientSecret) {
log.err("CREDENTIALS", `Please provide a valid clientSecret in file ${path.normalize(global.client.dirConfig)}`);
process.exit();
}
if (!refreshToken) {
log.err("CREDENTIALS", `Please provide a valid refreshToken in file ${path.normalize(global.client.dirConfig)}`);
process.exit();
}
const oauth2ClientForGGDrive = new google.auth.OAuth2(clientId, clientSecret, "https://developers.google.com/oauthplayground");
oauth2ClientForGGDrive.setCredentials({ refresh_token: refreshToken });
const driveApi = google.drive({
version: 'v3',
auth: oauth2ClientForGGDrive
});
const word = [
'A', 'Á', 'À', 'Ả', 'Ã', 'Ạ', 'a', 'á', 'à', 'ả', 'ã', 'ạ',
'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ', 'Ặ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ',
'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ',
'B', 'b',
'C', 'c',
'D', 'Đ', 'd', 'đ',
'E', 'É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'e', 'é', 'è', 'ẻ', 'ẽ', 'ẹ',
'Ê', 'Ế', 'Ề', 'Ể', 'Ễ', 'Ệ', 'ê', 'ế', 'ề', 'ể', 'ễ', 'ệ',
'F', 'f',
'G', 'g',
'H', 'h',
'I', 'Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'i', 'í', 'ì', 'ỉ', 'ĩ', 'ị',
'J', 'j',
'K', 'k',
'L', 'l',
'M', 'm',
'N', 'n',
'O', 'Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'o', 'ó', 'ò', 'ỏ', 'õ', 'ọ',
'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ', 'Ộ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ',
'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ',
'P', 'p',
'Q', 'q',
'R', 'r',
'S', 's',
'T', 't',
'U', 'Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'u', 'ú', 'ù', 'ủ', 'ũ', 'ụ',
'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự', 'ư', 'ứ', 'ừ', 'ử', 'ữ', 'ự',
'V', 'v',
'W', 'w',
'X', 'x',
'Y', 'Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'y', 'ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ',
'Z', 'z',
' '
];
const regCheckURL = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
class CustomError extends Error {
constructor(obj) {
if (typeof obj === 'string')
obj = { message: obj };
if (typeof obj !== 'object' || obj === null)
throw new TypeError('Object required');
obj.message ? super(obj.message) : super();
Object.assign(this, obj);
}
}
function lengthWhiteSpacesEndLine(text) {
let length = 0;
for (let i = text.length - 1; i >= 0; i--) {
if (text[i] == ' ')
length++;
else
break;
}
return length;
}
function lengthWhiteSpacesStartLine(text) {
let length = 0;
for (let i = 0; i < text.length; i++) {
if (text[i] == ' ')
length++;
else
break;
}
return length;
}
function setErrorUptime() {
global.statusAccountBot = 'block spam';
global.responseUptimeCurrent = global.responseUptimeError;
}
const defaultStderrClearLine = process.stderr.clearLine;
function convertTime(miliSeconds, replaceSeconds = "s", replaceMinutes = "m", replaceHours = "h", replaceDays = "d", replaceMonths = "M", replaceYears = "y", notShowZero = false) {
if (typeof replaceSeconds == 'boolean') {
notShowZero = replaceSeconds;
replaceSeconds = "s";
}
const second = Math.floor(miliSeconds / 1000 % 60);
const minute = Math.floor(miliSeconds / 1000 / 60 % 60);
const hour = Math.floor(miliSeconds / 1000 / 60 / 60 % 24);
const day = Math.floor(miliSeconds / 1000 / 60 / 60 / 24 % 30);
const month = Math.floor(miliSeconds / 1000 / 60 / 60 / 24 / 30 % 12);
const year = Math.floor(miliSeconds / 1000 / 60 / 60 / 24 / 30 / 12);
let formattedDate = '';
const dateParts = [
{ value: year, replace: replaceYears },
{ value: month, replace: replaceMonths },
{ value: day, replace: replaceDays },
{ value: hour, replace: replaceHours },
{ value: minute, replace: replaceMinutes },
{ value: second, replace: replaceSeconds }
];
for (let i = 0; i < dateParts.length; i++) {
const datePart = dateParts[i];
if (datePart.value)
formattedDate += datePart.value + datePart.replace;
else if (formattedDate != '')
formattedDate += '00' + datePart.replace;
else if (i == dateParts.length - 1)
formattedDate += '0' + datePart.replace;
}
if (formattedDate == '')
formattedDate = '0' + replaceSeconds;
if (notShowZero)
formattedDate = formattedDate.replace(/00\w+/g, '');
return formattedDate;
}
function createOraDots(text) {
const spin = new ora({
text: text,
spinner: {
interval: 80,
frames: [
'⠋', '⠙', '⠹',
'⠸', '⠼', '⠴',
'⠦', '⠧', '⠇',
'⠏'
]
}
});
spin._start = () => {
utils.enableStderrClearLine(false);
spin.start();
};
spin._stop = () => {
utils.enableStderrClearLine(true);
spin.stop();
};
return spin;
}
function createQueue(callback) {
const queue = [];
const queueObj = {
push: function (task) {
queue.push(task);
if (queue.length == 1)
queueObj.next();
},
running: null,
length: function () {
return queue.length;
},
next: function () {
if (queue.length > 0) {
const task = queue[0];
queueObj.running = task;
callback(task, async function (err, result) {
queueObj.running = null;
queue.shift();
queueObj.next();
});
}
}
};
return queueObj;
}
function enableStderrClearLine(isEnable = true) {
process.stderr.clearLine = isEnable ? defaultStderrClearLine : () => { };
}
function formatNumber(number) {
const regionCode = global.GoatBot.config.language;
if (isNaN(number))
throw new Error('The first argument (number) must be a number');
number = Number(number);
return number.toLocaleString(regionCode || "en-US");
}
function getExtFromAttachmentType(type) {
switch (type) {
case "photo":
return 'png';
case "animated_image":
return "gif";
case "video":
return "mp4";
case "audio":
return "mp3";
default:
return "txt";
}
}
function getExtFromMimeType(mimeType = "") {
return mimeDB[mimeType] ? (mimeDB[mimeType].extensions || [])[0] || "unknow" : "unknow";
}
function getExtFromUrl(url = "") {
if (!url || typeof url !== "string")
throw new Error('The first argument (url) must be a string');
const reg = /(?<=https:\/\/cdn.fbsbx.com\/v\/.*?\/|https:\/\/video.xx.fbcdn.net\/v\/.*?\/|https:\/\/scontent.xx.fbcdn.net\/v\/.*?\/).*?(\/|\?)/g;
const fileName = url.match(reg)[0].slice(0, -1);
return fileName.slice(fileName.lastIndexOf(".") + 1);
}
function getPrefix(threadID) {
if (!threadID || isNaN(threadID))
throw new Error('The first argument (threadID) must be a number');
threadID = String(threadID);
let prefix = global.GoatBot.config.prefix;
const threadData = global.db.allThreadData.find(t => t.threadID == threadID);
if (threadData)
prefix = threadData.data.prefix || prefix;
return prefix;
}
function getTime(timestamps, format) {
// check if just have timestamps -> format = timestamps
if (!format && typeof timestamps == 'string') {
format = timestamps;
timestamps = undefined;
}
return moment(timestamps).tz(config.timeZone).format(format);
}
function isNumber(value) {
return !isNaN(parseFloat(value));
}
function jsonStringifyColor(obj, filter, indent, level) {
// source: https://www.npmjs.com/package/node-json-color-stringify
indent = indent || 0;
level = level || 0;
let output = '';
if (typeof obj === 'string')
output += colors.green(`"${obj}"`);
else if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)
output += colors.yellow(obj);
else if (obj === undefined)
output += colors.gray('undefined');
else if (obj !== undefined && typeof obj !== 'function')
if (!Array.isArray(obj)) {
if (Object.keys(obj).length === 0)
output += '{}';
else {
output += colors.gray('{\n');
Object.keys(obj).forEach(key => {
let value = obj[key];
if (filter) {
if (typeof filter === 'function')
value = filter(key, value);
else if (typeof filter === 'object' && filter.length !== undefined)
if (filter.indexOf(key) < 0)
return;
}
// if (value === undefined)
// return;
if (!isNaN(key[0]) || key.match(/[^a-zA-Z0-9_]/))
key = colors.green(JSON.stringify(key));
output += ' '.repeat(indent + level * indent) + `${key}:${indent ? ' ' : ''}`;
output += utils.jsonStringifyColor(value, filter, indent, level + 1) + ',\n';
});
output = output.replace(/,\n$/, '\n');
output += ' '.repeat(level * indent) + colors.gray('}');
}
}
else {
if (obj.length === 0)
output += '[]';
else {
output += colors.gray('[\n');
obj.forEach(subObj => {
output += ' '.repeat(indent + level * indent) + utils.jsonStringifyColor(subObj, filter, indent, level + 1) + ',\n';
});
output = output.replace(/,\n$/, '\n');
output += ' '.repeat(level * indent) + colors.gray(']');
}
}
else if (typeof obj === 'function')
output += colors.green(obj.toString());
output = output.replace(/,$/gm, colors.gray(','));
if (indent === 0)
return output.replace(/\n/g, '');
return output;
}
function message(api, event) {
async function sendMessageError(err) {
if (typeof err === "object" && !err.stack)
err = utils.removeHomeDir(JSON.stringify(err, null, 2));
else
err = utils.removeHomeDir(`${err.name || err.error}: ${err.message}`);
return await api.sendMessage(utils.getText("utils", "errorOccurred", err), event.threadID, event.messageID);
}
return {
send: async (form, callback) => {
try {
global.statusAccountBot = 'good';
return await api.sendMessage(form, event.threadID, callback);
}
catch (err) {
if (JSON.stringify(err).includes('spam')) {
setErrorUptime();
throw err;
}
}
},
reply: async (form, callback) => {
try {
global.statusAccountBot = 'good';
return await api.sendMessage(form, event.threadID, callback, event.messageID);
}
catch (err) {
if (JSON.stringify(err).includes('spam')) {
setErrorUptime();
throw err;
}
}
},
unsend: async (messageID, callback) => await api.unsendMessage(messageID, callback),
reaction: async (emoji, messageID, callback) => {
try {
global.statusAccountBot = 'good';
return await api.setMessageReaction(emoji, messageID, callback, true);
}
catch (err) {
if (JSON.stringify(err).includes('spam')) {
setErrorUptime();
throw err;
}
}
},
err: async (err) => await sendMessageError(err),
error: async (err) => await sendMessageError(err)
};
}
function randomString(max, onlyOnce = false, possible) {
if (!max || isNaN(max))
max = 10;
let text = "";
possible = possible || "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < max; i++) {
let random = Math.floor(Math.random() * possible.length);
if (onlyOnce) {
while (text.includes(possible[random]))
random = Math.floor(Math.random() * possible.length);
}
text += possible[random];
}
return text;
}
function randomNumber(min, max) {
if (!max) {
max = min;
min = 0;
}
if (min == null || min == undefined || isNaN(min))
throw new Error('The first argument (min) must be a number');
if (max == null || max == undefined || isNaN(max))
throw new Error('The second argument (max) must be a number');
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function removeHomeDir(fullPath) {
if (!fullPath || typeof fullPath !== "string")
throw new Error('The first argument (fullPath) must be a string');
while (fullPath.includes(process.cwd()))
fullPath = fullPath.replace(process.cwd(), "");
return fullPath;
}
function splitPage(arr, limit) {
const allPage = _.chunk(arr, limit);
return {
totalPage: allPage.length,
allPage
};
}
async function translateAPI(text, lang) {
try {
const res = await axios.get(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${lang}&dt=t&q=${encodeURIComponent(text)}`);
return res.data[0][0][0];
}
catch (err) {
throw new CustomError(err.response ? err.response.data : err);
}
}
async function downloadFile(url = "", path = "") {
if (!url || typeof url !== "string")
throw new Error(`The first argument (url) must be a string`);
if (!path || typeof path !== "string")
throw new Error(`The second argument (path) must be a string`);
let getFile;
try {
getFile = await axios.get(url, {
responseType: "arraybuffer"
});
}
catch (err) {
throw new CustomError(err.response ? err.response.data : err);
}
fs.writeFileSync(path, Buffer.from(getFile.data));
return path;
}
async function findUid(link) {
try {
const response = await axios.post(
'https://seomagnifier.com/fbid',
new URLSearchParams({
'facebook': '1',
'sitelink': link
}),
{
headers: {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': 'PHPSESSID=0d8feddd151431cf35ccb0522b056dc6'
}
}
);
const id = response.data;
// try another method if this one fails
if (isNaN(id)) {
const html = await axios.get(link);
const $ = cheerio.load(html.data);
const el = $('meta[property="al:android:url"]').attr('content');
if (!el) {
throw new Error('UID not found');
}
const number = el.split('/').pop();
return number;
}
return id;
} catch (error) {
throw new Error('An unexpected error occurred. Please try again.');
}
}
async function getStreamsFromAttachment(attachments) {
const streams = [];
for (const attachment of attachments) {
const url = attachment.url;
const ext = utils.getExtFromUrl(url);
const fileName = `${utils.randomString(10)}.${ext}`;
streams.push({
pending: axios({
url,
method: "GET",
responseType: "stream"
}),
fileName
});
}
for (let i = 0; i < streams.length; i++) {
const stream = await streams[i].pending;
stream.data.path = streams[i].fileName;
streams[i] = stream.data;
}
return streams;
}
async function getStreamFromURL(url = "", pathName = "", options = {}) {
if (!options && typeof pathName === "object") {
options = pathName;
pathName = "";
}
try {
if (!url || typeof url !== "string")
throw new Error(`The first argument (url) must be a string`);
const response = await axios({
url,
method: "GET",
responseType: "stream",
...options
});
if (!pathName)
pathName = utils.randomString(10) + (response.headers["content-type"] ? '.' + utils.getExtFromMimeType(response.headers["content-type"]) : ".noext");
response.data.path = pathName;
return response.data;
}
catch (err) {
throw err;
}
}
async function translate(text, lang) {
if (typeof text !== "string")
throw new Error(`The first argument (text) must be a string`);
if (!lang)
lang = 'en';
if (typeof lang !== "string")
throw new Error(`The second argument (lang) must be a string`);
const wordTranslate = [''];
const wordNoTranslate = [''];
const wordTransAfter = [];
let lastPosition = 'wordTranslate';
if (word.indexOf(text.charAt(0)) == -1)
wordTranslate.push('');
else
wordNoTranslate.splice(0, 1);
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (word.indexOf(char) !== -1) { // is word
const lengWordNoTranslate = wordNoTranslate.length - 1;
if (wordNoTranslate[lengWordNoTranslate] && wordNoTranslate[lengWordNoTranslate].includes('{') && !wordNoTranslate[lengWordNoTranslate].includes('}')) {
wordNoTranslate[lengWordNoTranslate] += char;
continue;
}
const lengWordTranslate = wordTranslate.length - 1;
if (lastPosition == 'wordTranslate') {
wordTranslate[lengWordTranslate] += char;
}
else {
wordTranslate.push(char);
lastPosition = 'wordTranslate';
}
}
else { // is no word
const lengWordNoTranslate = wordNoTranslate.length - 1;
const twoWordLast = wordNoTranslate[lengWordNoTranslate]?.slice(-2) || '';
if (lastPosition == 'wordNoTranslate') {
if (twoWordLast == '}}') {
wordTranslate.push("");
wordNoTranslate.push(char);
}
else
wordNoTranslate[lengWordNoTranslate] += char;
}
else {
wordNoTranslate.push(char);
lastPosition = 'wordNoTranslate';
}
}
}
for (let i = 0; i < wordTranslate.length; i++) {
const text = wordTranslate[i];
if (!text.match(/[^\s]+/))
wordTransAfter.push(text);
else
wordTransAfter.push(utils.translateAPI(text, lang));
}
let output = '';
for (let i = 0; i < wordTransAfter.length; i++) {
let wordTrans = (await wordTransAfter[i]);
if (wordTrans.trim().length === 0) {
output += wordTrans;
if (wordNoTranslate[i] != undefined)
output += wordNoTranslate[i];
continue;
}
wordTrans = wordTrans.trim();
const numberStartSpace = lengthWhiteSpacesStartLine(wordTranslate[i]);
const numberEndSpace = lengthWhiteSpacesEndLine(wordTranslate[i]);
wordTrans = ' '.repeat(numberStartSpace) + wordTrans.trim() + ' '.repeat(numberEndSpace);
output += wordTrans;
if (wordNoTranslate[i] != undefined)
output += wordNoTranslate[i];
}
return output;
}
async function shortenURL(url) {
try {
const result = await axios.get(`https://tinyurl.com/api-create.php?url=${encodeURIComponent(url)}`);
return result.data;
}
catch (err) {
let error;
if (err.response) {
error = new Error();
Object.assign(error, err.response.data);
}
else
error = new Error(err.message);
}
}
async function uploadImgbb(file /* stream or image url */) {
let type = "file";
try {
if (!file)
throw new Error('The first argument (file) must be a stream or a image url');
if (regCheckURL.test(file) == true)
type = "url";
if (
(type != "url" && (!(typeof file._read === 'function' && typeof file._readableState === 'object')))
|| (type == "url" && !regCheckURL.test(file))
)
throw new Error('The first argument (file) must be a stream or an image URL');
const res_ = await axios({
method: 'GET',
url: 'https://imgbb.com'
});
const auth_token = res_.data.match(/auth_token="([^"]+)"/)[1];
const timestamp = Date.now();
const res = await axios({
method: 'POST',
url: 'https://imgbb.com/json',
headers: {
"content-type": "multipart/form-data"
},
data: {
source: file,
type: type,
action: 'upload',
timestamp: timestamp,
auth_token: auth_token
}
});
return res.data;
// {
// "status_code": 200,
// "success": {
// "message": "image uploaded",
// "code": 200
// },
// "image": {
// "name": "Banner-Project-Goat-Bot",
// "extension": "png",
// "width": 2560,
// "height": 1440,
// "size": 194460,
// "time": 1688352855,
// "expiration": 0,
// "likes": 0,
// "description": null,
// "original_filename": "Banner Project Goat Bot.png",
// "is_animated": 0,
// "is_360": 0,
// "nsfw": 0,
// "id_encoded": "D1yzzdr",
// "size_formatted": "194.5 KB",
// "filename": "Banner-Project-Goat-Bot.png",
// "url": "https://i.ibb.co/wdXBBtc/Banner-Project-Goat-Bot.png", // => this is url image
// "url_viewer": "https://ibb.co/D1yzzdr",
// "url_viewer_preview": "https://ibb.co/D1yzzdr",
// "url_viewer_thumb": "https://ibb.co/D1yzzdr",
// "image": {
// "filename": "Banner-Project-Goat-Bot.png",
// "name": "Banner-Project-Goat-Bot",
// "mime": "image/png",
// "extension": "png",
// "url": "https://i.ibb.co/wdXBBtc/Banner-Project-Goat-Bot.png",
// "size": 194460
// },
// "thumb": {
// "filename": "Banner-Project-Goat-Bot.png",
// "name": "Banner-Project-Goat-Bot",
// "mime": "image/png",
// "extension": "png",
// "url": "https://i.ibb.co/D1yzzdr/Banner-Project-Goat-Bot.png"
// },
// "medium": {
// "filename": "Banner-Project-Goat-Bot.png",
// "name": "Banner-Project-Goat-Bot",
// "mime": "image/png",
// "extension": "png",
// "url": "https://i.ibb.co/tHtQQRL/Banner-Project-Goat-Bot.png"
// },
// "display_url": "https://i.ibb.co/tHtQQRL/Banner-Project-Goat-Bot.png",
// "display_width": 2560,
// "display_height": 1440,
// "delete_url": "https://ibb.co/D1yzzdr/<TOKEN>",
// "views_label": "lượt xem",
// "likes_label": "thích",
// "how_long_ago": "mới đây",
// "date_fixed_peer": "2023-07-03 02:54:15",
// "title": "Banner-Project-Goat-Bot",
// "title_truncated": "Banner-Project-Goat-Bot",
// "title_truncated_html": "Banner-Project-Goat-Bot",
// "is_use_loader": false
// },
// "request": {
// "type": "file",
// "action": "upload",
// "timestamp": "1688352853967",
// "auth_token": "a2606b39536a05a81bef15558bb0d61f7253dccb"
// },
// "status_txt": "OK"
// }
}
catch (err) {
throw new CustomError(err.response ? err.response.data : err);
}
}
async function uploadZippyshare(stream) {
const res = await axios({
method: 'POST',
url: 'https://api.zippysha.re/upload',
httpsAgent: agent,
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
file: stream
}
});
const fullUrl = res.data.data.file.url.full;
const res_ = await axios({
method: 'GET',
url: fullUrl,
httpsAgent: agent,
headers: {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43"
}
});
const downloadUrl = res_.data.match(/id="download-url"(?:.|\n)*?href="(.+?)"/)[1];
res.data.data.file.url.download = downloadUrl;
return res.data;
}
const drive = {
default: driveApi,
parentID: "",
async uploadFile(fileName, mimeType, file) {
if (!file && typeof fileName === "string") {
file = mimeType;
mimeType = undefined;
}
let response;
try {
response = (await driveApi.files.create({
resource: {
name: fileName,
parents: [this.parentID]
},
media: {
mimeType,
body: file
},
fields: "*"
})).data;
}
catch (err) {
throw new Error(err.errors.map(e => e.message).join("\n"));
}
await utils.drive.makePublic(response.id);
return response;
},
async deleteFile(id) {
if (!id || typeof id !== "string")
throw new Error('The first argument (id) must be a string');
try {
await driveApi.files.delete({
fileId: id
});
return true;
}
catch (err) {
throw new Error(err.errors.map(e => e.message).join("\n"));
}
},
getUrlDownload(id = "") {
if (!id || typeof id !== "string")
throw new Error('The first argument (id) must be a string');
return `https://docs.google.com/uc?id=${id}&export=download&confirm=t${googleApiKey ? `&key=${googleApiKey}` : ''}`;
},
async getFile(id, responseType) {
if (!id || typeof id !== "string")
throw new Error('The first argument (id) must be a string');
if (!responseType)
responseType = "arraybuffer";
if (typeof responseType !== "string")
throw new Error('The second argument (responseType) must be a string');
const response = await driveApi.files.get({
fileId: id,
alt: 'media'
}, {
responseType
});
const headersResponse = response.headers;
const fileName = headersResponse["content-disposition"]?.split('filename="')[1]?.split('"')[0] || `${utils.randomString(10)}.${utils.getExtFromMimeType(headersResponse["content-type"])}`;
if (responseType == "arraybuffer")
return Buffer.from(response.data);
else if (responseType == "stream")
response.data.path = fileName;
const file = response.data;
return file;
},
async getFileName(id) {
if (!id || typeof id !== "string")
throw new Error('The first argument (id) must be a string');
const { fileNames: tempFileNames } = global.temp.filesOfGoogleDrive;
if (tempFileNames[id])
return tempFileNames[id];
try {
const { data: response } = await driveApi.files.get({
fileId: id,
fields: "name"
});
tempFileNames[id] = response.name;
return response.name;
}
catch (err) {
throw new Error(err.errors.map(e => e.message).join("\n"));
}
},
async makePublic(id) {
if (!id || typeof id !== "string")
throw new Error('The first argument (id) must be a string');
try {
await driveApi.permissions.create({
fileId: id,
requestBody: {
role: 'reader',
type: 'anyone'
}
});
return id;
}
catch (err) {
const error = new Error(err.errors.map(e => e.message).join("\n"));
error.name = 'CAN\'T_MAKE_PUBLIC';
throw new Error(err.errors.map(e => e.message).join("\n"));
}
},
async checkAndCreateParentFolder(folderName) {
if (!folderName || typeof folderName !== "string")
throw new Error('The first argument (folderName) must be a string');
let parentID;
const { data: findParentFolder } = await driveApi.files.list({
q: `name="${folderName}" and mimeType="application/vnd.google-apps.folder" and trashed=false`,
fields: '*'
});
const parentFolder = findParentFolder.files.find(i => i.ownedByMe);
if (!parentFolder) {
const { data } = await driveApi.files.create({
requestBody: {
name: folderName,
mimeType: 'application/vnd.google-apps.folder'
}
});
await driveApi.permissions.create({
fileId: data.id,
requestBody: {
role: 'reader',
type: 'anyone'
}
});
parentID = data.id;
}
else if (!parentFolder.shared) {
await driveApi.permissions.create({
fileId: parentFolder.id,
requestBody: {
role: 'reader',
type: 'anyone'
}
});
parentID = parentFolder.data.id;
}
else
parentID = parentFolder.id;
return parentID;
}
};
class GoatBotApis {
constructor(apiKey) {
this.apiKey = apiKey;
const url = `https://goatbot.tk/api`;
this.api = axios.create({
baseURL: url,
headers: {
"x-api-key": apiKey
}
});
// modify axios response
this.api.interceptors.response.use((response) => {
return {
status: response.status,
statusText: response.statusText,
responseHeaders: {
'x-remaining-requests': parseInt(response.headers['x-remaining-requests']),
'x-free-remaining-requests': parseInt(response.headers['x-free-remaining-requests']),
'x-used-requests': parseInt(response.headers['x-used-requests'])
},
data: response.data
};
});
// modify axios response error
this.api.interceptors.response.use(undefined, async (error) => {
let responseDataError;
const promise = () => new Promise((resolveFunc) => {
// decode all response data to utf8 (string) if responseType is
if (error.response.config.responseType === "arraybuffer") {
responseDataError = Buffer.from(error.response.data, "binary").toString("utf8");
resolveFunc();
}
else if (error.response.config.responseType === "stream") {
let data = "";
error.response.data.on("data", (chunk) => {
data += chunk;
});
error.response.data.on("end", () => {
responseDataError = data;
resolveFunc();
});
}
else {
responseDataError = error.response.data;
resolveFunc();
}
});
await promise();
try {
responseDataError = JSON.parse(responseDataError);
}
catch (err) { }
return Promise.reject({
status: error.response.status,
statusText: error.response.statusText,
responseHeaders: {
'x-remaining-requests': parseInt(error.response.headers['x-remaining-requests']),