Switched bot to use nodejs.

This commit is contained in:
2023-06-25 12:16:20 +02:00
parent 14a59e5c66
commit 949cb4be86
12 changed files with 2147 additions and 141 deletions

6
.env.sample Normal file
View File

@@ -0,0 +1,6 @@
RETRIES=3
WEBHOOK=''
BOT_BROWSER='uc'
PRINT_CONSOLE_LOGS=0
MCR_BOT_WEBHOOK=''
MCR_BOT_WEBHOOK_NAME='Microsoft Rewards Bot Manager'

49
.eslintrc.json Normal file
View File

@@ -0,0 +1,49 @@
{
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2021
},
"rules": {
"arrow-spacing": ["warn", { "before": true, "after": true }],
"brace-style": ["error", "stroustrup", { "allowSingleLine": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
"indent": ["error", "tab"],
"keyword-spacing": "error",
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"no-console": "off",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }],
"no-trailing-spaces": ["error"],
"no-var": "error",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-blocks": "error",
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"yoda": "error"
}
}

3
.gitignore vendored
View File

@@ -1,4 +1,5 @@
vpn/ vpn/
accounts/ accounts/
Microsoft-Rewards-bot/ Microsoft-Rewards-bot/
config.txt node_modules/
.env

View File

@@ -42,7 +42,13 @@ bash setup-vpn.sh
Copy your accounts file named as [vpnname].json in the Bot folder then run Copy your accounts file named as [vpnname].json in the Bot folder then run
```bash ```bash
bash start.sh npm start --all
```
For single run of a specific VPN/Account file
```bash
npm start --accounts [name]
``` ```
### If using LXC ### If using LXC

View File

@@ -1,5 +0,0 @@
retries=3
webhook=''
print_log_to_webhook=0
mcr_bot_webhook=''
mcr_bot_webhook_name='Microsoft Rewards Bot Manager'

223
index.js Normal file
View File

