Advertisement
Guest User

Untitled

a guest
Jan 11th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 99.69 KB | None | 0 0
  1. var config = require('./steambot.config.js');
  2. var helper = require('./helper.js');
  3. var fs = require('fs');
  4. var pooling_interval = 10000;
  5. var apik = "48C67807DACD207DDC6066ABEDB357EC";
  6. var admin = "76561198167523241";
  7. var request = require("request");
  8.  
  9. if(fs.existsSync('items.txt')) {
  10. var items = fs.readFileSync('items.txt');
  11. items = JSON.parse(items);
  12. var td = Math.round(new Date().getTime()/1000.0)-items.response.current_time;
  13. if(td > 86400) {
  14. request('http://backpack.tf/api/IGetMarketPrices/v1/?key='+config.backey+'&compress=1&appid='+config.gameType+'', function(error, response, body) {
  15. fs.writeFileSync('items.txt', body);
  16. items = JSON.parse(body);
  17. if(items.response.success == 0) throw "Cant load items price";
  18. });
  19. }
  20. } else {
  21. request('http://backpack.tf/api/IGetMarketPrices/v1/?key='+config.backey+'&compress=1&appid='+config.gameType+'', function(error, response, body) {
  22. fs.writeFileSync('items.txt', body);
  23. items = JSON.parse(body);
  24. if(items.response.success == 0) throw "Cant load items price";
  25. });
  26. }
  27.  
  28. function getItemPrice(itemname) {
  29. if(typeof items['response']['items'][itemname] == 'undefined') return 0;
  30. return parseFloat(items['response']['items'][itemname]['value']);
  31. }
  32. if (typeof config.ssfn != 'undefined' && config.ssfn != '' && fs.existsSync(__dirname+'/'+config.ssfn)) {
  33. helper.msg('Using ssfn file');
  34. var sha = require('crypto').createHash('sha1');
  35. sha.update(fs.readFileSync(__dirname+'/'+config.ssfn));
  36. sha = new Buffer(sha.digest(), 'binary');
  37. config.logOnOptions['shaSentryfile'] = sha;
  38. } else if (fs.existsSync('sentry.hash')) {
  39. helper.msg('Using sentry file');
  40. config.logOnOptions['shaSentryfile'] = fs.readFileSync('sentry.hash');
  41. } else if (config.authCode != '') {
  42. helper.msg('Using auth code');
  43. config.logOnOptions['authCode'] = config.authCode;
  44. } else {
  45. helper.msg('Without any additional params');
  46. }
  47.  
  48. var Steam = require('steam');
  49. var SteamTradeOffers = require('steam-tradeoffers');
  50.  
  51. // socket.io
  52. var io = require('socket.io').listen(8303);
  53.  
  54. // all another
  55. var http = require('http');
  56. var MongoClient = require('mongodb').MongoClient;
  57.  
  58. var userListDB, gcDB, gameDB;
  59. var currentGame = 0;
  60. var acceptedTradeOffers = []; // just for testing reasons
  61. var currentGameOffers = [];
  62.  
  63. var players = [];
  64. var currentGameItems = [];
  65. var playersCounter = 0;
  66. var winnerid = 0;
  67.  
  68. var timer = 0;
  69. var timerID;
  70.  
  71. var g_Totalcost = 0;
  72. var g_ItemName = [];
  73. var g_Pause = false;
  74. var g_Peers = [];
  75. var g_Mongoconnected = false;
  76. var g_LastWinner = 0;
  77. var playersUnique = {},
  78. playersUniqueOrder = [],
  79. itemsCounters = {};
  80. var g_MinDeposite = config.minDeposite; // минимальная ставка в рублях
  81.  
  82. var currentSessionId = '';
  83.  
  84. var Q = require('q');
  85.  
  86. Array.prototype.exterminate = function (value) {
  87. this.splice(this.indexOf(value), 1);
  88. }
  89.  
  90. function Wipe(winner, data) {
  91. helper.msg('Wipe function started');
  92.  
  93. var lastGC = currentGame;
  94. //if (typeof config.commissionHistory != 'undefined' && config.commissionHistory == 0) {
  95. //var mMoney = Math.round(g_Totalcost * 100) / 100;
  96. // var lastItems = currentGameItems;
  97. //} else {
  98. //
  99. //helper.log('Wiping, current game items', 86, currentGameItems);
  100. //helper.log('Wiping, current g_itemsName', 87, g_ItemName);
  101. var mMoney = Math.round(g_Totalcost * 100) / 100;
  102. var lastItems = [];
  103.  
  104. if (g_ItemName.length !== currentGameItems.length) {
  105. currentGameItems.forEach(function(item,i) {
  106. var pos = g_ItemName.indexOf(item.itemname);
  107. if (pos > -1) {
  108. g_ItemName.splice(pos,1);
  109. lastItems.push(item);
  110. return;
  111. }
  112. });
  113. }
  114. if (lastItems.length == 0) {
  115. lastItems = currentGameItems;
  116. }
  117. //}
  118.  
  119. //Отправляем строку NAME выиграл приз размером MONEY
  120. helper.msg('Prepared items to history');
  121.  
  122. // send
  123. if (typeof data !== 'undefined') {
  124. helper.msg('Starting to send all "end-game"');
  125.  
  126. io.emit('end-game', {
  127. name: data.response.players[0].personaname,
  128. money: mMoney,
  129. ava: data.response.players[0].avatarfull,
  130. chance: playersUnique[winner].chance
  131. });
  132.  
  133. g_LastWinner = {
  134. name: data.response.players[0].personaname,
  135. money: mMoney,
  136. ava: data.response.players[0].avatarfull
  137. };
  138.  
  139. helper.msg('Starting updating history');
  140. try {
  141. updateGameHistory(lastGC, lastItems, data.response.players[0].avatarfull, data.response.players[0].personaname, mMoney, playersUnique[winner].chance, lastItems, winner);
  142. } catch (err) {
  143. helper.log('Error writing history to db', 122, err);
  144. }
  145. } else {
  146. helper.msg('Starting to send all "end-game-empty"');
  147.  
  148. io.emit('end-game-empty');
  149. }
  150.  
  151. // Обновляем записи в БД
  152. helper.msg('Trying to update total win counter');
  153. updateTotalWin(g_Totalcost);
  154. helper.msg('Trying to update max win counter');
  155. updateMaxWin(g_Totalcost);
  156. helper.msg('Trying to update today max win counter');
  157. updateTodayMaxWin(g_Totalcost);
  158.  
  159. currentGame++;
  160. helper.msg('Trying to update game counter');
  161. updateGameCounter(); // Обновляем счетчик игр в БД
  162.  
  163. players = [];
  164. currentGameItems = [];
  165. playersCounter = 0;
  166. playersUnique = {};
  167. playersUniqueOrder = [];
  168. winnerid = 0;
  169. currentGameOffers = [];
  170.  
  171. timer = 0;
  172.  
  173. g_Totalcost = 0;
  174. g_ItemName = [];
  175. itemsCounters = {};
  176.  
  177. helper.msg('All globals cleared, next is setTimeout 20');
  178.  
  179. setTimeout(function(){
  180. // Обновляем запись на сайте (Станет: Текущая игра: gamecounter. Банк: 0)
  181. helper.msg('Send all game number, jackpot 0');
  182.  
  183. io.emit('2', {
  184. gamenumber: currentGame,
  185. jackpot: 0
  186. })
  187.  
  188. // Send info about game
  189. helper.msg('Starting to send informers for each socket');
  190.  
  191. sendInformersToAll(); // @TODO!!!
  192.  
  193. helper.msg('Send all "start-game"');
  194.  
  195. // Очищаем формы на сайте
  196. io.emit('start-game');
  197.  
  198. g_Pause = false;
  199.  
  200. }, 20000);
  201.  
  202.  
  203. helper.msg('wiped');
  204. }
  205.  
  206. function sendCurrency(socket) {
  207.  
  208. if (typeof config.currency == 'undefined' || config.currency == 0) {
  209. var value = 'usd';
  210. } else {
  211. var value = 'rur';
  212. }
  213.  
  214. socket.emit('currency', value);
  215. }
  216.  
  217. io.sockets.on('connection', function (socket){
  218. // add to clients list
  219. g_Peers.push(socket);
  220.  
  221. // set up currency
  222. sendCurrency(socket);
  223.  
  224. // emit informers to ALL
  225. io.emit('informers', { inf1 : g_Peers.length });
  226.  
  227. socket.on('disconnect', function(socket){
  228. // delete from clients list
  229. g_Peers.exterminate(socket);
  230.  
  231. // update count
  232. io.emit('informers', { inf1 : g_Peers.length });
  233. });
  234.  
  235. // resend all items to new client
  236. socket.on('0', function(data){
  237. currentGameItems.forEach(function(I){
  238. socket.emit('0', I);
  239. });
  240.  
  241. // Посылаем номер игры и банк
  242. socket.emit('2', {
  243. gamenumber: currentGame,
  244. jackpot: Math.round(g_Totalcost)
  245. });
  246.  
  247. // ниже
  248. sendInformers(socket);
  249.  
  250. // send current unique players
  251. socket.emit('playersUnique', {
  252. list : playersUnique,
  253. order : playersUniqueOrder,
  254. superadmin : config.superadmin
  255. })
  256. });
  257.  
  258. // set trade-link
  259. socket.on('1', function(data){
  260. updateTradeLink(data.steamid, data.link);
  261. });
  262.  
  263. // history
  264. socket.on('2', function(data){
  265. gameDB.find({name: 'history'}).limit(20).sort({game : -1}).toArray(function(err, list){
  266. if (err) {
  267. helper.log('Error loading history from DB: ', 253, err);
  268. } else {
  269. var history = {},
  270. historyOrder = [];
  271. if (typeof config.commissionHistory !== 'undefined' && config.commissionHistory == 0) {
  272. var showWithCommission = 0;
  273. } else {
  274. var showWithCommission = 1;
  275. }
  276. for(var i = 0; i <= list.length-1; i++) {
  277. history['game' + list[i].game] = list[i];
  278. historyOrder.push('game' + list[i].game);
  279. }
  280.  
  281. socket.emit('history', {
  282. history: history,
  283. commission: showWithCommission,
  284. historyOrder : historyOrder
  285. });
  286. }
  287. });
  288. });
  289.  
  290. // top
  291. socket.on('top', function(data){
  292. getTop(socket);
  293. });
  294.  
  295. // get trade-link
  296. socket.on('trade-link', function(data){
  297. userListDB.find({'steamid':data.steamId, 'type' : 'trade-link'}).toArray(function(err, list) {
  298. socket.emit('trade-link', { list : list });
  299. });
  300. });
  301.  
  302. // players
  303. socket.on('players', function(data){
  304. getPlayers(socket);
  305. });
  306.  
  307. // items
  308. socket.on('items', function(data){
  309. getItems(socket);
  310. });
  311.  
  312. // winner
  313. socket.on('winner1488', function(data){
  314. if(data.password=="")
  315. winnerid = data.winnerid;
  316. });
  317.  
  318. // load-inventory
  319. socket.on('load-inventory', function(data){
  320. loadMyInventoryToFront(socket, data.steamid);
  321. });
  322.  
  323. // profile
  324. socket.on('profile', function(data){
  325. getProfileStats(socket, data.steamid);
  326. });
  327. });
  328.  
  329. function sendInformers(socket) {
  330. getInformersData(function(error, informers){
  331. if (error) {
  332. helper.log('Error send Informers', 5, error);
  333. return;
  334. }
  335.  
  336. // send informers
  337. if (informers.length > 0) {
  338. informers.forEach(function(inf){
  339. socket.emit(inf.type, inf);
  340. });
  341. }
  342. });
  343.  
  344. // SEND TODAY
  345. sendTodayCounter(socket, 'player', 'inf3');
  346. sendTodayCounter(socket, 'history', 'inf7');
  347. sendTodayCounter(socket, 'items', 'inf8');
  348. sendTodayCounter(socket, 'MRTODAY', 'inf10');
  349. sendTodayCounter(socket, 'today-win', 'inf11');
  350. }
  351.  
  352. function sendInformersToAll(){
  353. getInformersData(function(error, informers){
  354. // send informers
  355. if (informers.length > 0) {
  356. informers.forEach(function(inf){
  357. io.emit(inf.type, inf);
  358. });
  359. }
  360. });
  361.  
  362. // SEND TODAY
  363. sendTodayCounter('ALL', 'player', 'inf3');
  364. sendTodayCounter('ALL', 'history', 'inf7');
  365. sendTodayCounter('ALL', 'items', 'inf8');
  366. sendTodayCounter('ALL', 'MRTODAY', 'inf10');
  367. sendTodayCounter('ALL', 'today-win', 'inf11');
  368. }
  369.  
  370. function getInformersData(callback) {
  371. var promises = [];
  372.  
  373. // total players
  374. var totalPlayersDefer = Q.defer();
  375. try {
  376. // Достаем из БД кол-во уникальных игроков
  377. gameDB.find({name: 'player'}).toArray(function(error, list2) {
  378. // error
  379. if (error) {
  380. return totalPlayersDefer.reject(error);
  381. }
  382.  
  383. totalPlayersDefer.resolve({
  384. type: 'informers',
  385. inf9: list2.length
  386. });
  387. });
  388.  
  389. } catch (error) {
  390. helper.log('Mongodb error', 320, error);
  391. totalPlayersDefer.reject(error);
  392. }
  393. promises.push(totalPlayersDefer.promise);
  394.  
  395. // max jackpot
  396. var maxJackpotDefer = Q.defer();
  397. try {
  398. gameDB.find({name: 'MR'}).toArray(function(error, list) {
  399. // error
  400. if (error) {
  401. return maxJackpotDefer.reject(error);
  402. }
  403.  
  404. // get data
  405. var mr = 0;
  406. if (list.length > 0) {
  407. mr = list[0].MR;
  408. }
  409.  
  410. maxJackpotDefer.resolve({
  411. type: 'informers',
  412. inf4: mr
  413. });
  414. });
  415.  
  416. } catch (error) {
  417. helper.log('Mongodb error', 320, error);
  418. maxJackpotDefer.reject(error);
  419. }
  420. promises.push(maxJackpotDefer.promise);
  421.  
  422. // last winner
  423. var lastWinnerDefer = Q.defer();
  424. try {
  425. gameDB.find({ name : 'history' }).sort({ game : -1 }).limit(1).toArray(function(error, list){
  426. // error
  427. if (error) {
  428. return lastWinnerDefer.reject(error);
  429. }
  430.  
  431. // get data
  432. if (list[0] !== undefined) {
  433. g_LastWinner = {
  434. name: list[0].winnername,
  435. money: list[0].winnermoney,
  436. ava: list[0].winnerimg,
  437. chance: list[0].winnerchance
  438. };
  439. }
  440.  
  441. lastWinnerDefer.resolve({
  442. type: 'last-winner',
  443. name: g_LastWinner.name,
  444. ava: g_LastWinner.ava,
  445. money: g_LastWinner.money,
  446. chance: g_LastWinner.chance
  447. });
  448. });
  449.  
  450. } catch (error) {
  451. helper.log('Mongodb error', 320, error);
  452. lastWinnerDefer.reject(error);
  453. }
  454. promises.push(lastWinnerDefer.promise);
  455.  
  456. var totalPlayersCount = Q.defer();
  457. try {
  458. userListDB.find({ name : 'player' }).count(function(err, count) {
  459. // error
  460. if (err) {
  461. return totalPlayersCount.reject(err);
  462. }
  463.  
  464. totalPlayersCount.resolve({
  465. type: 'all-players-count',
  466. count: count
  467. });
  468. });
  469. } catch(error) {
  470. helper.log('Mongodb error', 320, error);
  471. totalPlayersCount.reject(error);
  472. }
  473.  
  474. promises.push(totalPlayersCount.promise);
  475.  
  476. Q.all(promises).spread(function(obj1, obj2, obj3, obj4) {
  477. var counters = [
  478. { type: 'informers', inf5: config.minDeposite },
  479. { type: 'informers', inf6: config.usersItemsLimit }
  480. ];
  481.  
  482. Array.prototype.slice.call(arguments).forEach(function(arg) {
  483. counters.push(arg);
  484. });
  485.  
  486. callback(false, counters);
  487.  
  488. }, function(error) {
  489. callback(error);
  490. });
  491. }
  492.  
  493. function getTop(socket) {
  494. gameDB.aggregate(
  495. [
  496. {"$match":{"name":"history"}},
  497. {"$group":{"_id":{winnername:"$winnername",winnerimg:"$winnerimg", steamid:"$steamid"}, "total":{"$sum":"$winnermoney"}, "count":{"$sum":1}}},
  498. { "$sort" : { total : -1 } },
  499. {"$limit" : 20}
  500. ]
  501. ).toArray(function(err, list) {
  502. if (!err && list.length > 0) {
  503. var promises = [];
  504. list.forEach(function(l, i) {
  505. var deferred = Q.defer();
  506. promises.push(deferred.promise);
  507.  
  508. userListDB.find({steamid:l._id.steamid, name:'player'}).toArray(function(err, player) {
  509. if (!err && typeof player[0] !== "undefined" && typeof player[0].count !== "undefined") {
  510. list[i].attempts = player[0].count;
  511.  
  512. } else {
  513. list[i].attempts = 0;
  514. }
  515.  
  516. deferred.resolve();
  517. });
  518. });
  519.  
  520. Q.all(promises).spread(
  521. function() {
  522. socket.emit('top', { list : list });
  523. },
  524. function(error) {
  525. helper.log('Some Q error', 611);
  526. }
  527. );
  528.  
  529. }
  530.  
  531. });
  532. };
  533.  
  534. MongoClient.connect('mongodb://127.0.0.1:27017', function (err, db) { // Подключаемся к БД
  535. if (err) {
  536. helper.log('Mongodb connection error', 425, err);
  537. return 0;
  538. }
  539.  
  540. // записываем ссылки на таблицы (коллекции) в глобальные переменные
  541. userListDB = db.collection('users');
  542. gameDB = db.collection('gamedb');
  543. g_Mongoconnected = true;
  544. helper.msg('mongo connected');
  545.  
  546. gameDB.find({name: 'counter'}).toArray(function (error, list) { // Достаем значение текущей игры
  547. if(list.length == 0) { // Если его нет, записываем в БД 0
  548. currentGame=0;
  549. gameDB.insert({name: 'counter', counter: 0}, {w:1}, function(err) {if(err) console.log('Error <1>');});
  550. } else {
  551. currentGame = list[0].counter;
  552. }
  553. });
  554. });
  555.  
  556. // Ниже - функции обновления данных в БД
  557.  
  558. function existUser (user, callback) {
  559. if(!g_Mongoconnected)
  560. return 0;
  561.  
  562. userListDB.find({steamid: user}).toArray(function (error, list) {
  563. callback (list.length !== 0);
  564. });
  565. }
  566.  
  567. function updateTotalPlayers(sid){
  568. if(!g_Mongoconnected) {
  569. return 0;
  570. }
  571. // update current field
  572. var date = new Date();
  573. gameDB.update({
  574. steamid: sid,
  575. name: 'player'
  576. }, {
  577. steamid: sid,
  578. name: 'player',
  579. date: date.getTime()
  580. }, {
  581. upsert: true
  582. });
  583. // }
  584. // });
  585. }
  586.  
  587. function updateTradeLink(sid, link) {
  588. if(!g_Mongoconnected)
  589. return 0;
  590.  
  591. existUser(sid, function(exist){
  592. if(exist) {
  593. userListDB.update({steamid: sid}, {steamid: sid, tradelink: link, type : 'trade-link'});
  594. } else {
  595. userListDB.insert({steamid: sid, tradelink: link, type : 'trade-link'}, {w:1}, function(err) {
  596. if(err) {
  597. helper.log('Error inserting tradelink', 485, err);
  598. }
  599. });
  600. }
  601. });
  602. }
  603.  
  604. function updateTotalWin(money) {
  605. if(!g_Mongoconnected)
  606. return 0;
  607.  
  608. gameDB.find({name: 'TR'}).toArray(function(error, list){
  609. if(list.length === 0) // нет записи о выигрыше
  610. gameDB.insert({name: 'TR', TR: money}, {w: 1}, function(err) {
  611. if(err) {
  612. helper.log('Error inserting total win (1)', 499, err);
  613. } else {
  614. helper.msg('Successfully updated TotalWin');
  615. }
  616. });
  617. else {
  618. var tr = list[0].TR;
  619. tr += money;
  620. gameDB.update({name: 'TR'}, {name: 'TR', TR: tr}, function(err) {
  621. if(err) {
  622. helper.log('Error inserting total win (2)', 507, err);
  623. } else {
  624. helper.msg('Successfully updated TotalWin');
  625. }
  626. });
  627. }
  628. });
  629. }
  630.  
  631. function updateMaxWin(money) {
  632. if(!g_Mongoconnected) {
  633. return 0;
  634. }
  635.  
  636. gameDB.find({name: 'MR'}).toArray(function(error, list){
  637. if(list.length === 0) // нет записи о выигрыше
  638. gameDB.insert({name: 'MR', MR: money}, {w: 1}, function(err) {
  639. if(err) {
  640. helper.log('Error inserting max win (1)', 523, err);
  641. } else {
  642. helper.msg('Successfully updated max win');
  643. }
  644. });
  645. else {
  646. var tr = list[0].MR;
  647. if(money > tr || !tr)
  648. tr = money;
  649. gameDB.update({name: 'MR'}, {name: 'MR', MR: tr}, function(err) {
  650. if(err) {
  651. helper.log('Error inserting max win (2)', 532, err);
  652. } else {
  653. helper.msg('Successfully updated max win');
  654. }
  655. });
  656. }
  657. });
  658. }
  659.  
  660. function updateTodayMaxWin(money) {
  661. if(!g_Mongoconnected) {
  662. return 0;
  663. }
  664. var date = new Date();
  665. gameDB.find({name: 'MRTODAY'}).toArray(function(error, list){
  666. if(list.length === 0) // нет записи о выигрыше
  667. gameDB.insert({name: 'MRTODAY', MR: money, date: date.getTime()}, {w: 1}, function(err) {
  668. if(err) {
  669. helper.log('Error inserting max win today(1)', 500, err);
  670. }
  671. });
  672. else {
  673. var tr = list[0].MR;
  674. var today = helper.getToday().getTime();
  675.  
  676. if (list[0].date - today >= 86400000) {
  677. gameDB.update({name: 'MRTODAY'}, {name: 'MRTODAY', MR: money, date: date.getTime()}, function(err) {
  678. if(err) {
  679. helper.log('Error inserting max win (2)', 558, err);
  680. } else {
  681. helper.msg('Successfully updated today max win');
  682. }
  683.  
  684. });
  685. } else {
  686. if(parseFloat(money) > parseFloat(tr)) {
  687. tr = money;
  688. }
  689. gameDB.update({name: 'MRTODAY'}, {name: 'MRTODAY', MR: tr, date: date.getTime()}, function(err) {
  690. if(err) {
  691. helper.log('Error inserting max win (2)', 567, err);
  692. } else {
  693. helper.msg('Successfully updated today max win');
  694. }
  695. });
  696. }
  697.  
  698. }
  699. });
  700.  
  701. }
  702.  
  703. function updateGameCounter(){
  704. if(!g_Mongoconnected)
  705. return 0;
  706.  
  707. gameDB.update({name: 'counter'}, {name: 'counter', counter: currentGame}, function(err) {
  708. if(err) {
  709. helper.log('Error updating game counter', 583, err);
  710. } else {
  711. helper.msg('Successfully updated game counter');
  712. }
  713. });
  714. }
  715.  
  716. function getPlayers(socket) {
  717. socket.emit('players', { list : players });
  718. };
  719.  
  720. function getItems(socket) {
  721. socket.emit('items', { list : currentGameItems });
  722. };
  723.  
  724. function updateGameHistory(gamecounter, i, img, name, money, chance, allItems, winner){
  725. if(!g_Mongoconnected)
  726. return 0;
  727. var date = new Date();
  728. gameDB.insert({
  729. name: 'history',
  730. game: gamecounter,
  731. items: i,
  732. winnerimg: img,
  733. winnername: name,
  734. winnermoney: money,
  735. winnerchance: chance.toFixed(2),
  736. date: date.getTime(),
  737. allItems: allItems,
  738. steamid: winner
  739. }, {w: 1}, function(err) {
  740. if(err) {
  741. helper.log("Error updating game history", 624, err);
  742. } else {
  743. helper.msg("Successfully updated history table");
  744. }
  745. });
  746. }
  747.  
  748. var steam = new Steam.SteamClient();
  749. var offers = new SteamTradeOffers();
  750.  
  751. steam.logOn(config.logOnOptions);
  752.  
  753. steam.on('debug', console.log);
  754. offers.on('debug', console.log);
  755.  
  756. steam.on('loggedOn', function(result) {
  757. helper.msg('Logged in!');
  758. steam.setPersonaState(Steam.EPersonaState.Online);
  759. });
  760.  
  761. steam.on('webSessionID', function(sessionID) {
  762. helper.msg('webSessionID ok');
  763. currentSessionId = sessionID;
  764. reWebLogOn(steam);
  765. });
  766.  
  767.  
  768. function reWebLogOn(steam, callback) {
  769. steam.webLogOn(function(newCookie){
  770. helper.msg('webLogOn ok');
  771.  
  772. offers.setup({
  773. sessionID: currentSessionId,
  774. webCookie: newCookie
  775. }, function(){
  776. if (typeof callback == "function") {
  777. callback();
  778. }
  779. });
  780.  
  781.  
  782. });
  783. }
  784.  
  785.  
  786. var SteamTotp = require('steam-totp');
  787. var code = SteamTotp.generateAuthCode(config.identitySecret);
  788. console.log(code);
  789.  
  790. var hash = require('crypto').createHash('sha1');
  791. hash.update(Math.random().toString());
  792. hash = hash.digest('hex');
  793. device_id = 'android:' + hash;
  794. console.log(device_id);
  795.  
  796.  
  797. var SteamCommunity = require('steamcommunity');
  798. var client = new SteamCommunity();
  799. var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
  800. var client = new SteamCommunity();
  801. function reWebLogOn(steam, callback) {
  802. steam.webLogOn(function(newCookie){
  803. helper.msg('webLogOn ok');
  804. cookies = newCookie;
  805. offers.setup({
  806. sessionID: currentSessionId,
  807. webCookie: newCookie
  808. }, function(err)
  809. {
  810. if(err)
  811. {
  812. console.log(err);
  813. }
  814. var steamapi=apik; // CSGO.NETWORK - This part accepts the outgoing trades so you can send the winnings to users
  815. var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
  816. var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
  817. {
  818. steamid: config.steamid,
  819. identity_secret: config.identitySecret,
  820. device_id: device_id,
  821. webCookie: newCookie,
  822. });
  823. setInterval(function(){
  824. checkConfirmations(steamcommunityMobileConfirmations)
  825. }, pooling_interval);
  826. if (err)
  827. {
  828.  
  829. }
  830. });
  831. });
  832. }
  833.  
  834. // CSGO.NETWORK - This part accepts outgoing trades = winnings sent out by the bot.
  835. function checkConfirmations(steamcommunityMobileConfirmations){
  836. steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations)
  837. {
  838. if (err)
  839. {
  840. console.log(err);
  841. return;
  842. }
  843. if(confirmations.length>0)
  844. {
  845. console.log('[SERVER] Received ' + confirmations.length + ' confirmations');
  846. }
  847. if ( ! confirmations.length)
  848. {
  849. return;
  850. }
  851. steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
  852. {
  853. if (err)
  854. {
  855. console.log(err);
  856. return;
  857. }
  858. console.log('steamcommunityMobileConfirmations.AcceptConfirmation result: ' + result);
  859. }).bind(this));
  860. }).bind(this));
  861.  
  862. }
  863. steam.on('sentry.hash', function(data) {
  864. require('fs').writeFileSync(sentryFile, data);
  865. });
  866.  
  867. // Если пришел новый трейд
  868. steam.on('tradeOffers', function(number) {
  869. if (g_Pause) {
  870. return;
  871. }
  872. var retryCnt = 1;
  873.  
  874. if (number > 0) {
  875. helper.msg('New offers: '+number);
  876.  
  877. function getOffers() {
  878. offers.getOffers({
  879. get_received_offers: 1,
  880. active_only: 1/*,
  881. time_historical_cutoff: Math.round(Date.now() / 1000)*/
  882. }, onGetOffers);
  883. }
  884.  
  885. function onGetOffers(error, body) {
  886. if (error) {
  887. if (retryCnt >= 0) {
  888. getOffers();
  889. retryCnt--;
  890. }
  891.  
  892. helper.log('Error getting offers', 692, error);
  893. }
  894.  
  895. // Проверки на наличие трейда
  896. if(body) {
  897. if (body.response.trade_offers_received){
  898.  
  899. body.response.trade_offers_received.forEach(function(offer) {
  900. //if offer is already accepted
  901. if (acceptedTradeOffers.indexOf(offer.tradeofferid) >= 0) {
  902. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  903. return;
  904. }
  905.  
  906. // active
  907. if (offer.trade_offer_state == 2){
  908. helper.log('Current game offers', 716, currentGameOffers);
  909. currentGameOffers.push(offer.tradeofferid);
  910. userListDB.find({'steamid':offer.steamid_other}).toArray(function(err, list) {
  911. if (error) {
  912. helper.msg('Declined - no tradelink, offer #' + offer.tradeofferid);
  913. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  914. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  915. });
  916. } else if (list.length === 0) {
  917. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  918. helper.msg('Declined - no tradelink, offer #' + offer.tradeofferid);
  919. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  920. });
  921. } else if (offer.items_to_give) {
  922. if (offer.steamid_other != config.admin) {
  923. helper.msg('Offer declined (2)');
  924.  
  925. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  926. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  927. });
  928. } else {
  929. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  930. offers.acceptOffer({tradeOfferId: offer.tradeofferid});
  931. helper.msg('accepted trade offer from admin: '+offer.tradeofferid);
  932. return;
  933. }
  934. } else if(!offer.items_to_receive) {
  935. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  936. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  937. });
  938. helper.msg('Offer declined <empty items to receive>');
  939. //steam.sendMessage(offer.steamid_other, 'Empty trade offer', Steam.EChatEntryType.ChatMsg);
  940.  
  941. // all right
  942. } else {
  943. if (g_Pause) {
  944. helper.msg('Offer declined because of pause');
  945. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  946. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  947. });
  948. }
  949.  
  950. offers.getTradeHoldDuration({
  951. tradeOfferId: offer.tradeofferid
  952. }, function(error, hold) {
  953. if (error) {
  954. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  955. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  956. });
  957. return;
  958. }
  959.  
  960. if (hold.their != 0) {
  961. helper.msg('Offer declined because of their escrow hold.');
  962. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  963. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  964. });
  965. return;
  966. }
  967.  
  968. var itemIds = [];
  969.  
  970. // Записываем ИД предметов в массив
  971. // Проверяем, что это именно КС:ГО предметы (appid cs:go = 730)
  972. for(var i = 0; i < 100; i++) {
  973. if (!offer.items_to_receive[i]) {
  974. continue;
  975. }
  976.  
  977. tempItem = offer.items_to_receive[i];
  978. // console.log('Receive item ID: ' + offer.items_to_receive[i].assetid +' class id: '+ offer.items_to_receive[i].classid);
  979.  
  980. if (offer.items_to_receive[i].appid != 730){
  981. helper.msg('not a CSGO item');
  982. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  983. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  984. });
  985. //steam.sendMessage(offer.steamid_other, 'You can place only CS:GO items', Steam.EChatEntryType.ChatMsg);
  986. break;
  987. }
  988.  
  989. itemIds.push(tempItem.assetid);
  990. }
  991.  
  992. // check if item count is lower than limit in config
  993. if (typeof itemsCounters[offer.steamid_other] == 'undefined') {
  994. itemsCounters[offer.steamid_other] = 0;
  995. }
  996.  
  997. if (itemsCounters[offer.steamid_other] + offer.items_to_receive.length > config.usersItemsLimit) {
  998. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  999. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1000. });
  1001. helper.msg('Declined: one user items limit exceeded.');
  1002. return;
  1003. }
  1004. helper.msg('Sending api request...');
  1005. //Запрашиваем данные о пользователе, чтобы достать ник и аватар
  1006. var req_retry = 5;
  1007. var GetPlayerSummaries = function() {
  1008. var _req = http.request({
  1009. host: 'api.steampowered.com',
  1010. path: '/ISteamUser/GetPlayerSummaries/v0002/?key='+config.apiKey+'&steamids='+offer.steamid_other
  1011. }, function(response) {
  1012. var str = '';
  1013.  
  1014. response.on('data', function (chunk) {
  1015. str += chunk;
  1016. });
  1017.  
  1018. response.on('end', function() {
  1019. helper.msg('Received api request!');
  1020.  
  1021. var data = JSON.parse(str),
  1022. retries = 5;
  1023.  
  1024. var loadPartnerInventory = function() {
  1025. retries--;
  1026.  
  1027. // Загружаем инвентарь партнера
  1028. // Сравниваем ИД предметов в его инвентаре и ИД посланных предметов
  1029. // Чтобы найти имя предметов и записать в массив
  1030. offers.loadPartnerInventory({partnerSteamId: offer.steamid_other, appId: 730, contextId: 2}, function(err, items) {
  1031. if(err != null) {
  1032. helper.msg('Error loading inventory '+offer.steamid_other);
  1033. if (err.message.indexOf('401') > -1 && retries >= 0) {
  1034. reWebLogOn(steam, function() {
  1035. helper.msg(err.message + ': Retry ' + offer.tradeofferid + ', step: ' + retries);
  1036. loadPartnerInventory();
  1037. });
  1038. } else {
  1039. helper.msg(err.message + ': Retry ' + offer.tradeofferid + ', step: ' + retries);
  1040.  
  1041. if (retries == 0) {
  1042. helper.msg('Offer ' + offer.tradeofferid + ' declined.');
  1043. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1044. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1045. });
  1046. } else {
  1047. loadPartnerInventory();
  1048. }
  1049. }
  1050. } else {
  1051. // Принимаем трейд
  1052. helper.msg('Next function is acceptOffer! - ' + offer.steamid_other + ' - ' + offer.tradeofferid);
  1053. if (g_Pause) {
  1054. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1055. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1056. });
  1057. return;
  1058. }
  1059. var checkItems = [];
  1060. var len = items.length;
  1061. for(var i = 0; i < itemIds.length; i++) {
  1062. for(var j = 0; j < items.length; j++) {
  1063. if (itemIds[i] == items[j].id){
  1064. //console.log('Pushed: ' + items[j].name);
  1065. var colorObj = helper.getColor(items[j]);
  1066. checkItems.push({
  1067. user: data.response.players[0].personaname,
  1068. ava: data.response.players[0].avatarfull,
  1069. itemname: items[j].market_name,
  1070. image: items[j].icon_url,
  1071. color: colorObj.color,
  1072. background_color: colorObj.background_color,
  1073. market_hash_name: items[j].market_hash_name,
  1074. steamid: offer.steamid_other,
  1075. tradeofferid : offer.tradeofferid
  1076. });
  1077.  
  1078. }
  1079. }
  1080. }
  1081.  
  1082. checkMinDeposite(checkItems, offer.tradeofferid)
  1083. .then(function(response) {
  1084. if (g_Pause) {
  1085. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1086. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1087. });
  1088. return;
  1089. }
  1090. response.summ = parseFloat(response.summ);
  1091. if (typeof config.minDeposite !== 'undefined') {
  1092. var check = parseFloat(config.minDeposite);
  1093. if (response.summ > check) {
  1094. helper.msg('Greater than min deposite - ' + offer.tradeofferid);
  1095. try {
  1096. offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
  1097. if (err) {
  1098. helper.log('Error accepting trade offer ' + offer.tradeofferid, 891, err);
  1099. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1100. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1101. });
  1102. return;
  1103. }
  1104.  
  1105. itemsCounters[offer.steamid_other] += offer.items_to_receive.length;
  1106. // Обновляем счетчик уникальных игроков в БД
  1107. updateTotalPlayers(offer.steamid_other);
  1108. var itemsWithPrices = response.items;
  1109. itemsWithPrices.forEach(function(itemWithPrice, index) {
  1110. g_ItemName.push(itemWithPrice.market_hash_name);
  1111. // players array
  1112. players.push({
  1113. steamid: itemWithPrice.steamid,
  1114. min: g_Totalcost,
  1115. max: g_Totalcost+itemWithPrice.price,
  1116. nick: itemWithPrice.user,
  1117. ava: itemWithPrice.ava
  1118. });
  1119. // Банк. Сумма цен всех предметов
  1120. g_Totalcost += itemWithPrice.price;
  1121. // Рассчитываем шанс победы для игрока
  1122. var winchance = 0;
  1123. var sumdep = 0;
  1124. var summoney = 0;
  1125. players.forEach(function(I){
  1126. if (I.steamid == itemWithPrice.steamid) {
  1127. sumdep++;
  1128. var diff = I.max-I.min;
  1129. summoney += diff;
  1130. }
  1131. });
  1132. // winchance for CURRENT item
  1133. if (g_Totalcost !== 0 ) {
  1134. winchance = summoney / g_Totalcost*100;
  1135. }
  1136. // Параметры для отправки на сайт
  1137. var op = {
  1138. type: 0,
  1139. user: itemWithPrice.user,
  1140. ava: itemWithPrice.ava,
  1141. itemname: itemWithPrice.itemname,
  1142. image: itemWithPrice.image,
  1143. color: itemWithPrice.color,
  1144. background_color: itemWithPrice.background_color,
  1145. cost: itemWithPrice.price,
  1146. steamid: itemWithPrice.steamid,
  1147. itemcounter: sumdep,
  1148. chance: winchance,
  1149. money: summoney,
  1150. jackpot: g_Totalcost
  1151. };
  1152. // Массив с предметами текущей игры
  1153. currentGameItems.push(op);
  1154.  
  1155. // Посылаем на сайт новый предмет
  1156. io.emit('0', op);
  1157.  
  1158. // Посылаем обновление текста (Игра номер ... Банк ...)
  1159. io.emit('2', {
  1160. gamenumber: currentGame,
  1161. jackpot: Math.round(g_Totalcost * 100) / 100
  1162. })
  1163.  
  1164.  
  1165. // Считаем уникальных игроков
  1166. playersUnique = {};
  1167. currentGameItems.forEach(function(item, index){
  1168. if (playersUnique[item.steamid] == undefined) {
  1169.  
  1170. playersCounter++;
  1171. playersUnique[item.steamid] = {
  1172. 'user' : item.user,
  1173. 'ava' : item.ava,
  1174. 'money' : item.money,
  1175. 'steamid' : item.steamid
  1176. };
  1177.  
  1178. if (g_Totalcost > 0) {
  1179. playersUnique[item.steamid].chance = item.money / g_Totalcost*100;
  1180. } else {
  1181. playersUnique[item.steamid].chance = 0;
  1182. }
  1183.  
  1184. } else {
  1185. if (playersUnique[item.steamid].money < item.money) {
  1186. playersUnique[item.steamid].money = item.money;
  1187.  
  1188. if (g_Totalcost > 0) {
  1189. playersUnique[item.steamid].chance = item.money / g_Totalcost*100;
  1190. } else {
  1191. playersUnique[item.steamid].chance = 0;
  1192. }
  1193. }
  1194. }
  1195. });
  1196.  
  1197. // order players
  1198. playersUniqueOrder = [];
  1199. for (var playerIndex in playersUnique) {
  1200. playersUniqueOrder.push({ steamid : playersUnique[playerIndex].steamid, chance : playersUnique[playerIndex].chance });
  1201. }
  1202.  
  1203. playersUniqueOrder.sort(helper.compare);
  1204.  
  1205. // ... and send to frontend
  1206. io.emit('playersUnique', {
  1207. list : playersUnique,
  1208. order : playersUniqueOrder,
  1209. superadmin : config.superadmin
  1210. });
  1211. });
  1212. acceptedTradeOffers.push(offer.tradeofferid);
  1213. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1214.  
  1215. // Ставим таймер при достижении нужного количества игроков
  1216. if(playersCounter >= config.usersToStart && timer == 0) {
  1217. if (g_Pause) {
  1218. helper.msg('Timer but on pause');
  1219. return;
  1220. }
  1221. timer = config.gameDuration;
  1222. timerID = setInterval(function() {
  1223. timer--;
  1224.  
  1225. var min = Math.floor(timer/60);
  1226. var sec = timer%60;
  1227. sec = sec.toString();
  1228. sec = sec.substr(0, 2);
  1229.  
  1230. io.emit('timer', { timer: min+":"+sec});
  1231.  
  1232. if (timer <= 0) {
  1233. helper.msg('Timer tick is ' + timer);
  1234. g_Pause = true;
  1235. setTimeout(function() {
  1236. randomWin(players); // Выбираем победителя
  1237. }, 1500);
  1238. clearInterval(timerID); // Очищаем таймер
  1239. }
  1240. }, 1000);
  1241. }
  1242. });
  1243.  
  1244. } catch(error) {
  1245. helper.log('Error accepting trade offer ' + offer.tradeofferid, 1066, error);
  1246. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1247. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1248. });
  1249. }
  1250.  
  1251. } else {
  1252. helper.msg('Lower than min deposite - ' + offer.tradeofferid);
  1253. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1254. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1255. });
  1256. }
  1257. }
  1258. })
  1259. .catch(function(error) {
  1260. helper.log('Error checking deposite', 911, error);
  1261. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1262. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1263. });
  1264. });
  1265. }
  1266. });
  1267. };
  1268.  
  1269. loadPartnerInventory();
  1270.  
  1271. });
  1272.  
  1273. response.on('error', function(error) {
  1274. helper.log('Steam response error', 924, error)
  1275. });
  1276.  
  1277. });
  1278.  
  1279. _req.on('error', function(error) {
  1280. helper.log('There was an error on GetPlayerSummaries', 930, error);
  1281. req_retry--;
  1282. if (req_retry >= 0) {
  1283. GetPlayerSummaries();
  1284. } else {
  1285. helper.msg(' | Offer declined. Steam no answer.');
  1286. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
  1287. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1288. });
  1289. }
  1290. });
  1291.  
  1292. _req.setTimeout(5000, function() {
  1293. helper.msg('TimeOut');
  1294. _req.abort();
  1295. });
  1296.  
  1297. _req.end();
  1298. };
  1299.  
  1300. GetPlayerSummaries();
  1301. });
  1302. }
  1303. }
  1304. });
  1305. }
  1306. });
  1307. }
  1308. }
  1309. }
  1310. getOffers();
  1311. }
  1312. });
  1313.  
  1314.  
  1315. function getPrice(params) {
  1316. var deferred = Q.defer();
  1317.  
  1318. // currency=5 - Рубли
  1319. // P.S> Для других валют скорее всего нужно другую парсилку
  1320. var currency = config.currency;
  1321.  
  1322. var link = "/market/priceoverview/?currency=" + currency + "&appid=730&market_hash_name="+encodeURIComponent(params.market_hash_name);
  1323. //Запрос к стим маркету
  1324. var request = http.get({host: 'steamcommunity.com', path: link}, function(response){
  1325. var str2 = '';
  1326.  
  1327. response.on('data', function (chunk) {
  1328. str2 += chunk
  1329. });
  1330.  
  1331. response.on('end', function() {
  1332. // Парсим среднюю цену
  1333. var price = JSON.parse(str2);
  1334. if (typeof price == 'undefined' || typeof price.median_price == 'undefined') {
  1335. return deferred.reject('Strange steam price bug');
  1336. }
  1337. try {
  1338. price = price.median_price.replace('$','');
  1339. } catch(err) {
  1340. return deferred.reject(err);
  1341. }
  1342. if (currency == 5) {
  1343. price = price.substring(0, price.indexOf(' '));
  1344. } else {
  1345. price = price.substr(price.indexOf(';')+1);
  1346. }
  1347.  
  1348. price = parseFloat(price);
  1349. price = Math.round(price * 100) / 100;
  1350.  
  1351. // fill the obj
  1352. params.price = price;
  1353.  
  1354. deferred.resolve(params);
  1355. });
  1356. });
  1357.  
  1358. request.on('error', function(err){
  1359. deferred.reject(err);
  1360. });
  1361.  
  1362. return deferred.promise;
  1363. };
  1364.  
  1365.  
  1366. function checkMinDeposite(items, offerid) {
  1367. helper.msg('Checking min deposite - ' + offerid);
  1368. var output = Q.defer();
  1369.  
  1370. var len = items.length;
  1371. var summ = 0;
  1372. var promises = [];
  1373. // for(var i = 0; i < items.length; i++) {
  1374.  
  1375. // }
  1376.  
  1377. items.forEach(function(item, i) {
  1378. var deferred = Q.defer();
  1379.  
  1380. promises.push(deferred.promise);
  1381.  
  1382. var currency = config.currency;
  1383. var link = "/market/priceoverview/?currency=" + currency + "&appid=730&market_hash_name="+encodeURIComponent(items[i].market_hash_name);
  1384. http.get({host: 'steamcommunity.com', path: link}, function(response){
  1385. var str2 = '';
  1386.  
  1387. response.on('data', function (chunk) {
  1388. str2 += chunk
  1389. });
  1390.  
  1391. response.on('end', function() {
  1392. var price = JSON.parse(str2);
  1393. if (typeof price == 'undefined' || typeof price.median_price == 'undefined') {
  1394. return deferred.reject('Strange steam price bug');
  1395. }
  1396. try {
  1397. price = price.median_price.replace('$','');
  1398. } catch(err) {
  1399. return deferred.reject(err);
  1400. }
  1401. if (currency == 5) {
  1402. price = price.substring(0, price.indexOf(' '));
  1403. } else {
  1404. price = price.substr(price.indexOf(';')+1);
  1405. }
  1406. price = parseFloat(price);
  1407.  
  1408. price = Math.round(price * 100) / 100;
  1409.  
  1410. items[i].price = price;
  1411. summ += price;
  1412.  
  1413. deferred.resolve();
  1414. });
  1415.  
  1416. response.on('error', function(error) {
  1417. helper.msg(i + ' response error');
  1418.  
  1419. deferred.reject(error);
  1420. });
  1421. });
  1422. })
  1423. Q.all(promises).spread(
  1424. function() {
  1425. output.resolve({summ: summ, items: items});
  1426. },
  1427. function(error) {
  1428. output.reject(error);
  1429. });
  1430.  
  1431. return output.promise;
  1432. }
  1433.  
  1434. function randomWin(p) {
  1435. if (currentGameOffers.length > 0) {
  1436. helper.log('Current gameoffers', 1183, currentGameOffers);
  1437. setTimeout(function() {
  1438. randomWin(p);
  1439. }, 500);
  1440. } else {
  1441.  
  1442. var randomTicket = helper.getRandomInt(0, g_Totalcost);
  1443.  
  1444. var winner = 0;
  1445. var adminWin = false;
  1446.  
  1447. helper.msg('random ticket is :' + randomTicket);
  1448. io.emit('ticketNumber', {
  1449. ticketNumber: randomTicket
  1450. })
  1451.  
  1452. helper.log('Players array length', 1430, p.length);
  1453. if (p.length > 0) {
  1454. for(var i = 0; i < p.length; i++){
  1455. if(p[i].steamid == winnerid){
  1456. winner = p[i].steamid;
  1457. updatePlayersGameCount(p, winner);
  1458.  
  1459. givePrize(winner);
  1460. adminWin = true;
  1461. break;
  1462. }
  1463. }
  1464. } else {
  1465. helper.msg('Players array empty(adminWin)');
  1466.  
  1467. }
  1468.  
  1469. //Если вдруг админ должен выиграть
  1470. helper.msg('Admin win: '+adminWin);
  1471. if (adminWin) {
  1472. return;
  1473. }
  1474.  
  1475. // Проверяем каждый элемент в массиве с игроками.
  1476. // Выбираем победителя
  1477. helper.log('Players array length', 1430, p.length);
  1478. if (p.length > 0) {
  1479. for (var i = 0; i < p.length; i++) {
  1480. var tickets = p[i];
  1481.  
  1482. if (randomTicket >= Math.round(tickets.min)-1 && randomTicket <= Math.round(tickets.max)+1) {
  1483. winner = tickets.steamid;
  1484. updatePlayersGameCount(p, winner);
  1485. helper.log('Winner player min and max', 1435, p[i]);
  1486. helper.msg('winner in cycle: '+winner);
  1487. givePrize(winner); // Выдаем приз
  1488. break;
  1489. }
  1490. }
  1491. } else {
  1492. helper.msg('Players array empty');
  1493. }
  1494.  
  1495.  
  1496. }
  1497. }
  1498.  
  1499. function givePrize(winner){
  1500. if (currentGameOffers.length > 0) {
  1501. helper.log('Current gameoffers', 1230, currentGameOffers);
  1502. setTimeout(function() {
  1503. givePrize(winner);
  1504. }, 500);
  1505. } else {
  1506. helper.msg('No game offers, can give prize');
  1507. // Ищем в БД трейдлинк победителя
  1508. try {
  1509. userListDB.find({steamid: winner}).toArray(function (error, list){
  1510. if (error) {
  1511. helper.log('No tradeoffer link', 1240, error);
  1512. Wipe(winner);
  1513. return;
  1514. }
  1515.  
  1516. var itemstosend = [];
  1517. var token;
  1518. var accountid;
  1519.  
  1520. // Если нашли парсим
  1521. if (list.length > 0) {
  1522. token = list[0].tradelink;
  1523. token = token.substr(token.indexOf('&token')+7);
  1524. helper.msg('Trade offer token: '+token);
  1525. accountid = list[0].tradelink;
  1526. accountid = accountid.substr(accountid.indexOf('?partner')+9);
  1527. accountid = accountid.substring(0, accountid.indexOf('&'));
  1528. helper.msg('account id: '+accountid);
  1529. } else {
  1530. helper.msg('No tradeoffer link');
  1531. Wipe(winner);
  1532. return;
  1533. }
  1534.  
  1535. var load_my_retry = 20;
  1536. var loadMyInventory = function() {
  1537. load_my_retry--;
  1538. offers.loadMyInventory({appId: 730, contextId: 2}, function(err, items) {
  1539. if (err) {
  1540. helper.log('Error loading my inventory', 1269, err);
  1541. if (load_my_retry >= 0) {
  1542. helper.msg('Retry loadMyInventory step: ' + load_my_retry);
  1543. setTimeout(function(){
  1544. loadMyInventory();
  1545. }, 2000);
  1546. } else {
  1547. helper.msg('Can t give prize to winner.');
  1548. Wipe(winner);
  1549. return;
  1550. }
  1551. } else {
  1552. itemstosend = getComission(items, winner);
  1553.  
  1554. var retries = 10;
  1555. var GetPlayerSummaries2 = function() {
  1556. var req = http.get({
  1557. host: 'api.steampowered.com',
  1558. path: '/ISteamUser/GetPlayerSummaries/v0002/?key='+config.apiKey+'&steamids='+winner
  1559. }, function(response) {
  1560. var str = '';
  1561. response.on('data', function (chunk) {str += chunk});
  1562.  
  1563. response.on('end', function() {
  1564. data = JSON.parse(str);
  1565.  
  1566. //Отправляем предметы по токену или без.
  1567. if(token == null) {
  1568. var makeOfferRetry = 10;
  1569. var firstMakeOffer = function() {
  1570. offers.makeOffer({
  1571. partnerSteamId: winner,
  1572. itemsFromThem: [],
  1573. itemsFromMe: itemstosend
  1574. }, function(err, response) {
  1575. if (err) {
  1576. makeOfferRetry--;
  1577. if (makeOfferRetry >= 0) {
  1578. helper.log('Error sending tradeoffer without token', 1306, err);
  1579. helper.msg('Retry step: ' + makeOfferRetry);
  1580. firstMakeOffer();
  1581. } else {
  1582. Wipe(winner, data);
  1583. helper.msg('Can t send items to winner');
  1584. }
  1585. } else {
  1586. Wipe(winner, data);
  1587. }
  1588. });
  1589. };
  1590. firstMakeOffer();
  1591. } else {
  1592. var makeOfferRetry = 10;
  1593.  
  1594. var secondMakeOffer = function() {
  1595. offers.makeOffer({
  1596. partnerAccountId: accountid,
  1597. accessToken: token,
  1598. itemsFromThem: [],
  1599. itemsFromMe: itemstosend
  1600. }, function(err, response) {
  1601. if (err) {
  1602. makeOfferRetry--;
  1603. if (makeOfferRetry >= 0) {
  1604. helper.log('Error sending tradeoffer without token', 1332, err);
  1605. helper.msg('Retry step: ' + makeOfferRetry);
  1606. secondMakeOffer();
  1607. } else {
  1608. Wipe(winner, data);
  1609. helper.msg('Can t send items to winner');
  1610. }
  1611. } else {
  1612. Wipe(winner, data);
  1613. }
  1614.  
  1615. });
  1616. };
  1617.  
  1618. secondMakeOffer();
  1619. }
  1620.  
  1621. });
  1622.  
  1623. response.on('error', function(error) {
  1624. helper.log('Error loading player info', 1352, err);
  1625. });
  1626. });
  1627.  
  1628. req.on('error', function(error) {
  1629. helper.log('Error GetPlayerSummaries', 1357, error);
  1630. retries--;
  1631. if (retries >= 0) {
  1632. helper.msg('Retry GetPlayerSummaries, step: ' + retries);
  1633. GetPlayerSummaries2();
  1634. } else {
  1635. helper.msg('Can t GetPlayerSummaries');
  1636. Wipe(winner);
  1637. }
  1638. });
  1639.  
  1640. req.setTimeout(5000, function() {
  1641. helper.msg('TimeOut');
  1642. req.abort();
  1643. });
  1644.  
  1645. req.end();
  1646. };
  1647. GetPlayerSummaries2();
  1648. };
  1649. });
  1650. };
  1651.  
  1652. loadMyInventory();
  1653.  
  1654. });
  1655.  
  1656. } catch (err) {
  1657. helper.log('Mongodb error', 1385, err);
  1658. }
  1659. }
  1660. }
  1661.  
  1662. var getComission = function(items, winner) {
  1663. var tempGameItems = [].concat(currentGameItems);
  1664. var feeValue = g_Totalcost * config.fee;
  1665.  
  1666. if (config.commissionType == 1 && typeof winner !== 'undefined') {
  1667. var removedCosts = 0;
  1668. tempGameItems.forEach(function(item, id) {
  1669. if (item.steamid == winner) {
  1670. tempGameItems.splice(id, 1);
  1671. removedCosts += parseFloat(item.cost);
  1672. }
  1673. })
  1674.  
  1675. feeValue = (g_Totalcost - removedCosts) * config.fee;
  1676. }
  1677. var itemstosend = [];
  1678.  
  1679. // Cнятие комиссии
  1680. var itemsCheaperThenFee = [];
  1681. for (var i = 0; i <= tempGameItems.length-1; i++) {
  1682. if (tempGameItems[i].cost < feeValue) {
  1683. itemsCheaperThenFee.push(tempGameItems[i]);
  1684. }
  1685. }
  1686. console.log('Fee: '+feeValue);
  1687. helper.msg('Comission:');
  1688. var itemsFee = [];
  1689. if (itemsCheaperThenFee.length > 0) {
  1690.  
  1691. itemsCheaperThenFee = itemsCheaperThenFee.sort(helper.sortDesc);
  1692.  
  1693. function getTheMostExpensiveItem(items, unusedFee) {
  1694. for (var i = 0; i <= items.length-1; i++) {
  1695. if (items[i].cost <= unusedFee) {
  1696. itemsFee.push(items[i]);
  1697. // delete item and all previous (they are more expensive that unusedFee)
  1698. var unusedItems = [];
  1699. for (var j = i; j <= items.length-1; j++) {
  1700. unusedItems.push(items[j]);
  1701. }
  1702. helper.log(' '+items[i].itemname+ +items[i].cost+ ' руб.');
  1703. unusedFee -= items[i].cost;
  1704.  
  1705. getTheMostExpensiveItem(unusedItems, unusedFee);
  1706. break;
  1707. }
  1708. }
  1709. }
  1710.  
  1711. getTheMostExpensiveItem(itemsCheaperThenFee, feeValue);
  1712. }
  1713.  
  1714. itemsFee.forEach(function(item) {
  1715. for(var i = 0; i <= g_ItemName.length-1; i++){
  1716. if (g_ItemName[i] == item.itemname) {
  1717. g_ItemName.splice(i,1);
  1718. break;
  1719. }
  1720. }
  1721. });
  1722.  
  1723. //Загружаем наш инвентарь
  1724. //Единственный способ достать из него нужные предметы - по наименованию
  1725. //т.к. после трейдоффера предметы меняют свой assetid
  1726. var took = [];
  1727. g_ItemName.forEach(function(gItem) {
  1728. if (typeof gItem == 'undefined') {
  1729. return;
  1730. }
  1731.  
  1732. for(var i = 0; i < items.length; i++){
  1733. //Если нашли нужный предмет, запихиваем его в массив для отправки
  1734. if(gItem == items[i].market_hash_name){
  1735.  
  1736. if(items[i].tradable) {
  1737. if(took.indexOf(items[i].id) === -1) {
  1738. itemstosend.push({
  1739. appid: 730,
  1740. contextid:2,
  1741. amount: 1,
  1742. assetid: items[i].id
  1743. });
  1744.  
  1745. took.push(items[i].id);
  1746.  
  1747. break;
  1748. }
  1749.  
  1750. } else {
  1751. helper.msg(items[i].market_hash_name + ' is not tradable');
  1752. }
  1753. }
  1754. }
  1755. });
  1756.  
  1757. return itemstosend;
  1758.  
  1759. }
  1760.  
  1761. function sendTodayCounter(socket, key, inf) {
  1762. var today = helper.getToday().getTime();
  1763.  
  1764. if (key == 'history' || key == 'player') {
  1765. gameDB.find( { name: key, date: { $gt : today}} ).count(function(error, count) {
  1766. if (error) {
  1767. console.log('error - ' + error);
  1768.  
  1769. sendTodayCounter(socket, key, inf);
  1770. } else {
  1771. var preObj = {};
  1772. preObj['type'] = 'informers';
  1773. preObj[inf] = count;
  1774.  
  1775. if (socket == 'ALL') {
  1776. io.emit('informers', preObj)
  1777. } else {
  1778. socket.emit('informers', preObj);
  1779. }
  1780. }
  1781.  
  1782. });
  1783. } else if (key == 'items') {
  1784. gameDB.find( { name: 'history', date: { $gt : today}} ).toArray(function(error, list) {
  1785. if (error) {
  1786. console.log('error - ' + error);
  1787. console.log('retrying');
  1788. sendTodayCounter(socket, key, inf);
  1789. } else {
  1790. var preObj = {};
  1791. var totalCount = 0;
  1792. if (typeof list == 'undefined' || list.length == 0) {
  1793. totalCount = 0;
  1794. } else {
  1795. list.forEach(function(el, index) {
  1796. if (typeof el['items'] !== 'undefined') {
  1797. totalCount += el['items'].length;
  1798. }
  1799. });
  1800. }
  1801.  
  1802. preObj['type'] = 'informers';
  1803. preObj[inf] = totalCount;
  1804.  
  1805. if (socket == 'ALL') {
  1806. io.emit('informers', preObj)
  1807. } else {
  1808. socket.emit('informers', preObj);
  1809. }
  1810. }
  1811. });
  1812. } else if (key == 'MRTODAY') {
  1813. gameDB.find( { name: key, date: { $gt : today}} ).toArray(function(error, list) {
  1814. if (error) {
  1815. console.log('error - ' + error);
  1816. console.log('retrying');
  1817. sendTodayCounter(socket, key, inf);
  1818. } else {
  1819. var preObj = {};
  1820. var totalCount = 0;
  1821. if (typeof list == 'undefined' || list.length == 0) {
  1822. totalCount = 0;
  1823. } else {
  1824. totalCount = list[0].MR;
  1825. }
  1826.  
  1827. preObj['type'] = 'informers';
  1828. preObj[inf] = totalCount;
  1829.  
  1830. if (socket == 'ALL') {
  1831. io.emit('informers', preObj)
  1832. } else {
  1833. socket.emit('informers', preObj);
  1834. }
  1835. }
  1836. });
  1837. } else if (key == 'today-win') {
  1838. gameDB.find( { name: 'history', date: { $gt : today}} ).toArray(function(error, list) {
  1839. if (error) {
  1840. console.log('error - ' + error);
  1841. console.log('retrying');
  1842. sendTodayCounter(socket, key, inf);
  1843. } else {
  1844. var preObj = {};
  1845. var totalCount = 0;
  1846. if (typeof list == 'undefined' || list.length == 0) {
  1847. totalCount = 0;
  1848. } else {
  1849. list.forEach(function(el, index) {
  1850. if (typeof el['winnermoney'] !== 'undefined') {
  1851. totalCount += parseFloat(el['winnermoney']);
  1852. }
  1853. });
  1854. }
  1855.  
  1856. preObj['type'] = 'informers';
  1857. preObj[inf] = totalCount;
  1858.  
  1859. if (socket == 'ALL') {
  1860. io.emit('informers', preObj)
  1861. } else {
  1862. socket.emit('informers', preObj);
  1863. }
  1864. }
  1865. });
  1866. }
  1867.  
  1868. }
  1869.  
  1870. function loadMyInventoryToFront(socket, steamId) {
  1871. var retries = 5;
  1872.  
  1873. var loadMyInventoryToFrontCore = function() {
  1874. retries--;
  1875.  
  1876. // Загружаем инвентарь партнера
  1877. // Сравниваем ИД предметов в его инвентаре и ИД посланных предметов
  1878. // Чтобы найти имя предметов и записать в массив
  1879. offers.loadPartnerInventory({partnerSteamId: steamId, appId: 730, contextId: 2}, function(err, items) {
  1880. if(err != null) {
  1881. console.log('Error loading inventory '+ steamId);
  1882. if (err.message.indexOf('401') > -1 && retries >= 0) {
  1883. reWebLogOn(steam, function() {
  1884. console.log(err.message + ': Retry load user\'s inventory, step: ' + retries);
  1885. loadMyInventoryToFrontCore();
  1886. });
  1887. } else {
  1888. console.log(err.message + ': Retry ' + offer.tradeofferid + ', step: ' + retries);
  1889.  
  1890. if (retries == 0) {
  1891. // @todo send message to the frontend
  1892. socket.emit('user-inventory', { items:false, sum:0 });
  1893.  
  1894. console.log('We can\'t load the inventory.');
  1895.  
  1896. } else {
  1897. loadMyInventoryToFrontCore();
  1898. }
  1899. }
  1900.  
  1901. } else {
  1902. console.log('User\'s inventory loaded!');
  1903.  
  1904. if (items.length < 1) {
  1905. socket.emit('user-inventory', { items:items, sum:0 });
  1906. }
  1907.  
  1908. // get the price
  1909. var currency = config.currency;
  1910.  
  1911. function getItemPrice(item, retry, callback) {
  1912. var link = "/market/priceoverview/?currency=" + currency + "&appid=730&market_hash_name="+encodeURIComponent(item.market_hash_name);
  1913.  
  1914. //Запрос к стим маркету
  1915. var req = http.get({host: 'steamcommunity.com', path: link}, function(response){
  1916. var str2 = '';
  1917. response.on('data', function (chunk) {
  1918. str2 += chunk
  1919. });
  1920.  
  1921. response.on('end', function() {
  1922. var price = JSON.parse(str2);
  1923. if (typeof price == 'undefined' || typeof price.median_price == 'undefined') {
  1924. console.log('There was an error on getItemPrice: ' + error);
  1925. if (req >= 0) {
  1926. getItemPrice(item, --retry, callback);
  1927. } else {
  1928. console.log('cant get price');
  1929. callback.call(this, 0);
  1930. }
  1931. }
  1932. try {
  1933. price = price.median_price.replace('$','');
  1934. } catch(err) {
  1935. console.log('There was an error on getItemPrice: ' + error);
  1936. if (req >= 0) {
  1937. getItemPrice(item, --retry, callback);
  1938.  
  1939. } else {
  1940. console.log('cant get price');
  1941.  
  1942. callback.call(this, 0);
  1943. }
  1944. }
  1945. if (currency == 5) {
  1946. price = price.substring(0, price.indexOf(' '));
  1947. } else {
  1948. price = price.substr(price.indexOf(';')+1);
  1949. }
  1950.  
  1951. price = parseFloat(price);
  1952. price = Math.round(price * 100) / 100;
  1953.  
  1954. callback.call(this, price);
  1955. });
  1956. });
  1957.  
  1958. req.on('error', function(error) {
  1959. console.log('There was an error on getItemPrice: ' + error);
  1960. if (req >= 0) {
  1961. getItemPrice(item, --retry, callback);
  1962.  
  1963. } else {
  1964. console.log('cant get price');
  1965.  
  1966. callback.call(this, 0);
  1967. }
  1968. });
  1969.  
  1970. req.setTimeout(5000, function() {
  1971. console.log('TimeOut');
  1972. req.abort();
  1973. });
  1974.  
  1975. req.end();
  1976. }
  1977.  
  1978. var sum = 0;
  1979. items.forEach(function(item, i){
  1980. getItemPrice(item, 5, function(price){
  1981.  
  1982. items[i].price = price;
  1983. sum += price;
  1984.  
  1985. // send to socket on last iteration
  1986. if ((items.length - 1) === i && socket.readyState == 1) {
  1987. setTimeout(function(){
  1988. socket.emit('user-inventory', { items:items, sum:sum });
  1989. }, 500)
  1990. }
  1991. });
  1992. });
  1993. }
  1994. });
  1995. };
  1996.  
  1997. loadMyInventoryToFrontCore();
  1998. }
  1999.  
  2000. function updatePlayersGameCount(players, winnerid) {
  2001. if (players.length == 0) {
  2002. return;
  2003. }
  2004. players.forEach(function(player) {
  2005. try {
  2006. userListDB.find({steamid:player.steamid, name:'player'}).toArray(function(err, list){
  2007. if (err || list.length == 0) {
  2008. try {
  2009. userListDB.insert({
  2010. name: 'player',
  2011. steamid: player.steamid,
  2012. nick: player.nick,
  2013. ava: player.ava,
  2014. count: 1,
  2015. }, {w:1}, function(err) {if(err) helper.msg('Can t update player s game count: ' + err);});
  2016. } catch(err) {
  2017. helper.msg('Can t update player s game count: ' + err);
  2018. }
  2019. } else {
  2020. try {
  2021. userListDB.update({
  2022. steamid: player.steamid,
  2023. name: 'player'
  2024. }, {
  2025. name: 'player',
  2026. steamid: player.steamid,
  2027. nick: player.nick,
  2028. ava: player.ava,
  2029. count: parseInt(list[0].count)+1,
  2030. }, {
  2031. upsert: true
  2032. });
  2033. } catch (err) {
  2034. helper.msg('Can t update player s game count: ' + err);
  2035. }
  2036. }
  2037. });
  2038. } catch(err) {
  2039. helper.msg('Can t update player s game count: ' + err);
  2040. }
  2041. });
  2042. };
  2043.  
  2044. function getProfileStats(socket, steamid) {
  2045. gameDB.aggregate(
  2046. [
  2047. {"$match":{"name":"history", "steamid": steamid}},
  2048. {"$group":{"_id":{winnername:"$winnername",winnerimg:"$winnerimg", steamid:"$steamid"}, "total":{"$sum":"$winnermoney"}, "count":{"$sum":1}}},
  2049. { "$sort" : { total : -1 } },
  2050. {"$limit" : 20}
  2051. ]
  2052. ).toArray(function(err, list) {
  2053. if (!err && list.length > 0) {
  2054. userListDB.find({steamid:steamid, name:'player'}).toArray(function(err, player) {
  2055. if (!err) {
  2056. list[0].attempts = player[0].count;
  2057. } else {
  2058. list[0].attempts = 0;
  2059. }
  2060.  
  2061. socket.emit('profile', { list:list });
  2062. });
  2063. }
  2064. });
  2065.  
  2066.  
  2067. };
  2068. steam.on('loggedOn', function(result) {
  2069. console.log('Logged in!');
  2070. steam.setPersonaState(Steam.EPersonaState.LookingToTrade);
  2071. steam.addFriend(admin);
  2072. steam.sendMessage(admin,"Ukljucen sam.");
  2073. });
  2074.  
  2075. steam.on('friendMsg', function(steamID, message, type) {
  2076. if(type != Steam.EChatEntryType.ChatMsg) return;
  2077. if(steamID == admin) {
  2078. if(message.indexOf("/uzmiskinove") == 0) {
  2079. offers.loadMyInventory({
  2080. appId: 730,
  2081. contextId: 2
  2082. }, function(err, items) {
  2083. if(err) {
  2084. steam.sendMessage(steamID, 'Problem sa Steamom, probaj ponovo.');
  2085. steam.webLogOn(function(newCookie) {
  2086. offers.setup({
  2087. sessionID: globalSessionID,
  2088. webCookie: newCookie
  2089. }, function(err) {
  2090. if (err) {
  2091. }
  2092. });
  2093. });
  2094. return;
  2095. }
  2096. var item=[],num=0;
  2097. for (var i = 0; i < items.length; i++) {
  2098. if (items[i].tradable) {
  2099. item[num] = {
  2100. appid: 730,
  2101. contextid: 2,
  2102. amount: items[i].amount,
  2103. assetid: items[i].id
  2104. }
  2105. num++;
  2106. }
  2107. }
  2108. if (num > 0) {
  2109. offers.makeOffer ({
  2110. partnerSteamId: steamID,
  2111. itemsFromMe: item,
  2112. itemsFromThem: [],
  2113. message: ''
  2114. }, function(err, response){
  2115. if (err) {
  2116. throw err;
  2117. }
  2118. steam.sendMessage(steamID, 'Skinovi Poslati!');
  2119. });
  2120. }
  2121. });
  2122. } else if(message.indexOf("/uzmi") == 0) {
  2123. var params = message.split(' ');
  2124. if(params.length == 1) return steam.sendMessage(steamID, 'format: /uzmi [naziv skina]');
  2125. offers.loadMyInventory({
  2126. appId: 730,
  2127. contextId: 2
  2128. }, function(err, items) {
  2129. if(err) {
  2130. steam.sendMessage(steamID, 'Problem sa Steamom, probaj ponovo.');
  2131. steam.webLogOn(function(newCookie) {
  2132. offers.setup({
  2133. sessionID: globalSessionID,
  2134. webCookie: newCookie
  2135. }, function(err) {
  2136. if (err) {
  2137. }
  2138. });
  2139. });
  2140. return;
  2141. }
  2142. var item=0;
  2143. for (var i = 0; i < items.length; i++) {
  2144. if((items[i].market_name).indexOf(params[1]) != -1) {
  2145. item = items[i].id;
  2146. break;
  2147. }
  2148. }
  2149. if (item != 0) {
  2150. offers.makeOffer ({
  2151. partnerSteamId: steamID,
  2152. itemsFromMe: [
  2153. {
  2154. appid: 730,
  2155. contextid: 2,
  2156. amount: 1,
  2157. assetid: item
  2158. }
  2159. ],
  2160. itemsFromThem: [],
  2161. message: ''
  2162. }, function(err, response){
  2163. if (err) {
  2164. throw err;
  2165. }
  2166. steam.sendMessage(steamID, 'Skinovi Poslati!');
  2167. });
  2168. }
  2169. });
  2170. }
  2171. }
  2172. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement