Switched to ES6, Added public IP module, Code optimization.

This commit is contained in:
2023-06-26 13:49:38 +02:00
parent 7ddf460928
commit 7dd0cf5e1f
3 changed files with 68 additions and 80 deletions

View File

@@ -5,7 +5,11 @@
"es6": true "es6": true
}, },
"parserOptions": { "parserOptions": {
"ecmaVersion": 2021 "ecmaVersion": 2021,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
}, },
"rules": { "rules": {
"arrow-spacing": ["warn", { "before": true, "after": true }], "arrow-spacing": ["warn", { "before": true, "after": true }],

137
index.js
View File

@@ -1,6 +1,7 @@
const { execSync, spawn } = require('child_process'); import { execSync, spawn } from 'child_process';
const fs = require('node:fs'); import { publicIpv4 } from 'public-ip';
const os = require('os'); import fs from 'fs';
import os from 'os';
const host = os.hostname(); const host = os.hostname();
const args = process.argv.slice(2); const args = process.argv.slice(2);
@@ -12,26 +13,18 @@ const managerWebhook = process.env.MANAGER_WEBHOOK;
const managerWebhookName = process.env.MANAGER_WEBHOOK_NAME || 'Microsoft Rewards Bot Manager'; const managerWebhookName = process.env.MANAGER_WEBHOOK_NAME || 'Microsoft Rewards Bot Manager';
async function logManager(message, type) { async function logManager(message, type) {
if (type === 'info') { if (type === 'info') console.log(`\x1b[34m${message}\x1b[0m`);
console.log(`\x1b[34m${message}\x1b[0m`); else if (type === 'error') console.log(`\x1b[31m${message}\x1b[0m`);
} else console.log(`\x1b[37m${message}\x1b[0m`);
else if (type === 'error') {
console.log(`\x1b[31m${message}\x1b[0m`);
}
else {
console.log(`\x1b[37m${message}\x1b[0m`);
}
if (managerWebhook) { if (managerWebhook) {
const webhook = managerWebhook;
const botUsername = `${managerWebhookName}`;
const payload = { const payload = {
content: message, content: message,
username: botUsername, username: managerWebhookName,
}; };
try { try {
await fetch(webhook, { await fetch(managerWebhook, {
method: 'POST', method: 'POST',
headers: { headers: {
'Accept': 'application/json', 'Accept': 'application/json',
@@ -41,7 +34,7 @@ async function logManager(message, type) {
}); });
} }
catch (error) { catch (error) {
console.log('Error sending webhook message:', error.message); console.error(`[${host}] Error sending webhook message: ${error.message}`);
} }
} }
} }
@@ -50,15 +43,13 @@ async function logBotConsole(message) {
console.log(message); console.log(message);
if (botConsoleWebhook) { if (botConsoleWebhook) {
const webhook = botConsoleWebhook;
const botUsername = `${botConsoleWebhookName}`;
const payload = { const payload = {
content: message, content: message,
username: botUsername, username: botConsoleWebhookName,
}; };
try { try {
await fetch(webhook, { await fetch(botConsoleWebhook, {
method: 'POST', method: 'POST',
headers: { headers: {
'Accept': 'application/json', 'Accept': 'application/json',
@@ -68,7 +59,7 @@ async function logBotConsole(message) {
}); });
} }
catch (error) { catch (error) {
console.log('Error sending webhook message:', error.message); console.error(`[${host}] Error sending webhook message: ${error.message}`);
} }
} }
} }
@@ -79,16 +70,16 @@ async function checkUpdate() {
const currentHead = execSync('git rev-parse HEAD').toString().trim(); const currentHead = execSync('git rev-parse HEAD').toString().trim();
const remoteHead = execSync('git rev-parse "@{u}"').toString().trim(); const remoteHead = execSync('git rev-parse "@{u}"').toString().trim();
if (currentHead !== remoteHead) { if (currentHead !== remoteHead) {
logManager('Updates available! Please run the updater script.', 'info'); logManager(`[${host}] Updates available! Please run the updater script.`, 'info');
} }
} }
catch (error) { catch (error) {
logManager('Failed to check for updates.', 'error'); logManager('[${host}] Failed to check for updates.', 'error');
} }
} }
async function vpnConnect(vpnName) { async function vpnConnect(vpnName) {
if (!vpnName) return logManager('Please provide the VPN name as an argument.', 'error'); if (!vpnName) return logManager(`[${host}] Please provide the VPN name as an argument.`, 'error');
logManager(`[${host}] Disconnecting from VPNs`, 'info'); logManager(`[${host}] Disconnecting from VPNs`, 'info');
await vpnDisconnect(); await vpnDisconnect();
@@ -104,16 +95,16 @@ async function vpnConnect(vpnName) {
} }
else { else {
try { try {
const response = await fetch('https://api.ipify.org/?format=json', { // const response = await fetch('https://api.ipify.org/?format=json', {
method: 'GET', // method: 'GET',
headers: { // headers: {
'Accept': 'application/json', // 'Accept': 'application/json',
'Content-Type': 'application/json', // 'Content-Type': 'application/json',
}, // },
}); // });
const res = await response.json(); // const res = await response.json();
const ip = res.ip; // const ip = res.ip;
await logManager(`[${host}] VPN connection successfully established to ${vpnName} (IP: ${ip}).`, 'info'); await logManager(`[${host}] VPN connection successfully established to ${vpnName} (IP: ${await publicIpv4()}).`, 'info');
} }
catch (err) { catch (err) {
const ip = 'Unknown'; const ip = 'Unknown';
@@ -278,13 +269,41 @@ function isRootUser() {
return process.getuid && process.getuid() === 0; return process.getuid && process.getuid() === 0;
} }
async function main() { async function runAll() {
await checkUpdate(); await checkUpdate();
const vpns = execSync('nmcli connection show | awk \'/vpn/ {print $1}\'').toString().trim().split('\n'); const vpns = execSync('nmcli connection show | awk \'/vpn/ {print $1}\'').toString().trim().split('\n');
for (const vpn of vpns) {
const currentDate = new Date();
const formattedDate = `${currentDate.getDate()}-${currentDate.getMonth() + 1}-${currentDate.getFullYear()}`;
const logEntries = JSON.parse(fs.readFileSync('batch_logs.json', 'utf8'));
const entry = logEntries.find(entries => entries.accountName === vpn);
if (entry && entry.accountName === formattedDate) {
logManager(`[${host}] ${vpn} already runned today!`, 'info');
continue;
}
console.log(entry && entry.accountName === formattedDate);
logManager(`[${host}] Switching to VPN: [${vpn}]`, 'info');
const con = await vpnConnect(vpn);
if (con) continue;
await startBot(vpn);
}
return 0;
}
async function runBatch(vpn) {
logManager(`[${host}] Connecting to VPN: [${vpn}]`, 'info');
const con = await vpnConnect(vpn);
if (con) return 1;
await startBot(vpn);
return 0;
}
(async () => {
await checkUpdate();
if (fs.existsSync('.env')) { if (fs.existsSync('.env')) {
require('dotenv').config({ path: '.env' }); require('dotenv').config({ path: '.env' });
logManager(`[${host}] Config file: .env`, 'info'); logManager(`[${host}] Config file: .env.`, 'info');
} }
else { else {
logManager(`[${host}] Config file: not found.`, 'error'); logManager(`[${host}] Config file: not found.`, 'error');
@@ -304,61 +323,25 @@ async function main() {
} }
logManager(`[${host}] Log file: batch_logs.json`, 'info'); logManager(`[${host}] Log file: batch_logs.json`, 'info');
for (const vpn of vpns) {
const currentDate = new Date();
const formattedDate = `${currentDate.getDate()}-${currentDate.getMonth() + 1}-${currentDate.getFullYear()}`;
const logEntries = JSON.parse(fs.readFileSync('batch_logs.json', 'utf8'));
const entry = logEntries.find(entries => entries.accountName === vpn);
if (entry && entry.accountName === formattedDate) continue;
logManager(`[${host}] Switching to VPN: [${vpn}]`, 'info');
const con = await vpnConnect(vpn);
if (con) continue;
await startBot(vpn);
}
return 0;
}
async function uniqueRun(vpn) {
await checkUpdate();
if (fs.existsSync('.env')) {
require('dotenv').config({ path: '.env' });
logManager(`[${host}] Config file: .env.`, 'info');
}
else {
logManager(`[${host}] Config file: not found.`, 'error');
process.exit(1);
}
logManager(`[${host}] Bot Console Webhook: ${botConsoleWebhook ? 'True' : 'False'}\n[${host}] Bot Report Webhook: ${reportWebhook ? 'True' : 'False'}\n[${host}] Bot Manager Webhook: ${managerWebhook ? 'True' : 'False'}`);
logManager(`[${host}] Starting mcr-bot on host: ${host}`, 'info');
logManager(`[${host}] Connecting to VPN: [${vpn}]`, 'info');
const con = await vpnConnect(vpn);
if (con) return 1;
await startBot(vpn);
return 0;
}
(async () => {
for (let i = 0; i < args.length; i++) { for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) { if (args[i].startsWith('--')) {
if (args[i] === '--accounts' && i + 1 < args.length) { if (args[i] === '--accounts' && i + 1 < args.length) {
const accounts = args[i + 1]; const accounts = args[i + 1];
await uniqueRun(accounts); return await runBatch(accounts);
break;
} }
else if (args[i] === '--all') { else if (args[i] === '--all') {
const n = true; const n = true;
while (n) { while (n) {
try { try {
await main(); await runAll();
await sleep(1000); await sleep(1000);
} }
catch (error) { catch (error) {
logManager('An error occurred:\n' + error.message, 'error'); logManager(`[${host}] An error occurred: ${error.message}`, 'error');
} }
} }
} }
} }
} }
logManager(`[${host}] Missing arguments`);
})(); })();

View File

@@ -5,8 +5,9 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js" "start": "node index.js --all"
}, },
"type": "module",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.justw.tf/Lightemerald/mcr-bot.git" "url": "https://git.justw.tf/Lightemerald/mcr-bot.git"
@@ -20,4 +21,4 @@
"pino": "^8.14.1", "pino": "^8.14.1",
"public-ip": "^6.0.1" "public-ip": "^6.0.1"
} }
} }