forked from YANDEVA/BotPack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
233 lines (193 loc) · 6.92 KB
/
index.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
const { spawn, exec } = require("child_process");
const express = require("express");
const app = express();
const logger = require("./utils/log.js");
const path = require('path');
const net = require('net');
const chalk = require('chalk');
const pkg = require('./package.json');
const check = require('get-latest-version');
const fs = require('fs')
const semver = require('semver');
const readline = require('readline');
let configJson;
let packageJson;
const sign = '(›^-^)›';
const fbstate = 'appstate.json';
try {
configJson = require('./config.json');
} catch (error) {
console.error('Error loading config.json:', error);
process.exit(1); // Exit the script with an error code
}
const delayedLog = async (message) => {
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (const char of message) {
process.stdout.write(char);
await delay(50);
}
console.log();
};
const showMessage = async () => {
const message = chalk.yellow(' ') + `The "removeSt" property is set true in the config.json. Therefore, the Appstate was cleared effortlessly! You can now place a new one in the same directory.`;
await delayedLog(message);
};
if (configJson.removeSt) {
fs.writeFileSync(fbstate, sign, { encoding: 'utf8', flag: 'w' });
showMessage();
configJson.removeSt = false;
fs.writeFileSync('./config.json', JSON.stringify(configJson, null, 2), 'utf8');
setTimeout(() => {
process.exit(0);
}, 10000);
return;
}
const getRandomPort = () => Math.floor(Math.random() * (65535 - 1024) + 1024);
const PORT = getRandomPort();
let currentPort = PORT;
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/includes/login/cover/index.html'));
});
app.get('/', (req, res) => res.sendStatus(200));
console.clear();
console.log(chalk.bold.dim(` ${process.env.REPL_SLUG}`.toUpperCase() + `(v${pkg.version})`));
logger(`Getting Started!`, "STARTER");
startBot(0);
async function isPortAvailable(port) {
return new Promise((resolve) => {
const tester = net.createServer()
.once('error', () => resolve(false))
.once('listening', () => {
tester.once('close', () => resolve(true)).close();
})
.listen(port, '127.0.0.1');
});
}
function startServer(port) {
app.listen(port, () => {
logger.loader(`Bot is running on port: ${port}`);
});
app.on('error', (error) => {
logger(`An error occurred while starting the server: ${error}`, "SYSTEM");
});
}
// # Please note that sometimes this function is the reason the bot will auto-restart, even if your custom.js auto-restart is set to false. This is because the port switches automatically if it is unable to connect to the current port. ↓↓↓↓↓↓
async function startBot(index) {
try {
const isAvailable = await isPortAvailable(currentPort);
if (!isAvailable) {
logger(`Retrying...`, "SYSTEM");
const newPort = getRandomPort();
logger.loader(`Current port ${currentPort} is not available. Switching to new port ${newPort}.`);
currentPort = newPort;
}
startServer(currentPort);
const child = spawn("node", ["--trace-warnings", "--async-stack-traces", "main.js"], {
cwd: __dirname,
stdio: "inherit",
shell: true,
env: {
...process.env,
CHILD_INDEX: index,
},
});
child.on("close", (codeExit) => {
if (codeExit !== 0) {
startBot(index);
}
});
child.on("error", (error) => {
logger(`An error occurred while starting the child process: ${error}`, "SYSTEM");
});
} catch (err) {
logger(`Error while starting the bot: ${err}`, "SYSTEM");
}
}
const excluded = configJson.UPDATE.EXCLUDED || [];
try {
packageJson = require('./package.json');
} catch (error) {
console.error('Error loading package.json:', error);
return;
}
function nv(version) {
return version.replace(/^\^/, '');
}
async function updatePackage(dependency, currentVersion, latestVersion) {
if (!excluded.includes(dependency)) {
const ncv = nv(currentVersion);
if (semver.neq(ncv, latestVersion)) {
console.log(chalk.bgYellow.bold(` UPDATE `), `There is a newer version ${chalk.yellow(`(^${latestVersion})`)} available for ${chalk.yellow(dependency)}. Updating to the latest version...`);
packageJson.dependencies[dependency] = `^${latestVersion}`;
fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, 2));
console.log(chalk.green.bold(`UPDATED`), `${chalk.yellow(dependency)} updated to ${chalk.yellow(`^${latestVersion}`)}`);
exec(`npm install ${dependency}@latest`, (error, stdout, stderr) => {
if (error) {
console.error('Error executing npm install command:', error);
return;
}
console.log('npm install output:', stdout);
});
}
}
}
async function checkAndUpdate() {
if (configJson.UPDATE && configJson.UPDATE.Package) {
try {
for (const [dependency, currentVersion] of Object.entries(packageJson.dependencies)) {
const latestVersion = await check(dependency);
await updatePackage(dependency, currentVersion, latestVersion);
}
} catch (error) {
console.error('Error checking and updating dependencies:', error);
}
} else {
console.log(chalk.yellow(''), 'Update for packages is not enabled in config.json');
}
}
// Do not remove anything if you don't know what you're doing! -Yan
setTimeout(() => {
checkAndUpdate();
}, 20000);
const jsonFilePath = 'includes/database/data/threadsData.json';
const userFile = 'includes/database/data/usersData.json';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function clean() {
try {
const sign = '{}';
fs.writeFileSync(jsonFilePath, sign, { encoding: 'utf8', flag: 'w' });
fs.writeFileSync(userFile, sign, { encoding: 'utf8', flag: 'w' });
console.log(chalk.yellow(''), `Thread and User data cleared successfully.`);
} catch (error) {
console.error(`Error clearing contents: ${error.message}`);
}
}
function cleanState() {
try {
fs.writeFileSync(fbstate, sign, { encoding: 'utf8', flag: 'w' });
console.log(chalk.yellow(''),`Appstate cleared successfully! Try adding a new one as a replacement for the previous appstate.`);
} catch (error) {
console.error(`Error clearing contents: ${error.message}`);
}
}
function command() {
rl.question('', (answer) => {
if (answer.trim().toLowerCase() === '-clr' || answer.trim().toLowerCase() === '-clean') {
clean();
} else if (answer.trim().toLowerCase() === '-cap' || answer.trim().toLowerCase() === '-fbstate') {
cleanState();
} else {
console.log(chalk.yellow(''), chalk.whiteBright(`Invalid command!`));
command();
}
rl.close();
});
}
setTimeout(() => {
command();
}, 20000);
// __@YanMaglinte was Here__ //
// -----------------------------//