Skip to content

Commit

Permalink
chore: Add and enforce no-use-before-define & prefer-constant eslint …
Browse files Browse the repository at this point in the history
…rules
  • Loading branch information
3urobeat committed May 4, 2024
1 parent 2a700c2 commit 77c9f8e
Show file tree
Hide file tree
Showing 78 changed files with 590 additions and 583 deletions.
4 changes: 3 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Created Date: 2024-05-03 12:17:16
* Author: 3urobeat
*
* Last Modified: 2024-05-03 12:58:49
* Last Modified: 2024-05-04 22:00:04
* Modified By: 3urobeat
*
* Copyright (c) 2024 3urobeat <https://github.com/3urobeat>
Expand Down Expand Up @@ -64,6 +64,8 @@ export default [
"no-tabs": "error",
"no-trailing-spaces": "error",
"no-extra-semi": "error",
"no-use-before-define": "error",
"prefer-const": "error",
"semi": ["error", "always"],
"semi-spacing": "error",
"semi-style": ["error", "last"],
Expand Down
6 changes: 3 additions & 3 deletions scripts/checkTranslationKeys.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const eng = require("../src/data/lang/english.json");


// Find all translations inside the same directory
let translations = fs.readdirSync("./src/data/lang/");
const translations = fs.readdirSync("./src/data/lang/");

console.log(`Checking ${translations.length - 1} translation(s). If the script exits with no further messages, all translations contain the same keys.`);

Expand All @@ -44,8 +44,8 @@ translations.forEach((name) => {


// Get key arrays of both translations
let engKeys = Object.keys(eng);
let langKeys = Object.keys(lang);
const engKeys = Object.keys(eng);
const langKeys = Object.keys(lang);


// Check lang for missing keys
Expand Down
8 changes: 4 additions & 4 deletions scripts/generateFileStructure.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function searchFolderRecursiveSync(src, firstCall) {
if (fs.lstatSync(src).isDirectory()) {
files = fs.readdirSync(src);

let targetFolder = path.join("./", src);
const targetFolder = path.join("./", src);

files.forEach(async (file) => {
let filepath = targetFolder + "/" + file;
Expand All @@ -59,7 +59,7 @@ function searchFolderRecursiveSync(src, firstCall) {
// Ignore this file/folder if name is in ignore array
if (ignore.includes(filepath)) return;

let curSource = path.join(src, file);
const curSource = path.join(src, file);

// Recursively call this function again if this is a dir
if (fs.lstatSync(curSource).isDirectory()) {
Expand All @@ -68,8 +68,8 @@ function searchFolderRecursiveSync(src, firstCall) {
} else {

// Construct URL and calculate checksum
let fileurl = "https://raw.githubusercontent.com/3urobeat/steam-comment-service-bot/beta-testing/" + filepath;
let filesum = crypto.createHash("md5").update(fs.readFileSync(filepath)).digest("hex");
const fileurl = "https://raw.githubusercontent.com/3urobeat/steam-comment-service-bot/beta-testing/" + filepath;
const filesum = crypto.createHash("md5").update(fs.readFileSync(filepath)).digest("hex");

// Add file to output array
output.push({ "path": filepath, "url": fileurl, "checksum": filesum });
Expand Down
8 changes: 4 additions & 4 deletions src/bot/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const Bot = function(controller, index) {
*/
this.friendMessageBlock = [];

let proxyIndex = this.index % controller.data.proxies.length; // Spread all accounts equally with a simple modulo calculation
const proxyIndex = this.index % controller.data.proxies.length; // Spread all accounts equally with a simple modulo calculation

/**
* Additional login related information for this bot account
Expand Down Expand Up @@ -207,7 +207,7 @@ Bot.prototype._loginToSteam = async function() {
this.user.logOff();
if (this.sessionHandler.session) this.sessionHandler.session.cancelLoginAttempt(); // TODO: This might cause an error as idk if we are polling. Maybe use the timeout event of steam-session

let logOffInterval = setInterval(() => {
const logOffInterval = setInterval(() => {
logger("warn", `[${this.logPrefix}] Login requested but account seems to be logged in! Attempting log off before continuing...`, true, true); // Cannot log with date to prevent log output file spam

// Resolve when logged off or when logOnTries has changed (handleLoginTimeout has probably taken action)
Expand All @@ -226,15 +226,15 @@ Bot.prototype._loginToSteam = async function() {


// Find proxyIndex from steam-user object options instead of loginData to get reliable log data
let thisProxy = this.data.proxies.find((e) => e.proxy == this.user.options.httpProxy);
const thisProxy = this.data.proxies.find((e) => e.proxy == this.user.options.httpProxy);

// Log login message for this account, with mentioning proxies or without
if (!thisProxy.proxy) logger("info", `[${this.logPrefix}] Trying to log in without proxy... (Attempt ${this.loginData.logOnTries}/${this.controller.data.advancedconfig.maxLogOnRetries + 1})`, false, true, logger.animation("loading"));
else logger("info", `[${this.logPrefix}] Trying to log in with proxy ${thisProxy.proxyIndex}... (Attempt ${this.loginData.logOnTries}/${this.controller.data.advancedconfig.maxLogOnRetries + 1})`, false, true, logger.animation("loading"));


// Call our steam-session helper to get a valid refresh token for us
let refreshToken = await this.sessionHandler.getToken();
const refreshToken = await this.sessionHandler.getToken();

if (!refreshToken) return this.loginData.pendingLogin = false; // Stop execution if getRefreshToken aborted login attempt, it either skipped this account or stopped the bot itself

Expand Down
2 changes: 1 addition & 1 deletion src/bot/events/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Bot.prototype._attachSteamErrorEvent = function() {


// Check if all logOnTries are used or if this is a fatal error
let blockedEnumsForRetries = [EResult.Banned, EResult.AccountNotFound]; // No need to block InvalidPassword anymore as the SessionHandler handles credentials
const blockedEnumsForRetries = [EResult.Banned, EResult.AccountNotFound]; // No need to block InvalidPassword anymore as the SessionHandler handles credentials

if (this.loginData.logOnTries > this.controller.data.advancedconfig.maxLogOnRetries || blockedEnumsForRetries.includes(err.eresult)) {
logger("error", `Couldn't log in bot${this.index} after ${this.loginData.logOnTries} attempt(s). ${err} (${err.eresult})`);
Expand Down
20 changes: 10 additions & 10 deletions src/bot/events/friendMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,23 @@ const Bot = require("../bot.js");
Bot.prototype._attachSteamFriendMessageEvent = function() {

this.user.chat.on("friendMessage", async (msg) => {
let message = msg.message_no_bbcode;
let steamID = msg.steamid_friend;
const message = msg.message_no_bbcode;
const steamID = msg.steamid_friend;

let steamID64 = new SteamID(String(steamID)).getSteamID64();
let username = this.user.users[steamID64] ? this.user.users[steamID64].player_name : ""; // Set username to nothing in case they are not cached yet to avoid errors
const steamID64 = new SteamID(String(steamID)).getSteamID64();
const username = this.user.users[steamID64] ? this.user.users[steamID64].player_name : ""; // Set username to nothing in case they are not cached yet to avoid errors

let relationshipStatus = SteamUser.EFriendRelationship.None;
if (this.user.myFriends[steamID64]) relationshipStatus = SteamUser.EFriendRelationship[this.user.myFriends[steamID64]];

let resInfo = { userID: steamID64, cmdprefix: "!", fromSteamChat: true }; // Object required for sendChatMessage(), our commandHandler respondModule implementation
const resInfo = { userID: steamID64, cmdprefix: "!", fromSteamChat: true }; // Object required for sendChatMessage(), our commandHandler respondModule implementation


// Check if another friendMessage handler is currently active
if (this.friendMessageBlock.includes(steamID64)) return logger("debug", `[${this.logPrefix}] Ignoring friendMessage event from ${steamID64} as user is on friendMessageBlock list.`);

// Check if this event should be handled or if user is blocked
let isBlocked = await this.checkMsgBlock(steamID64, message);
const isBlocked = await this.checkMsgBlock(steamID64, message);
if (isBlocked) return; // Stop right here if user is blocked, on cooldown or not a friend


Expand Down Expand Up @@ -74,7 +74,7 @@ Bot.prototype._attachSteamFriendMessageEvent = function() {
if (err) logger("error", "Database error on friendMessage. This is weird. Error: " + err);

if (!doc) { // Add user to database if he/she is missing for some reason
let lastcommentobj = {
const lastcommentobj = {
id: new SteamID(String(steamID)).getSteamID64(),
time: Date.now() - (this.data.config.requestCooldown * 60000) // Subtract requestCooldown so that the user is able to use the command instantly
};
Expand All @@ -94,10 +94,10 @@ Bot.prototype._attachSteamFriendMessageEvent = function() {


// Ask command handler to figure out things for us when a message with prefix was sent
let cont = message.slice(1).split(" "); // Remove prefix and split
let args = cont.slice(1); // Remove cmd name to only get arguments
const cont = message.slice(1).split(" "); // Remove prefix and split
const args = cont.slice(1); // Remove cmd name to only get arguments

let success = await this.controller.commandHandler.runCommand(cont[0].toLowerCase(), args, this.sendChatMessage, this, resInfo); // Don't listen to your IDE, this *await is necessary*
const success = await this.controller.commandHandler.runCommand(cont[0].toLowerCase(), args, this.sendChatMessage, this, resInfo); // Don't listen to your IDE, this *await is necessary*

if (!success) this.sendChatMessage(this, resInfo, await this.controller.data.getLang("commandnotfound", { "cmdprefix": resInfo.cmdprefix }, steamID64)); // Send cmd not found msg if runCommand() returned false
});
Expand Down
6 changes: 3 additions & 3 deletions src/bot/events/relationship.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Bot.prototype._attachSteamFriendRelationshipEvent = function() {
this.user.on("friendRelationship", (steamID, relationship) => {

if (relationship == 2) {
let steamID64 = new SteamID(String(steamID)).getSteamID64();
const steamID64 = new SteamID(String(steamID)).getSteamID64();

if (!this.data.advancedconfig.acceptFriendRequests) return logger("info", `[${this.logPrefix}] Received friend request from ${steamID64} but acceptFriendRequests is turned off in advancedconfig.json`);

Expand All @@ -47,7 +47,7 @@ Bot.prototype._attachSteamFriendRelationshipEvent = function() {


// Add user to lastcomment database
let time = Date.now() - (this.controller.data.config.requestCooldown * 60000); // Subtract requestCooldown so that the user is able to use the command instantly;
const time = Date.now() - (this.controller.data.config.requestCooldown * 60000); // Subtract requestCooldown so that the user is able to use the command instantly;

this.controller.data.lastCommentDB.update({ id: steamID64 }, { $set: { time: time } }, { upsert: true }, (err) => {
if (err) logger("error", "Error inserting new user into lastcomment.db database! Error: " + err);
Expand Down Expand Up @@ -86,7 +86,7 @@ Bot.prototype._attachSteamGroupRelationshipEvent = function() {
this.user.on("groupRelationship", (steamID, relationship) => {

if (relationship == 2) { // Ignore if relationship type is not "Invited"
let steamID64 = new SteamID(String(steamID)).getSteamID64();
const steamID64 = new SteamID(String(steamID)).getSteamID64();

// Check if acceptgroupinvites is set to false and only allow botsgroup invite to be accepted
if (!this.controller.data.config.acceptgroupinvites) {
Expand Down
6 changes: 3 additions & 3 deletions src/bot/events/webSession.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Bot.prototype._attachSteamWebSessionEvent = function() {
if (this.user.myFriends[Object.keys(this.user.myFriends)[i]] == 2) {

if (this.controller.data.advancedconfig.acceptFriendRequests) {
let thisfriend = Object.keys(this.user.myFriends)[i];
const thisfriend = Object.keys(this.user.myFriends)[i];

// Accept friend request
this.user.addFriend(thisfriend);
Expand All @@ -76,7 +76,7 @@ Bot.prototype._attachSteamWebSessionEvent = function() {


// Add user to lastcomment database
let time = Date.now() - (this.controller.data.config.requestCooldown * 60000); // Subtract requestCooldown so that the user is able to use the command instantly;
const time = Date.now() - (this.controller.data.config.requestCooldown * 60000); // Subtract requestCooldown so that the user is able to use the command instantly;

this.controller.data.lastCommentDB.update({ id: thisfriend }, { $set: { time: time } }, { upsert: true }, (err) => {
if (err) logger("error", "Error inserting new user into lastcomment.db database! Error: " + err);
Expand Down Expand Up @@ -105,7 +105,7 @@ Bot.prototype._attachSteamWebSessionEvent = function() {
// Groups:
for (let i = 0; i < Object.keys(this.user.myGroups).length; i++) {
if (this.user.myGroups[Object.keys(this.user.myGroups)[i]] == 2) {
let thisgroup = Object.keys(this.user.myGroups)[i];
const thisgroup = Object.keys(this.user.myGroups)[i];

// Check if acceptgroupinvites is set to false and only allow botsgroup invite to be accepted
if (!this.controller.data.config.acceptgroupinvites) {
Expand Down
4 changes: 2 additions & 2 deletions src/bot/helpers/handleLoginTimeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Bot.prototype.handleLoginTimeout = function() {
if (this.data.advancedconfig.loginTimeout == 0) return logger("debug", `Bot handleLoginTimeout(): Ignoring timeout attach request for bot${this.index} because loginTimeout is disabled in advancedconfig!`);
else logger("debug", `Bot handleLoginTimeout(): Attached ${this.data.advancedconfig.loginTimeout / 1000} seconds timeout for bot${this.index}...`);

let currentLogOnTry = this.loginData.logOnTries;
const currentLogOnTry = this.loginData.logOnTries;

// Check if account is still offline with the same logOnTries value 60 seconds later and force progress
setTimeout(() => {
Expand All @@ -36,7 +36,7 @@ Bot.prototype.handleLoginTimeout = function() {
if (this.loginData.waitingFor2FA) return setTimeout(() => this.handleLoginTimeout(), 5000);

// Ignore timeout if account progressed since then
let newLogOnTry = this.loginData.logOnTries;
const newLogOnTry = this.loginData.logOnTries;

if (currentLogOnTry != newLogOnTry || this.status != Bot.EStatus.OFFLINE) return logger("debug", `Bot handleLoginTimeout(): Timeout for bot${this.index} done, acc not stuck. old/new logOnTries: ${currentLogOnTry}/${newLogOnTry} - acc status: ${this.status}`);

Expand Down
6 changes: 3 additions & 3 deletions src/bot/helpers/handleMissingGameLicenses.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const Bot = require("../bot.js");
* Handles checking for missing game licenses, requests them and then starts playing
*/
Bot.prototype.handleMissingGameLicenses = function() {
let data = this.controller.data;
const data = this.controller.data;

// Check if user provided games specifically for this account. We only need to check this for child accounts
let configChildGames = data.config.childaccplayinggames;
Expand All @@ -35,10 +35,10 @@ Bot.prototype.handleMissingGameLicenses = function() {
}

// Shorthander for starting to play
let startPlaying = () => { if (this.index == 0) this.user.gamesPlayed(this.controller.data.config.playinggames); else this.user.gamesPlayed(configChildGames); };
const startPlaying = () => { if (this.index == 0) this.user.gamesPlayed(this.controller.data.config.playinggames); else this.user.gamesPlayed(configChildGames); };


let options = {
const options = {
includePlayedFreeGames: true,
filterAppids: this.index == 0 ? data.config.playinggames.filter(e => !isNaN(e)) : configChildGames.filter(e => !isNaN(e) && e != null), // We only need to check for these appIDs. Filter custom game string and null values
includeFreeSub: false
Expand Down
10 changes: 5 additions & 5 deletions src/bot/helpers/handleRelog.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Bot.prototype.switchProxy = function(newProxyIndex) {
Bot.prototype.checkAndSwitchMyProxy = async function() {

// Attempt to ping github.com (basically any non steamcommunity url) without a proxy to determine if the internet connection is not working
let hostConnectionRes = await this.controller.misc.checkConnection("https://github.com/3urobeat/steam-comment-service-bot", true)
const hostConnectionRes = await this.controller.misc.checkConnection("https://github.com/3urobeat/steam-comment-service-bot", true)
.catch((err) => {
if (this.index == 0) logger("info", `[Main] Your internet connection seems to be down. ${err.statusMessage}`); // Only log message for main acc to reduce clutter
});
Expand All @@ -86,10 +86,10 @@ Bot.prototype.checkAndSwitchMyProxy = async function() {


// Check if our proxy is down
let thisProxy = this.data.proxies.find((e) => e.proxyIndex == this.loginData.proxyIndex);
const thisProxy = this.data.proxies.find((e) => e.proxyIndex == this.loginData.proxyIndex);

if (!thisProxy.isOnline) {
let activeProxies = this.controller.getBotsPerProxy(true); // Get all online proxies and their associated bot accounts
const activeProxies = this.controller.getBotsPerProxy(true); // Get all online proxies and their associated bot accounts

// Check if no available proxy was found (exclude host) and return false
if (activeProxies.length == 0) {
Expand All @@ -99,7 +99,7 @@ Bot.prototype.checkAndSwitchMyProxy = async function() {


// Find proxy with least amount of associated bots
let leastUsedProxy = activeProxies.reduce((a, b) => a.bots.length < b.bots.length ? a : b);
const leastUsedProxy = activeProxies.reduce((a, b) => a.bots.length < b.bots.length ? a : b);

logger("warn", `[${this.logPrefix}] Failed to ping Steam using proxy ${this.loginData.proxyIndex}! Switching to proxy ${leastUsedProxy.proxyIndex} which currently has the least amount of usage and appears to be online.`);

Expand Down Expand Up @@ -127,7 +127,7 @@ Bot.prototype.handleRelog = async function() {
this.loginData.relogTries++;

// Check if proxy might be offline
let proxySwitched = await this.checkAndSwitchMyProxy();
const proxySwitched = await this.checkAndSwitchMyProxy();

if (proxySwitched) return; // Stop execution if proxy was switched and bot is getting relogged

Expand Down

0 comments on commit 77c9f8e

Please sign in to comment.