@@ -0,0 +1,223 @@
const { execSync } = require('child_process');
const { get, post } = require('./modules/fetchHandler');
const fs = require('node:fs');
const os = require('os');
const host = os.hostname();
const args = process.argv.slice(2);
async function consoleLog(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 (process.env.MCR_BOT_WEBHOOK) {
const webhook = process.env.MCR_BOT_WEBHOOK;
const botUsername = `m${process.env.MCR_BOT_WEBHOOK_NAME}`;
await post(webhook, { content: message, username: botUsername });
}
}
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) {
consoleLog('Updates available! Please run the updater script.', 'info');
}
}
catch (error) {
consoleLog('Failed to check for updates.', 'error');
}
}
async function vpnConnect(vpnName) {
if (!vpnName) return consoleLog('Please provide the VPN name as an argument.', 'error');
consoleLog(`[${host}] Disconnecting from VPNs`, 'info');
await vpnDisconnect();
const maxAttempts = process.env.RETRIES;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
execSync(`nmcli connection up "${vpnName}"`);
const status = execSync('nmcli connection show --active')
.toString()
.includes(vpnName);
if (status) {
const ip = await get('https://api.ipify.org');
consoleLog(`[${host}] VPN connection successfully established to ${vpnName} (IP: ${ip.data}).`, 'info');
return 0;
}
else {
consoleLog(`[${host}] Failed to connect to VPN: ${vpnName}. Retrying (attempt ${attempt} of ${maxAttempts})...`, 'error');
await sleep(1000);
}
}
catch (error) {
consoleLog(`[${host}] Failed to connect to VPN: ${vpnName}. Retrying (attempt ${attempt} of ${maxAttempts})...`, 'error');
await sleep(1000);
}
}
consoleLog(`[${host}] Maximum number of connection attempts reached. Failed to connect to VPN: ${vpnName}`, 'error');
return 1;
}
function vpnDisconnect() {
const vpnConnection = execSync('nmcli connection show --active | awk \'/vpn/ {print $1}\'').toString().trim();
if (!vpnConnection) {
consoleLog(`[${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) {
consoleLog(`[${host}] Successfully disconnected from all VPNs.`, 'info');
return 0;
}
else {
consoleLog(`[${host}] Failed to disconnect from all VPNs.`, 'error');
return 1;
}
}
catch (error) {
consoleLog(`[${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 = `--discord ${process.env.WEBHOOK}`;
if (process.env.PRINT_CONSOLE_LOGS === '1') {
commandSuffix += ' --print-to-webhook';
}
if (process.env.BOT_BROWSER === '1') {
commandSuffix += ' --browser ' + process.env.BOT_BROWSER;
}
const containerEnv = fs.readFileSync('/proc/1/environ', 'utf8');
const isLXCContainer = containerEnv.includes('container=lxc') || containerEnv.includes('container=lxc-libvirt');
let commandPrefix = `python ./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`;
if (isLXCContainer) {
commandPrefix += ' --virtual-display';
}
consoleLog(`[${host}] Script started for ${accountName}`);
try {
execSync(`timeout 150m bash -c "${commandPrefix} ${commandSuffix}; exit"`, { stdio: 'inherit', shell: '/bin/bash' });
}
catch (error) {
consoleLog(`[${host}] Failed to start bot for ${accountName}.`, 'error');
}
}
else {
consoleLog(`[${host}] File ${accountPath} does not exist, skipping starting bot for this VPN!`, 'error');
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
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' });
}
else {
consoleLog(`[${host}] Config file not found.`, 'error');
process.exit(1);
}
if (!process.env.WEBHOOK) {
consoleLog(`[${host}] Webhook not set! Updates won't be sent to it.`);
}
else {
if (!process.env.MCR_BOT_WEBHOOK) {
process.env.MCR_BOT_WEBHOOK = process.env.WEBHOOK;
}
consoleLog(`[${host}] Webhook set!`);
consoleLog(`[${host}] Starting mcr-bot on host: ${host}`, 'info');
}
for (const vpn of vpns) {
consoleLog(`[${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' });
}
else {
consoleLog(`[${host}] Config file not found.`, 'error');
process.exit(1);
}
if (!process.env.WEBHOOK) {
consoleLog(`[${host}] Webhook not set! Updates won't be sent to it.`);
}
else {
if (!process.env.MCR_BOT_WEBHOOK) {
process.env.MCR_BOT_WEBHOOK = process.env.WEBHOOK;
}
consoleLog(`[${host}] Webhook set!`);
consoleLog(`[${host}] Starting mcr-bot on host: ${host}`, 'info');
}
consoleLog(`[${host}] Switching 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) {
consoleLog('An error occurred:\n' + error.message, 'error');
}
}
}
}
}
})();

71
modules/fetchHandler.js Normal file
View File

@@ -0,0 +1,71 @@
const fetch = (...args) => import('node-fetch').then(({ default: fth }) => fth(...args));
const { error } = require('./logHandler');
async function get(url, token = 'none') {
const options = {
method: 'GET',
headers: { 'Content-Type': 'application/json', authorization: `${token}` },
};
return await fetch(url, options)
.then(res => res.json())
.then(json => {
return json;
})
.catch(err => error(err));
}
async function post(url, body, token = 'none') {
const options = {
method: 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/json', authorization: `${token}` },
body: JSON.stringify(body),
};
return await fetch(url, options)
.then(res => res.json())
.then(json => {
return json;
})
.catch(err => error(err));
}
async function patch(url, body, token = 'none') {
const options = {
method: 'PATCH',
mode: 'cors',
headers: { 'Content-Type': 'application/json', authorization: `${token}` },
body: JSON.stringify(body),
};
return await fetch(url, options)
.then(res => res.json())
.then(json => {
return json;
})
.catch(err => error(err));
}
async function put(url, body, token = 'none') {
const options = {
method: 'PUT',
mode: 'cors',
headers: { 'Content-Type': 'application/json', authorization: `${token}` },
body: JSON.stringify(body),
};
return await fetch(url, options)
.then(res => res.json())
.then(json => {
return json;
})
.catch(err => error(err));
}
module.exports = {
get,
post,
patch,
put,
};

26
modules/logHandler.js Normal file
View File

@@ -0,0 +1,26 @@
const pino = require('pino');
const logger = pino();
function log(x) {
logger.info(x);
}
function debug(x) {
logger.debug(x);
}
function warn(x) {
logger.warn(x);
}
function error(x) {
logger.error(x);
}
module.exports = {
log,
debug,
warn,
error,
};

1738
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "mcr-bot",
"version": "1.0.0",
"description": "This repo contains the script to manage multiple mcr bot on a single VM/Container.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"repository": {
"type": "git",
"url": "https://git.justw.tf/Lightemerald/mcr-bot.git"
},
"author": "Lightemerald",
"dependencies": {
"child_process": "^1.0.2",
"dotenv": "^16.3.1",
"eslint": "^8.43.0"
}
}

View File

@@ -30,11 +30,11 @@ update_package_manager() {
install_requirements() { install_requirements() {
if command -v apt-get &>/dev/null; then if command -v apt-get &>/dev/null; then
sudo apt install chromium chromium-driver network-manager network-manager-openvpn openvpn python3 python3-pip python3-tk xvfb git wget curl unzip nano -y sudo apt install chromium chromium-driver network-manager network-manager-openvpn openvpn python3 python3-pip python3-tk xvfb git wget curl unzip nano nodejs -y
elif command -v dnf &>/dev/null; then elif command -v dnf &>/dev/null; then
sudo dnf install chromium chrom*driver NetworkManager NetworkManager-openvpn openvpn python python*-pip python*-tkinter xorg-x11-server-Xvfb git wget unzip nano -y sudo dnf install chromium chrom*driver NetworkManager NetworkManager-openvpn openvpn python python*-pip python*-tkinter xorg-x11-server-Xvfb git wget unzip nano nodejs -y
elif command -v pacman &>/dev/null; then elif command -v pacman &>/dev/null; then
sudo pacman -Sy chromium networkmanager networkmanager-openvpn openvpn python python-pip xorg-server-xvfb git curl wget unzip nano base-devel --noconfirm sudo pacman -Sy chromium networkmanager networkmanager-openvpn openvpn python python-pip xorg-server-xvfb git curl wget unzip nano base-devel nodejs --noconfirm
fi fi
} }
@@ -44,7 +44,7 @@ install_requirements
git clone https://git.justw.tf/Lightemerald/mcr-bot && cd mcr-bot git clone https://git.justw.tf/Lightemerald/mcr-bot && cd mcr-bot
git clone https://git.justw.tf/Lightemerald/Microsoft-Rewards-bot && cd Microsoft-Rewards-bot && pip install -r requirements.txt git clone https://git.justw.tf/Lightemerald/Microsoft-Rewards-bot && cd Microsoft-Rewards-bot && pip install -r requirements.txt
cd .. && mkdir vpn && mkdir accounts cd .. && mkdir vpn && mkdir accounts
cp ./config.txt.sample config.txt cp ./.env.sample .env
chmod +x ./*.sh chmod +x ./*.sh
clear clear
echo -e "Edit config.txt\nAdd your VPN files (.ovpn) in ./vpn\nThen run setup-vpn.sh\nAdd your accounts files (.json) with the same name as the VPN in ./accounts\nFinally, run start.sh" echo -e "Edit config.txt\nAdd your VPN files (.ovpn) in ./vpn\nThen run setup-vpn.sh\nAdd your accounts files (.json) with the same name as the VPN in ./accounts\nFinally, run 'npm start''"

129
start.sh
View File

@@ -1,129 +0,0 @@
#!/bin/bash
function console_log() {
local message="$1"
local type="$2"
if [ "$type" == "info" ]; then
echo -e "\033[34m$message\033[0m"
elif [ "$type" == "error" ]; then
echo -e "\033[31m$message\033[0m"
else
echo -e "\033[37m$message\033[0m"
fi
if [ -n "$mcr_bot_webhook" ]; then
curl --silent -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data "{\"content\": \"$message\", \"username\": \"m$mcr_bot_webhook_name\"}" "$mcr_bot_webhook"
fi
}
function check_update() {
git fetch
if [ "$(git rev-parse HEAD)" != "$(git rev-parse "@{u}")" ]; then
console_log "Updates available! Please run the updater script." "info"
fi
}
function vpn_connect() {
local vpn_name=$1
local max_attempts=$retries
if [[ -z $vpn_name ]]; then
console_log "Please provide the VPN name as an argument." "error"
return 1
fi
for ((attempt = 1; attempt <= max_attempts; attempt++)); do
nmcli connection up "$vpn_name"
status=$(nmcli connection show --active | grep "$vpn_name")
if [[ -n $status ]]; then
ip=$(curl -s https://api.ipify.org)
console_log "[$host] VPN connection successfully established to $vpn_name (IP: $ip)." "info"
return 0
else
console_log "[$host] Failed to connect to VPN: $vpn_name. Retrying (attempt $attempt of $max_attempts)..." "error"
sleep 1
fi
done
console_log "[$host] Maximum number of connection attempts reached. Failed to connect to VPN: $vpn_name" "error"
return 1
}
function vpn_disconnect() {
nmcli connection down "$(nmcli connection show --active | grep vpn | awk '{print $1}')"
status=$(nmcli connection show --active | awk '/vpn/ {print $1}')
if [[ -z $status ]]; then
console_log "[$host] Successfully disconnected from all VPNs." "info"
return 0
else
console_log "[$host] Failed to disconnect from all VPNs." "error"
return 1
fi
}
function start_bot() {
local account_name=$1
if [ -f "./accounts/$account_name.json" ]; then
if [ -n "$webhook" ]; then
if [[ "$print_log_to_webhook" == 1 ]]; then
command_suffix="--discord $webhook --print-to-webhook"
else
command_suffix="--discord $webhook"
fi
fi
if grep -q "container=lxc" /proc/1/environ || grep -q "container=lxc-libvirt" /proc/1/environ; then
command_prefix="cd Microsoft-Rewards-bot && python ms_rewards_farmer.py --accounts-file ../accounts/$account_name.json --dont-check-for-updates --shuffle --session --superfast --on-finish exit --no-webdriver-manager --browser uc --skip-unusual --virtual-display"
else
command_prefix="cd Microsoft-Rewards-bot && python ms_rewards_farmer.py --accounts-file ../accounts/$account_name.json --dont-check-for-updates --shuffle --session --superfast --on-finish exit --no-webdriver-manager --browser uc --skip-unusual"
fi
console_log "[$host] Script started for $account_name"
timeout 150m sh -c "$command_prefix $command_suffix; exit; exec bash"
return 0
else
console_log "[$host] File ./accounts/$account_name.json does not exist, skipping starting bot for this VPN!" "error"
return 1
fi
}
function main() {
check_update
local vpns
vpns=$(nmcli connection show | grep vpn | awk '{print $1}')
local host
host=$(hostname -f)
if [ -f "config.txt" ]; then
source "config.txt"
else
console_log "[$host] Config file not found." "error"
exit 1
fi
if [ -z "$webhook" ]; then
console_log "[$host] Webhook not set! Updates won't be sent to it"
else
if [ -z "$mcr_bot_webhook" ]; then
mcr_bot_webhook=$webhook
fi
console_log "[$host] Webhook set!"
console_log "[$host] Starting mcr-bot on host: $host" "info"
fi
for vpn in $vpns; do
console_log "[$host] Switching to VPN: [$vpn]" "info"
if vpn_connect "$vpn"; then
start_bot "$vpn"
console_log "[$host] Disconnecting from VPN: [$vpn]" "info"
vpn_disconnect
else
console_log "[$host] Failed to connect to VPN: [$vpn]. Skipping to the next VPN." "error"
fi
done
return 0
}
while true; do
main &
wait $!
done