Advertisement
Guest User

bot.js

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