Compare commits

53 Commits
legacy ... main

Author SHA1 Message Date
6a7a0069aa Added better check and error handling to log file 2023-06-29 14:50:18 +02:00
fb759c693c Fixed potential issue with log file being empty. 2023-06-29 14:15:31 +02:00
49086c0891 Cleaned code 2023-06-26 13:58:15 +02:00
1b030935f6 Fix dotenv import 2023-06-26 13:52:14 +02:00
7dd0cf5e1f Switched to ES6, Added public IP module, Code optimization. 2023-06-26 13:49:38 +02:00
7ddf460928 Final part of run logs 2023-06-26 13:16:00 +02:00
f53657acaf First part of the run logs 2023-06-26 13:06:06 +02:00
4267b18c82 Update readme 2023-06-26 12:07:39 +02:00
253d8c9ff3 Now support to three different webhook channel
- Bot Report webhook
- Bot Console webhook
- Bot Manager webhook
2023-06-26 11:59:43 +02:00
8a3d2a671c Fix promise loop 2023-06-26 11:23:29 +02:00
c058bf3414 Better Handling of process 2023-06-26 10:35:32 +02:00
5a2ef0f7ad Added visibility to the type of output (stdout|stderr) 2023-06-26 10:31:41 +02:00
fe21c4f7f1 changed to unbeffered output 2023-06-26 10:29:15 +02:00
ceab8f480d Fix 2023-06-26 10:23:45 +02:00
349940efd4 2nd change 2023-06-26 10:21:37 +02:00
eae1bf2a5c Changed stdio 2023-06-26 10:19:54 +02:00
d71ffd5f8d Test log 2023-06-26 10:09:37 +02:00
2f705277e3 Remove log 2023-06-26 10:04:25 +02:00
c43c01a3a2 Added stdio 2023-06-26 10:02:34 +02:00
e96367ecaa Test 2023-06-26 09:54:11 +02:00
465835c185 Readded timeout using JS instead of bash 2023-06-26 09:47:43 +02:00
c50998eb82 Promisified bot process 2023-06-26 09:41:31 +02:00
a48b62833d Fix when no webhook set 2023-06-26 09:34:20 +02:00
60620177a9 Fix 2023-06-26 09:30:30 +02:00
9f882e1daf Added error handling to the bot. 2023-06-26 09:04:15 +02:00
912e501025 Roll back 2023-06-25 16:01:28 +02:00
0a4fa4072b Fix 2023-06-25 16:00:38 +02:00
2d0ff2f675 Better ip check 2023-06-25 15:34:52 +02:00
e2d6fd3d96 Fix browser config 2023-06-25 15:04:37 +02:00
014ca1b4f4 Fix check LXC 2023-06-25 15:02:20 +02:00
95f1119315 Fix start 2023-06-25 14:45:02 +02:00
9bb5b92ac6 test 2023-06-25 14:31:53 +02:00
fc1a6e686a Fix ip check 2023-06-25 14:29:31 +02:00
e2d84918d6 test 2023-06-25 14:27:07 +02:00
310516ab48 Fix again 2023-06-25 14:25:49 +02:00
61291c068c Fix 2023-06-25 14:23:38 +02:00
4b60d648b6 test 2023-06-25 14:22:17 +02:00
93bac87ae1 Fix8 2023-06-25 14:20:15 +02:00
8e439a0e68 Fix7 2023-06-25 14:12:29 +02:00
d58c4599b3 Fix6 2023-06-25 14:11:35 +02:00
c1717d80b6 Fix5 2023-06-25 14:06:15 +02:00
80f4b9a224 Fix4 2023-06-25 14:04:03 +02:00
41ca964e56 Fix3 2023-06-25 12:39:02 +02:00
c6f8780ff7 Fix2 2023-06-25 12:30:33 +02:00
0c139b6529 Fix 2023-06-25 12:27:24 +02:00
949cb4be86 Switched bot to use nodejs. 2023-06-25 12:16:20 +02:00
14a59e5c66 Fix loop 2023-06-22 14:31:41 +02:00
a4ffb097ea Fix update.sh 2023-06-22 13:34:04 +02:00
3322060a9f Added usage of Undetected Chrome ofr safety. 2023-06-22 13:32:35 +02:00
b22a9acd07 Replaced bot links to the mirror since official github has been taken down 2023-06-22 13:21:32 +02:00
057527f86a Improved scripts using ShellCheck 2023-06-22 13:04:01 +02:00
5b918e762b Added loop 2023-06-22 12:01:51 +02:00
6c28e77aea Updated Script to V2
- New bot manager using timeout instead of schedules
 - Moved accounts to an accounts folder
 - New dynamic Updater
 - Improved VPN Importer to avoid duplicate
 - Switched back to master Bot
 - New config file
