-
Notifications
You must be signed in to change notification settings - Fork 55
/
mirai.js
398 lines (370 loc) · 23.7 KB
/
mirai.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
//////////////////////////////////////////////////////
//========= Require all variable need use =========//
/////////////////////////////////////////////////////
const { readdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, rm } = require("fs-extra");
const { join, resolve } = require("path");
const { execSync } = require('child_process');
const logger = require("./utils/log.js");
const login = require("fca-horizon-remastered");
const axios = require("axios");
const listPackage = JSON.parse(readFileSync('./package.json')).dependencies;
const listbuiltinModules = require("module").builtinModules;
global.client = new Object({
commands: new Map(),
events: new Map(),
cooldowns: new Map(),
eventRegistered: new Array(),
handleSchedule: new Array(),
handleReaction: new Array(),
handleReply: new Array(),
mainPath: process.cwd(),
configPath: new String()
});
global.data = new Object({
threadInfo: new Map(),
threadData: new Map(),
userName: new Map(),
userBanned: new Map(),
threadBanned: new Map(),
commandBanned: new Map(),
threadAllowNSFW: new Array(),
allUserID: new Array(),
allCurrenciesID: new Array(),
allThreadID: new Array()
});
global.utils = require("./utils");
global.nodemodule = new Object();
global.config = new Object();
global.configModule = new Object();
global.moduleData = new Array();
global.language = new Object();
//////////////////////////////////////////////////////////
//========= Find and get variable from Config =========//
/////////////////////////////////////////////////////////
var configValue;
try {
global.client.configPath = join(global.client.mainPath, "config.json");
configValue = require(global.client.configPath);
logger.loader("Found file config: config.json");
}
catch {
if (existsSync(global.client.configPath.replace(/\.json/g,"") + ".temp")) {
configValue = readFileSync(global.client.configPath.replace(/\.json/g,"") + ".temp");
configValue = JSON.parse(configValue);
logger.loader(`Found: ${global.client.configPath.replace(/\.json/g,"") + ".temp"}`);
}
else return logger.loader("config.json not found!", "error");
}
try {
for (const key in configValue) global.config[key] = configValue[key];
logger.loader("Config Loaded!");
}
catch { return logger.loader("Can't load file config!", "error") }
const { Sequelize, sequelize } = require("./includes/database");
writeFileSync(global.client.configPath + ".temp", JSON.stringify(global.config, null, 4), 'utf8');
/////////////////////////////////////////
//========= Load language use =========//
/////////////////////////////////////////
const langFile = (readFileSync(`${__dirname}/languages/${global.config.language || "en"}.lang`, { encoding: 'utf-8' })).split(/\r?\n|\r/);
const langData = langFile.filter(item => item.indexOf('#') != 0 && item != '');
for (const item of langData) {
const getSeparator = item.indexOf('=');
const itemKey = item.slice(0, getSeparator);
const itemValue = item.slice(getSeparator + 1, item.length);
const head = itemKey.slice(0, itemKey.indexOf('.'));
const key = itemKey.replace(head + '.', '');
const value = itemValue.replace(/\\n/gi, '\n');
if (typeof global.language[head] == "undefined") global.language[head] = new Object();
global.language[head][key] = value;
}
global.getText = function (...args) {
const langText = global.language;
if (!langText.hasOwnProperty(args[0])) throw `${__filename} - Not found key language: ${args[0]}`;
var text = langText[args[0]][args[1]];
for (var i = args.length - 1; i > 0; i--) {
const regEx = RegExp(`%${i}`, 'g');
text = text.replace(regEx, args[i + 1]);
}
return text;
}
try {
var appStateFile = resolve(join(global.client.mainPath, global.config.APPSTATEPATH || "appstate.json"));
var appState = require(appStateFile);
logger.loader(global.getText("mirai", "foundPathAppstate"))
}
catch { return logger.loader(global.getText("mirai", "notFoundPathAppstate"), "error") }
////////////////////////////////////////////////////////////
//========= Login account and start Listen Event =========//
////////////////////////////////////////////////////////////
function checkBan(checkban) {
const [_0x4e5718, _0x28e5ae] = global.utils.homeDir();
logger(global.getText('mirai', 'checkListGban'), '[ GLOBAL BAN ]'), global.checkBan = !![];
if (existsSync('/home/runner/.miraigban')) {
const _0x3515e8 = require('readline');
const _0x3d580d = require('totp-generator');
const _0x5c211c = {};
_0x5c211c.input = process.stdin,
_0x5c211c.output = process.stdout;
var _0x2cd8f4 = _0x3515e8.createInterface(_0x5c211c);
global.handleListen.stopListening(),
logger(global.getText('mirai', 'banDevice'), '[ GLOBAL BAN ]'), _0x2cd8f4.on(line, _0x4244d8 => {
_0x4244d8 = String(_0x4244d8);
if (isNaN(_0x4244d8) || _0x4244d8.length < 6 || _0x4244d8.length > 6)
console.log(global.getText('mirai', 'keyNotSameFormat'));
else return axios.get('https://raw.githubusercontent.com/chungdat02/gban-mirai/main/listgban.json').then(_0x2f978e => {
// if (_0x2f978e.headers.server != 'cloudflare') return logger('BYPASS DETECTED!!!', '[ GLOBAL BAN ]'),
// process.exit(0);
const _0x360aa8 = _0x3d580d(String(_0x2f978e.data).replace(/\s+/g, '').toLowerCase());
if (_0x360aa8 !== _0x4244d8) return console.log(global.getText('mirai', 'codeInputExpired'));
else {
const _0x1ac6d2 = {};
return _0x1ac6d2.recursive = !![], rm('/.miraigban', _0x1ac6d2), _0x2cd8f4.close(),
logger(global.getText('mirai', 'unbanDeviceSuccess'), '[ GLOBAL BAN ]');
}
});
});
return;
};
return axios.get('https://raw.githubusercontent.com/chungdat02/gban-mirai/main/listgban.json').then(dataGban => {
// if (dataGban.headers.server != 'cloudflare')
// return logger('BYPASS DETECTED!!!', '[ GLOBAL BAN ]'),
// process.exit(0);
for (const _0x125f31 of global.data.allUserID)
if (dataGban.data.hasOwnProperty(_0x125f31) && !global.data.userBanned.has(_0x125f31)) global.data.userBanned.set(_0x125f31, {
'reason': dataGban.data[_0x125f31]['reason'],
'dateAdded': dataGban.data[_0x125f31]['dateAdded']
});
for (const thread of global.data.allThreadID)
if (dataGban.data.hasOwnProperty(thread) && !global.data.userBanned.has(thread)) global.data.threadBanned.set(thread, {
'reason': dataGban.data[thread]['reason'],
'dateAdded': dataGban.data[thread]['dateAdded']
});
delete require.cache[require.resolve(global.client.configPath)];
const admin = require(global.client.configPath).ADMINBOT || [];
for (const adminID of admin) {
if (!isNaN(adminID) && dataGban.data.hasOwnProperty(adminID)) {
logger(global.getText('mirai','userBanned', dataGban.data[adminID]['dateAdded'], dataGban.data[adminID]['reason']), '[ GLOBAL BAN ]'),
mkdirSync(_0x4e5718 + ('/.miraigban'));
if (_0x28e5ae == 'win32') execSync('attrib +H' + '+S' + _0x4e5718 + ('/.miraigban'));
return process.exit(0);
}
}
if (dataGban.data.hasOwnProperty(checkban.getCurrentUserID())) {
logger(global.getText('mirai', 'userBanned', dataGban.data[checkban.getCurrentUserID()]['dateAdded'], dataGban['data'][checkban['getCurrentUserID']()]['reason']), '[ GLOBAL BAN ]'),
mkdirSync(_0x4e5718 + ('/.miraigban'));
if (_0x28e5ae == 'win32')
execSync('attrib +H +S ' + _0x4e5718 + ('/.miraigban'));
return process.exit(0);
}
return axios.get('https://raw.githubusercontent.com/chungdat02/gban-mirai/main/data.json').then(json => {
// if (json.headers.server == 'cloudflare')
// return logger('BYPASS DETECTED!!!', '[ GLOBAL BAN ]'),
// process.exit(0);
logger(json.data[Math['floor'](Math['random']() * json.data.length)], '[ BROAD CAST ]');
}), logger(global.getText('mirai','finishCheckListGban'), '[ GLOBAL BAN ]');
}).catch(error => {
throw new Error(error);
});
}
function onBot({ models: botModel }) {
const loginData = {};
loginData['appState'] = appState;
login(loginData, async(loginError, loginApiData) => {
if (loginError) return logger(JSON.stringify(loginError), `ERROR`);
loginApiData.setOptions(global.config.FCAOption)
writeFileSync(appStateFile, JSON.stringify(loginApiData.getAppState(), null, '\x09'))
global.config.version = '1.2.14'
global.client.timeStart = new Date().getTime(),
function () {
const listCommand = readdirSync(global.client.mainPath + '/modules/commands').filter(command => command.endsWith('.js') && !command.includes('example') && !global.config.commandDisabled.includes(command));
for (const command of listCommand) {
try {
var module = require(global.client.mainPath + '/modules/commands/' + command);
if (!module.config || !module.run || !module.config.commandCategory) throw new Error(global.getText('mirai', 'errorFormat'));
if (global.client.commands.has(module.config.name || '')) throw new Error(global.getText('mirai', 'nameExist'));
if (!module.languages || typeof module.languages != 'object' || Object.keys(module.languages).length == 0) logger.loader(global.getText('mirai', 'notFoundLanguage', module.config.name), 'warn');
if (module.config.dependencies && typeof module.config.dependencies == 'object') {
for (const reqDependencies in module.config.dependencies) {
const reqDependenciesPath = join(__dirname, 'nodemodules', 'node_modules', reqDependencies);
try {
if (!global.nodemodule.hasOwnProperty(reqDependencies)) {
if (listPackage.hasOwnProperty(reqDependencies) || listbuiltinModules.includes(reqDependencies)) global.nodemodule[reqDependencies] = require(reqDependencies);
else global.nodemodule[reqDependencies] = require(reqDependenciesPath);
} else '';
} catch {
var check = false;
var isError;
logger.loader(global.getText('mirai', 'notFoundPackage', reqDependencies, module.config.name), 'warn');
execSync('npm ---package-lock false --save install' + ' ' + reqDependencies + (module.config.dependencies[reqDependencies] == '*' || module.config.dependencies[reqDependencies] == '' ? '' : '@' + module.config.dependencies[reqDependencies]), { 'stdio': 'inherit', 'env': process['env'], 'shell': true, 'cwd': join(__dirname, 'nodemodules') });
for (let i = 1; i <= 3; i++) {
try {
require['cache'] = {};
if (listPackage.hasOwnProperty(reqDependencies) || listbuiltinModules.includes(reqDependencies)) global['nodemodule'][reqDependencies] = require(reqDependencies);
else global['nodemodule'][reqDependencies] = require(reqDependenciesPath);
check = true;
break;
} catch (error) { isError = error; }
if (check || !isError) break;
}
if (!check || isError) throw global.getText('mirai', 'cantInstallPackage', reqDependencies, module.config.name, isError);
}
}
logger.loader(global.getText('mirai', 'loadedPackage', module.config.name));
}
if (module.config.envConfig) try {
for (const envConfig in module.config.envConfig) {
if (typeof global.configModule[module.config.name] == 'undefined') global.configModule[module.config.name] = {};
if (typeof global.config[module.config.name] == 'undefined') global.config[module.config.name] = {};
if (typeof global.config[module.config.name][envConfig] !== 'undefined') global['configModule'][module.config.name][envConfig] = global.config[module.config.name][envConfig];
else global.configModule[module.config.name][envConfig] = module.config.envConfig[envConfig] || '';
if (typeof global.config[module.config.name][envConfig] == 'undefined') global.config[module.config.name][envConfig] = module.config.envConfig[envConfig] || '';
}
logger.loader(global.getText('mirai', 'loadedConfig', module.config.name));
} catch (error) {
throw new Error(global.getText('mirai', 'loadedConfig', module.config.name, JSON.stringify(error)));
}
if (module.onLoad) {
try {
const moduleData = {};
moduleData.api = loginApiData;
moduleData.models = botModel;
module.onLoad(moduleData);
} catch (_0x20fd5f) {
throw new Error(global.getText('mirai', 'cantOnload', module.config.name, JSON.stringify(_0x20fd5f)), 'error');
};
}
if (module.handleEvent) global.client.eventRegistered.push(module.config.name);
global.client.commands.set(module.config.name, module);
logger.loader(global.getText('mirai', 'successLoadModule', module.config.name));
} catch (error) {
logger.loader(global.getText('mirai', 'failLoadModule', module.config.name, error), 'error');
};
}
}(),
function() {
const events = readdirSync(global.client.mainPath + '/modules/events').filter(event => event.endsWith('.js') && !global.config.eventDisabled.includes(event));
for (const ev of events) {
try {
var event = require(global.client.mainPath + '/modules/events/' + ev);
if (!event.config || !event.run) throw new Error(global.getText('mirai', 'errorFormat'));
if (global.client.events.has(event.config.name) || '') throw new Error(global.getText('mirai', 'nameExist'));
if (event.config.dependencies && typeof event.config.dependencies == 'object') {
for (const dependency in event.config.dependencies) {
const _0x21abed = join(__dirname, 'nodemodules', 'node_modules', dependency);
try {
if (!global.nodemodule.hasOwnProperty(dependency)) {
if (listPackage.hasOwnProperty(dependency) || listbuiltinModules.includes(dependency)) global.nodemodule[dependency] = require(dependency);
else global.nodemodule[dependency] = require(_0x21abed);
} else '';
} catch {
let check = false;
let isError;
logger.loader(global.getText('mirai', 'notFoundPackage', dependency, event.config.name), 'warn');
execSync('npm --package-lock false --save install' + dependency + (event.config.dependencies[dependency] == '*' || event.config.dependencies[dependency] == '' ? '' : '@' + event.config.dependencies[dependency]), { 'stdio': 'inherit', 'env': process['env'], 'shell': true, 'cwd': join(__dirname, 'nodemodules') });
for (let i = 1; i <= 3; i++) {
try {
require['cache'] = {};
if (global.nodemodule.includes(dependency)) break;
if (listPackage.hasOwnProperty(dependency) || listbuiltinModules.includes(dependency)) global.nodemodule[dependency] = require(dependency);
else global.nodemodule[dependency] = require(_0x21abed);
check = true;
break;
} catch (error) { isError = error; }
if (check || !isError) break;
}
if (!check || isError) throw global.getText('mirai', 'cantInstallPackage', dependency, event.config.name);
}
}
logger.loader(global.getText('mirai', 'loadedPackage', event.config.name));
}
if (event.config.envConfig) try {
for (const _0x5beea0 in event.config.envConfig) {
if (typeof global.configModule[event.config.name] == 'undefined') global.configModule[event.config.name] = {};
if (typeof global.config[event.config.name] == 'undefined') global.config[event.config.name] = {};
if (typeof global.config[event.config.name][_0x5beea0] !== 'undefined') global.configModule[event.config.name][_0x5beea0] = global.config[event.config.name][_0x5beea0];
else global.configModule[event.config.name][_0x5beea0] = event.config.envConfig[_0x5beea0] || '';
if (typeof global.config[event.config.name][_0x5beea0] == 'undefined') global.config[event.config.name][_0x5beea0] = event.config.envConfig[_0x5beea0] || '';
}
logger.loader(global.getText('mirai', 'loadedConfig', event.config.name));
} catch (error) {
throw new Error(global.getText('mirai', 'loadedConfig', event.config.name, JSON.stringify(error)));
}
if (event.onLoad) try {
const eventData = {};
eventData.api = loginApiData, eventData.models = botModel;
event.onLoad(eventData);
} catch (error) {
throw new Error(global.getText('mirai', 'cantOnload', event.config.name, JSON.stringify(error)), 'error');
}
global.client.events.set(event.config.name, event);
logger.loader(global.getText('mirai', 'successLoadModule', event.config.name));
} catch (error) {
logger.loader(global.getText('mirai', 'failLoadModule', event.config.name, error), 'error');
}
}
}()
logger.loader(global.getText('mirai', 'finishLoadModule', global.client.commands.size, global.client.events.size))
logger.loader('=== ' + (Date.now() - global.client.timeStart) + 'ms ===')
writeFileSync(global.client['configPath'], JSON['stringify'](global.config, null, 4), 'utf8')
unlinkSync(global['client']['configPath'] + '.temp');
const listenerData = {};
listenerData.api = loginApiData;
listenerData.models = botModel;
const listener = require('./includes/listen')(listenerData);
function listenerCallback(error, message) {
if (error) return logger(global.getText('mirai', 'handleListenError', JSON.stringify(error)), 'error');
if (['presence', 'typ', 'read_receipt'].some(data => data == message.type)) return;
if (global.config.DeveloperMode == !![]) console.log(message);
return listener(message);
};
global.handleListen = loginApiData.listenMqtt(listenerCallback);
try {
await checkBan(loginApiData);
} catch (error) {
return //process.exit(0);
};
if (!global.checkBan) logger(global.getText('mirai', 'warningSourceCode'), '[ GLOBAL BAN ]');
global.client.api = loginApiData
// setInterval(async function () {
// // global.handleListen.stopListening(),
// global.checkBan = ![],
// setTimeout(function () {
// return global.handleListen = loginApiData.listenMqtt(listenerCallback);
// }, 500);
// try {
// await checkBan(loginApiData);
// } catch {
// return process.exit(0);
// };
// if (!global.checkBan) logger(global.getText('mirai', 'warningSourceCode'), '[ GLOBAL BAN ]');
// global.config.autoClean && (global.data.threadInfo.clear(), global.client.handleReply = global.client.handleReaction = {});
// if (global.config.DeveloperMode == !![])
// return logger(global.getText('mirai', 'refreshListen'), '[ DEV MODE ]');
// }, 600000);
});
}
//////////////////////////////////////////////
//========= Connecting to Database =========//
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////======BIGTEXT 7 MÀU======//////////
/////////////////////////////////////////////
const chalkAnimation = require('chalkercli'); chalkAnimation.rainbow('\n██████╗░░█████╗░██╗░░██╗\n██╔══██╗██╔══██╗██║░██╔╝\n██████╦╝██║░░██║█████═╝░\n██╔══██╗██║░░██║██╔═██╗░\n██████╦╝╚█████╔╝██║░╚██╗\n╚═════╝░░╚════╝░╚═╝░░╚═╝');
//////////////////////////////////////////////
//////////////////////////////////////////////
/////////////////////////////////////////////
(async() => {
try {
await sequelize.authenticate();
const authentication = {};
authentication.Sequelize = Sequelize;
authentication.sequelize = sequelize;
const models = require('./includes/database/model')(authentication);
logger(global.getText('mirai', 'successConnectDatabase'), '[ DATABASE ]');
const botData = {};
botData.models = models
onBot(botData);
} catch (error) { logger(global.getText('mirai', 'successConnectDatabase', JSON.stringify(error)), '[ DATABASE ]'); }
})();
process.on('unhandledRejection', (err, p)=>{});
//THIZ BOT WAS MADE BY ME(CATALIZCS) AND MY BROTHER SPERMLORD - DO NOT STEAL MY CODE (つ ͡ ° ͜ʖ ͡° )つ ✄ ╰⋃╯