Files
mcr-bot/index.js
2023-06-26 13:16:00 +02:00

364 lines
11 KiB
JavaScript

const { execSync, spawn } = require('child_process');
const fs = require('node:fs');
const os = require('os');
const host = os.hostname();
const args = process.argv.slice(2);
const reportWebhook = process.env.REPORT_WEBHOOK;
const botConsoleWebhook = process.env.BOT_CONSOLE_WEBHOOK;
const botConsoleWebhookName = process.env.BOT_CONSOLE_WEBHOOK_NAME || 'Microsoft Rewards Bot';
const managerWebhook = process.env.MANAGER_WEBHOOK;
const managerWebhookName = process.env.MANAGER_WEBHOOK_NAME || 'Microsoft Rewards Bot Manager';
async function logManager(message, type) {
if (type === 'info') {
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`);
}
if (managerWebhook) {
const webhook = managerWebhook;
const botUsername = `${managerWebhookName}`;
const payload = {
content: message,
username: botUsername,
};
try {
await fetch(webhook, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
}
catch (error) {
console.log('Error sending webhook message:', error.message);
}
}
}
async function logBotConsole(message) {
console.log(message);
if (botConsoleWebhook) {
const webhook = botConsoleWebhook;
const botUsername = `${botConsoleWebhookName}`;
const payload = {
content: message,
username: botUsername,
};
try {
await fetch(webhook, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
}
catch (error) {
console.log('Error sending webhook message:', error.message);
}
}
}
async function checkUpdate() {
try {
execSync('git fetch');
const currentHead = execSync('git rev-parse HEAD').toString().trim();
const remoteHead = execSync('git rev-parse "@{u}"').toString().trim();
if (currentHead !== remoteHead) {
logManager('Updates available! Please run the updater script.', 'info');
}
}
catch (error) {
logManager('Failed to check for updates.', 'error');
}
}
async function vpnConnect(vpnName) {
if (!vpnName) return logManager('Please provide the VPN name as an argument.', 'error');
logManager(`[${host}] Disconnecting from VPNs`, 'info');
await vpnDisconnect();
const maxAttempts = process.env.RETRIES;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
await execSync(`nmcli connection up "${vpnName}"`);
const status = await execSync('nmcli connection show --active').toString().includes(vpnName);
if (!status) {
logManager(`[${host}] Failed to connect to VPN: ${vpnName}. Retrying (attempt ${attempt} of ${maxAttempts})...`, 'error');
await sleep(1000);
}
else {
try {
const response = await fetch('https://api.ipify.org/?format=json', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
const res = await response.json();
const ip = res.ip;
await logManager(`[${host}] VPN connection successfully established to ${vpnName} (IP: ${ip}).`, 'info');
}
catch (err) {
const ip = 'Unknown';
await logManager(`[${host}] VPN connection successfully established to ${vpnName} (IP: ${ip}).`, 'info');
}
return 0;
}
}
logManager(`[${host}] Maximum number of connection attempts reached. Failed to connect to VPN: ${vpnName}`, 'error');
await vpnDisconnect();
return 1;
}
function vpnDisconnect() {
const vpnConnection = execSync('nmcli connection show --active | awk \'/vpn/ {print $1}\'').toString().trim();
if (!vpnConnection) {
logManager(`[${host}] Successfully disconnected from all VPNs.`, 'info');
return 0;
}
try {
execSync(`nmcli connection down "${vpnConnection}"`);
const status = execSync('nmcli connection show --active | awk \'/vpn/ {print $1}\'').toString().trim();
if (!status) {
logManager(`[${host}] Successfully disconnected from all VPNs.`, 'info');
return 0;
}
else {
logManager(`[${host}] Failed to disconnect from all VPNs.`, 'error');
return 1;
}
}
catch (error) {
logManager(`[${host}] Failed to disconnect from all VPNs.`, 'error');
return 1;
}
}
async function startBot(accountName) {
const accountPath = `./accounts/${accountName}.json`;
if (fs.existsSync(accountPath)) {
let commandSuffix = '';
if (reportWebhook === '1') {
commandSuffix += ` --discord ${reportWebhook}`;
}
if (process.env.BOT_BROWSER) {
commandSuffix += ' --browser ' + process.env.BOT_BROWSER;
}
let commandPrefix = `python -u ./Microsoft-Rewards-bot/ms_rewards_farmer.py --accounts-file ../accounts/${accountName}.json --dont-check-for-updates --shuffle --session --superfast --on-finish exit --no-webdriver-manager --skip-unusual`;
logManager(`[${host}] Script started for ${accountName}`);
if (isRootUser()) {
console.log('The user is root.');
const containerEnv = fs.readFileSync('/proc/1/environ', 'utf8');
const isLXCContainer = containerEnv.includes('container=lxc') || containerEnv.includes('container=lxc-libvirt');
if (isLXCContainer) {
commandPrefix += ' --virtual-display';
}
}
return new Promise((resolve, reject) => {
// const childProcess = spawn('bash', ['-c', `${commandPrefix} ${commandSuffix}`], { stdio: 'inherit' });
const childProcess = spawn('bash', ['-c', `${commandPrefix} ${commandSuffix}`], {
stdio: ['pipe', 'pipe', 'pipe'],
});
childProcess.stdout.on('data', (data) => {
const output = data.toString().trim();
logBotConsole(`[${host}][${accountName}] STDOUT: ${output}`);
if (output.includes('Press enter') || output.includes('Press any key')) {
setTimeout(() => {
childProcess.stdin.write('\n');
}, 1000);
}
});
childProcess.stderr.on('data', (data) => {
const output = data.toString().trim();
logBotConsole(`[${host}][${accountName}] STDERR: ${output}`);
if (output.includes('Press enter') || output.includes('Press any key')) {
setTimeout(() => {
childProcess.stdin.write('\n');
}, 1000);
}
});
childProcess.on('exit', (code) => {
if (code !== 0) {
logManager(`[${host}] Bot process for ${accountName} exited with code ${code}. Restarting...`, 'error');
startBot(accountName).then(resolve).catch(reject);
}
else {
const currentDate = new Date();
const formattedDate = `${currentDate.getDate()}-${currentDate.getMonth() + 1}-${currentDate.getFullYear()}`;
const logEntry = { accountName: accountName, date: formattedDate };
fs.readFile('batch_logs.json', 'utf8', (err, data) => {
if (err) {
logManager(`Failed to read batch_logs.json: ${err}`, 'error');
resolve();
return;
}
let logEntries = [];
try {
logEntries = JSON.parse(data);
}
catch (parseError) {
logManager(`Failed to parse batch_logs.json: ${parseError}`, 'error');
}
const existingEntryIndex = logEntries.findIndex(entry => entry.accountName === accountName);
if (existingEntryIndex !== -1) {
logEntries[existingEntryIndex] = logEntry;
}
else {
logEntries.push(logEntry);
}
fs.writeFile('batch_logs.json', JSON.stringify(logEntries, null, 2), err => {
if (err) {
logManager(`Failed to write to batch_logs.json: ${err}`, 'error');
}
resolve();
});
});
}
});
childProcess.on('close', (code) => {
console.log(`[${accountName}] Child process exited with code ${code}`);
});
childProcess.on('error', (err) => {
logManager(`[${host}] Failed to start bot for ${accountName}.`, 'error');
reject(err);
});
setTimeout(() => {
logManager(`[${host}] Bot process for ${accountName} exceeded the timeout. Killing the process...`, 'error');
childProcess.kill();
}, 150 * 60 * 1000);
});
}
else {
logManager(`[${host}] File ${accountPath} does not exist, skipping starting bot for this VPN!`, 'error');
return Promise.resolve({ error: `File ${accountPath} does not exist.` });
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function isRootUser() {
return process.getuid && process.getuid() === 0;
}
async function main() {
await checkUpdate();
const vpns = execSync('nmcli connection show | awk \'/vpn/ {print $1}\'').toString().trim().split('\n');
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');
if (!fs.existsSync('batch_logs.json')) {
fs.writeFile('batch_logs.json', JSON.stringify([], null, 2), err => {
if (err) {
logManager(`Failed to create batch_logs.json: ${err}`, 'error');
process.exit(1);
}
});
}
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++) {
if (args[i].startsWith('--')) {
if (args[i] === '--accounts' && i + 1 < args.length) {
const accounts = args[i + 1];
await uniqueRun(accounts);
break;
}
else if (args[i] === '--all') {
const n = true;
while (n) {
try {
await main();
await sleep(1000);
}
catch (error) {
logManager('An error occurred:\n' + error.message, 'error');
}
}
}
}
}
})();