2023-06-20 17:14:12 +02:00
13 changed files with 3272 additions and 195 deletions

7
.env.sample Normal file
View File

@@ -0,0 +1,7 @@
RETRIES=3
BOT_BROWSER='uc'
REPORT_WEBHOOK=''
BOT_CONSOLE_WEBHOOK=''
BOT_CONSOLE_WEBHOOK_NAME='Microsoft Rewards Bot'
MANAGER_WEBHOOK=''
MANAGER_WEBHOOK_NAME='Microsoft Rewards Bot Manager'

53
.eslintrc.json Normal file
View File

@@ -0,0 +1,53 @@
{
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2021,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"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"
}
}

5
.gitignore vendored
View File

@@ -1,3 +1,6 @@
vpn/
accounts/
Microsoft-Rewards-bot/
config.txt
node_modules/
.env
batch_logs.json

View File

@@ -11,12 +11,14 @@ This repo contains the script to manage multiple mcr bot on a single VM/Containe
├── update.sh
├── Microsoft-Rewards-bot
│ ├── ms_rewards_farmer.py
│ ├── vpnname1.json
│ ├── vpnname2.json
│ ├── ...
├── accounts
│ ├── name1.json
│ ├── name2.json
│ ├── ...
├── vpn
│ ├── vpnname1.ovpn
│ ├── vpnname2.ovpn
│ ├── name1.ovpn
│ ├── name2.ovpn
│ ├── ...
```
@@ -40,7 +42,13 @@ bash setup-vpn.sh
Copy your accounts file named as [vpnname].json in the Bot folder then run
```bash
bash start.sh
node main --all
```
For single run of a specific VPN/Account file
```bash
node main --accounts [name]
```
### If using LXC

View File

@@ -1,5 +0,0 @@
interval=300
schedule=("01:00" "03:15" "05:30" "07:45" "10:00" "12:15" "14:30" "16:45" "19:00" "21:15")
retries=3
webhook=''
log_all=0

View File

@@ -37,21 +37,21 @@ if [[ -z $CTID || -z $CONTAINER_NAME || -z $DISTRO || -z $ROOTPASS ]]; then
exit 1
fi
template=$(pveam available | grep $DISTRO | sort -rV | head -n 1 | awk '{print $2}')
template=$(pveam available | grep "$DISTRO" | sort -rV | head -n 1 | awk '{print $2}')
if [[ -z $template ]]; then
echo "$DISTRO template not found."
exit 1
fi
template=$(pveam list local | grep $template | awk '{print $1}')
template=$(pveam list local | grep "$template" | awk '{print $1}')
if [[ -z $template ]]; then
echo "$DISTRO template not found. Downloading..."
pveam download local $template
pveam download local "$template"
fi
pct create $CTID $template --hostname $CONTAINER_NAME --memory 1024 --storage local-lvm --net0 name=eth0,bridge=vmbr0,firewall=1,ip=dhcp --unprivileged --ostype $DISTRO --password="$ROOTPASS"
echo -e "lxc.cgroup.devices.allow: c 10:200 rwm\nlxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file" >> /etc/pve/lxc/$CTID.conf
pct start $CTID
pct status $CTID | grep "status: running" || sleep 10
pct create "$CTID" "$template" --hostname "$CONTAINER_NAME" --memory 1024 --storage local-lvm --net0 name=eth0,bridge=vmbr0,firewall=1,ip=dhcp --unprivileged --ostype "$DISTRO" --password="$ROOTPASS"
echo -e "lxc.cgroup.devices.allow: c 10:200 rwm\nlxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file" >> /etc/pve/lxc/"$CTID".conf
pct start "$CTID"
pct status "$CTID" | grep "status: running" || sleep 10
echo lxc now running

324
index.js Normal file
View File

@@ -0,0 +1,324 @@
import { execSync, spawn } from 'child_process';
import { publicIpv4 } from 'public-ip';
import dotenv from 'dotenv';
import fs from 'fs';
import os from '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 payload = {
content: message,
username: managerWebhookName,
};
try {
await fetch(managerWebhook, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
}
catch (error) {
console.error(`[${host}] Error sending webhook message: ${error.message}`);
}
}
}
async function logBotConsole(message) {
console.log(message);
if (botConsoleWebhook) {
const payload = {
content: message,
username: botConsoleWebhookName,
};
try {
await fetch(botConsoleWebhook, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
}
catch (error) {
console.error(`[${host}] 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(`[${host}] Updates available! Please run the updater script.`, 'info');
}
}
catch (error) {
logManager('[${host}] Failed to check for updates.', 'error');
}
}
async function vpnConnect(vpnName) {
if (!vpnName) return logManager(`[${host}] 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 {
await logManager(`[${host}] VPN connection successfully established to ${vpnName} (IP: ${await publicIpv4() || 'Unknown'}).`, '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()) {
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: ['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');
return resolve();
}
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) => {
logManager(`[${accountName}] Bot 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 runAll() {
await checkUpdate();
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) || false;
if (entry && entry.date === formattedDate) {
logManager(`[${host}] ${vpn} already ran today!`, 'info');
continue;
}
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')) {
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', '[]', err => {
if (err) {
logManager(`Failed to create batch_logs.json: ${err}`, 'error');
process.exit(1);
}
});
}
else {
const fileContent = await fs.readFile('batch_logs.json', 'utf-8');
try {
JSON.parse(fileContent);
}
catch (error) {
logManager(`[${host}] Existing log file is not in proper JSON format: ${error}`, 'error');
process.exit(1);
}
}
logManager(`[${host}] Log file: batch_logs.json`, 'info');
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];
return await runBatch(accounts);
}
else if (args[i] === '--all') {
const n = true;
while (n) {
try {
await runAll();
await sleep(1000);
}
catch (error) {
logManager(`[${host}] An error occurred: ${error.message}`, 'error');
}
}
}
}
}
logManager(`[${host}] Missing arguments`);
})();

2797
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

24
package.json Normal file
View File

@@ -0,0 +1,24 @@
{
"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 --all"
},
"type": "module",
"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",
"node-fetch": "^3.3.1",
"pino": "^8.14.1",
"public-ip": "^6.0.1"
}
}

View File

@@ -30,11 +30,11 @@ update_package_manager() {
install_requirements() {
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
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
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
}
@@ -42,9 +42,10 @@ update_package_manager
install_requirements
git clone https://git.justw.tf/Lightemerald/mcr-bot && cd mcr-bot
git clone https://github.com/farshadz1997/Microsoft-Rewards-bot && cd Microsoft-Rewards-bot && git checkout 03476776e9c58029dedaeee431958b5d04364bcf && pip install -r requirements.txt
cd .. && mkdir vpn
cp ./config.txt.sample config.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
cp ./.env.sample .env
npm i
chmod +x ./*.sh
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 ./Microsoft-Rewards-bot\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''"

View File

@@ -1,9 +1,14 @@
#!/bin/bash
folder_path="vpn"
vpn_connections=$(nmcli connection show | grep vpn | awk '{print $1}')
for vpn in $vpn_connections; do
nmcli connection delete "$vpn"
done
folder_path="vpn"
for file in "$folder_path"/*; do
if [[ -f "$file" ]]; then
nmcli con import type openvpn file ./$file
nmcli con import type openvpn file ./"$file"
fi
done

165
start.sh
View File

@@ -1,165 +0,0 @@
#!/bin/bash
if [ "$(ps -o comm= $PPID)" != "kgx" ]
then
echo "Script is running under $(ps -o comm= $PPID)"
if command -v kgx >/dev/null; then
echo "gnome-console is already installed"
else
echo "Installing gnome-console"
if command -v dnf >/dev/null; then
sudo dnf install gnome-console -y
elif command -v apt-get >/dev/null; then
sudo apt-get install kgx -y
elif command -v pacman >/dev/null; then
sudo pacman -Sy gnome-console --noconfirm
else
echo "Unsupported package manager, install gnome console (kgx) on your own."
exit 1
fi
fi
echo "Restarting script in gnome-console..."
if grep -q "container=lxc" /proc/1/environ || grep -q "container=lxc-libvirt" /proc/1/environ; then
Xvfb :1 -screen 0 1024x768x16 &
DISPLAY=:1.0 kgx -e "/bin/bash -c 'cd $(dirname "$(readlink -f "$0")"); ./$(basename "$0")'" &
else
kgx -e "/bin/bash -c 'cd $(dirname "$(readlink -f "$0")"); ./$(basename "$0")'" &
fi
read -t 2
pkill -f "gnome-terminal"
exit
fi
function send_webhook() {
local message="$1"
if [ -z "$webhook" ]; then
echo "$message"
else
echo "$message"
curl --silent -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data "{\"content\": \"$message\", \"username\": \"mMicrosoft Rewards Bot Manager\"}" "$webhook"
fi
}
vpns=$(nmcli connection show | grep vpn | awk '{print $1}')
host=$(hostname -f)
config_file="config.txt"
if [ -f "$config_file" ]; then
source "$config_file"
else
echo "Config file not found."
exit 1
fi
if [ -z "$webhook" ]; then
echo "Webhook not set! Updates won't be sent to it"
else
echo "Webhook set!"
send_webhook "Starting mcr-bot on host: $host"
fi
while true
do
current_time=$(date +%H:%M)
next_index=-1
for i in "${!schedule[@]}"
do
if [[ "$current_time" < "${schedule[$i]}" ]]
then
next_index=$i
break
fi
done
if [ $next_index -eq -1 ]
then
next_index=0
fi
next_time="${schedule[$next_index]}"
if [[ "$current_time" > "${schedule[$next_index]}" ]]
then
next_seconds=$(($(date -d "$next_time +1 day" +%s) - $(date +%s)))
else
next_seconds=$(($(date -d "$next_time" +%s) - $(date +%s)))
fi
if [ $next_seconds -lt 0 ]
then
send_webhook "[$host] ERROR: Schedules are not setup correctly!"
exit
fi
send_webhook "[$host] Next schedule: $next_time"
while [ $next_seconds -gt 0 ]
do
echo -ne "\033[0K\rWaiting for $next_time... (in $next_seconds s) "
read -t 1
next_seconds=$(( $next_seconds - 1 ))
done
echo ""
next_vpn_index=$(( $next_index + 1 ))
vpn=$(echo "$vpns" | sed -n "${next_vpn_index}p")
send_webhook "[$host] Switching to VPN: [$next_vpn_index] - $vpn"
if [ "$vpn" != "" ]
then
send_webhook "[$host] Killing potential previous bot..."
pkill -f "gnome-terminal"
send_webhook "[$host] Switching VPN..."
nmcli connection down $(nmcli connection show --active | grep vpn | awk '{print $1}')
attempt=1
while [ $attempt -le $retries ]
do
nmcli connection up $vpn
read -t 2
if nmcli connection show --active | grep -q $vpn
then
ip=$(curl -s https://api.ipify.org)
send_webhook "[$host] VPN connection successfully established (IP: $ip).\nStarting script..."
if [ -f "./Microsoft-Rewards-bot/$vpn.json" ]
then
if [ -z "$webhook" ]; then
command_suffix="--accounts-file $vpn.json"
else
if [[ "$log_all" == 1 ]]; then
command_suffix="--accounts-file $vpn.json --discord $webhook --print-to-webhook"
else
command_suffix="--accounts-file $vpn.json --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 --dont-check-for-updates --shuffle --session --superfast --on-finish exit --no-webdriver-manager --skip-unusual --virtual-display"
else
command_prefix="cd Microsoft-Rewards-bot && python ms_rewards_farmer.py --dont-check-for-updates --shuffle --session --superfast --on-finish exit --no-webdriver-manager --skip-unusual"
fi
gnome-terminal -- sh -c "$command_prefix $command_suffix; exit; exec bash" &
read -t 2
send_webhook "[$host] Script started"
read -t 1
break
else
send_webhook "[$host] ERROR: File ./Microsoft-Rewards-bot/$vpn.json does not exist, skipping starting bot for this VPN"
read -t 3
break
fi
else
send_webhook "[$host] ERROR: Failed to establish VPN connection (attempt $attempt of $retries)"
if [ $attempt -eq $retries ]
then
send_webhook "[$host] ERROR: Max retries reached, switching to the next schedule"
fi
read -t 1
fi
attempt=$(( $attempt + 1 ))
done
else
send_webhook "[$host] ERROR: VPN name is empty"
fi
done

View File

@@ -1,6 +1,31 @@
#!/bin/bash
git fetch
if [ "$(git rev-parse HEAD)" != "$(git rev-parse "@{u}")" ]; then
git stash && git pull
cd .. && chmod +x ./*.sh
exec "$0"
fi
if [ ! -d "accounts" ]; then
mkdir "accounts"
fi
if [ ! -d "vpn" ]; then
mkdir "vpn"
fi
if [ ! -d "Microsoft-Rewards-bot" ]; then
git clone https://git.justw.tf/Lightemerald/Microsoft-Rewards-bot
fi
sudo dnf up -y
git stash && git pull
cd Microsoft-Rewards-bot && git stash && git pull && git checkout 03476776e9c58029dedaeee431958b5d04364bcf && pip install -r requirements.txt
clear
cd Microsoft-Rewards-bot || exit
git fetch
if [ "$(git rev-parse HEAD)" != "$(git rev-parse "@{u}")" ]; then
git stash && git pull && git checkout master && pip install -r requirements.txt
fi
cd .. && chmod +x ./*.sh
clear
echo "Update done!"