Skip to content

Commit

Permalink
Version 2.10.3 (read commit description)
Browse files Browse the repository at this point in the history
Fixed globalcommentcooldown not getting applied correctly leading to multiple comment processes at the same time (#91). Fixed HTTP 429 error not aborting comment process. friendMessage in log will now get cut off after 75 characters. Changed globalcommentcooldown unit from ms to minutes. Minor other changes.
  • Loading branch information
3urobeat committed Mar 25, 2021
1 parent c9ef7fa commit fa6d0f4
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 34 deletions.
2 changes: 1 addition & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"allowcommentcmdusage": true,
"skipSteamGuard": false,
"commentcooldown": 5,
"globalcommentcooldown": 90000,
"globalcommentcooldown": 10,
"repeatedComments": 2,
"randomizeAccounts": false,
"unfriendtime": 31,
Expand Down
28 changes: 18 additions & 10 deletions src/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,23 @@ module.exports.run = async (logOnOptions, loginindex) => {
* @param {Object} res An express response object that will be available if the function is called from the express webserver
*/
commentcmd = (steamID, args, res) => {
controller.lastcomment.findOne({ id: new SteamID(String(steamID)).getSteamID64() }, (err, lastcommentdoc) => {
var steam64id = new SteamID(String(steamID)).getSteamID64()

controller.lastcomment.findOne({ id: steam64id }, (err, lastcommentdoc) => {
if (!lastcommentdoc) logger("User is missing from database?? How is this possible?! Error maybe: " + err)

require("./comment.js").run(logger, chatmsg, lang, community, thisbot, steamID, args, res, lastcommentdoc, failedcomments, activecommentprocess, lastcommentrequestmsg, commentedrecently, commentcounter, lastsuccessfulcomment, (fc, acp, cr, cc) => { //callback transports stuff back to be able to store the stuff here
failedcomments = fc //update failedcomments
activecommentprocess = acp
module.exports.activecommentprocess = acp //update exported value so that updater knows whats up
commentedrecently = cr
commentcounter = cc
})
try { //catch any unhandled error to be able to remove user from activecommentprocess array
require("./comment.js").run(logger, chatmsg, lang, community, thisbot, steamID, args, res, lastcommentdoc, failedcomments, activecommentprocess, lastcommentrequestmsg, commentedrecently, commentcounter, lastsuccessfulcomment, (fc, acp, cr, cc) => { //callback transports stuff back to be able to store the stuff here
failedcomments = fc //update failedcomments
activecommentprocess = acp
module.exports.activecommentprocess = acp //update exported value so that updater knows whats up
commentedrecently = cr
commentcounter = cc
})
} catch (err) {
activecommentprocess = activecommentprocess.filter(item => item != steam64id) //Remove user from array to make sure you can't get stuck in there (not perfect as this won't trigger when the error occurrs in a nested function)
logger("Error while processing comment request: " + err)
}
})
}
}
Expand Down Expand Up @@ -392,8 +399,9 @@ module.exports.run = async (logOnOptions, loginindex) => {

if (!ownercheck) lastmessage[steam64id][1]++ //push new message to array if user isn't an owner


logger(`[${thisbot}] Friend message from ${steam64id}: ${message}`); //log message
//log friend message but cut it if it is >= 75 chars
if (message.length >= 75) logger(`[${thisbot}] Friend message from ${steam64id}: ${message.slice(0, 75) + "..."}`);
else logger(`[${thisbot}] Friend message from ${steam64id}: ${message}`);

//Deny non-friends the use of any command
if (bot.myFriends[steam64id] != 3) return chatmsg(steamID, lang.usernotfriend)
Expand Down
31 changes: 19 additions & 12 deletions src/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ module.exports.run = (logger, chatmsg, lang, community, thisbot, steamID, args,
}

if (config.globalcommentcooldown != 0) { //check for global cooldown
if ((Date.now() - commentedrecently) < config.globalcommentcooldown) {
var remainingglobalcooldown = Math.abs((((Date.now() - commentedrecently)) - (config.globalcommentcooldown)) / 1000)
if ((Date.now() - commentedrecently) < (config.globalcommentcooldown * 60000)) {
var remainingglobalcooldown = Math.abs(((Date.now() - commentedrecently) - (config.globalcommentcooldown * 60000)) / 1000)
var remainingglobalcooldownunit = "seconds"
if (remainingglobalcooldown > 120) { var remainingglobalcooldown = remainingglobalcooldown / 60; var remainingglobalcooldownunit = "minutes" }
if (remainingglobalcooldown > 120) { var remainingglobalcooldown = remainingglobalcooldown / 60; var remainingglobalcooldownunit = "hours" }

respondmethod(403, lang.commentglobaloncooldown.replace("remainingglobalcooldown", controller.round(remainingglobalcooldown, 2)).replace("timeunit", remainingglobalcooldownunit)) //send error message
respondmethod(403, lang.commentglobaloncooldown.replace("globalcommentcooldown", config.globalcommentcooldown).replace("remainingglobalcooldown", controller.round(remainingglobalcooldown, 2)).replace("timeunit", remainingglobalcooldownunit)) //send error message
return; } }

/* --------- Check numberofcomments argument if it was provided --------- */
Expand Down Expand Up @@ -143,7 +143,12 @@ module.exports.run = (logger, chatmsg, lang, community, thisbot, steamID, args,
var breakloop = false
failedcomments[requesterSteamID] = {}
activecommentprocess.push(requesterSteamID)
callback(failedcomments, activecommentprocess, commentedrecently, commentcounter) //callback updated acp

if (config.globalcommentcooldown !== 0) { //activate globalcommentcooldown
commentedrecently = Date.now() + (numberofcomments + config.commentdelay) //globalcommentcooldown should start after the last comment was processed
}

callback(failedcomments, activecommentprocess, commentedrecently, commentcounter) //callback updated acp and cr

function comment(k, i) {
setTimeout(() => {
Expand All @@ -152,9 +157,14 @@ module.exports.run = (logger, chatmsg, lang, community, thisbot, steamID, args,
if (!activecommentprocess.includes(requesterSteamID)) { //Check if user is not anymore in activecommentprocess array (for example by using !abort)
failedcomments[requesterSteamID][`Comment ${i} (bot${k})`] = "Skipped because user aborted comment process." //push reason to failedcomments obj
return; } //Stop further execution and skip to next iteration

if (Object.values(failedcomments[requesterSteamID]).includes("postUserComment error: Error: HTTP error 429")) { //Check if we got IP blocked (cooldown) by checking for a HTTP 429 error pushed into the failedcomments array by a previous iteration and send message
if (!Object.values(failedcomments[requesterSteamID]).includes("postUserComment error: Skipped because of previous HTTP 429 error.")) { //send chat.sendFriendMessage only the first time

//regex is confusing so I hope this pattern isn't too terrible
let regexPattern1 = /postUserComment error: Error: HTTP error 429.*\n.*/gm //Thanks: https://stackoverflow.com/a/49277142
let regexPattern2 = /postUserComment error: Skipped because of previous HTTP 429 error.*/gm

//Array.includes() needs an exact match and since we already want to match with only a part of the string we can do it using Array.some() and regex
if (Object.values(failedcomments[requesterSteamID]).some(e => regexPattern1.test(e))) { //Check if we got IP blocked (cooldown) by checking for a HTTP 429 error pushed into the failedcomments array by a previous iteration and send message
if (!Object.values(failedcomments[requesterSteamID]).some(e => regexPattern2.test(e))) { //send chat.sendFriendMessage only the first time
respondmethod(500, `${lang.comment429stop.replace("failedamount", numberofcomments - i + 1).replace("numberofcomments", numberofcomments)}\n\n${lang.commentfailedcmdreference}`) //add !failed cmd reference to message

//push all other comments to instanly complete the failedcomments obj
Expand Down Expand Up @@ -267,12 +277,9 @@ module.exports.run = (logger, chatmsg, lang, community, thisbot, steamID, args,
}


/* --------- Activate globalcooldown & give user cooldown --------- */
if (config.globalcommentcooldown !== 0) {
commentedrecently = Date.now() }

/* --------- Give user cooldown --------- */
//add estimated wait time in ms to start the cooldown after the last recieved comment
controller.lastcomment.update({ id: requesterSteamID }, { $set: { time: Date.now() + (((numberofcomments - 1) * config.commentdelay)) } }, {}, (err) => {
controller.lastcomment.update({ id: requesterSteamID }, { $set: { time: Date.now() + ((numberofcomments - 1) * config.commentdelay) } }, {}, (err) => {
if (err) logger("Error adding cooldown to user in database! You should probably *not* ignore this error!\nError: " + err)
})

Expand Down
2 changes: 1 addition & 1 deletion src/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -571,9 +571,9 @@ var readyinterval = setInterval(() => { //log startup to console

var unfriendloop = setInterval(() => { //eslint-disable-line
if (lastcommentUnfriendCheck + 30000 > Date.now()) return; //last check is more recent than 30 seconds
lastcommentUnfriendCheck = Date.now()

lastcomment.find({ time: { $lte: Date.now() - (config.unfriendtime * 86400000) } }, (err, docs) => { //until is a date in ms, so we check if it is less than right now
lastcommentUnfriendCheck = Date.now()
if (docs.length < 1) return; //nothing found

docs.forEach((e) => { //take action for all results
Expand Down
6 changes: 3 additions & 3 deletions src/data.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"version": "2102",
"versionstr": "2.10.2",
"version": "2103",
"versionstr": "2.10.3",
"branch": "master",
"filetostart": "./src/updater.js",
"filetostarturl": "https://raw.githubusercontent.com/HerrEurobeat/steam-comment-service-bot/master/src/updater.js",
Expand All @@ -9,7 +9,7 @@
"aboutstr": "This bot was created by 3urobeat.\nGitHub: https://github.com/HerrEurobeat/steam-comment-service-bot \nSteam: https://steamcommunity.com/id/3urobeat \nIf you like my work, any donation would be appreciated! https://paypal.me/3urobeat",
"firststart": true,
"compatibilityfeaturedone": false,
"whatsnew": "Fixed bot stuck on startup when using accounts.txt with empty lines. Fixed updater not waiting for active comment process. Added a commentcounter. Fixed user not getting removed from activecommentprocess when requesting 1 comment. Minor other changes listed on GitHub.",
"whatsnew": "Fixed globalcommentcooldown not getting applied correctly leading to multiple comment processes at the same time. Fixed HTTP 429 error not aborting comment process. Changed globalcommentcooldown unit from ms to minutes. Minor other changes.",
"urlrequestsecretkey": "",
"timesloggedin": 0,
"totallogintime": 0
Expand Down
4 changes: 2 additions & 2 deletions src/defaultlang.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"commentcmdusage2": "'!comment' for a comment on your profile!",
"commentuseroncooldown": "You requested a comment in the last commentcooldown minutes. Please wait the remaining remainingcooldown timeunit.",
"commentuseralreadyrecieving": "You are currently recieving previously requested comments. Please wait for them to be completed.",
"commentglobaloncooldown": "Someone else requested a comment in the last remainingglobalcooldown timeunit or Steam has applied a cooldown on this account.\nPlease wait a few minutes before trying again.",
"commentglobaloncooldown": "Someone else requested a comment in the last globalcommentcooldown minutes or Steam has applied a cooldown on this account.\nPlease wait the remaining remainingglobalcooldown timeunit before trying again.",
"commentinvalidnumber": "This is not a valid number!\nCommand usage: commentcmdusage",
"commentrequesttoohigh": "You can request max. maxrequestamount comments.\nCommand usage: commentcmdusage",
"commentinvalidprofileid": "This is not a valid profileid! A profile id must look like this: 76561198260031749\nCommand usage: commentcmdusage",
Expand All @@ -21,7 +21,7 @@
"commenterroroccurred": "Oops, an error occurred!",
"commentsuccess1": "Okay I commented on your/the recieving profile! If you are a nice person then please comment on my profile too!",
"commentprocessstarted": "Estimated wait time for numberofcomments comments: waittime timeunit.",
"commentfailedcmdreference": "To get detailed information why which comment failed please type '!failed'. You can read why your error was probably caused here: https://github.com/HerrEurobeat/steam-comment-service-bot/wiki/Errors,-FAQ-&-Common-problems",
"commentfailedcmdreference": "To get detailed information why which comment failed please type '!failed'. You can read what probably caused your error here: https://github.com/HerrEurobeat/steam-comment-service-bot/wiki/Errors,-FAQ-&-Common-problems",
"comment429stop": "Stopped comment process because of a HTTP 429 (cooldown) error. Please try again later. Failed: failedamount/numberofcomments",
"commentsuccess2": "All comments have been sent. Failed: failedamount/numberofcomments\nIf you are a nice person then please comment on my profile too!",
"commentlimitederror": "-----------------------------------\nIt seems like at least one of the requested comments could have failed because you/the recieving account aren't/isn't friend with the commenting bot account.\n\nPlease make sure that you have added these accounts in order to eventually avoid this error in the future: \naccstoadd\n-----------------------------------",
Expand Down
31 changes: 26 additions & 5 deletions src/updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ function downloadandupdate(url, name, compatibilityfeaturedone, callback) {
}
}

/**
* Checks for an available update from the GitHub repo
* @param {Boolean} forceupdate Force an update
* @param {Object} responseSteamID If defined bot0 will respond to that steamID telling if an update was found
* @param {Boolean} compatibilityfeaturedone Only works with forceupdate! Changes compatibilityfeaturedone in data.json to true
*/
var checkforupdate = (forceupdate, responseSteamID, compatibilityfeaturedone) => {
try {
/* ------------------ Check for new version ------------------ */
Expand All @@ -126,13 +132,13 @@ var checkforupdate = (forceupdate, responseSteamID, compatibilityfeaturedone) =>
res.setEncoding('utf8');

res.on('data', function(chunk) {
var onlineversion = JSON.parse(chunk).version //parse version number from get request
var onlineversion = Number(JSON.parse(chunk).version) //parse version number from get request
var onlineversionstr = JSON.parse(chunk).versionstr

module.exports.onlinemestr = JSON.parse(chunk).mestr //get mestr and aboutstr from GitHub to check for modification
module.exports.onlineaboutstr = JSON.parse(chunk).aboutstr

if (onlineversion > extdata.version || forceupdate == true || releasemode == "beta-testing" && !onlineversion.includes("BETA") && extdata.version.includes("BETA") || releasemode == "beta-testing" && onlineversion.includes("BETA") && !extdata.version.includes("BETA")) { //version number greater or forceupdate is true?
if (onlineversion > Number(extdata.version) || forceupdate == true || releasemode == "beta-testing" && !onlineversionstr.includes("BETA") && extdata.versionstr.includes("BETA") || releasemode == "beta-testing" && onlineversionstr.includes("BETA") && !extdata.versionstr.includes("BETA")) { //version number greater or forceupdate is true?
logger("", true)
logger(`\x1b[32mUpdate available!\x1b[0m Your version: \x1b[31m${extdata.versionstr}\x1b[0m | New version: \x1b[32m${onlineversionstr}\x1b[0m`, true)
logger("", true)
Expand Down Expand Up @@ -421,7 +427,7 @@ function compatibilityfeatures() {
//Compatibility features
try { //this is sadly needed when updating to 2.10 because I forgot in 2.9.x to set compatibilityfeature to false again which completly skips the comp feature
var extdata = require("./data.json")
if (extdata.firststart && fs.existsSync('./src/lastcomment.json') && (extdata.version == "2100" || extdata.version == "BETA 2.10 b5")) extdata.compatibilityfeaturedone = false
if (extdata.firststart && fs.existsSync('./src/lastcomment.json') && (extdata.version == "2100" || extdata.versionstr == "BETA 2.10 b5")) extdata.compatibilityfeaturedone = false
} catch (err) { } //eslint-disable-line

if (!fs.existsSync('./src')) { //this has to trigger if user was on version <2.6
Expand Down Expand Up @@ -500,7 +506,7 @@ function compatibilityfeatures() {
checkforupdate(true)
}

} else if (!extdata.compatibilityfeaturedone && (extdata.version == "2.8" || extdata.version == "BETA 2.8 b3")) {
} else if (!extdata.compatibilityfeaturedone && (extdata.versionstr == "2.8" || extdata.versionstr == "BETA 2.8 b3")) {
if (fs.existsSync('./updater.js')) {
logger("Applying 2.8 compatibility changes...")

Expand All @@ -512,7 +518,7 @@ function compatibilityfeatures() {
checkforupdate(true, null, true)
}

} else if (!extdata.compatibilityfeaturedone && (extdata.version == "2100" || extdata.version == "BETA 2.10 b5")) {
} else if (!extdata.compatibilityfeaturedone && (extdata.version == "2100" || extdata.versionstr == "BETA 2.10 b5")) {
logger("Applying 2.10 compatibility changes...")

if (fs.existsSync('./src/lastcomment.json')) {
Expand All @@ -539,6 +545,21 @@ function compatibilityfeatures() {
logger("I will now update again. Please wait a moment...")
checkforupdate(true, null, true)

} else if (!extdata.compatibilityfeaturedone && extdata.version == "2103" && config.globalcommentcooldown != 10) {
config.globalcommentcooldown = config.globalcommentcooldown / 60000

fs.writeFile('./config.json', JSON.stringify(config, null, 2), (err) => {
if (err) logger("Error writing converted globalcommentcooldown to config. Please change globalcommentcooldown in the config to 10 yourself. Error: " + err, true)
})

extdata.compatibilityfeaturedone = true

fs.writeFile('./src/data.json', JSON.stringify(extdata, null, 2), (err) => {
if (err) logger("Error in compatibilityfeature changing compatibilityfeaturedone to true! Please open 'data.json' in the 'src' folder and do this manually!\nOtherwise this will be retried on every startup. Error: " + err, true)
})

checkforupdate() //check will start the bot afterwards

} else {
if (releasemode == "beta-testing") logger("\x1b[0m[\x1b[31mNotice\x1b[0m] Your updater and bot is running in beta mode. These versions are often unfinished and can be unstable.\n If you would like to switch, open data.json and change 'beta-testing' to 'master'.\n If you find an error or bug please report it: https://github.com/HerrEurobeat/steam-comment-service-bot/issues/new/choose\n", true)
checkforupdate() //check will start the bot afterwards
Expand Down

0 comments on commit fa6d0f4

Please sign in to comment.