Guest User

Untitled

a guest
Apr 7th, 2016
1,040
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var SteamUser = require('steam-user');
  2. var SteamTotp = require('steam-totp'); //use npm install steam-totp@1.0.0 (steamcommunity has this dependancy)
  3. var SteamMobileAuth = require('steamcommunity-mobile-confirmations');
  4. var Steam = require('steam'); //use npm install steam@0.6.8 - this code isn't compatible with the latest version.
  5. var SteamTradeOffers = require('steam-tradeoffers'); //use npm install steam-tradeoffers
  6. var mysql = require('mysql');
  7. var request = require("request");
  8. var SteamCommunity = require('steamcommunity');
  9.  
  10. var community = new SteamCommunity();
  11. var steam = new Steam.SteamClient();
  12. var offers = new SteamTradeOffers();
  13.  
  14. var admin = ''; //the id of the person that can use /commands and empty the bots inventory via chat etc
  15.  
  16. //contents of mafile
  17. var TOTP_UserConfig =  ; //object containing shared_secret, identitiy_secret etc. get it by logging in the bot with this software https://github.com/Jessecar96/SteamDesktopAuthenticator/releases (after you log in you will have an mafile created, copy-paste the contents of that file here)
  18.  
  19. var client = new SteamUser();
  20. var code = SteamTotp.generateAuthCode(TOTP_UserConfig.shared_secret);
  21. var logOnOptions = {
  22.     "accountName": "",
  23.     "password": "",
  24.     "twoFactorCode": code
  25. }
  26.  
  27.  
  28. // EDIT THESE VARIABLES IN include/config.php AS WELL ON THE SITE!
  29. var GameTime = 80; //round time in seconds (recommended: 120) //should make this 3-5 seconds longer than the one in config.php
  30. var maxitems=10; //max items a player can deposit PER ROUND (recommended: 10)
  31. var maxitemsinpot=50; //max items in pot (recommended: 50)
  32. var minbet=0.03; //min value PER BET an user can deposit
  33. //if you chance one of these variables ^ and you get any kind of errors on the site you may also want to check app.js in static/js/app.js
  34. var accesspassword=''; //you can set this to whatever you want as long as its matching the same variable in include/config.php (this is used to safely access endgame.php and cost.php)
  35. var gamedbprefix='';
  36. var offerssent=[]; //as long as the bot is running it adds the game ids in this array and checks it before sending an offer (another thing to stop multiple offers...). if the bot is restarted this is emptied
  37. var itemprices={}; //as long as the bot is running it adds the item prices in this array, whenever it gets an item from this array it doesnt try to get it from the site (saves time, resources)
  38. var sitename = ""; //site url WITH NO http:// in front of it and NO forward slash ( / ) after it
  39. var steamstatusurl = 'http://'+sitename+'/steamstatus.php';
  40. var contentcreatorsurl = 'http://'+sitename+'/cc.php';
  41. var gamestarted='no';
  42.  
  43. // (HAS TO BE GENERATED ON THE BOT ACCOUNT !!!)
  44. var apik = ''; //steam api key, you can get one at https://steamcommunity.com/dev
  45. ////
  46. var prf=gamedbprefix;
  47.  
  48.  
  49.  
  50. //when first logging in the bot you will receive an authentication code via e-mail and then the bot won't be able to trade for 7 days
  51. var authCode = ''; //this is the code you'll receive via e-mail when first logging in the bot
  52. var mobileConfirmations;
  53. var globalSessionID;
  54.  
  55.  
  56. if (require('fs').existsSync('sentry_' + logOnOptions['accountName'] + '.hash')) {
  57.     logOnOptions['shaSentryfile'] = require('fs').readFileSync('sentry_' + logOnOptions['accountName'] + '.hash');
  58.  
  59. } else if (require('fs').existsSync('ssfn_' + logOnOptions['accountName'])) {
  60.     var sha = require('crypto').createHash('sha1');
  61.     sha.update(require('fs').readFileSync('ssfn_' + logOnOptions['accountName']));
  62.     var sentry = new Buffer(sha.digest(), 'binary');
  63.     logOnOptions['shaSentryfile'] = sentry;
  64.     require('fs').writeFileSync('sentry_' + logOnOptions['accountName'] + '.hash', sentry);
  65.  
  66.     myconsolelog('Converting ssfn to sentry file!');
  67.     myconsolelog('Now you can remove ssfn_' + logOnOptions['accountName']);
  68.  
  69. } else if (authCode != '') {
  70.  
  71.     logOnOptions['authCode'] = authCode;
  72.  
  73. }
  74.  
  75.  
  76.  
  77. //socket
  78. var connections=0;
  79. var app = require('express')();
  80. var http = require('http').Server(app);
  81. var io = require('socket.io')(http);
  82. io.on('connection', function(socket){
  83.  
  84.     connections=connections+1;
  85.  //   myconsolelog('[socket] a user connected. total connections: '+connections);
  86.     //
  87.  
  88.     socket.emit('handshake',1);
  89.     socket.emit('online',connections);
  90.  
  91.     request(steamstatusurl+'?pw='+accesspassword, function(error, response, body) {
  92.         //myconsolelog('steamstatus: '+body);
  93.         io.emit('steamstatus',body);
  94.     });
  95.     request(contentcreatorsurl+'?pw='+accesspassword, function(error, response, body) {
  96.         //myconsolelog('steamstatus: '+body);
  97.         io.emit('cc',body);
  98.     });
  99.  
  100.     socket.on('disconnect', function(){
  101.  
  102.         connections=connections-1;
  103. //        myconsolelog('[socket] user disconnected total connections: '+connections);
  104.         socket.emit('online',connections);
  105.  
  106.     });
  107.    
  108. });
  109. //
  110.  
  111.  
  112. var mysqlInfo; //ENABLE REMOTE MYSQL IF THE DATABASE IS HOSTED ON ANOTHER SERVER THAN THE BOT (usually the case)
  113. mysqlInfo = {
  114.     host: 'localhost',
  115.     user: '',
  116.     password: '',
  117.     database: 'needforskins',
  118.     charset: 'utf8_general_ci'
  119. };
  120.  
  121. var mysqlConnection = mysql.createConnection(mysqlInfo);
  122.  
  123. mysqlConnection.connect(function(err) {
  124.     if (err) {
  125.         myconsolelog('MYSQL ERROR. err.code: '+err.code+' (err.fatal: '+err.fatal+')');
  126.         myconsolelog('MYSQL ERROR. err.stack: '+err.stack);
  127.         return;
  128.     }
  129.  
  130.     myconsolelog('Connected to MySQL database "'+mysqlInfo['database']+'" on host "'+mysqlInfo['host']+'". Connection id: ' + mysqlConnection.threadId);
  131. });
  132.  
  133. var recheck = true;
  134.  
  135. client.logOn(logOnOptions);
  136.  
  137. client.on('debug', function(text) {
  138.     console.log(text);
  139.     require('fs').appendFile('debug.log', text + "\r\n");
  140. });
  141.  
  142.  
  143. client.on('error', function(text){
  144.         console.log('There was an error: ' + text);
  145. });
  146.  
  147. client.on('loggedOn', function(result) {
  148.         console.log('Logged in!');
  149.         client.setPersona(SteamUser.Steam.EPersonaState.LookingToTrade);
  150.            setTimeout(loadinventory,5000);
  151.  
  152.        
  153.     setTimeout(function() {
  154.         mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, rows, fields) {
  155.             if (err) return;
  156.  
  157.             mysqlConnection.query('SELECT `starttime` FROM `games` WHERE `id`=\'' + rows[0].value + '\'', function(errs, rowss, fieldss) {
  158.                 if (errs) return;
  159.  
  160.                 var timeleft;
  161.                 if (rowss[0].starttime == 2147483647) timeleft = GameTime;
  162.                 else {
  163.                     var unixtime = Math.round(new Date().getTime() / 1000.0);
  164.                     timeleft = rowss[0].starttime + GameTime - unixtime;
  165.                     if (timeleft < 0) timeleft = 0;
  166.                 }
  167.                 if (timeleft != GameTime) {
  168.                     setTimeout(EndGame, timeleft * 1000);
  169.                     io.emit('roundstart','1');
  170.                     gamestarted='yes';
  171.                     myconsolelog('Restoring game on ' + timeleft + 'second');
  172.                 }
  173.             });
  174.         });
  175.     }, 1500);
  176.        
  177.        
  178.        
  179. });
  180.  
  181. function weblogon() {
  182.         client.webLogOn();    
  183. }
  184.  
  185.  
  186. client.on('webSession', function(sessionID, cookies) {
  187.                 globalSessionID = sessionID;  
  188.                 offers.setup({
  189.                         sessionID: sessionID,
  190.                         webCookie: cookies,
  191.                         APIKey: apik
  192.                 }, function(err) {
  193.                         if (err) {
  194.                             console.log('offers.setup error: '+err);
  195.                             return;
  196.                         }
  197.                     console.log("SessionID and cookies set."+sessionID+' / '+cookies);
  198.                     /*mobileConfirmations = new SteamMobileAuth(
  199.                     {
  200.                             steamid:         TOTP_UserConfig.steamid,
  201.                             identity_secret: TOTP_UserConfig.identity_secret,
  202.                             //device_id:       TOTP_UserConfig.device_id,
  203.                             device_id:       "android:" + Date.now(),
  204.                             webCookie:       cookies
  205.                     });*/
  206.                 });
  207.  
  208.                     community.setCookies(cookies);
  209.                     community.startConfirmationChecker(25000,TOTP_UserConfig.identity_secret);
  210.  
  211.                     console.log("Mobile Conf. set-up and set cookies for community");
  212. });
  213.  
  214. setInterval(function () {
  215. console.log('checking confirmations');
  216. community.checkConfirmations();
  217. },35000);
  218.  
  219. community.on('newConfirmation',function(conf){
  220.     console.log('newConfirmation '+conf);
  221.  
  222.                         var timekey3=Math.round(Date.now() / 1000);
  223.                         var confirmationkey3 = SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, timekey3, "allow");
  224.  
  225.                             community.respondToConfirmation(conf.id,conf.key,timekey3,confirmationkey3,true,function(err){
  226.                             if(err) console.log(err);
  227.                             else conf.id+' confirmed (newConfirmation)';
  228.                         });
  229. });
  230. community.on('confKeyNeeded', function(tag, callback) {
  231.     console.log('confKeyNeeded');
  232.     var time = Math.floor(Date.now() / 1000);
  233.     callback(null, time, SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, time, tag));
  234. });
  235.  
  236. function myconsolelog(text){
  237.     console.log(text);
  238.     require('fs').appendFile('bot_debug.log', text + "\r\n");
  239. }
  240.  
  241. function getUserName(steamid) {
  242.     getUserInfo(steamid, function(error, data) {
  243.         if (error) throw error;
  244.         var datadec = JSON.parse(JSON.stringify(data.response));
  245.         return (cleanString(datadec.players[0].personaname));
  246.     });
  247. }
  248.  
  249. function proceedWinners() {
  250.     var url = 'http://' + sitename + '/endgame.php?pw='+accesspassword;
  251.     request(url, function(error, response, body) {
  252.  
  253.         myconsolelog('proceedwinners() callback response: '+body);
  254.         gamestarted='no';
  255.         io.emit('roundend',body);
  256.  
  257.     });
  258. }
  259.  
  260. function getUserInfo(steamids, callback) {
  261.     var url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + apik + '&steamids=' + steamids + '&format=json';
  262.     request({
  263.         url: url,
  264.         json: true
  265.     }, function(error, response, body) {
  266.         if (!error && response.statusCode === 200) {
  267.             callback(null, body);
  268.         } else if (error) {
  269.             getUserInfo(steamids, callback);
  270.         }
  271.     });
  272. }
  273.  
  274. function addslashes(str) {
  275.     str = str.replace(/\\/g, '\\\\');
  276.     str = str.replace(/\'/g, '\\\'');
  277.     str = str.replace(/\"/g, '\\"');
  278.     str = str.replace(/\0/g, '\\0');
  279.     return str;
  280. }
  281.  
  282. var locked = false,
  283.     proceeded;
  284. var itemscopy;
  285. var detected = false;
  286. var detected2 = false;
  287. var endtimer = -1;
  288.  
  289. function updateOffer(tradeoffer,gameid) {
  290.                                                        
  291.         var url = "https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key="+apik+"&format=json&tradeofferid="+tradeoffer+"";
  292.         request(url, function(error, response, body){
  293.                
  294.                 var sResponse = JSON.parse(body);
  295.                 var offerState = sResponse.response.offer.trade_offer_state;
  296.                 mysqlConnection.query('UPDATE `queue` SET `tradeStatus`=\''+offerState+'\' WHERE `id`=\''+gameid+'\'', function(err, row, fields) { if (err) throw err; });
  297.                 console.log("Successfully updated round #" + gameid);
  298.                
  299.         });
  300. }
  301.  
  302. function checktrade(tradeoffer,rid) {
  303.        
  304. var url = "https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key="+apik+"&format=json&tradeofferid="+tradeoffer+"";
  305. request(url, function(error, response, body){
  306.        
  307.         if (body.indexOf("trade_offer_state") != -1) {
  308.         var sResponse = JSON.parse(body);
  309.        
  310.         var offerState = sResponse.response.offer.trade_offer_state;
  311.         mysqlConnection.query('UPDATE queue SET tradeStatus="'+offerState+'" WHERE id="'+rid+'"', function(err, row, fields) { if (err) throw err; });
  312.        
  313.         if (offerState == "8") {
  314.                
  315.                 mysqlConnection.query('SELECT * FROM `queue` WHERE id="'+rid+'"', function(err, row, fields) {
  316.                 for(var i=0; i < row.length; i++) {
  317.                                
  318.                                 //Get the number of attempts
  319.                                 var attempts = row[i].attempts;
  320.                                 if (attempts == 0) {
  321.                                        
  322.                                         //If another attempt to send items not made yet set attempts to 1
  323.                                         attempts++;
  324.                                         mysqlConnection.query('UPDATE queue SET attempts='+attempts+' WHERE id="'+rid+'"', function(err, row, fields) { if (err) throw err; });
  325.                                         console.log('Updating the attempts made to send round #' + rid);
  326.                                        
  327.                                 } else {
  328.                                
  329.                                         if (attempts == 1) {
  330.                                                 //If attempts has already been made set attempts to 2
  331.                                                 mysqlConnection.query('UPDATE queue SET attempts=2 WHERE id="'+rid+'"', function(err, row, fields) { if (err) throw err; });
  332.                                                 console.log('Updating the attempts made to send round #' + rid);
  333.                                         }
  334.                                
  335.                                 }
  336.                                        
  337.                 }
  338.                 });
  339.         }
  340.        
  341.         }
  342.        
  343. });
  344. }
  345.  
  346. function sendoffers() {
  347.     myconsolelog('........');
  348.     myconsolelog('sendoffers() was called.');
  349.  
  350.     detected2 = false;
  351.     offers.loadMyInventory({
  352.         appId: 730,
  353.         contextId: 2
  354.     }, function(err, itemx) {
  355.         if (err) {
  356.             myconsolelog('Tried checking offers: ERROR 1! (error while loading own inventory). Check if steam servers are down at http://steamstat.us');
  357.             weblogon();
  358.             setTimeout(sendoffers, 2000);
  359.             return;
  360.         }
  361.         if (detected2 == true) {
  362.             myconsolelog('Tried checking offers: ERROR 2! (detected2==true) Maybe its sent already?');
  363.             return;
  364.         }
  365.         if(itemx.length>0){ //sendoffers() cant work if the bot's inventory isnt being loaded (servers down)
  366.             myconsolelog(itemx.length+' items in inventory.');
  367.         }else{
  368.             myconsolelog('WARNING! '+itemx.length+' items in inventory. The inventory may actually be empty OR steam servers are down. Check http://steamstat.us');
  369.         }
  370.         detected2 = true;
  371.         itemscopy = itemx;
  372.         detected = false;
  373.  
  374.                 //Update the Status of trades
  375.                 mysqlConnection.query('SELECT * FROM queue WHERE tradeStatus =\'2\' OR tradeStatus =\'8\' AND token !="" ORDER BY id DESC LIMIT 10', function(err, rows, fields) {
  376.                                 for (var i=0;i < rows.length; i++) {
  377.                                         var rid = rows[i].id;
  378.                                         var tradeoffer = rows[i].status.replace("sent ","");
  379.                                         checktrade(tradeoffer,rid);
  380.                                 }
  381.                                 console.log("Updating the status of trades..");
  382.                 });
  383.  
  384.         mysqlConnection.query('SELECT * FROM `queue` WHERE `status`=\'active\' ORDER BY `gameid` DESC LIMIT 1', function(err, row, fields) {
  385.             if (err) {
  386.                 myconsolelog('Tried checking offers: ERROR 3! (mysql query error: '+err.stack+')');
  387.                 return;
  388.             }
  389.             if (detected == true) {
  390.                 myconsolelog('Tried checking offers: ERROR 4! (detected==true)');
  391.                 return;
  392.             }
  393.  
  394.             detected = true;
  395. ///AUG | Chameleon (Field-Tested)/Dual Berettas | Moon in Libra (Factory New)/AK-47 | Safari Mesh (Field-Tested)/XM1014 | Blue Spruce (Field-Tested)/G3SG1 | Polar Camo (Minimal Wear)
  396.             for (var y = 0; y < row.length; y++) {
  397.                 myconsolelog('Y: '+y+' Processing offer '+row[y].id+' for game '+row[y].gameid);
  398.                 if(!in_array(row[y].gameid,offerssent)){
  399.                     if(row[y].token.length<5){
  400.                         myconsolelog('Token is: '+row[y].token+' which seems to be incorrect. Stopping the process...');
  401.                         myconsolelog('The "token" is the last part in trade url and it is 6 characters long, maybe user hasn\'t set his trade url in the database. Check user with steam id '+row[y].userid);
  402.                     }
  403.  
  404.                     var queueid = row[y].id;
  405.                     var gameid = row[y].gameid;
  406.                     var theuserid = row[y].userid;
  407.                     var thetoken = row[y].token;
  408.                     var theitems=row[y].items;
  409.  
  410.                     var sendItems = (row[y].items).split('/');
  411.                     var item = [],
  412.                         queries = [],
  413.                         itemstobesent = '',
  414.                         itemidsintheoffer = [],
  415.                         num = 0;
  416.  
  417.                     for (var x = 0; x < itemscopy.length; x++) {
  418.                         (function(z){ //fucking bullshit asynchronous crap
  419.                         mysqlConnection.query('SELECT * FROM `sentitems` WHERE `itemid`=\''+itemscopy[z].id+'\'', function(errz, rowz, fieldsz) {
  420.                             if (errz) {
  421.                                 myconsolelog('Q:'+queueid+'/G:'+gameid+'/ Error while trying to check for sent items (mysql query error: '+errz.stack+')');
  422.                                 return;
  423.                             }
  424.                             itemscopy[z].market_name=itemscopy[z].market_name.replace('★','&#9733;');
  425.                             itemscopy[z].market_name=itemscopy[z].market_name.replace('龍王','??');
  426.                             itemscopy[z].market_name=itemscopy[z].market_name.replace('壱','?');
  427.  
  428.                             var countitems=rowz.length;
  429.                                 for (var j = 0; j < sendItems.length; j++) {
  430.                                     if (itemscopy[z].tradable && (itemscopy[z].market_name).indexOf(sendItems[j]) == 0) {
  431.                                             if(!(countitems>0)){
  432.                                                     item[num] = {
  433.                                                         appid: 730,
  434.                                                         contextid: 2,
  435.                                                         amount: 1, //was itemscopy[z].amount ?
  436.                                                         assetid: itemscopy[z].id
  437.                                                     }
  438.                                                     itemstobesent=itemstobesent+''+itemscopy[z].market_name+'/';
  439.                                                     queries[num]='INSERT INTO `sentitems` (`itemid`,`name`,`gameid`,`queueid`,`userid`) VALUES ("'+itemscopy[z].id+'","'+itemscopy[z].market_name.replace('龍王','??')+'","'+gameid+'","'+queueid+'","'+theuserid+'")';
  440.                                                     myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Added '+itemscopy[z].market_name+' in the list for sending ('+queueid+'/G:'+gameid+'/Z:'+z+')');
  441.  
  442.                                                     sendItems[j] = "emptyqq";
  443.                                                     itemscopy[z].market_name = "zzzzzz";
  444.                                                     num++;
  445.  
  446.                                                 }else{
  447.                                                     myconsolelog('Q:'+queueid+'/G:'+gameid+'/Z:'+z+' '+itemscopy[z].market_name+' with id '+itemscopy[z].id+' was already sent in another offer. looking for another item...');
  448.                                                 }
  449.                                     }
  450.                                 }
  451.                             if(num==sendItems.length){
  452.                                 myconsolelog(num+'=='+sendItems.length);
  453.                                     //myconsolelog('Gone through all the items TRYING to send the offer now. Result: num: '+num+'; sendItems.length: '+sendItems.length);
  454.                                     offers.makeOffer({
  455.                                         partnerSteamId: theuserid,
  456.                                         itemsFromMe: item,
  457.                                         accessToken: thetoken,
  458.                                         itemsFromThem: [],
  459.                                         message: 'Congratulations! You won a round on '+sitename+'! These are the winnings from round #' + gameid
  460.                                     }, function(err, response) {
  461.                                             if (err) {
  462.                                             //myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+y+'(y) / '+z+'(z) / '+j+' (j) / '+x+' (x) / '+num+' (num) / '+sendItems.length+' (sendItems.length) / '+item+' (item)');
  463.                                                 myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'(ERROR) Tried sending offers: Token: '+thetoken+'; USERID: '+theuserid+'; items: '+itemstobesent+' (steam servers down? too many offers sent already? empty token (from trade link) in database? check pls). ' + err + '. https://github.com/SteamRE/SteamKit/blob/master/Resources/SteamLanguage/eresult.steamd');
  464.                                                
  465.                                                 //myconsolelog('Trying sendoffers again in 2 seconds...');
  466.                                                 //setTimeout(sendoffers, 2000);
  467.  
  468.                                                 return;
  469.                                             }
  470.                                             offerssent[gameid]=gameid; //add it to the array
  471.  
  472.                                             //myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+y+'(y) / '+z+'(z) / '+j+' (j) / '+x+' (x) / '+num+' (num) / '+sendItems.length+' (sendItems.length) / '+item+' (item)');
  473.                                             myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Trade offer ' + queueid + ' (game '+gameid+') sent! Marking items as sent in the database....');
  474.  
  475.                                             var thetheitems=theitems.replace(/\/$/, '');
  476.                                             var theitemstobesent=itemstobesent.replace(/\/$/, '');
  477.  
  478.                                             var numtheitems = (thetheitems).split('/').length;
  479.                                             var numitemstobesent = (theitemstobesent).split('/').length;
  480.  
  481.                                             if(numtheitems!=numitemstobesent){
  482.                                                 myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'WARNING !!! Sent '+numtheitems+' items! Needed to send '+numitemstobesent+'!!!');
  483.                                                 myconsolelog('Sent ('+numtheitems+'): '+thetheitems);
  484.                                                 myconsolelog('Needed to send ('+numitemstobesent+'): '+theitemstobesent);
  485.                                             }else{
  486.                                                 myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'ALL IS GOOD! Sent '+numtheitems+' items! Needed to send '+numitemstobesent+'.');
  487.                                             }
  488.                                             //myconsolelog('Tried sending: '+thetheitems+'. Ended up sending: '+theitemstobesent);
  489.  
  490.                                             for(bla=0;bla<queries.length;bla++){
  491.                                                 mysqlConnection.query(queries[bla], function (blaerr, blarows, blafields){
  492.                                                     if(blaerr) {
  493.                                                         throw blaerr;
  494.                                                     }
  495.                                                     myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'SUCCESS marking the item as sent in the database.');
  496.                                                 });
  497.                                             }
  498.  
  499.  
  500.                                             myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Calling sendoffers again in 2 seconds...');
  501.                                             setTimeout(sendoffers, 2000);
  502.                                             updateOffer(response.tradeofferid,gameid);
  503.                                             mysqlConnection.query('UPDATE `queue` SET `status`=\'sent ' + response.tradeofferid + '\' WHERE `id`=\'' + queueid + '\'', function(err, row, fields) {
  504.                                                 if (err) throw err;
  505.                                             });
  506.  
  507.                                     });
  508.  
  509.                                 num++; //avoid running this multiple times when the loop runs
  510.                             }
  511.                         });
  512.                         })(x);
  513.                     }
  514.                 }else{
  515.                     myconsolelog('Tried processing game '+row[y].gameid+' (queue '+row[y].id+') again? Check the queues in the database...');
  516.                 }
  517.             }
  518.         });
  519.     })
  520. }
  521.  
  522. function cleanString(input) {
  523.     var output = "";
  524.     for (var i=0; i<input.length; i++) {
  525.         if (input.charCodeAt(i) <= 127) {
  526.             output += input.charAt(i);
  527.         }
  528.     }
  529.     return output;
  530. }
  531.  
  532. (function() {
  533.     /**
  534.      * Decimal adjustment of a number.
  535.      *
  536.      * @param {String}  type  The type of adjustment.
  537.      * @param {Number}  value The number.
  538.      * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
  539.      * @returns {Number} The adjusted value.
  540.      */
  541.     function decimalAdjust(type, value, exp) {
  542.         // If the exp is undefined or zero...
  543.         if (typeof exp === 'undefined' || +exp === 0) {
  544.             return Math[type](value);
  545.         }
  546.         value = +value;
  547.         exp = +exp;
  548.         // If the value is not a number or the exp is not an integer...
  549.         if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
  550.             return NaN;
  551.         }
  552.         // Shift
  553.         value = value.toString().split('e');
  554.         value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  555.         // Shift back
  556.         value = value.toString().split('e');
  557.         return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  558.     }
  559.  
  560.     // Decimal round
  561.     if (!Math.round10) {
  562.         Math.round10 = function(value, exp) {
  563.             return decimalAdjust('round', value, exp);
  564.         };
  565.     }
  566.     // Decimal floor
  567.     if (!Math.floor10) {
  568.         Math.floor10 = function(value, exp) {
  569.             return decimalAdjust('floor', value, exp);
  570.         };
  571.     }
  572.     // Decimal ceil
  573.     if (!Math.ceil10) {
  574.         Math.ceil10 = function(value, exp) {
  575.             return decimalAdjust('ceil', value, exp);
  576.         };
  577.     }
  578. })();
  579.  
  580. function EndGame() {
  581.     endtimer = -1;
  582.     proceedWinners();
  583.     myconsolelog('EndGame was called... (EndGame ends the timer, proceedWinners(), sendoffers())');
  584.  
  585.     setTimeout(sendoffers, 2000);
  586.  
  587. }
  588.  
  589. function loadinventory(){
  590.     offers.loadMyInventory({
  591.         appId: 730,
  592.         contextId: 2
  593.     }, function(err, itemx) {
  594.         if (err) {
  595.             myconsolelog('Error on loading inventory. '+err+'. Calling weblogon(). Calling loadinventory again after 2 seconds... (if this persists check the api key or check if steam servers are down at http://steamstat.us)');
  596.             weblogon();
  597.             setTimeout(loadinventory,3500);
  598.             return;
  599.         }
  600.  
  601.         setTimeout(function(){ checkoffers(1); },3500);
  602.         myconsolelog('Own inventory loaded successfully. Items list in itemx var.');
  603.         if(itemx.length>0){
  604.             myconsolelog(itemx.length+' items in inventory.');
  605.         }else{
  606.             myconsolelog('WARNING! '+itemx.length+' items in inventory. The inventory may actually be empty OR steam servers are down. Check http://steamstat.us');
  607.         }
  608.  
  609.         //myconsolelog(itemx);
  610.     });
  611. }
  612.  
  613.  
  614. client.on('friendMessage', function(steamID, message) {
  615.  
  616.     if(steamID.getSteamID64() == admin) {
  617.  
  618.         if (message.indexOf("/sendallitems") == 0) {
  619.  
  620.             offers.loadMyInventory({
  621.                 appId: 730,
  622.                 contextId: 2
  623.             }, function(err, items) {
  624.  
  625.                 if (err) {
  626.                     client.chatMessage(steamID, 'Error while trying to load invenotry to send items. Calling weblogon() - try again please.');
  627.                     myconsolelog('Error while trying to load inventory to send items. Calling weblogon() - try again please.');
  628.                     weblogon();
  629.                     return;
  630.                 }
  631.  
  632.                 var item = [],
  633.                     num = 0;
  634.  
  635.                 for (var i = 0; i < items.length; i++) {
  636.                     if (items[i].tradable) {
  637.                         item[num] = {
  638.                             appid: 730,
  639.                             contextid: 2,
  640.                             amount: items[i].amount,
  641.                             assetid: items[i].id
  642.                         }
  643.                         num++;
  644.                     }
  645.                 }
  646.  
  647.                 if (num > 0) {
  648.                     offers.makeOffer({
  649.                         partnerSteamId: steamID,
  650.                         itemsFromMe: item,
  651.                         itemsFromThem: [],
  652.                         message: 'You requested all the items with the /sendallitems command.'
  653.                     }, function(err, response) {
  654.                         if (err) {
  655.                             client.chatMessage(steamID, 'Error while trying to send offer with items. Calling weblogon() - try again please.');
  656.                             myconsolelog('Error while trying to send offer with items. Calling weblogon() - try again please.');
  657.                             weblogon();
  658.                             return;
  659.                         }
  660.                         client.chatMessage(steamID, 'Trade offer with all items from the inventory sent!');
  661.                         myconsolelog('Offer from /sendallitems request sent to '+steamID);
  662.                     });
  663.  
  664.                 }
  665.             });
  666.  
  667.         } else if (message.indexOf("/send") == 0) {
  668.             var params = message.split(' ');
  669.  
  670.             if (params.length == 1) return client.chatMessage(steamID, 'Format: /send [item name]');
  671.             myconsolelog('Received /send request');
  672.  
  673.  
  674.             offers.loadMyInventory({
  675.                 appId: 730,
  676.                 contextId: 2
  677.             }, function(err, items) {
  678.  
  679.                 if (err) {
  680.                     client.chatMessage(steamID, 'Could not load the inventory. Calling weblogon() - try again please.');
  681.                     myconsolelog('Could not load the inventory. Calling weblogon() - try again please.');
  682.                     weblogon();
  683.                     return;
  684.                 }
  685.  
  686.                 var item = 0;
  687.                 for (var i = 0; i < items.length; i++) {
  688.                     if ((items[i].market_name).indexOf(params[1]) != -1) {
  689.                         item = items[i].id;
  690.                         break;
  691.                     }
  692.                 }
  693.  
  694.                 if (item != 0) {
  695.                     offers.makeOffer({
  696.                         partnerSteamId: steamID,
  697.                         itemsFromMe: [{
  698.                             appid: 730,
  699.                             contextid: 2,
  700.                             amount: 1,
  701.                             assetid: item
  702.                         }],
  703.                         itemsFromThem: [],
  704.                         message: 'You requested this item with the /send command.'
  705.                     }, function(err, response) {
  706.                         if (err) {
  707.                             throw err;
  708.                         }
  709.                         client.chatMessage(steamID, 'Trade offer with the requested item sent!');
  710.                         myconsolelog('Offer from /send request sent to '+steamID);
  711.                     });
  712.                 }else{
  713.  
  714.                     client.chatMessage(steamID, 'Couldn\'t match the item requested! /send is case sensitive!');
  715.                     myconsolelog('Couldn\'t match the item selected by '+steamID);
  716.                 }
  717.  
  718.             });
  719.  
  720.         } else if (message.indexOf("/show") == 0) {
  721.  
  722.             var params = message.split(' ');
  723.  
  724.             offers.loadMyInventory({
  725.                 appId: 730,
  726.                 contextId: 2
  727.             }, function(err, items) {
  728.  
  729.                 if (err) {
  730.                     client.chatMessage(steamID, '(2) Could not load the inventory. Calling weblogon() - try again please.');
  731.                     myconsolelog('(2) Could not load the inventory. Calling weblogon() - try again please.');
  732.                     weblogon();
  733.                     return;
  734.                 }
  735.  
  736.                 client.chatMessage(steamID, 'Items list: ');
  737.  
  738.                 for (var i = 0; i < items.length; i++) {
  739.                     client.chatMessage(steamID, 'http://steamcommunity.com/id/tradecschance1/inventory/#' + items[i].appid + '_' + items[i].contextid + '_' + items[i].id);
  740.                 }
  741.  
  742.             });
  743.  
  744.  
  745.         } else if (message.indexOf("/end") == 0) {
  746.  
  747.             client.chatMessage(steamID, 'Got request to end the game (/end)');
  748.             if (endtimer != -1) clearTimeout(endtimer);
  749.             EndGame();
  750.  
  751.         } else if (message.indexOf("/so") == 0) {
  752.  
  753.             client.chatMessage(steamID, 'Got request to send pending offers (/so)');
  754.             sendoffers();
  755.  
  756.         } else if (message.indexOf("/co") == 0) {
  757.  
  758.             client.chatMessage(steamID, 'Got request to check incomming offers (/co)');
  759.             checkoffers(1);
  760.  
  761.         } else {
  762.  
  763.             client.chatMessage(steamID, 'Available commands:\r\n/co - checks incomming offers\r\n/so - sends pending offers (calls sendoffers())\r\n/end - ends the game (clears timeout endtimer, calls EndGame())\r\n/show - displays all the items in the inventory\r\n/send [item] - sends trade offer with [item]\r\n/sendallitems - sends offer with all the items in the inventory (it breaks active offers, only use it when there are no active offers)');
  764.             myconsolelog('Displayed available commands to '+steamID);
  765.         }
  766.  
  767.     }
  768.  
  769.     getUserInfo(steamID, function(error, data) {
  770.         if (error) throw error;
  771.         var datadec = JSON.parse(JSON.stringify(data.response));
  772.         var name = datadec.players[0].personaname;
  773.         myconsolelog(name + ': ' + message); // Log it
  774.     });
  775.  
  776.     //client.chatMessage(steamID, 'I\'m a bot that accepts all your unwanted items.  If you would like to grab a few crates from me, please request a trade.');
  777. });
  778.  
  779. function in_array(needle, haystack, strict) {
  780.     var found = false,
  781.         key, strict = !!strict;
  782.  
  783.     for (key in haystack) {
  784.         if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
  785.             found = true;
  786.             break;
  787.         }
  788.     }
  789.  
  790.     return found;
  791. }
  792.  
  793. var declinedoffer=false;
  794.  
  795. var isGood = true;
  796. function getStatus() {
  797.         return isGood;
  798. }
  799.  
  800. function setStatus(data) {
  801.         isGood = data;
  802. }
  803.  
  804. function checkoffers(thenumber) {
  805.     declinedoffer=false;
  806.     myconsolelog('Checking for offers...');
  807.     if (thenumber > 0) {
  808.         offers.getOffers({
  809.             get_received_offers: 1,
  810.             active_only: 1,
  811.             get_sent_offers: 0,
  812.             get_descriptions: 1,
  813.             language: "en_us"
  814.         }, function(error, body) {
  815.            
  816.             myconsolelog('Trade offers not empty... '+thenumber);
  817.  
  818.             if (error) {
  819.                 myconsolelog('Error getting offers. Steam servers down? Error: '+error);
  820.                 return;
  821.             }
  822.             if (body.response.trade_offers_received) {
  823.  
  824.  
  825.                 body.response.trade_offers_received.forEach(function(offer) {
  826.                     if (offer.trade_offer_state == 2) {
  827.                         mysqlConnection.query('SELECT * FROM `users` WHERE `steamid`="'+offer.steamid_other+'"',function(usrerr,usrres,usrfields){
  828.                             if(usrres.length==0){
  829.                                 console.log('user does not exist in database: '+offer.steamid_other);
  830.                                 return;
  831.                             }
  832.                             var tlink=usrres[0].tlink;
  833.                             if (tlink == '') {
  834.                                 console.log('no trade link in db for user: '+offer.steamid_other);
  835.                                 return;
  836.                             }
  837.                             var tokenStr = tlink.split('token=', 2);
  838.                             var token = tokenStr[1];
  839.                            
  840.                             offers.getHoldDuration({
  841.                                 partnerSteamId:offer.steamid_other,
  842.                                 accessToken:token,
  843.                             }, function (holderr,duration) {
  844.                                 if(holderr){
  845.                                         console.log('holdduration error: '+holderr);
  846.                                         myconsolelog('Could not get trade duration for trade id '+offer.tradeofferid+'. it usually means the partner cant receive trade offers (a cooldown of some sort - like 2fa, steamguard, etc) - DECLINING OFFER');
  847.                                         offers.declineOffer({
  848.                                             tradeOfferId: offer.tradeofferid
  849.                                         });
  850.                                         declinedoffer=true;
  851.                                         var unixtime = Math.round(new Date().getTime() / 1000.0);
  852.                                         var messagedata={to:offer.steamid_other,msg:'Trade declined. It apears you can not receive trade offers. Try again later.',time:unixtime,type:'tradehold'};
  853.                                         io.emit('message',messagedata);
  854.                                         return;
  855.                                     }
  856.                                     if ((duration.my != 0) || (duration.their != 0)) {
  857.                                     myconsolelog('Trade declined because either the bot or the person sending the offer has a trade period '+offer.tradeofferid);
  858.                                     offers.declineOffer({
  859.                                         tradeOfferId: offer.tradeofferid
  860.                                     });
  861.                                     declinedoffer=true;
  862.                                     if(duration.their!=0){
  863.                                         var unixtime = Math.round(new Date().getTime() / 1000.0);
  864.                                         var messagedata={to:offer.steamid_other,msg:'Trade declined. You can not instantly trade because you are not using trade confirmations through the mobile authenticator.',time:unixtime,type:'tradehold'};
  865.                                         io.emit('message',messagedata);
  866.                                     }
  867.                                     return;
  868.                                 }
  869.                             });
  870.                     });
  871.  
  872.                     myconsolelog('Trade offer incomming...');
  873.                     myconsolelog('Trade offer id '+offer.tradeofferid+' from '+offer.steamid_other);
  874.  
  875.                         if (offer.items_to_give) {
  876.                             myconsolelog('Trade declined (items requested from the bot inventory)');
  877.                             offers.declineOffer({
  878.                                 tradeOfferId: offer.tradeofferid
  879.                             });
  880.                             return;
  881.                         }
  882.                         myconsolelog('dbg 1');
  883.  
  884.                         if (offer.items_to_receive == undefined){
  885.                             myconsolelog('Undefined items_to_receive. Retrying checkoffers...');
  886.                                weblogon();
  887.                             setTimeout(function(){ checkoffers(1) },3500);
  888.                             return;
  889.                         }
  890.                         myconsolelog('dbg 2');
  891.  
  892.                         mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
  893.                             if(err) throw err;
  894.                         myconsolelog('dbg 3');
  895.  
  896.                             var current_game = row[0].value;
  897.                             mysqlConnection.query('SELECT COUNT(*) AS `totalitems` FROM `'+prf+current_game+'`', function(totalerr, totalres, totalfields){
  898.                                 if(totalerr) throw totalerr;
  899.                                 if(totalres.totalitems>maxitemsinpot){
  900.                                             myconsolelog('Trade declined (pot reached limit)');
  901.                                             offers.declineOffer({
  902.                                                 tradeOfferId: offer.tradeofferid
  903.                                             });
  904.  
  905.                                             offer.items_to_receive = [];
  906.                                             var unixtime = Math.round(new Date().getTime() / 1000.0);
  907.                                             //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'too much items\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  908.                                            
  909.                                             var messagedata={to:offer.steamid_other,msg:'Trade declined. The pot reached the maximum limit of '+maxitemsinpot+' items. Deposit again next round.',time:unixtime,type:'toomanyitems'};
  910.                                             io.emit('message',messagedata);
  911.                                             myconsolelog('[socket] too many items message sent to '+offer.steamid_other);
  912.                                             declinedoffer=true;
  913.                                              return;
  914.                                 }else{
  915.                                     mysqlConnection.query('SELECT COUNT(*) AS `usersitems` FROM `'+prf+current_game+'` WHERE `userid`=\''+offer.steamid_other+'\'', function(errs, rows, fieldss) {
  916.                                         if(errs) throw errs;
  917.                                         myconsolelog('dbg 4');
  918.  
  919.                                         if (offer.items_to_receive.length > maxitems || offer.items_to_receive.length+rows[0].usersitems > maxitems) {
  920.  
  921.                                             myconsolelog('Trade declined (too many items)');
  922.                                             offers.declineOffer({
  923.                                                 tradeOfferId: offer.tradeofferid
  924.                                             });
  925.  
  926.                                             offer.items_to_receive = [];
  927.                                             var unixtime = Math.round(new Date().getTime() / 1000.0);
  928.                                             //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'too much items\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  929.                                            
  930.                                             var messagedata={to:offer.steamid_other,msg:'Trade declined. You offered too many items. Max '+maxitems+' items per round!',time:unixtime,type:'toomanyitems'};
  931.                                             io.emit('message',messagedata);
  932.                                             myconsolelog('[socket] too many items message sent to '+offer.steamid_other);
  933.                                             declinedoffer=true;
  934.                                             return;
  935.                                         }
  936.                                         myconsolelog('dbg 5');
  937.                                     });
  938.                                 }
  939.                             myconsolelog('dbg 5.5');
  940.                             });
  941.                         myconsolelog('dbg 6');
  942.                         });
  943.                         myconsolelog('dbg 7');
  944.                         var delock = false;
  945.  
  946.                         offers.loadPartnerInventory({
  947.                             partnerSteamId: offer.steamid_other,
  948.                             appId: 730,
  949.                             contextId: 2,
  950.                             tradeOfferId: offer.tradeofferid,
  951.                             language: "en"
  952.                         }, function(err, hitems) {
  953.                             myconsolelog('dbg 8');
  954.                             if (err) {
  955.                                 myconsolelog('Error loading partnerinventory. Calling weblogon and trying again.');
  956.                                 setTimeout(function(){ checkoffers(1) },3500);
  957.                                weblogon();
  958.                                 recheck = true;
  959.                                 return;
  960.                             }
  961.                             myconsolelog('dbg 9');
  962.                             if (delock == true) return;
  963.                             delock = true;
  964.  
  965.                             var items = offer.items_to_receive;
  966.                             var wgg = [],
  967.                                 num = 0;
  968.                             for (var i = 0; i < items.length; i++) {
  969.                                 for (var j = 0; j < hitems.length; j++) {
  970.                                     if (items[i].assetid == hitems[j].id) {
  971.                                         wgg[num] = hitems[j];
  972.                                         num++;
  973.                                         break;
  974.                                     }
  975.                                 }
  976.                             }
  977. myconsolelog('dbg 10');
  978.                             var price = [];
  979.  
  980.                             for (var i = 0; i < num; i++) {
  981.                                 if (wgg[i].appid != 730 && !declinedoffer) { //got other items than cs items
  982.  
  983.                                     myconsolelog('Trade declined (got other items than cs items)');
  984.  
  985.                                     offers.declineOffer({
  986.                                         tradeOfferId: offer.tradeofferid
  987.                                     });
  988.  
  989.                                     var unixtime = Math.round(new Date().getTime() / 1000.0);
  990.                                     //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'only csgo items\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  991.                                    
  992.                                     var messagedata={to:offer.steamid_other,msg:'Trade declined. You offered something else than CS:GO items!',time:unixtime,type:'otheritems'};
  993.                                     io.emit('message',messagedata);
  994.                                     myconsolelog('[socket] got other items than cs items message sent to '+offer.steamid_other);
  995.                                     declinedoffer=true;
  996.                                     return;
  997.                                 }
  998. myconsolelog('dbg 11');
  999.                                 if (wgg[i].market_name.indexOf("Souvenir") != -1 && !declinedoffer) {
  1000.                                     var unixtime = Math.round(new Date().getTime() / 1000.0);
  1001.  
  1002.                                     myconsolelog('Trade declined (got souvenir items)');
  1003.  
  1004.                                     offers.declineOffer({
  1005.                                         tradeOfferId: offer.tradeofferid
  1006.                                     });
  1007.  
  1008.                                     //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'You cant bet souvenir weapons\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  1009.                                    
  1010.                                     var messagedata={to:offer.steamid_other,msg:'Trade declined. You cannot deposit souvenir items!',time:unixtime,type:'souvenir'};
  1011.                                     io.emit('message',messagedata);
  1012.                                     myconsolelog('[socket] got souvenir items message sent to '+offer.steamid_other);
  1013.                                     declinedoffer=true;
  1014.                                     return;
  1015.                                 }
  1016. myconsolelog('dbg 12');
  1017. /*
  1018.                                 if (!declinedoffer && wgg[i].market_name.indexOf("Weapon Case") != -1 || wgg[i].market_name == 'Chroma 2 Case' || wgg[i].market_name == 'Chroma Case' || wgg[i].market_name == 'eSports 2013 Winter Case' || wgg[i].market_name == 'Falchion Case' || wgg[i].market_name.indexOf("Sticker Capsule") != -1) {
  1019.                                     var unixtime = Math.round(new Date().getTime() / 1000.0);
  1020.                                     offers.declineOffer({
  1021.                                         tradeOfferId: offer.tradeofferid
  1022.                                     });
  1023.                                     //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'You cant bet weapon cases\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  1024.                                     myconsolelog('Trade declined (received weapon case... ' + wgg[i].market_name+')');
  1025.  
  1026.                                     var messagedata={to:offer.steamid_other,msg:'Trade declined. You cannot deposit weapon cases!',time:unixtime,type:'weaponcase'};
  1027.                                     io.emit('message',messagedata);
  1028.                                     myconsolelog('[socket] got weapon cases message sent to '+offer.steamid_other);
  1029.                                     declinedoffer=true;
  1030.                                     return;
  1031.                                 }
  1032. */
  1033.  
  1034. myconsolelog('dbg 13');
  1035.  
  1036.                                 var itemname = wgg[i].market_name;
  1037.  
  1038.                                 var url = 'http://' + sitename + '/cost.php?pw='+accesspassword+'&item=' + encodeURIComponent(itemname);
  1039.                                 if(!declinedoffer){
  1040.                                     myconsolelog('dbg 14');
  1041.  
  1042.                                         (function(someshit) {
  1043.                                         if(!(itemname in itemprices)){
  1044.                                         request(url, function(error, response, body) {
  1045.                                             if (!error && response.statusCode === 200) {
  1046.  
  1047.                                                 var unixtime = Math.round(new Date().getTime() / 1000.0);
  1048.                                                 if (body == "notfound") {
  1049.                                                     offers.declineOffer({
  1050.                                                         tradeOfferId: offer.tradeofferid
  1051.                                                     });
  1052.                                                     myconsolelog('Trade declined. Item not found (notfound response when trying to get item cost).');
  1053.                                                     //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'Item not available \',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  1054.                                                
  1055.                                                     var messagedata={to:offer.steamid_other,msg:'Trade declined. An item you sent is unavailable ('+wgg[someshit].market_name+')!',time:unixtime,type:'itemunavailable'};
  1056.                                                     io.emit('message',messagedata);
  1057.                                                     myconsolelog('[socket] item unavailable message sent to '+offer.steamid_other);
  1058.                                                    
  1059.                                                 } else if (body == "unauthorized") {
  1060.                                                     offers.declineOffer({
  1061.                                                         tradeOfferId: offer.tradeofferid
  1062.                                                     });
  1063.                                                     myconsolelog('Trade declined. Could not get price for item (unauthorized acces when accessing cost.php on the server. Check if accesspassword variable is set accordingly in bot_source.js (see include/config.php on site)');
  1064.                                                     //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'Item not available \',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  1065.                                                
  1066.                                                     var messagedata={to:offer.steamid_other,msg:'Trade declined. Unknown error please try again or contact an administrator!',time:unixtime,type:'unauthorized'};
  1067.                                                     io.emit('message',messagedata);
  1068.                                                     myconsolelog('[socket] item cost unknown error message sent to '+offer.steamid_other);
  1069.                                                    
  1070.                                                 } else {
  1071.                                                     wgg[someshit].cost = parseFloat(body);
  1072.                                                    
  1073.                                                     itemprices[wgg[someshit].market_name]=wgg[someshit].cost;
  1074.  
  1075.                                                     myconsolelog('Got item price from site: ' + wgg[someshit].market_name + ' = ' + body);
  1076.  
  1077.  
  1078.                                                 }
  1079.                                             } else {
  1080.                                                 offers.declineOffer({
  1081.                                                     tradeOfferId: offer.tradeofferid
  1082.                                                 });
  1083.                                             myconsolelog('Declined offer (error on getting price on ' + wgg[someshit].market_name + ')');
  1084.  
  1085.                                             var messagedata={to:offer.steamid_other,msg:'Trade declined. We could not get the price on one of your items ('+wgg[someshit].market_name+')!',time:unixtime,type:'priceerror'};
  1086.                                             io.emit('message',messagedata);
  1087.                                             myconsolelog('[socket] couldnt get price on item message sent to '+offer.steamid_other);
  1088.                                                    
  1089.                                             }
  1090.                                         });
  1091.                                         }else{
  1092.                                             myconsolelog('Got item price from local array. '+wgg[someshit].market_name+' = '+itemprices[wgg[someshit].market_name]);
  1093.                                             wgg[someshit].cost=parseFloat(itemprices[wgg[someshit].market_name]);
  1094.                                         }
  1095.                                     })(i)
  1096.                                 }else{
  1097.                                     myconsolelog('dbg 15');
  1098.                                     myconsolelog('declinedoffer is true apparently? declinedoffer: '+declinedoffer)
  1099.                                     return;
  1100.                                 }
  1101.                             }
  1102.                             if(!declinedoffer)
  1103.                             setTimeout(function() { // UNDEFINED PRICES? LOOK AT THIS! ITS GLIZDA!
  1104.                                 myconsolelog('Timeout step 1...');
  1105.                                 var sum = 0;
  1106.                                 for (var i = 0; i < num; i++) {
  1107.                                     sum += wgg[i].cost;
  1108.                                 }
  1109.                                 myconsolelog('Timeout step 1.2...');
  1110.  
  1111.                                 if (sum < minbet && !declinedoffer) {
  1112.                                         num = 0;
  1113.                                         var unixtime = Math.round(new Date().getTime() / 1000.0);
  1114.                                         offers.declineOffer({
  1115.                                             tradeOfferId: offer.tradeofferid
  1116.                                         });
  1117.                                         myconsolelog('Trade declined, value was too small.');
  1118.  
  1119.                                         //mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'Value is too small. ' + sum + '<' + row[0].value + '\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
  1120.                                        
  1121.                                         var messagedata={to:offer.steamid_other,msg:'Trade declined. The value of your items was too small ($'+sum+')! Min $'+minbet+' per bet.',time:unixtime,type:'priceerror'};
  1122.                                         io.emit('message',messagedata);
  1123.                                         myconsolelog('[socket] value too small message sent to '+offer.steamid_other);
  1124.                                         declinedoffer=true;
  1125.  
  1126.                                         return;
  1127.                                 }
  1128.                                 myconsolelog('Timeout step 1.3... (next: getuserinfo) - if this hangs up too long then steam servers are probably fucking up: getUserInfo('+offer.steamid_other);
  1129.  
  1130.                                 getUserInfo(offer.steamid_other, function(error, data) {
  1131.                                     myconsolelog('Timeout step 1.4...');
  1132.                                     if (error) throw error;
  1133.                                     myconsolelog('Timeout step 2...');
  1134.  
  1135.                                     var datadec = JSON.parse(JSON.stringify(data.response));
  1136.                                     var name = addslashes(cleanString(datadec.players[0].personaname));
  1137.                                     var avatar = (datadec.players[0].avatarfull);
  1138.                                     if (num == 0) return;
  1139.                                     offers.acceptOffer({
  1140.                                         tradeOfferId: offer.tradeofferid
  1141.                                     }, function(err, response) {
  1142.                                         if (err != null){
  1143.                                         myconsolelog('Erorr while accepting offer (?) Calling weblogon and checking offers again in 2 seconds...'+err);
  1144.                                weblogon();
  1145.                             setTimeout(function(){ checkoffers(1) },2000);
  1146.                                        return;
  1147.                                      }
  1148.                                         myconsolelog('Accepted trade offer #' + offer.tradeofferid + ' by ' + name + ' (' + offer.steamid_other + ')');
  1149.  
  1150.                                         mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
  1151.                                             if(err) throw err;
  1152.                                             var restosocket={};
  1153.                                             restosocket.newitems=[];
  1154.  
  1155.                                             var current_game = row[0].value;
  1156.  
  1157.                                             restosocket.current_game = current_game;
  1158.  
  1159.                                             mysqlConnection.query('SELECT `totalvalue`,`itemsnum` FROM `games` WHERE `id`=\'' + current_game + '\'', function(err1, row1, fields1) {
  1160.                                                 var current_bank = parseFloat(row1[0].totalvalue);
  1161.                                                 var itemsnum = row1[0].itemsnum;
  1162.  
  1163.                                               for (var j = 0; j < num; j++) {
  1164.  
  1165.                                                      restosocket.newitems[j]={};
  1166.                                                      var qualityclasssplit=wgg[j].type.split(' ');
  1167.                                                      var qc=qualityclasssplit[0].toLowerCase();
  1168.                                                      var qcdb;
  1169.                                                     /* consumer, industrial, mil-spec, restricted, classified, covert, knife, contraband */
  1170.  
  1171.                                                      if(qc=='consumer' || qc=='base'){
  1172.                                                         qcdb='1consumer';
  1173.                                                      }else if (qc=='industrial'){
  1174.                                                         qcdb='2industrial';
  1175.                                                      }else if (qc=='mil-spec'){
  1176.                                                         qcdb='3mil-spec';
  1177.                                                      }else if (qc=='restricted'){
  1178.                                                         qcdb='4restricted';
  1179.                                                      }else if (qc=='classified'){
  1180.                                                         qcdb='5classified';
  1181.                                                      }else if (qc=='covert'){
  1182.                                                         qcdb='6covert';
  1183.                                                      }else if (qc=='★'){
  1184.                                                         qcdb='7knife';
  1185.                                                         wgg[j].market_name=wgg[j].market_name.replace('★','&#9733;');
  1186.                                                      }else if (qc=='contraband'){
  1187.                                                         qcdb='9contraband';
  1188.                                                      }else{
  1189.                                                         qcdb='1consumer';
  1190.                                                      }
  1191.  
  1192.                                                     mysqlConnection.query('INSERT INTO `'+prf + current_game + '` (`userid`,`offerid`,`username`,`item`,`qualityclass`,`color`,`value`,`avatar`,`image`,`from`,`to`) VALUES (\'' + offer.steamid_other + '\',\''+offer.tradeofferid+'\',\'' + name + '\',\'' + wgg[j].market_name + '\',\''+qcdb+'\',\'' + wgg[j].name_color + '\',\'' + wgg[j].cost + '\',\'' + avatar + '\',\'' + wgg[j].icon_url + '\',\'' + current_bank + '\'+\'0\',\'' + current_bank + '\'+\'' + wgg[j].cost + '\')', function(err, row, fields) {});
  1193.                                                     mysqlConnection.query('UPDATE `games` SET `itemsnum`=`itemsnum`+1, `totalvalue`=`totalvalue`+\'' + wgg[j].cost + '\' WHERE `id` = \'' + current_game + '\'', function(err, row, fields) {});
  1194.                                                     restosocket.newitems[j]={currentgame:current_game,userid:offer.steamid_other,offerid:offer.tradeofferid,username:name,item:wgg[j].market_name,qualityclass:qcdb,color:wgg[j].name_color,cost:wgg[j].cost,avatar:avatar,icon:wgg[j].icon_url};
  1195.                                                    
  1196.                                                     current_bank = parseFloat(current_bank + wgg[j].cost);
  1197.                                                     itemsnum++;
  1198.                                                 }
  1199.                                                 restosocket.current_bank = current_bank;
  1200.                                                 restosocket.itemsnum = itemsnum;
  1201.                                                      
  1202.                                                 mysqlConnection.query('SELECT COUNT(DISTINCT userid) AS playerscount FROM `'+prf + current_game+'`', function(err, rows) {
  1203.                                                     if(err) throw err;
  1204.                                                     var playerscount = rows[0].playerscount;
  1205.                                                     myconsolelog('Current Players: ' + playerscount);
  1206.  
  1207.  
  1208.  
  1209.                                                     if (playerscount == 1 && items.length > 0 && gamestarted==='no') { //STARTING GAME
  1210.                                                         myconsolelog('Game started var: '+gamestarted);
  1211.                                                         myconsolelog('Found 2 Players... Starting game.');
  1212.                                                         endtimer = setTimeout(EndGame, GameTime * 1000);
  1213.  
  1214.                                                         io.emit('roundstart','1');
  1215.                                                         gamestarted='yes';
  1216.  
  1217.                                                         mysqlConnection.query('UPDATE `games` SET `starttime`=UNIX_TIMESTAMP() WHERE `id` = \'' + current_game + '\'', function(err3, row3, fields3) {});
  1218.  
  1219.                                                         var gamestartmessage;
  1220.                                                         mysqlConnection.query('SELECT * FROM `games` WHERE `id`=\''+current_game+'\'', function(err6,row6,fields6){
  1221.                                                             if(err6) throw err6;
  1222.  
  1223.                                                             var gamestartedstarttime=row6.starttime;
  1224.  
  1225.                                                         });
  1226.  
  1227.                                                         myconsolelog('[socket] game start info sent to everyone');
  1228.                                                     }else{
  1229.                                                         myconsolelog('Game started var: '+gamestarted);
  1230.                                                         gamestarted='no';
  1231.                                                         var gamestartedstarttime=2147483647;
  1232.                                                     }
  1233.  
  1234.                                                     restosocket.playersnum=playerscount;
  1235.                                                     restosocket.gamestarted=gamestarted;
  1236.                                                     restosocket.gamestartedstarttime=gamestartedstarttime;
  1237.  
  1238.                                                     io.emit('roundupdate',JSON.stringify(restosocket));
  1239.                                                     io.emit('online',connections);
  1240.  
  1241.                                                     myconsolelog('[socket] sent game update & updated online count '+connections);
  1242.                                                 });
  1243.  
  1244.                                                 if (itemsnum > 50 || itemsnum == 50) {
  1245.                                                     myconsolelog('Hit ' + itemsnum + ' items... Not ending the game atm cause roulette is bugged.');
  1246.                                                 }
  1247.  
  1248.                                                 myconsolelog('Accepted (CONFIRMATION) trade offer #' + offer.tradeofferid + ' by ' + name + ' (' + offer.steamid_other + ')');
  1249.  
  1250.  
  1251.  
  1252.                                        
  1253.                                             });
  1254.                                         });
  1255.                                     });
  1256.                                 });
  1257.  
  1258.  
  1259.                             }, 3500);
  1260.  
  1261.                         });
  1262.                     }
  1263.                         /*}else{
  1264.                             myconsolelog('Trade declined because either the bot or the person sending the offer has a trade period');
  1265.                             offers.declineOffer({
  1266.                                 tradeOfferId: offer.tradeofferid
  1267.                             });
  1268.                             if(duration.their!=0){
  1269.                                 var unixtime = Math.round(new Date().getTime() / 1000.0);
  1270.                                 var messagedata={to:offer.steamid_other,msg:'Trade declined. You can not instantly trade because you are not using trade confirmations through the mobile authenticator.',time:unixtime,type:'tradehold'};
  1271.                                 io.emit('message',messagedata);
  1272.                             }
  1273.                         } }); });*/
  1274.                });
  1275.             }
  1276.         });
  1277.     }else{
  1278.         myconsolelog('No offers? number: '+thenumber);
  1279.     }
  1280. }
  1281.  
  1282. function currentstate(current_game){
  1283.     var res;
  1284.     mysqlConnection.query('SELECT * FROM `games` WHERE `id`=\''+current_game+'\'', function(err,row,fields){
  1285.         if(err) throw err;
  1286.  
  1287.         mysqlConnection.query('SELECT * FROM `\''+prf+current_game+'\'', function(err2,row2,fields2){
  1288.  
  1289.         });
  1290.     });
  1291.  
  1292.     return res;
  1293. }
  1294.  
  1295.  
  1296. var pew;
  1297. client.on('tradeOffers', checkoffers);
  1298.  
  1299. client.on('sentry', function(data) {
  1300.     require('fs').writeFileSync('sentry_' + logOnOptions['accountName'] + '.hash', data);
  1301. });
  1302.  
  1303. setInterval(function() {
  1304.     mysqlConnection.query('SELECT 1');
  1305. }, 5000);
  1306.  
  1307.  
  1308. setInterval(function(){
  1309.     request(steamstatusurl+'?pw='+accesspassword, function(error, response, body) {
  1310.         //myconsolelog('steamstatus: '+body);
  1311.         io.emit('steamstatus',body);
  1312.     });
  1313.     request(contentcreatorsurl+'?pw='+accesspassword, function(error, response, body) {
  1314.         //myconsolelog('steamstatus: '+body);
  1315.         io.emit('cc',body);
  1316.     });
  1317. }, 30000);
  1318.  
  1319.  
  1320. //sock
  1321. http.listen(3000, function(){
  1322.   myconsolelog("\r\n\r\n"+'[socket] Listening on *:3000');
  1323. });
Add Comment
Please, Sign In to add comment