Guest User

Untitled

a guest
Jul 5th, 2016
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 74.06 KB | None | 0 0
  1. var SteamUser = require('steam-user');
  2. var SteamTotp = require('steam-totp');
  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@1.2.3 - this code isn't compatible with the latest version.
  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 = {"steamid":"","steamguard_scheme":"2","shared_secret":"","status":1,"revocation_code":"","secret_1":"","server_time":"1461216042","identity_secret":"","uri":"","token_gid":"","serial_number":"","account_name":""} //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=100; //round time in seconds (recommended: 120) //should make this 3-5 seconds longer than the one in config.php
  30. var maxitems=25; //max items a player can deposit PER ROUND (recommended: 10)
  31. var maxitemsinpot=100; //max items in pot (recommended: 50)
  32. var minbet=0.01; //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='z_round_';
  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: '',
  115. user: '',
  116. password: '',
  117. database: '',
  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.  
  154. setTimeout(function() {
  155. mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, rows, fields) {
  156. if (err) return;
  157.  
  158. mysqlConnection.query('SELECT `starttime` FROM `games` WHERE `id`=\'' + rows[0].value + '\'', function(errs, rowss, fieldss) {
  159. if (errs) return;
  160.  
  161. var timeleft;
  162. if (rowss[0].starttime == 2147483647) timeleft = GameTime;
  163. else {
  164. var unixtime = Math.round(new Date().getTime() / 1000.0);
  165. timeleft = rowss[0].starttime + GameTime - unixtime;
  166. if (timeleft < 0) timeleft = 0;
  167. }
  168. if (timeleft != GameTime) {
  169. setTimeout(EndGame, timeleft * 1000);
  170. io.emit('roundstart','1');
  171. gamestarted='yes';
  172. myconsolelog('Restoring game on ' + timeleft + 'second');
  173. }
  174. });
  175. });
  176. weblogon();
  177. }, 1500);
  178.  
  179.  
  180. });
  181.  
  182. function weblogon() {
  183. client.webLogOn();
  184. }
  185.  
  186.  
  187. client.on('webSession', function(sessionID, cookies) {
  188. console.log('received websession: '+sessionID+' / '+cookies);
  189. globalSessionID = sessionID;
  190. offers.setup({
  191. sessionID: sessionID,
  192. webCookie: cookies,
  193. APIKey: apik
  194. }, function(err) {
  195. if (err) {
  196. console.log('offers.setup error: '+err);
  197. return;
  198. }
  199. console.log("SessionID and cookies set."+sessionID+' / '+cookies);
  200. /*mobileConfirmations = new SteamMobileAuth(
  201. {
  202. steamid: TOTP_UserConfig.steamid,
  203. identity_secret: TOTP_UserConfig.identity_secret,
  204. //device_id: TOTP_UserConfig.device_id,
  205. device_id: "android:" + Date.now(),
  206. webCookie: cookies
  207. });*/
  208. });
  209.  
  210.  
  211. community.setCookies(cookies);
  212.  
  213. community.startConfirmationChecker(25000,TOTP_UserConfig.identity_secret);
  214.  
  215. console.log("Mobile Conf. set-up and set cookies for community"+cookies);
  216. });
  217.  
  218. /*
  219.  
  220. client.on('loggedOn', function(result) {
  221. myconsolelog('Logged in on Steam!');
  222. steam.setPersonaState(Steam.EPersonaState.LookingToTrade);
  223. steam.addFriend(admin);
  224. client.chatMessage(admin, "I'm online now.");
  225. loadinventory();
  226. });
  227.  
  228. client.on('webSessionID', function(sessionID) {
  229. globalSessionID = sessionID;
  230. weblogon();
  231. setTimeout(function() {
  232. mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, rows, fields) {
  233. if (err) return;
  234.  
  235. mysqlConnection.query('SELECT `starttime` FROM `games` WHERE `id`=\'' + rows[0].value + '\'', function(errs, rowss, fieldss) {
  236. if (errs) return;
  237.  
  238. var timeleft;
  239. if (rowss[0].starttime == 2147483647) timeleft = GameTime;
  240. else {
  241. var unixtime = Math.round(new Date().getTime() / 1000.0);
  242. timeleft = rowss[0].starttime + GameTime - unixtime;
  243. if (timeleft < 0) timeleft = 0;
  244. }
  245. if (timeleft != GameTime) {
  246. setTimeout(EndGame, timeleft * 1000);
  247. io.emit('roundstart','1');
  248. gamestarted='yes';
  249. myconsolelog('Restoring game on ' + timeleft + 'second');
  250. }
  251. });
  252. });
  253. }, 1500);
  254. });
  255.  
  256. function weblogon() {
  257. steam.webLogOn(function(newCookie) {
  258. offers.setup({
  259. sessionID: globalSessionID,
  260. webCookie: newCookie
  261. }, function(err) {
  262. if (err) {}
  263. });
  264. });
  265. }
  266.  
  267. */
  268.  
  269. setInterval(function () {
  270. //console.log("Auth key: "+SteamTotp.generateAuthCode(TOTP_UserConfig.shared_secret));
  271. /*
  272. if (mobileConfirmations) {
  273. mobileConfirmations.FetchConfirmations(function (err, confirmations) {
  274. if (err) {
  275. console.log('FetchConfirmations error: '+err);
  276. weblogon();
  277. return;
  278. }
  279. console.log('mobileConfirmations.FetchConfirmations received ' + confirmations.length + ' confirmations');
  280. if (confirmations.length > 0) {
  281. if ( ! confirmations.length)
  282. {
  283. return;
  284. }
  285. mobileConfirmations.AcceptConfirmation(confirmations[0], function (err, result){
  286. if (err) {
  287. console.log('acc confirmation err: '+err);
  288. return;
  289. }
  290. console.log('mobileConfirmations.AcceptConfirmation result: ' + result);
  291. });
  292. };
  293. });
  294. }*/
  295. /*
  296. community.getConfirmations(function ( err, conf ) { //if this doesnt confirm it try the code above
  297. if ( err ) {
  298. console.log('community.getConfirmations error: '+err);
  299. } else {
  300. conf.forEach(function ( item ) {
  301. item.respond(security.getAllowKey().time, security.getAllowKey().key, true, function () {
  302.  
  303. });
  304. })
  305. }
  306. });*/
  307. /*
  308. var time_conf = Math.floor(Date.now() / 1000);
  309. var key_conf = SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, time_conf, 'conf');
  310.  
  311. community.getConfirmations(time_conf, key_conf, function (err, confirmations) {
  312. if (err) { logger.error(err); return; }
  313. console.log('confirmations:');
  314. console.log(confirmations);
  315.  
  316. var time_details = Math.floor(Date.now() / 1000);
  317. var key_details = SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, time_details, 'details');
  318.  
  319. confirmations.forEach(function(confirmation) {
  320. confirmation.getOfferID(time_details, key_details, function(err, offerID) {
  321. if (err) { logger.error(err); return; }
  322. console.log('offerid: '+offerID);
  323. confirmation.respond(time_details,key_details,true,function(err){
  324. if(err) console.log('confirmation.respond err: '+err);
  325. });
  326. });
  327. });
  328. });*/
  329. console.log('checking confirmations');
  330. community.checkConfirmations();
  331. /*
  332. var timekey=Math.round(Date.now() / 1000);
  333. var confirmationkey = SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, timekey, "conf");
  334.  
  335. community.getConfirmations(timekey, confirmationkey, function(err2,confirmations){
  336. if(err2){
  337. console.log(err2);
  338. }else{
  339. console.log(confirmations); //Gives '[]' even if there are waiting trades
  340. confirmations.forEach(function(conf,index,array){
  341. setTimeout(function(conf){
  342. var timekey2=Math.round(Date.now() / 1000);
  343. var confirmationkey2 = SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, timekey2, "allow");
  344.  
  345. community.respondToConfirmation(conf.id,conf.key,timekey2,confirmationkey2,true,function(err){
  346. if(err) console.log(err);
  347. else conf.id+' confirmed';
  348. });
  349. },index*1500,conf);
  350. });
  351. }
  352. });
  353. */
  354.  
  355. },25000);
  356.  
  357. community.on('newConfirmation',function(conf){
  358. console.log('newConfirmation '+conf);
  359.  
  360. var timekey3=Math.round(Date.now() / 1000);
  361. var confirmationkey3 = SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, timekey3, "allow");
  362.  
  363. community.respondToConfirmation(conf.id,conf.key,timekey3,confirmationkey3,true,function(err){
  364. if(err) console.log(err);
  365. else conf.id+' confirmed (newConfirmation)';
  366. });
  367. });
  368. community.on('confKeyNeeded', function(tag, callback) {
  369. console.log('confKeyNeeded');
  370. var time = Math.floor(Date.now() / 1000);
  371. callback(null, time, SteamTotp.getConfirmationKey(TOTP_UserConfig.identity_secret, time, tag));
  372. });
  373.  
  374. function myconsolelog(text){
  375. console.log(text);
  376. require('fs').appendFile('bot_debug.log', text + "\r\n");
  377. }
  378.  
  379. function getUserName(steamid) {
  380. getUserInfo(steamid, function(error, data) {
  381. if (error) throw error;
  382. var datadec = JSON.parse(JSON.stringify(data.response));
  383. return (cleanString(datadec.players[0].personaname));
  384. });
  385. }
  386.  
  387. function proceedWinners() {
  388. var url = 'http://' + sitename + '/endgame.php?pw='+accesspassword;
  389. request(url, function(error, response, body) {
  390.  
  391. myconsolelog('proceedwinners() callback response: '+body);
  392. gamestarted='no';
  393. io.emit('roundend',body);
  394.  
  395. });
  396. }
  397.  
  398. function getUserInfo(steamids, callback) {
  399. var url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + apik + '&steamids=' + steamids + '&format=json';
  400. request({
  401. url: url,
  402. json: true
  403. }, function(error, response, body) {
  404. if (!error && response.statusCode === 200) {
  405. callback(null, body);
  406. } else if (error) {
  407. getUserInfo(steamids, callback);
  408. }
  409. });
  410. }
  411.  
  412. function addslashes(str) {
  413. str = str.replace(/\\/g, '\\\\');
  414. str = str.replace(/\'/g, '\\\'');
  415. str = str.replace(/\"/g, '\\"');
  416. str = str.replace(/\0/g, '\\0');
  417. return str;
  418. }
  419.  
  420. var locked = false,
  421. proceeded;
  422. var itemscopy;
  423. var detected = false;
  424. var detected2 = false;
  425. var endtimer = -1;
  426.  
  427. function updateOffer(tradeoffer,gameid) {
  428.  
  429. var url = "https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key="+apik+"&format=json&tradeofferid="+tradeoffer+"";
  430. request(url, function(error, response, body){
  431.  
  432. var sResponse = JSON.parse(body);
  433. var offerState = sResponse.response.offer.trade_offer_state;
  434. mysqlConnection.query('UPDATE `queue` SET `tradeStatus`=\''+offerState+'\' WHERE `id`=\''+gameid+'\'', function(err, row, fields) { if (err) throw err; });
  435. console.log("Successfully updated round #" + gameid);
  436.  
  437. });
  438. }
  439.  
  440. function checktrade(tradeoffer,rid) {
  441.  
  442. var url = "https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key="+apik+"&format=json&tradeofferid="+tradeoffer+"";
  443. request(url, function(error, response, body){
  444.  
  445. if (body.indexOf("trade_offer_state") != -1) {
  446. var sResponse = JSON.parse(body);
  447.  
  448. var offerState = sResponse.response.offer.trade_offer_state;
  449. mysqlConnection.query('UPDATE queue SET tradeStatus="'+offerState+'" WHERE id="'+rid+'"', function(err, row, fields) { if (err) throw err; });
  450.  
  451. if (offerState == "8") {
  452.  
  453. mysqlConnection.query('SELECT * FROM `queue` WHERE id="'+rid+'"', function(err, row, fields) {
  454. for(var i=0; i < row.length; i++) {
  455.  
  456. //Get the number of attempts
  457. var attempts = row[i].attempts;
  458. if (attempts == 0) {
  459.  
  460. //If another attempt to send items not made yet set attempts to 1
  461. attempts++;
  462. mysqlConnection.query('UPDATE queue SET attempts='+attempts+' WHERE id="'+rid+'"', function(err, row, fields) { if (err) throw err; });
  463. console.log('Updating the attempts made to send round #' + rid);
  464.  
  465. } else {
  466.  
  467. if (attempts == 1) {
  468. //If attempts has already been made set attempts to 2
  469. mysqlConnection.query('UPDATE queue SET attempts=2 WHERE id="'+rid+'"', function(err, row, fields) { if (err) throw err; });
  470. console.log('Updating the attempts made to send round #' + rid);
  471. }
  472.  
  473. }
  474.  
  475. }
  476. });
  477. }
  478.  
  479. }
  480.  
  481. });
  482. }
  483.  
  484. function sendoffers() {
  485. myconsolelog('........');
  486. myconsolelog('sendoffers() was called.');
  487.  
  488. detected2 = false;
  489. offers.loadMyInventory({
  490. appId: 730,
  491. contextId: 2
  492. }, function(err, itemx) {
  493. if (err) {
  494. myconsolelog('Tried checking offers: ERROR 1! (error while loading own inventory). Check if steam servers are down at http://steamstat.us');
  495. weblogon();
  496. setTimeout(sendoffers, 2000);
  497. return;
  498. }
  499. if (detected2 == true) {
  500. myconsolelog('Tried checking offers: ERROR 2! (detected2==true) Maybe its sent already?');
  501. return;
  502. }
  503. if(itemx.length>0){ //sendoffers() cant work if the bot's inventory isnt being loaded (servers down)
  504. myconsolelog(itemx.length+' items in inventory.');
  505. }else{
  506. myconsolelog('WARNING! '+itemx.length+' items in inventory. The inventory may actually be empty OR steam servers are down. Check http://steamstat.us');
  507. }
  508. detected2 = true;
  509. itemscopy = itemx;
  510. detected = false;
  511.  
  512. //Update the Status of trades
  513. mysqlConnection.query('SELECT * FROM queue WHERE tradeStatus =\'2\' OR tradeStatus =\'8\' AND token !="" ORDER BY id DESC LIMIT 10', function(err, rows, fields) {
  514. for (var i=0;i < rows.length; i++) {
  515. var rid = rows[i].id;
  516. var tradeoffer = rows[i].status.replace("sent ","");
  517. checktrade(tradeoffer,rid);
  518. }
  519. console.log("Updating the status of trades..");
  520. });
  521.  
  522. mysqlConnection.query('SELECT * FROM `queue` WHERE `status`=\'active\' ORDER BY `gameid` DESC LIMIT 1', function(err, row, fields) {
  523. if (err) {
  524. myconsolelog('Tried checking offers: ERROR 3! (mysql query error: '+err.stack+')');
  525. return;
  526. }
  527. if (detected == true) {
  528. myconsolelog('Tried checking offers: ERROR 4! (detected==true)');
  529. return;
  530. }
  531.  
  532. detected = true;
  533. ///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)
  534. for (var y = 0; y < row.length; y++) {
  535. myconsolelog('Y: '+y+' Processing offer '+row[y].id+' for game '+row[y].gameid);
  536. if(!in_array(row[y].gameid,offerssent)){
  537. if(row[y].token.length<5){
  538. myconsolelog('Token is: '+row[y].token+' which seems to be incorrect. Stopping the process...');
  539. 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);
  540. }
  541.  
  542. var queueid = row[y].id;
  543. var gameid = row[y].gameid;
  544. var theuserid = row[y].userid;
  545. var thetoken = row[y].token;
  546. var theitems=row[y].items;
  547.  
  548. var sendItems = (row[y].items).split('/');
  549. var item = [],
  550. queries = [],
  551. itemstobesent = '',
  552. itemidsintheoffer = [],
  553. num = 0;
  554.  
  555. for (var x = 0; x < itemscopy.length; x++) {
  556. (function(z){ //fucking bullshit asynchronous crap
  557. mysqlConnection.query('SELECT * FROM `sentitems` WHERE `itemid`=\''+itemscopy[z].id+'\'', function(errz, rowz, fieldsz) {
  558. if (errz) {
  559. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ Error while trying to check for sent items (mysql query error: '+errz.stack+')');
  560. return;
  561. }
  562. itemscopy[z].market_name=itemscopy[z].market_name.replace('★','&#9733;');
  563. itemscopy[z].market_name=itemscopy[z].market_name.replace('龍王','??');
  564. itemscopy[z].market_name=itemscopy[z].market_name.replace('壱','?');
  565.  
  566. var countitems=rowz.length;
  567. for (var j = 0; j < sendItems.length; j++) {
  568. if (itemscopy[z].tradable && (itemscopy[z].market_name).indexOf(sendItems[j]) == 0) {
  569. if(!(countitems>0)){
  570. item[num] = {
  571. appid: 730,
  572. contextid: 2,
  573. amount: 1, //was itemscopy[z].amount ?
  574. assetid: itemscopy[z].id
  575. }
  576. itemstobesent=itemstobesent+''+itemscopy[z].market_name+'/';
  577. queries[num]='INSERT INTO `sentitems` (`itemid`,`name`,`gameid`,`queueid`,`userid`) VALUES ("'+itemscopy[z].id+'","'+itemscopy[z].market_name.replace('龍王','??')+'","'+gameid+'","'+queueid+'","'+theuserid+'")';
  578. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Added '+itemscopy[z].market_name+' in the list for sending ('+queueid+'/G:'+gameid+'/Z:'+z+')');
  579.  
  580. sendItems[j] = "empty";
  581. itemscopy[z].market_name = "zzzzagain";
  582. num++;
  583.  
  584. }else{
  585. 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...');
  586. }
  587. }
  588. }
  589. if(num==sendItems.length){
  590. myconsolelog(num+'=='+sendItems.length);
  591. //myconsolelog('Gone through all the items TRYING to send the offer now. Result: num: '+num+'; sendItems.length: '+sendItems.length);
  592. offers.makeOffer({
  593. partnerSteamId: theuserid,
  594. itemsFromMe: item,
  595. accessToken: thetoken,
  596. itemsFromThem: [],
  597. message: 'Congratulations! You won a round on '+sitename+'! These are the winnings from round #' + gameid
  598. }, function(err, response) {
  599. if (err) {
  600. //myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+y+'(y) / '+z+'(z) / '+j+' (j) / '+x+' (x) / '+num+' (num) / '+sendItems.length+' (sendItems.length) / '+item+' (item)');
  601. 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');
  602.  
  603. //myconsolelog('Trying sendoffers again in 2 seconds...');
  604. //setTimeout(sendoffers, 2000);
  605.  
  606. return;
  607. }
  608. offerssent[gameid]=gameid; //add it to the array
  609.  
  610. //myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+y+'(y) / '+z+'(z) / '+j+' (j) / '+x+' (x) / '+num+' (num) / '+sendItems.length+' (sendItems.length) / '+item+' (item)');
  611. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Trade offer ' + queueid + ' (game '+gameid+') sent! Marking items as sent in the database....');
  612.  
  613. var thetheitems=theitems.replace(/\/$/, '');
  614. var theitemstobesent=itemstobesent.replace(/\/$/, '');
  615.  
  616. var numtheitems = (thetheitems).split('/').length;
  617. var numitemstobesent = (theitemstobesent).split('/').length;
  618.  
  619. if(numtheitems!=numitemstobesent){
  620. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'WARNING !!! Sent '+numtheitems+' items! Needed to send '+numitemstobesent+'!!!');
  621. myconsolelog('Sent ('+numtheitems+'): '+thetheitems);
  622. myconsolelog('Needed to send ('+numitemstobesent+'): '+theitemstobesent);
  623. }else{
  624. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'ALL IS GOOD! Sent '+numtheitems+' items! Needed to send '+numitemstobesent+'.');
  625. }
  626. //myconsolelog('Tried sending: '+thetheitems+'. Ended up sending: '+theitemstobesent);
  627.  
  628. for(bla=0;bla<queries.length;bla++){
  629. mysqlConnection.query(queries[bla], function (blaerr, blarows, blafields){
  630. if(blaerr) {
  631. throw blaerr;
  632. }
  633. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'SUCCESS marking the item as sent in the database.');
  634. });
  635. }
  636.  
  637.  
  638. myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Calling sendoffers again in 2 seconds...');
  639. setTimeout(sendoffers, 2000);
  640. updateOffer(response.tradeofferid,gameid);
  641. mysqlConnection.query('UPDATE `queue` SET `status`=\'sent ' + response.tradeofferid + '\' WHERE `id`=\'' + queueid + '\'', function(err, row, fields) {
  642. if (err) throw err;
  643. });
  644.  
  645. });
  646.  
  647. num++; //avoid running this multiple times when the loop runs
  648. }
  649. });
  650. })(x);
  651. }
  652. }else{
  653. myconsolelog('Tried processing game '+row[y].gameid+' (queue '+row[y].id+') again? Check the queues in the database...');
  654. }
  655. }
  656. });
  657. })
  658. }
  659.  
  660. function cleanString(input) {
  661. var output = "";
  662. for (var i=0; i<input.length; i++) {
  663. if (input.charCodeAt(i) <= 127) {
  664. output += input.charAt(i);
  665. }
  666. }
  667. return output;
  668. }
  669.  
  670. (function() {
  671. /**
  672. * Decimal adjustment of a number.
  673. *
  674. * @param {String} type The type of adjustment.
  675. * @param {Number} value The number.
  676. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
  677. * @returns {Number} The adjusted value.
  678. */
  679. function decimalAdjust(type, value, exp) {
  680. // If the exp is undefined or zero...
  681. if (typeof exp === 'undefined' || +exp === 0) {
  682. return Math[type](value);
  683. }
  684. value = +value;
  685. exp = +exp;
  686. // If the value is not a number or the exp is not an integer...
  687. if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
  688. return NaN;
  689. }
  690. // Shift
  691. value = value.toString().split('e');
  692. value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  693. // Shift back
  694. value = value.toString().split('e');
  695. return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  696. }
  697.  
  698. // Decimal round
  699. if (!Math.round10) {
  700. Math.round10 = function(value, exp) {
  701. return decimalAdjust('round', value, exp);
  702. };
  703. }
  704. // Decimal floor
  705. if (!Math.floor10) {
  706. Math.floor10 = function(value, exp) {
  707. return decimalAdjust('floor', value, exp);
  708. };
  709. }
  710. // Decimal ceil
  711. if (!Math.ceil10) {
  712. Math.ceil10 = function(value, exp) {
  713. return decimalAdjust('ceil', value, exp);
  714. };
  715. }
  716. })();
  717.  
  718. function EndGame() {
  719. endtimer = -1;
  720. proceedWinners();
  721. myconsolelog('EndGame was called... (EndGame ends the timer, proceedWinners(), sendoffers())');
  722.  
  723. setTimeout(sendoffers, 2000);
  724.  
  725. }
  726.  
  727. function loadinventory(){
  728. offers.loadMyInventory({
  729. appId: 730,
  730. contextId: 2
  731. }, function(err, itemx) {
  732. if (err) {
  733. 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)');
  734. weblogon();
  735. setTimeout(loadinventory,3500);
  736. return;
  737. }
  738.  
  739. setTimeout(function(){ checkoffers(1); },5500);
  740. myconsolelog('Own inventory loaded successfully. Items list in itemx var.');
  741. if(itemx.length>0){
  742. myconsolelog(itemx.length+' items in inventory.');
  743. }else{
  744. myconsolelog('WARNING! '+itemx.length+' items in inventory. The inventory may actually be empty OR steam servers are down. Check http://steamstat.us');
  745. }
  746.  
  747. //myconsolelog(itemx);
  748. });
  749. }
  750.  
  751.  
  752. client.on('friendMessage', function(steamID, message) {
  753.  
  754. if(steamID == admin) {
  755.  
  756.  
  757.  
  758. if(message.indexOf("/uzmiskinove") == 0) {
  759. offers.loadMyInventory({
  760. appId: 730,
  761. contextId: 2
  762. }, function(err, items) {
  763. if(err) {
  764. steam.sendMessage(steamID, 'Problem sa Steamom, probaj ponovo.');
  765. steam.webLogOn(function(newCookie) {
  766. offers.setup({
  767. sessionID: globalSessionID,
  768. webCookie: newCookie
  769. }, function(err) {
  770. if (err) {
  771. }
  772. });
  773. });
  774. return;
  775. }
  776. var item=[],num=0;
  777. for (var i = 0; i < items.length; i++) {
  778. if (items[i].tradable) {
  779. item[num] = {
  780. appid: 730,
  781. contextid: 2,
  782. amount: items[i].amount,
  783. assetid: items[i].id
  784. }
  785. num++;
  786. }
  787. }
  788. if (num > 0) {
  789. offers.makeOffer ({
  790. partnerSteamId: admin,
  791. itemsFromMe: item,
  792. itemsFromThem: [],
  793. message: ''
  794. }, function(err, response){
  795. if (err) {
  796. throw err;
  797. }
  798.  
  799. });
  800. }
  801. });
  802.  
  803. } else if (message.indexOf("/send") == 0) {
  804. var params = message.split(' ');
  805.  
  806. if (params.length == 1) return client.chatMessage(steamID, 'Format: /send [item name]');
  807. myconsolelog('Received /send request');
  808.  
  809.  
  810. offers.loadMyInventory({
  811. appId: 730,
  812. contextId: 2
  813. }, function(err, items) {
  814.  
  815. if (err) {
  816. client.chatMessage(steamID, 'Could not load the inventory. Calling weblogon() - try again please.');
  817. myconsolelog('Could not load the inventory. Calling weblogon() - try again please.');
  818. weblogon();
  819. return;
  820. }
  821.  
  822. var item = 0;
  823. for (var i = 0; i < items.length; i++) {
  824. if ((items[i].market_name).indexOf(params[1]) != -1) {
  825. item = items[i].id;
  826. break;
  827. }
  828. }
  829.  
  830. if (item != 0) {
  831. offers.makeOffer({
  832. partnerSteamId: admin,
  833. itemsFromMe: [{
  834. appid: 730,
  835. contextid: 2,
  836. amount: 1,
  837. assetid: item
  838. }],
  839. itemsFromThem: [],
  840. message: 'You requested this item with the /send command.'
  841. }, function(err, response) {
  842. if (err) {
  843. throw err;
  844. }
  845. client.chatMessage(steamID, 'Trade offer with the requested item sent!');
  846. myconsolelog('Offer from /send request sent to '+steamID);
  847. });
  848. }else{
  849.  
  850. client.chatMessage(steamID, 'Couldn\'t match the item requested! /send is case sensitive!');
  851. myconsolelog('Couldn\'t match the item selected by '+steamID);
  852. }
  853.  
  854. });
  855.  
  856. } else if (message.indexOf("/show") == 0) {
  857.  
  858. var params = message.split(' ');
  859.  
  860. offers.loadMyInventory({
  861. appId: 730,
  862. contextId: 2
  863. }, function(err, items) {
  864.  
  865. if (err) {
  866. client.chatMessage(steamID, '(2) Could not load the inventory. Calling weblogon() - try again please.');
  867. myconsolelog('(2) Could not load the inventory. Calling weblogon() - try again please.');
  868. weblogon();
  869. return;
  870. }
  871.  
  872. client.chatMessage(steamID, 'Items list: ');
  873.  
  874. for (var i = 0; i < items.length; i++) {
  875. client.chatMessage(steamID, 'http://steamcommunity.com/id/tradecschance1/inventory/#' + items[i].appid + '_' + items[i].contextid + '_' + items[i].id);
  876. }
  877.  
  878. });
  879.  
  880.  
  881. } else if (message.indexOf("/end") == 0) {
  882.  
  883. client.chatMessage(steamID, 'Got request to end the game (/end)');
  884. if (endtimer != -1) clearTimeout(endtimer);
  885. EndGame();
  886.  
  887. } else if (message.indexOf("/so") == 0) {
  888.  
  889. client.chatMessage(steamID, 'Got request to send pending offers (/so)');
  890. sendoffers();
  891.  
  892. } else if (message.indexOf("/co") == 0) {
  893.  
  894. client.chatMessage(steamID, 'Got request to check incomming offers (/co)');
  895. checkoffers(1);
  896.  
  897. } else {
  898.  
  899. 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)');
  900. myconsolelog('Displayed available commands to '+steamID);
  901. }
  902.  
  903. }
  904.  
  905. getUserInfo(steamID, function(error, data) {
  906. if (error) throw error;
  907. var datadec = JSON.parse(JSON.stringify(data.response));
  908. var name = datadec.players[0].personaname;
  909. myconsolelog(name + ': ' + message); // Log it
  910. });
  911.  
  912. //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.');
  913. });
  914.  
  915. function in_array(needle, haystack, strict) {
  916. var found = false,
  917. key, strict = !!strict;
  918.  
  919. for (key in haystack) {
  920. if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
  921. found = true;
  922. break;
  923. }
  924. }
  925.  
  926. return found;
  927. }
  928.  
  929. var declinedoffer=false;
  930.  
  931. var isGood = true;
  932. function getStatus() {
  933. return isGood;
  934. }
  935.  
  936. function setStatus(data) {
  937. isGood = data;
  938. }
  939.  
  940. function checkoffers(thenumber) {
  941. declinedoffer=false;
  942. myconsolelog('Checking for offers...');
  943. if (thenumber > 0) {
  944. offers.getOffers({
  945. get_received_offers: 1,
  946. active_only: 1,
  947. get_sent_offers: 0,
  948. get_descriptions: 1,
  949. language: "en_us"
  950. }, function(error, body) {
  951.  
  952. myconsolelog('Trade offers not empty... '+thenumber);
  953.  
  954. if (error) {
  955. myconsolelog('Error getting offers. Steam servers down? Error: '+error);
  956. return;
  957. }
  958. if (body.response.trade_offers_received) {
  959.  
  960.  
  961. body.response.trade_offers_received.forEach(function(offer) {
  962. if (offer.trade_offer_state == 2) {
  963. mysqlConnection.query('SELECT * FROM `users` WHERE `steamid`="'+offer.steamid_other+'"',function(usrerr,usrres,usrfields){
  964. if(usrres.length==0){
  965. console.log('user does not exist in database: '+offer.steamid_other);
  966. return;
  967. }
  968. var tlink=usrres[0].tlink;
  969. if (tlink == '') {
  970. console.log('no trade link in db for user: '+offer.steamid_other);
  971. return;
  972. }
  973. var tokenStr = tlink.split('token=', 2);
  974. var token = tokenStr[1];
  975. console.log(offer.steamid_other+' - '+token);
  976. offers.getHoldDuration({
  977. partnerSteamId:offer.steamid_other,
  978. accessToken:token,
  979. }, function (holderr,duration) {
  980. if(holderr){
  981. console.log('holdduration error: '+holderr);
  982. 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');
  983. offers.declineOffer({
  984. tradeOfferId: offer.tradeofferid
  985. });
  986. declinedoffer=true;
  987. var unixtime = Math.round(new Date().getTime() / 1000.0);
  988. var messagedata={to:offer.steamid_other,msg:'Trade declined. It apears you can not receive trade offers. Try again later.',time:unixtime,type:'tradehold'};
  989. io.emit('message',messagedata);
  990. return;
  991. }
  992. if ((duration.my != 0) || (duration.their != 0)) {
  993. myconsolelog('Trade declined because either the bot or the person sending the offer has a trade period '+offer.tradeofferid);
  994. offers.declineOffer({
  995. tradeOfferId: offer.tradeofferid
  996. });
  997. declinedoffer=true;
  998. if(duration.their!=0){
  999. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1000. 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'};
  1001. io.emit('message',messagedata);
  1002. }
  1003. return;
  1004. }
  1005. });
  1006. });
  1007.  
  1008. myconsolelog('Trade offer incomming...');
  1009. myconsolelog('Trade offer id '+offer.tradeofferid+' from '+offer.steamid_other);
  1010.  
  1011. if (offer.items_to_give) {
  1012. myconsolelog('Trade declined (items requested from the bot inventory)');
  1013. offers.declineOffer({
  1014. tradeOfferId: offer.tradeofferid
  1015. });
  1016. return;
  1017. }
  1018. myconsolelog('dbg 1');
  1019.  
  1020. if (offer.items_to_receive == undefined){
  1021. myconsolelog('Undefined items_to_receive. Retrying checkoffers...');
  1022. weblogon();
  1023. setTimeout(function(){ checkoffers(1) },3500);
  1024. return;
  1025. }
  1026. myconsolelog('dbg 2');
  1027.  
  1028. mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
  1029. if(err) throw err;
  1030. myconsolelog('dbg 3');
  1031.  
  1032. var current_game = row[0].value;
  1033. mysqlConnection.query('SELECT COUNT(*) AS `totalitems` FROM `'+prf+current_game+'`', function(totalerr, totalres, totalfields){
  1034. if(totalerr) throw totalerr;
  1035. if(totalres.totalitems>maxitemsinpot){
  1036. myconsolelog('Trade declined (pot reached limit)');
  1037. offers.declineOffer({
  1038. tradeOfferId: offer.tradeofferid
  1039. });
  1040.  
  1041. offer.items_to_receive = [];
  1042. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1043. //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) {});
  1044.  
  1045. 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'};
  1046. io.emit('message',messagedata);
  1047. myconsolelog('[socket] too many items message sent to '+offer.steamid_other);
  1048. declinedoffer=true;
  1049. return;
  1050. }else{
  1051. mysqlConnection.query('SELECT COUNT(*) AS `usersitems` FROM `'+prf+current_game+'` WHERE `userid`=\''+offer.steamid_other+'\'', function(errs, rows, fieldss) {
  1052. if(errs) throw errs;
  1053. myconsolelog('dbg 4');
  1054.  
  1055. if (offer.items_to_receive.length > maxitems || offer.items_to_receive.length+rows[0].usersitems > maxitems) {
  1056.  
  1057. myconsolelog('Trade declined (too many items)');
  1058. offers.declineOffer({
  1059. tradeOfferId: offer.tradeofferid
  1060. });
  1061.  
  1062. offer.items_to_receive = [];
  1063. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1064. //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) {});
  1065.  
  1066. var messagedata={to:offer.steamid_other,msg:'Trade declined. You offered too many items. Max '+maxitems+' items per round!',time:unixtime,type:'toomanyitems'};
  1067. io.emit('message',messagedata);
  1068. myconsolelog('[socket] too many items message sent to '+offer.steamid_other);
  1069. declinedoffer=true;
  1070. return;
  1071. }
  1072. myconsolelog('dbg 5');
  1073. });
  1074. }
  1075. myconsolelog('dbg 5.5');
  1076. });
  1077. myconsolelog('dbg 6');
  1078. });
  1079. myconsolelog('dbg 7');
  1080. var delock = false;
  1081.  
  1082. offers.loadPartnerInventory({
  1083. partnerSteamId: offer.steamid_other,
  1084. appId: 730,
  1085. contextId: 2,
  1086. tradeOfferId: offer.tradeofferid,
  1087. language: "en"
  1088. }, function(err, hitems) {
  1089. myconsolelog('dbg 8');
  1090. if (err) {
  1091. myconsolelog('Error loading partnerinventory. Calling weblogon and trying again.');
  1092. setTimeout(function(){ checkoffers(1) },3500);
  1093. weblogon();
  1094. recheck = true;
  1095. return;
  1096. }
  1097. myconsolelog('dbg 9');
  1098. if (delock == true) return;
  1099. delock = true;
  1100.  
  1101. var items = offer.items_to_receive;
  1102. var wgg = [],
  1103. num = 0;
  1104. for (var i = 0; i < items.length; i++) {
  1105. for (var j = 0; j < hitems.length; j++) {
  1106. if (items[i].assetid == hitems[j].id) {
  1107. wgg[num] = hitems[j];
  1108. num++;
  1109. break;
  1110. }
  1111. }
  1112. }
  1113. myconsolelog('dbg 10');
  1114. var price = [];
  1115.  
  1116. for (var i = 0; i < num; i++) {
  1117. if (wgg[i].appid != 730 && !declinedoffer) { //got other items than cs items
  1118.  
  1119. myconsolelog('Trade declined (got other items than cs items)');
  1120.  
  1121. offers.declineOffer({
  1122. tradeOfferId: offer.tradeofferid
  1123. });
  1124.  
  1125. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1126. //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) {});
  1127.  
  1128. var messagedata={to:offer.steamid_other,msg:'Trade declined. You offered something else than CS:GO items!',time:unixtime,type:'otheritems'};
  1129. io.emit('message',messagedata);
  1130. myconsolelog('[socket] got other items than cs items message sent to '+offer.steamid_other);
  1131. declinedoffer=true;
  1132. return;
  1133. }
  1134. myconsolelog('dbg 11');
  1135. if (wgg[i].market_name.indexOf("Souvenir") != -1 && !declinedoffer) {
  1136. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1137.  
  1138. myconsolelog('Trade declined (got souvenir items)');
  1139.  
  1140. offers.declineOffer({
  1141. tradeOfferId: offer.tradeofferid
  1142. });
  1143.  
  1144. //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) {});
  1145.  
  1146. var messagedata={to:offer.steamid_other,msg:'Trade declined. You cannot deposit souvenir items!',time:unixtime,type:'souvenir'};
  1147. io.emit('message',messagedata);
  1148. myconsolelog('[socket] got souvenir items message sent to '+offer.steamid_other);
  1149. declinedoffer=true;
  1150. return;
  1151. }
  1152. myconsolelog('dbg 12');
  1153. /*
  1154. 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) {
  1155. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1156. offers.declineOffer({
  1157. tradeOfferId: offer.tradeofferid
  1158. });
  1159. //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) {});
  1160. myconsolelog('Trade declined (received weapon case... ' + wgg[i].market_name+')');
  1161.  
  1162. var messagedata={to:offer.steamid_other,msg:'Trade declined. You cannot deposit weapon cases!',time:unixtime,type:'weaponcase'};
  1163. io.emit('message',messagedata);
  1164. myconsolelog('[socket] got weapon cases message sent to '+offer.steamid_other);
  1165. declinedoffer=true;
  1166. return;
  1167. }
  1168. */
  1169.  
  1170. myconsolelog('dbg 13');
  1171.  
  1172. var itemname = wgg[i].market_name;
  1173.  
  1174. var url = 'http://' + sitename + '/cost.php?pw='+accesspassword+'&item=' + encodeURIComponent(itemname);
  1175. if(!declinedoffer){
  1176. myconsolelog('dbg 14');
  1177.  
  1178. (function(someshit) {
  1179. if(!(itemname in itemprices)){
  1180. request(url, function(error, response, body) {
  1181. if (!error && response.statusCode === 200) {
  1182.  
  1183. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1184. if (body == "notfound") {
  1185. offers.declineOffer({
  1186. tradeOfferId: offer.tradeofferid
  1187. });
  1188. myconsolelog('Trade declined. Item not found (notfound response when trying to get item cost).');
  1189. //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) {});
  1190.  
  1191. var messagedata={to:offer.steamid_other,msg:'Trade declined. An item you sent is unavailable ('+wgg[someshit].market_name+')!',time:unixtime,type:'itemunavailable'};
  1192. io.emit('message',messagedata);
  1193. myconsolelog('[socket] item unavailable message sent to '+offer.steamid_other);
  1194.  
  1195. } else if (body == "unauthorized") {
  1196. offers.declineOffer({
  1197. tradeOfferId: offer.tradeofferid
  1198. });
  1199. 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)');
  1200. //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) {});
  1201.  
  1202. var messagedata={to:offer.steamid_other,msg:'Trade declined. Unknown error please try again or contact an administrator!',time:unixtime,type:'unauthorized'};
  1203. io.emit('message',messagedata);
  1204. myconsolelog('[socket] item cost unknown error message sent to '+offer.steamid_other);
  1205.  
  1206. } else {
  1207. wgg[someshit].cost = parseFloat(body);
  1208.  
  1209. itemprices[wgg[someshit].market_name]=wgg[someshit].cost;
  1210.  
  1211. myconsolelog('Got item price from site: ' + wgg[someshit].market_name + ' = ' + body);
  1212.  
  1213.  
  1214. }
  1215. } else {
  1216. offers.declineOffer({
  1217. tradeOfferId: offer.tradeofferid
  1218. });
  1219. myconsolelog('Declined offer (error on getting price on ' + wgg[someshit].market_name + ')');
  1220.  
  1221. 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'};
  1222. io.emit('message',messagedata);
  1223. myconsolelog('[socket] couldnt get price on item message sent to '+offer.steamid_other);
  1224.  
  1225. }
  1226. });
  1227. }else{
  1228. myconsolelog('Got item price from local array. '+wgg[someshit].market_name+' = '+itemprices[wgg[someshit].market_name]);
  1229. wgg[someshit].cost=parseFloat(itemprices[wgg[someshit].market_name]);
  1230. }
  1231. })(i)
  1232. }else{
  1233. myconsolelog('dbg 15');
  1234. myconsolelog('declinedoffer is true apparently? declinedoffer: '+declinedoffer)
  1235. return;
  1236. }
  1237. }
  1238. if(!declinedoffer)
  1239. setTimeout(function() { // UNDEFINED PRICES? LOOK AT THIS! ITS GLIZDA!
  1240. myconsolelog('Timeout step 1...');
  1241. var sum = 0;
  1242. for (var i = 0; i < num; i++) {
  1243. sum += wgg[i].cost;
  1244. }
  1245. myconsolelog('Timeout step 1.2...');
  1246.  
  1247. if (sum < minbet && !declinedoffer) {
  1248. num = 0;
  1249. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1250. offers.declineOffer({
  1251. tradeOfferId: offer.tradeofferid
  1252. });
  1253. myconsolelog('Trade declined, value was too small.');
  1254.  
  1255. //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) {});
  1256.  
  1257. 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'};
  1258. io.emit('message',messagedata);
  1259. myconsolelog('[socket] value too small message sent to '+offer.steamid_other);
  1260. declinedoffer=true;
  1261.  
  1262. return;
  1263. }
  1264. myconsolelog('Timeout step 1.3... (next: getuserinfo) - if this hangs up too long then steam servers are probably fucking up: getUserInfo('+offer.steamid_other);
  1265.  
  1266. getUserInfo(offer.steamid_other, function(error, data) {
  1267. myconsolelog('Timeout step 1.4...');
  1268. if (error) throw error;
  1269. myconsolelog('Timeout step 2...');
  1270.  
  1271. var datadec = JSON.parse(JSON.stringify(data.response));
  1272. var name = addslashes(cleanString(datadec.players[0].personaname));
  1273. var avatar = (datadec.players[0].avatarfull);
  1274. if (num == 0) return;
  1275. offers.acceptOffer({
  1276. tradeOfferId: offer.tradeofferid
  1277. }, function(err, response) {
  1278. if (err != null){
  1279. myconsolelog('Erorr while accepting offer (?) Calling weblogon and checking offers again in 2 seconds...'+err);
  1280. weblogon();
  1281. setTimeout(function(){ checkoffers(1) },2000);
  1282. return;
  1283. }
  1284. myconsolelog('Accepted trade offer #' + offer.tradeofferid + ' by ' + name + ' (' + offer.steamid_other + ')');
  1285.  
  1286. mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
  1287. if(err) throw err;
  1288. var restosocket={};
  1289. restosocket.newitems=[];
  1290.  
  1291. var current_game = row[0].value;
  1292.  
  1293. restosocket.current_game = current_game;
  1294.  
  1295. mysqlConnection.query('SELECT `totalvalue`,`itemsnum` FROM `games` WHERE `id`=\'' + current_game + '\'', function(err1, row1, fields1) {
  1296. var current_bank = parseFloat(row1[0].totalvalue);
  1297. var itemsnum = row1[0].itemsnum;
  1298.  
  1299. for (var j = 0; j < num; j++) {
  1300.  
  1301. restosocket.newitems[j]={};
  1302. var qualityclasssplit=wgg[j].type.split(' ');
  1303. var qc=qualityclasssplit[0].toLowerCase();
  1304. var qcdb;
  1305. /* consumer, industrial, mil-spec, restricted, classified, covert, knife, contraband */
  1306.  
  1307. if(qc=='consumer' || qc=='base'){
  1308. qcdb='1consumer';
  1309. }else if (qc=='industrial'){
  1310. qcdb='2industrial';
  1311. }else if (qc=='mil-spec'){
  1312. qcdb='3mil-spec';
  1313. }else if (qc=='restricted'){
  1314. qcdb='4restricted';
  1315. }else if (qc=='classified'){
  1316. qcdb='5classified';
  1317. }else if (qc=='covert'){
  1318. qcdb='6covert';
  1319. }else if (qc=='★'){
  1320. qcdb='7knife';
  1321. wgg[j].market_name=wgg[j].market_name.replace('★','&#9733;');
  1322. }else if (qc=='contraband'){
  1323. qcdb='9contraband';
  1324. }else{
  1325. qcdb='1consumer';
  1326. }
  1327.  
  1328. 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) {});
  1329. mysqlConnection.query('UPDATE `games` SET `itemsnum`=`itemsnum`+1, `totalvalue`=`totalvalue`+\'' + wgg[j].cost + '\' WHERE `id` = \'' + current_game + '\'', function(err, row, fields) {});
  1330. 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};
  1331.  
  1332. current_bank = parseFloat(current_bank + wgg[j].cost);
  1333. itemsnum++;
  1334. }
  1335. restosocket.current_bank = current_bank;
  1336. restosocket.itemsnum = itemsnum;
  1337.  
  1338. mysqlConnection.query('SELECT COUNT(DISTINCT userid) AS playerscount FROM `'+prf + current_game+'`', function(err, rows) {
  1339. if(err) throw err;
  1340. var playerscount = rows[0].playerscount;
  1341. myconsolelog('Current Players: ' + playerscount);
  1342.  
  1343.  
  1344.  
  1345. if (playerscount == 2 && items.length > 0 && gamestarted==='no') { //STARTING GAME
  1346. myconsolelog('Game started var: '+gamestarted);
  1347. myconsolelog('Found 2 Players... Starting game.');
  1348. endtimer = setTimeout(EndGame, GameTime * 1000);
  1349.  
  1350. io.emit('roundstart','1');
  1351. gamestarted='yes';
  1352.  
  1353. mysqlConnection.query('UPDATE `games` SET `starttime`=UNIX_TIMESTAMP() WHERE `id` = \'' + current_game + '\'', function(err3, row3, fields3) {});
  1354.  
  1355. var gamestartmessage;
  1356. mysqlConnection.query('SELECT * FROM `games` WHERE `id`=\''+current_game+'\'', function(err6,row6,fields6){
  1357. if(err6) throw err6;
  1358.  
  1359. var gamestartedstarttime=row6.starttime;
  1360.  
  1361. });
  1362.  
  1363. myconsolelog('[socket] game start info sent to everyone');
  1364. }else{
  1365. myconsolelog('Game started var: '+gamestarted);
  1366. gamestarted='no';
  1367. var gamestartedstarttime=2147483647;
  1368. }
  1369.  
  1370. restosocket.playersnum=playerscount;
  1371. restosocket.gamestarted=gamestarted;
  1372. restosocket.gamestartedstarttime=gamestartedstarttime;
  1373.  
  1374. io.emit('roundupdate',JSON.stringify(restosocket));
  1375. io.emit('online',connections);
  1376.  
  1377. myconsolelog('[socket] sent game update & updated online count '+connections);
  1378. });
  1379.  
  1380. if (itemsnum > 50 || itemsnum == 50) {
  1381. myconsolelog('Hit ' + itemsnum + ' items... Not ending the game atm cause roulette is bugged.');
  1382. }
  1383.  
  1384. myconsolelog('Accepted (CONFIRMATION) trade offer #' + offer.tradeofferid + ' by ' + name + ' (' + offer.steamid_other + ')');
  1385.  
  1386.  
  1387.  
  1388.  
  1389. });
  1390. });
  1391. });
  1392. });
  1393.  
  1394.  
  1395. }, 3500);
  1396.  
  1397. });
  1398. }
  1399. /*}else{
  1400. myconsolelog('Trade declined because either the bot or the person sending the offer has a trade period');
  1401. offers.declineOffer({
  1402. tradeOfferId: offer.tradeofferid
  1403. });
  1404. if(duration.their!=0){
  1405. var unixtime = Math.round(new Date().getTime() / 1000.0);
  1406. 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'};
  1407. io.emit('message',messagedata);
  1408. }
  1409. } }); });*/
  1410. });
  1411. }
  1412. });
  1413. }else{
  1414. myconsolelog('No offers? number: '+thenumber);
  1415. }
  1416. }
  1417.  
  1418. function currentstate(current_game){
  1419. var res;
  1420. mysqlConnection.query('SELECT * FROM `games` WHERE `id`=\''+current_game+'\'', function(err,row,fields){
  1421. if(err) throw err;
  1422.  
  1423. mysqlConnection.query('SELECT * FROM `\''+prf+current_game+'\'', function(err2,row2,fields2){
  1424.  
  1425. });
  1426. });
  1427.  
  1428. return res;
  1429. }
  1430.  
  1431.  
  1432. var pew;
  1433. client.on('tradeOffers', checkoffers);
  1434.  
  1435. client.on('sentry', function(data) {
  1436. require('fs').writeFileSync('sentry_' + logOnOptions['accountName'] + '.hash', data);
  1437. });
  1438.  
  1439. setInterval(function() {
  1440. mysqlConnection.query('SELECT 1');
  1441. }, 5000);
  1442.  
  1443.  
  1444. setInterval(function(){
  1445. request(steamstatusurl+'?pw='+accesspassword, function(error, response, body) {
  1446. //myconsolelog('steamstatus: '+body);
  1447. io.emit('steamstatus',body);
  1448. });
  1449. request(contentcreatorsurl+'?pw='+accesspassword, function(error, response, body) {
  1450. //myconsolelog('steamstatus: '+body);
  1451. io.emit('cc',body);
  1452. });
  1453. }, 30000);
  1454.  
  1455.  
  1456. //sock
  1457. http.listen(3000, function(){
  1458. myconsolelog("\r\n\r\n"+'[socket] Listening on *:3000');
  1459. });
Add Comment
Please, Sign In to add comment