forked from aizintel/AUTO
-
Notifications
You must be signed in to change notification settings - Fork 3
/
UpdatedVer
681 lines (679 loc) · 23.4 KB
/
UpdatedVer
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
const fs = require('fs');
const path = require('path');
const login = require('./fb-chat-api/index');
const express = require('express');
const app = express();
const chalk = require('chalk');
const bodyParser = require('body-parser');
const script = path.join(__dirname, 'script');
const cron = require('node-cron');
const config = fs.existsSync('./data') && fs.existsSync('./data/config.json') ? JSON.parse(fs.readFileSync('./data/config.json', 'utf8')) : createConfig();
const Utils = new Object({
commands: new Map(),
handleEvent: new Map(),
account: new Map(),
cooldowns: new Map(),
ObjectReply: new Map(),
handleReply: [],
});
fs.readdirSync(script).forEach((file) => {
const scripts = path.join(script, file);
const stats = fs.statSync(scripts);
if (stats.isDirectory()) {
fs.readdirSync(scripts).forEach((file) => {
try {
const {
config,
run,
handleEvent,
handleReply
} = require(path.join(scripts, file));
if (config) {
const {
name = [], role = '0', version = '1.0.0', hasPrefix = true, aliases = [], description = '', usage = '', credits = '', cooldown = '5'
} = Object.fromEntries(Object.entries(config).map(([key, value]) => [key.toLowerCase(), value]));
aliases.push(name);
if (run) {
Utils.commands.set(aliases, {
name,
role,
run,
aliases,
description,
usage,
version,
hasPrefix: config.hasPrefix,
credits,
cooldown
});
}
if (handleEvent) {
Utils.handleEvent.set(aliases, {
name,
handleEvent,
role,
description,
usage,
version,
hasPrefix: config.hasPrefix,
credits,
cooldown
});
}
if (handleReply) {
Utils.ObjectReply.set(aliases, {
name,
handleReply,
});
}
}
} catch (error) {
console.error(chalk.red(`Error installing command from file ${file}: ${error.message}`));
}
});
} else {
try {
const {
config,
run,
handleEvent,
handleReply
} = require(scripts);
if (config) {
const {
name = [], role = '0', version = '1.0.0', hasPrefix = true, aliases = [], description = '', usage = '', credits = '', cooldown = '5'
} = Object.fromEntries(Object.entries(config).map(([key, value]) => [key.toLowerCase(), value]));
aliases.push(name);
if (run) {
Utils.commands.set(aliases, {
name,
role,
run,
aliases,
description,
usage,
version,
hasPrefix: config.hasPrefix,
credits,
cooldown
});
}
if (handleEvent) {
Utils.handleEvent.set(aliases, {
name,
handleEvent,
role,
description,
usage,
version,
hasPrefix: config.hasPrefix,
credits,
cooldown
});
}
if (handleReply) {
Utils.ObjectReply.set(aliases, {
name,
handleReply,
});
}
}
} catch (error) {
console.error(chalk.red(`Error installing command from file ${file}: ${error.message}`));
}
}
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(express.json());
const routes = [{
path: '/',
file: 'index.html'
}, {
path: '/step_by_step_guide',
file: 'guide.html'
}, {
path: '/online_user',
file: 'online.html'
}, ];
routes.forEach(route => {
app.get(route.path, (req, res) => {
res.sendFile(path.join(__dirname, 'public', route.file));
});
});
app.get('/info', (req, res) => {
const data = Array.from(Utils.account.values()).map(account => ({
name: account.name,
profileUrl: account.profileUrl,
thumbSrc: account.thumbSrc,
time: account.time
}));
res.json(JSON.parse(JSON.stringify(data, null, 2)));
});
app.get('/commands', (req, res) => {
const command = new Set();
const commands = [...Utils.commands.values()].map(({
name
}) => (command.add(name), name));
const handleEvent = [...Utils.handleEvent.values()].map(({
name
}) => command.has(name) ? null : (command.add(name), name)).filter(Boolean);
const role = [...Utils.commands.values()].map(({
role
}) => (command.add(role), role));
const aliases = [...Utils.commands.values()].map(({
aliases
}) => (command.add(aliases), aliases));
res.json(JSON.parse(JSON.stringify({
commands,
handleEvent,
role,
aliases
}, null, 2)));
});
app.post('/login', async (req, res) => {
const {
state,
commands,
prefix,
admin
} = req.body;
try {
if (!state) {
throw new Error('Missing app state data');
}
const cUser = state.find(item => item.key === 'c_user');
if (cUser) {
const existingUser = Utils.account.get(cUser.value);
if (existingUser) {
console.log(`User ${cUser.value} is already logged in`);
return res.status(400).json({
error: false,
message: "Active user session detected; already logged in",
user: existingUser
});
} else {
try {
await accountLogin(state, commands, prefix, [admin]);
res.status(200).json({
success: true,
message: 'Authentication process completed successfully; login achieved.'
});
} catch (error) {
console.error(error);
res.status(400).json({
error: true,
message: error.message
});
}
}
} else {
return res.status(400).json({
error: true,
message: "There's an issue with the appstate data; it's invalid."
});
}
} catch (error) {
return res.status(400).json({
error: true,
message: "There's an issue with the appstate data; it's invalid."
});
}
});
app.listen(3000, () => {
console.log(`Server is running at http://localhost:5000`);
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Promise Rejection:', reason);
});
async function accountLogin(state, enableCommands = [], prefix, admin = []) {
return new Promise((resolve, reject) => {
login({
appState: state
}, async (error, api) => {
if (error) {
reject(error);
return;
}
const userid = await api.getCurrentUserID();
addThisUser(userid, enableCommands, state, prefix, admin);
try {
const userInfo = await api.getUserInfo(userid);
if (!userInfo || !userInfo[userid]?.name || !userInfo[userid]?.profileUrl || !userInfo[userid]?.thumbSrc) throw new Error('Unable to locate the account; it appears to be in a suspended or locked state.');
const {
name,
profileUrl,
thumbSrc
} = userInfo[userid];
let time = (JSON.parse(fs.readFileSync('./data/history.json', 'utf-8')).find(user => user.userid === userid) || {}).time || 0;
Utils.account.set(userid, {
name,
profileUrl,
thumbSrc,
time: time
});
const intervalId = setInterval(() => {
try {
const account = Utils.account.get(userid);
if (!account) throw new Error('Account not found');
Utils.account.set(userid, {
...account,
time: account.time + 1
});
} catch (error) {
clearInterval(intervalId);
return;
}
}, 1000);
} catch (error) {
reject(error);
return;
}
api.setOptions({
listenEvents: config[0].fcaOption.listenEvents,
logLevel: config[0].fcaOption.logLevel,
updatePresence: config[0].fcaOption.updatePresence,
selfListen: config[0].fcaOption.selfListen,
forceLogin: config[0].fcaOption.forceLogin,
online: config[0].fcaOption.online,
autoMarkDelivery: config[0].fcaOption.autoMarkDelivery,
autoMarkRead: config[0].fcaOption.autoMarkRead,
});
try {
api.listenMqtt(async (error, event) => {
if (error) {
if (error === 'Connection closed.') {}
}
if (event?.senderID === userid) return
let database = await fs.existsSync('./data/database.json') ? JSON.parse(fs.readFileSync('./data/database.json', 'utf8')) : createDatabase();
let history = await fs.existsSync('./data/history.json') ? JSON.parse(fs.readFileSync('./data/history.json')) : {};
if (!userid === event.senderID || database.length === 0 || !Object.keys(database[0]?.Threads || {}).includes(event?.threadID)) {
create = createThread(event.threadID, api);
} else {
update = updateThread(event?.senderID)
}
let blacklist = (history.find(blacklist => blacklist.userid === userid) || {}).blacklist || [];
let hasPrefix = (event.body && aliases((event.body || '')?.trim().toLowerCase().split(/ +/).shift())?.hasPrefix == false) ? '' : prefix;
let [command, ...args] = ((event.body || '').trim().toLowerCase().startsWith(hasPrefix?.toLowerCase()) ? (event.body || '').trim().substring(hasPrefix?.length).trim().split(/\s+/).map(arg => arg.trim()) : []);
if (hasPrefix && aliases(command)?.hasPrefix === false) {
api.sendMessage(`Invalid usage this command doesn't need a prefix`, event.threadID, event.messageID);
return;
}
if (event.body && enableCommands[0].commands.includes(aliases(command?.toLowerCase())?.name)) {
const role = aliases(command)?.role ?? 0;
const isAdmin = config?.[0]?.masterKey?.admin?.includes(event.senderID) || admin.includes(event.senderID);
const isThreadAdmin = isAdmin || (Object.values(database[0]?.Threads[event.threadID]?.adminIDs || {}).some(admin => admin.id === event.senderID));
if ((role === 1 && !isAdmin) || (role === 2 && !isThreadAdmin) || (role === 3 && !config?.[0]?.masterKey?.admin?.includes(event.senderID))) {
api.sendMessage(`You don't have permission to use this command.`, event.threadID, event.messageID);
return;
}
}
if (event.body && event.body?.toLowerCase().startsWith(prefix.toLowerCase()) && aliases(command)?.name && enableCommands[0].commands.includes(aliases(command?.toLowerCase())?.name)) {
if (blacklist.includes(event.senderID)) {
api.sendMessage("We're sorry, but you've been banned from using bot. If you believe this is a mistake or would like to appeal, please contact one of the bot admins for further assistance.", event.threadID, event.messageID);
return;
}
}
if (event.body && aliases(command)?.name) {
const now = Date.now();
const name = aliases(command)?.name;
const sender = Utils.cooldowns.get(`${event.senderID}_${name}_${userid}`);
const delay = aliases(command)?.cooldown ?? 0;
if (!sender || (now - sender.timestamp) >= delay * 1000) {
Utils.cooldowns.set(`${event.senderID}_${name}_${userid}`, {
timestamp: now,
command: name
});
} else {
const active = Math.ceil((sender.timestamp + delay * 1000 - now) / 1000);
api.sendMessage(`Please wait ${active} seconds before using the "${name}" command again.`, event.threadID, event.messageID);
return;
}
}
if (event.body && !command && event.body?.toLowerCase().startsWith(prefix.toLowerCase())) {
api.sendMessage(`Invalid command please use ${prefix}help to see the list of available commands.`, event.threadID, event.messageID);
return;
}
if (event.body && command && prefix && event.body?.toLowerCase().startsWith(prefix.toLowerCase()) && !aliases(command)?.name) {
api.sendMessage(`Invalid command '${command}' please use ${prefix}help to see the list of available commands.`, event.threadID, event.messageID);
return;
}
for (const {
handleEvent,
name
}
of Utils.handleEvent.values()) {
if (handleEvent && name && ((enableCommands[1].handleEvent || []).includes(name) || (enableCommands[0].commands || []).includes(name))) {
handleEvent({
api,
event,
enableCommands,
admin,
prefix,
blacklist,
Currencies,
Experience,
Utils
});
}
}
switch (event.type) {
case 'message':
case 'message_unsend':
case 'message_reaction':
case 'message_reply':
case 'message_reply':
if (enableCommands[0].commands.includes(aliases(command?.toLowerCase())?.name)) {
Utils.handleReply.findIndex(reply => reply.author === event.senderID) !== -1 ? (api.unsendMessage(Utils.handleReply.find(reply => reply.author === event.senderID).messageID), Utils.handleReply.splice(Utils.handleReply.findIndex(reply => reply.author === event.senderID), 1)) : null;
await ((aliases(command?.toLowerCase())?.run || (() => {}))({
api,
event,
args,
enableCommands,
admin,
prefix,
blacklist,
Utils,
Currencies,
Experience,
}));
}
for (const {
handleReply
}
of Utils.ObjectReply.values()) {
if (Array.isArray(Utils.handleReply) && Utils.handleReply.length > 0) {
if (!event.messageReply) return;
const indexOfHandle = Utils.handleReply.findIndex(reply => reply.author === event.messageReply.senderID);
if (indexOfHandle !== -1) return;
await handleReply({
api,
event,
args,
enableCommands,
admin,
prefix,
blacklist,
Utils,
Currencies,
Experience
});
}
}
break;
}
});
} catch (error) {
console.error('Error during API listen, outside of listen', userid);
Utils.account.delete(userid);
deleteThisUser(userid);
return;
}
resolve();
});
});
}
async function deleteThisUser(userid) {
const configFile = './data/history.json';
let config = JSON.parse(fs.readFileSync(configFile, 'utf-8'));
const sessionFile = path.join('./data/session', `${userid}.json`);
const index = config.findIndex(item => item.userid === userid);
if (index !== -1) config.splice(index, 1);
fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
try {
fs.unlinkSync(sessionFile);
} catch (error) {
console.log(error);
}
}
async function addThisUser(userid, enableCommands, state, prefix, admin, blacklist) {
const configFile = './data/history.json';
const sessionFolder = './data/session';
const sessionFile = path.join(sessionFolder, `${userid}.json`);
if (fs.existsSync(sessionFile)) return;
const config = JSON.parse(fs.readFileSync(configFile, 'utf-8'));
config.push({
userid,
prefix: prefix || "",
admin: admin || [],
blacklist: blacklist || [],
enableCommands,
time: 0,
});
fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
fs.writeFileSync(sessionFile, JSON.stringify(state));
}
function aliases(command) {
const aliases = Array.from(Utils.commands.entries()).find(([commands]) => commands.includes(command?.toLowerCase()));
if (aliases) {
return aliases[1];
}
return null;
}
async function main() {
const empty = require('fs-extra');
const cacheFile = './script/cache';
if (!fs.existsSync(cacheFile)) fs.mkdirSync(cacheFile);
const configFile = './data/history.json';
if (!fs.existsSync(configFile)) fs.writeFileSync(configFile, '[]', 'utf-8');
const config = JSON.parse(fs.readFileSync(configFile, 'utf-8'));
const sessionFolder = path.join('./data/session');
if (!fs.existsSync(sessionFolder)) fs.mkdirSync(sessionFolder);
const adminOfConfig = fs.existsSync('./data') && fs.existsSync('./data/config.json') ? JSON.parse(fs.readFileSync('./data/config.json', 'utf8')) : createConfig();
cron.schedule(`*/${adminOfConfig[0].masterKey.restartTime} * * * *`, async () => {
const history = JSON.parse(fs.readFileSync('./data/history.json', 'utf-8'));
history.forEach(user => {
(!user || typeof user !== 'object') ? process.exit(1): null;
(user.time === undefined || user.time === null || isNaN(user.time)) ? process.exit(1): null;
const update = Utils.account.get(user.userid);
update ? user.time = update.time : null;
});
await empty.emptyDir(cacheFile);
await fs.writeFileSync('./data/history.json', JSON.stringify(history, null, 2));
process.exit(1);
});
try {
for (const file of fs.readdirSync(sessionFolder)) {
const filePath = path.join(sessionFolder, file);
try {
const {
enableCommands,
prefix,
admin,
blacklist,
} = config.find(item => item.userid === path.parse(file).name) || {};
const state = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
if (enableCommands) await accountLogin(state, enableCommands, prefix, admin, blacklist);
} catch (error) {
deleteThisUser(path.parse(file).name);
}
}
} catch (error) {
console.log(error);
}
}
function createConfig() {
const config = [{
masterKey: {
admin: [],
devMode: false,
database: false,
restartTime: 15,
},
fcaOption: {
forceLogin: true,
listenEvents: true,
logLevel: "silent",
updatePresence: true,
selfListen: true,
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64",
online: true,
autoMarkDelivery: false,
autoMarkRead: false
}
}];
const dataFolder = './data';
if (!fs.existsSync(dataFolder)) fs.mkdirSync(dataFolder);
fs.writeFileSync('./data/config.json', JSON.stringify(config, null, 2));
return config;
}
async function createThread(threadID, api) {
try {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const threadInfo = await api.getThreadInfo(threadID);
const Threads = database.findIndex(Thread => Thread.Threads);
const Users = database.findIndex(User => User.Users);
if (Threads !== -1) {
database[Threads].Threads[threadID] = {
threadName: threadInfo.threadName,
participantIDs: threadInfo.participantIDs,
adminIDs: threadInfo.adminIDs
};
} else {
const Threads = threadInfo.isGroup ? {
[threadID]: {
threadName: threadInfo.threadName,
participantIDs: threadInfo.participantIDs,
adminIDs: threadInfo.adminIDs
}
} : {};
database.push({
Threads: {
Threads
}
});
}
if (Users !== -1) {
threadInfo.userInfo.forEach(userInfo => {
const Thread = database[Users].Users.some(user => user.id === userInfo.id);
if (!Thread) {
database[Users].Users.push({
id: userInfo.id,
name: userInfo.name,
money: 0,
exp: 0,
level: 1
});
}
});
} else {
const Users = threadInfo.isGroup ? threadInfo.userInfo.map(userInfo => ({
id: userInfo.id,
name: userInfo.name,
money: 0,
exp: 0,
level: 1
})) : [];
database.push({
Users
});
}
await fs.writeFileSync('./data/database.json', JSON.stringify(database, null, 2), 'utf-8');
return database;
} catch (error) {
console.log(error);
}
}
async function createDatabase() {
const data = './data';
const database = './data/database.json';
if (!fs.existsSync(data)) {
fs.mkdirSync(data, {
recursive: true
});
}
if (!fs.existsSync(database)) {
fs.writeFileSync(database, JSON.stringify([]));
}
return database;
}
async function updateThread(id) {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const user = database[1]?.Users.find(user => user.id === id);
if (!user) {
return;
}
user.exp += 1;
await fs.writeFileSync('./data/database.json', JSON.stringify(database, null, 2));
}
const Experience = {
async levelInfo(id) {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const data = database[1].Users.find(user => user.id === id);
if (!data) {
return;
}
return data;
},
async levelUp(id) {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const data = database[1].Users.find(user => user.id === id);
if (!data) {
return;
}
data.level += 1;
await fs.writeFileSync('./data/database.json', JSON.stringify(database, null, 2), 'utf-8');
return data;
}
}
const Currencies = {
async update(id, money) {
try {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const data = database[1].Users.find(user => user.id === id);
if (!data || !money) {
return;
}
data.money += money;
await fs.writeFileSync('./data/database.json', JSON.stringify(database, null, 2), 'utf-8');
return data;
} catch (error) {
console.error('Error updating Currencies:', error);
}
},
async increaseMoney(id, money) {
try {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const data = database[1].Users.find(user => user.id === id);
if (!data) {
return;
}
if (data && typeof data.money === 'number' && typeof money === 'number') {
data.money += money;
}
await fs.writeFileSync('./data/database.json', JSON.stringify(database, null, 2), 'utf-8');
return data;
} catch (error) {
console.error('Error checking Currencies:', error);
}
},
async decreaseMoney(id, money) {
try {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const data = database[1].Users.find(user => user.id === id);
if (!data) {
return;
}
if (data && typeof data.money === 'number' && typeof money === 'number') {
data.money -= money;
}
await fs.writeFileSync('./data/database.json', JSON.stringify(database, null, 2), 'utf-8');
return data;
} catch (error) {
console.error('Error checking Currencies:', error);
}
},
async getData(id) {
try {
const database = JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
const data = database[1].Users.find(user => user.id === id);
if (!data) {
return;
}
return data;
} catch (error) {
console.error('Error checking Currencies:', error);
}
}
};
main()