Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Initalizing packages
- */
- var SteamUser = require('steam-user');
- var TradeOfferManager = require('steam-tradeoffer-manager');
- var SteamTotp = require('steam-totp');
- var SteamCommunity = require('steamcommunity');
- var fs = require('fs');
- var request = require('request');
- var config = require('./config.json');
- var CryptoJS = require("crypto-js");
- var log4js = require('log4js');
- var express = require('express');
- var app = express();
- var community = new SteamCommunity();
- var client = new SteamUser();
- var manager = new TradeOfferManager({
- steam: client,
- domain: 'localhost',
- language: 'en'
- });
- var server = require('http').createServer();
- var io = require('socket.io')(server);
- server.listen(3001);
- log4js.configure({
- appenders: [
- { type: 'console' },
- { type: 'file', filename: '/var/Bot/logs/site.log' }
- ]
- });
- var logger = log4js.getLogger();
- var mysql = require('mysql');
- var db_config = {
- //debug: true,
- host: config.options.sql['host'],
- user: config.options.sql['username'],
- password: config.options.sql['password'],
- database: config.options.sql['database']
- };
- var pool;
- handleDisconnect();
- process.on('uncaughtException', function (err) {
- logger.error('Strange error');
- logger.error(err);
- });
- //GAME INFO
- var AppID = 730;
- var ContextID = 2;
- var minDep = config.options.minDeposit;
- var proxies = config.proxies;
- var percentRake = 10;
- var deletingTrades = [];
- var inventoryTimer = {};
- var socketBySteam = {};
- var tradingRequests = {};
- var loadGames = [];
- var timerGame = {};
- var timer11Game = {};
- var depositTrades = [];
- var depositSteamTrades = [];
- var gamesPending = {};
- var antiFlood = {};
- var timesFlooding = {};
- var inventoryUser = {};
- //CHAT FUNCTIONS
- var chatMessages = [];
- var usersOnline = {};
- var antiSpamChat = {};
- //CHAT FUNCTIONS
- /*
- Polling Steam and Logging On
- */
- client.logOn({
- accountName: config.bots[0].username,
- password: config.bots[0].password,
- twoFactorCode: SteamTotp.generateAuthCode(config.bots[0].sharedSecret)
- });
- app.get('/sendTrade', function(req, res) {
- var tradeID = req.query['tid'];
- if(!tradeID)
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'You need to enter a tradeid.'
- });
- }
- return;
- }
- pool.query('SELECT status,action,user,items,code FROM trades WHERE tid = ' + pool.escape(tradeID), function(err, row) {
- if(err) throw err;
- if(row.length == 0)
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'This TID does not exists in the db.'
- });
- }
- return;
- }
- if(row[0].status == 'PendingAccept' && row[0].action == 'winning')
- {
- pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(row[0].user), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0)
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'User does not exists in db.'
- });
- }
- return;
- }
- if(!ro[0].tradelink.includes('://'))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'You need to add your tradelink before requesting a tradeoffer.'
- });
- }
- return;
- }
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].user) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(ca, ma) {
- if(ca) throw ca;
- if(ma.length == 0) return;
- if(ma[0].tTrades != 0)
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'You isset an active tradeoffer.'
- });
- }
- return;
- }
- var Items = row[0].items.split('/');
- var create = manager.createOffer(row[0].user, ro[0].tradelink.split('token=')[1]);
- logger.debug(itemsDB);
- manager.loadInventory(AppID, ContextID, true, function(err, inv, curr) {
- if(err) throw err;
- if(inv.length == 0) return;
- for(var i in Items)
- {
- for(var z in inv)
- {
- if(Items[i] == inv[z].assetid && Items[i] != 1)
- {
- Items[i] = 1;
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": inv[z].assetid
- });
- }
- }
- }
- create.setMessage('Your winnings are here. Code: ' + row[0].code);
- create.send(function(err, status) {
- if(err) throw err;
- tradingRequests[create.id] = {
- action: 'winning',
- user: row[0].user
- };
- pool.query('UPDATE trades SET tid = ' + pool.escape(create.id) + ' WHERE tid = ' + pool.escape(tradeID));
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- code: row[0].code,
- tid: create.id
- });
- }
- setTimeout(function() {
- declineOffer(create);
- }, 90000);
- logger.debug('Winnings from tradeid #' + tradeID + ' were sent again to winner ' + row[0].user + ' new tradeoffer #' + create.id);
- });
- });
- });
- });
- }
- });
- });
- setTradingRequests();
- function setTradingRequests()
- {
- pool.query('SELECT * FROM trades WHERE status = ' + pool.escape('PendingAccept'), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- for(var i in row)
- {
- logger.debug('Trade #' + row[i].tid + ' added --> ' + row[i].action + ' + ' + row[i].user);
- tradingRequests[row[i].tid] = {
- action: row[i].action,
- user: row[i].user
- };
- }
- });
- }
- loadAllGames();
- function loadAllGames()
- {
- pool.query('SELECT * FROM games WHERE `ended` = 0', function(err, res, fields) {
- if(err) throw err;
- loadGames = [];
- for(var i in res)
- {
- loadGames.push({
- 'id': res[i].id,
- 'csteamid': res[i].csteamid,
- 'cname': res[i].cname,
- 'cavatar': res[i].cavatar,
- 'cskinsurl': res[i].cskinsurl,
- 'cskinsnames': res[i].cskinsnames,
- 'cskinsprices': res[i].cskinsprices,
- 'cskins': res[i].cskins,
- 'ctp': res[i].ctp,
- 'psteamid': res[i].psteamid,
- 'pname': res[i].pname,
- 'pavatar': res[i].pavatar,
- 'pskinsurl': res[i].pskinsurl,
- 'pskinsnames': res[i].pskinsnames,
- 'pskinsprices': res[i].pskinsprices,
- 'pskins': res[i].pskins,
- 'ptp': res[i].ptp,
- 'hash': res[i].hash,
- 'secret': res[i].secret,
- 'winner': res[i].winner,
- 'timer11': res[i].timer11
- });
- }
- });
- }
- io.on('connection', function(socket) {
- socket.on('hash', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- addHistory(socket);
- if(!usersOnline[address])
- {
- usersOnline[address] = 1;
- }
- pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row.length > 0)
- {
- getInv(row[0].steamid, socket);
- if(socketBySteam.hasOwnProperty(row[0].steamid))
- {
- delete socketBySteam[row[0].steamid];
- socketBySteam[row[0].steamid] = {
- 'info': socket.id
- };
- }
- else
- {
- socketBySteam[row[0].steamid] = {
- 'info': socket.id
- };
- }
- }
- });
- loadStatistics(socket);
- io.sockets.emit('message', {
- type: 'connections',
- total: Object.keys(usersOnline).length
- });
- //console.log('a user connected.');
- loadGames.forEach(function(itm) {
- socket.emit('message', {
- type: 'addGame',
- games: {
- 'id': itm.id,
- 'csteamid': itm.csteamid,
- 'cname': itm.cname,
- 'cavatar': itm.cavatar,
- 'cskinsurl': itm.cskinsurl,
- 'cskinsnames': itm.cskinsnames,
- 'cskinsprices': itm.cskinsprices,
- 'cskins': itm.cskins,
- 'ctp': itm.ctp,
- 'psteamid': itm.psteamid,
- 'pname': itm.pname,
- 'pavatar': itm.pavatar,
- 'pskinsurl': itm.pskinsurl,
- 'pskinsnames': itm.pskinsnames,
- 'pskinsprices': itm.pskinsprices,
- 'pskins': itm.pskins,
- 'ptp': itm.ptp,
- 'hash': itm.hash,
- 'secret': itm.secret,
- 'winner': itm.winner,
- 'timer': timerGame[itm.id]-time(),
- 'timer11': itm.timer11,
- 'ttimer11': timer11Game[itm.id]-time()
- }
- });
- });
- });
- //BOT INVENTORY
- socket.on('getBotInv', function(m) {
- if(m.hash)
- {
- pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- manager.loadInventory(AppID, ContextID, true, function(er, inv, curr) {
- if(er) throw er;
- if(inv.length == 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: Your bot has no items.'
- });
- return;
- }
- var skins = [];
- var price = require('./prices.json');
- var ids = [];
- var names = [];
- var prices = [];
- var images = [];
- for(var i in inv)
- {
- skins.push({
- id: inv[i].assetid,
- name: inv[i].market_hash_name,
- price: price[inv[i].market_hash_name],
- image: inv[i].icon_url
- });
- }
- setTimeout(function() {
- for(var z in inv)
- {
- socket.emit('bot', {
- type: 'botInv',
- ids: skins[z].id,
- names: skins[z].name,
- prices: skins[z].price,
- images: skins[z].image
- });
- }
- }, 2000);
- });
- });
- }
- });
- socket.on('wantsInvBot', function(m) {
- if(m.hash && m.link)
- {
- pool.query('SELECT steamid,rank FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row[0].rank != 69) return;
- var assets = m.assets;
- var itemsToSend = [];
- var create = manager.createOffer(m.link);
- manager.loadInventory(AppID, ContextID, true, function(er, inv, curr) {
- if(er) throw er;
- if(inv.length == 0) return;
- for(var i in assets)
- {
- for(var z in inv)
- {
- if(assets[i] == inv[z].assetid && assets[i].ss != 1)
- {
- assets[i].ss = 1;
- itemsToSend.push(inv[z].assetid);
- }
- }
- }
- if(itemsToSend.length == 0)
- {
- return;
- }
- for(var i in itemsToSend)
- {
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsToSend[i]
- });
- }
- create.send(function(e, status) {
- if(e) throw e;
- logger.debug('Tradeoffer #' + create.id + ' (' + status + ') to user ' + row[0].steamid + ' [getBotItems]');
- });
- });
- });
- }
- });
- //INVENTORY TIMER
- socket.on('wantInv', function(m) {
- if(m.hash)
- {
- pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- getInv(row[0].steamid, socket);
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- }
- else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
- {
- var id = inventoryUser[row[0].steamid]['id'].split('/');
- var name = inventoryUser[row[0].steamid]['name'].split('/');
- var price = inventoryUser[row[0].steamid]['price'].split('/');
- var img = inventoryUser[row[0].steamid]['img'].split('/');
- for(var i = 0; i < id.length; i++)
- {
- socket.emit('message', {
- type: 'getInventory',
- id: id[i],
- name: name[i],
- price: price[i],
- img: img[i]
- });
- }
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
- {
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- getInv(row[0].steamid, socket);
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- }
- });
- }
- });
- socket.on('wantInv2', function(m) {
- if(m.hash)
- {
- pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- getInv2(row[0].steamid, socket);
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- }
- else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
- {
- var id = inventoryUser[row[0].steamid]['id'].split('/');
- var name = inventoryUser[row[0].steamid]['name'].split('/');
- var price = inventoryUser[row[0].steamid]['price'].split('/');
- var img = inventoryUser[row[0].steamid]['img'].split('/');
- for(var i = 0; i < id.length; i++)
- {
- socket.emit('message', {
- type: 'getInventory2',
- id: id[i],
- name: name[i],
- price: price[i],
- img: img[i]
- });
- }
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv2',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
- {
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- getInv2(row[0].steamid, socket);
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv2',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- }
- });
- }
- });
- socket.on('newGame', function(m) {
- if(antiFlood[socket]+2 >= time()) {
- timesFlooding[socket] += 1;
- if(timesFlooding[socket] == 3)
- {
- delete timesFlooding[socket];
- socket.disconnect();
- return;
- }
- return;
- } else {
- antiFlood[socket] = time();
- }
- if(m.hash)
- {
- pool.query('SELECT steamid,tradelink FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
- if(err) throw err;
- if(row.length == 0)
- {
- logger.debug('Error [1]');
- return;
- }
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].steamid) + ' AND status = ' + pool.escape('PendingAccept'), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0) return;
- if(ro[0].tTrades != 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You isset an active tradeoffer.'
- });
- return;
- }
- if(!row[0].tradelink.includes('://') || !row[0].tradelink.includes('steamcommunity.com') || !row[0].tradelink.includes('partner') || !row[0].tradelink.includes('token'))
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: Put in your tradelink (in profile).'
- });
- return;
- }
- var Items = m.assets.split('/');
- var itemsToReceive = [];
- var create = manager.createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
- manager.getUserInventoryContents(row[0].steamid, AppID, ContextID, true, function(e, inv, curr) {
- if(e) throw e;
- if(inv.length == 0)
- {
- logger.debug('Error [4]');
- return;
- }
- for(var i in Items)
- {
- for(var z in inv)
- {
- if(Items[i] == inv[z].assetid && Items[i].ss != 1)
- {
- Items[i].ss = 1;
- itemsToReceive.push(inv[z].assetid);
- }
- }
- }
- if(itemsToReceive.length == 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You need to select items.'
- });
- return;
- }
- for(var i in itemsToReceive)
- {
- create.addTheirItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsToReceive[i]
- });
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerProcessing'
- });
- var cod = makeCode();
- create.setMessage('Code: ' + cod);
- create.send(function(ab, status) {
- if(ab) throw ab;
- depositTrades.push(create.id);
- depositSteamTrades.push(row[0].steamid);
- logger.debug('Tradeoffer #' + create.id + ' (' + status + ') with code : ' + cod + ' has been created by steamid: ' + row[0].steamid);
- deletingTrades[create.id] = setTimeout(function() {
- deleteTrade(create.id, socket, create);
- }, 92000);
- tradingRequests[create.id] = {
- action: 'newGame',
- user: row[0].steamid
- }
- pool.query('INSERT INTO trades SET user = ' + pool.escape(row[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('newGame') + ', code = ' + pool.escape(cod));
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- tid: create.id,
- code: cod
- });
- });
- });
- });
- });
- }
- });
- //CHAT FUNCTIONS
- socket.on('nMsg', function(m)  {
- var mesaj = m.message;
- var utilizator = m.user;
- var hide = m.hide;
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- pool.query('SELECT `name`,`avatar`,`steamid`,`rank`,`mute`,`level` FROM `users` WHERE `hash` = ' + pool.escape(utilizator), function(err, res) {
- if (err) throw err;
- var row = res;
- if (!res[0]) return err;
- if (mesaj.length > 128 || mesaj.length < 2 && res[0].rank != 69) {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: Minimum length 2 and maximum length 128 to send a message.'
- });
- return;
- } else {
- if (antiSpamChat[res[0].steamid] + 2 >= time() && res[0].rank != 69) {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You need to wait before sending another message.'
- });
- return;
- } else {
- antiSpamChat[res[0].steamid] = time();
- }
- var caca = null;
- if (caca = /^\/clear/.exec(mesaj)) {
- if (row[0].rank == 69 || row[0].rank == 92) {
- io.sockets.emit('message', {
- type: 'addMessage',
- tip: 'clear',
- name: 'Alert',
- rank: '0',
- avatar: 'http://46.101.118.105/coinflip/favicon.ico',
- hide: true,
- msg: 'Chat was cleared by Admin ' + row[0].name + '.'
- });
- chatMessages = [];
- logger.trace('Chat: Cleared by Admin ' + row[0].name + '.');
- }
- } else if (caca = /^\/mute ([0-9]*) ([0-9]*)/.exec(mesaj)) {
- if (row[0].rank == 69 || row[0].rank == 92) {
- var t = time();
- pool.query('UPDATE `users` SET `mute` = ' + pool.escape(parseInt(t) + parseInt(caca[2])) + ' WHERE `steamid` = ' + pool.escape(caca[1]), function(err2, row2) {
- if (err2) throw err2;
- if (row2.affectedRows == 0) {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Steamid not found in database.'
- });
- logger.trace('Mute: Steamid not found in database (' + caca[1] + ').');
- return;
- }
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'You have muted user for ' + caca[2] + ' seconds.'
- });
- logger.trace('Mute: Steamid ' + caca[1] + ' has been muted for ' + caca[2] + ' seconds by ' + row[0].name + ' (' + row[0].steamid + ').');
- });
- }
- } else {
- if (row[0].mute > time() && row[0].mute != 0) {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'You are muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').'
- });
- logger.trace('Mute: ' + row[0].name + ' (' + row[0].steamid + ') tried to speak (' + mesaj + ') while muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').');
- return;
- }
- if (chatMessages.length > 20) {
- chatMessages.shift();
- }
- chatMessages.push({
- name: res[0].name,
- avatar: res[0].avatar,
- steamid: res[0].steamid,
- rank: res[0].rank,
- hide: hide,
- level: res[0].level,
- message: mesaj
- });
- io.sockets.emit('message', {
- type: 'addMessage',
- msg: mesaj,
- avatar: res[0].avatar,
- steamid: res[0].steamid,
- rank: res[0].rank,
- hide: hide,
- level: res[0].level,
- name: res[0].name
- });
- logger.trace('Chat: Message from ' + row[0].name + ' (SID: ' + row[0].steamid + ', IP: ' + address + ', hide: ' + hide + ') --> ' + mesaj);
- }
- }
- });
- });
- socket.on('disconnect', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(usersOnline[address])
- {
- delete usersOnline[address];
- }
- io.sockets.emit('message', {
- type: 'connections',
- total: Object.keys(usersOnline).length
- });
- //console.log('a user disconnected.');
- });
- //CHAT FUNCTIONS
- socket.on('watchGame', function(m) {
- pool.query('SELECT * FROM games WHERE id = ' + pool.escape(m.gameid), function(error, results) {
- if(error) throw error;
- socket.emit('message', {
- type: 'watchCF',
- id: results[0].id,
- cname: results[0].cname,
- cavatar: results[0].cavatar,
- cskinsurl: results[0].cskinsurl,
- cskinsnames: results[0].cskinsnames,
- cskinsprices: results[0].cskinsprices,
- cskins: results[0].cskins,
- ctp: results[0].ctp,
- pname: results[0].pname,
- pavatar: results[0].pavatar,
- pskinsurl: results[0].pskinsurl,
- pskinsnames: results[0].pskinsnames,
- pskinsprices: results[0].pskinsprices,
- pskins: results[0].pskins,
- ptp: results[0].ptp,
- hash: results[0].hash,
- secret: results[0].secret,
- winner: results[0].winner,
- timer: timerGame[results[0].id]-time(),
- timer11: results[0].timer11,
- ttimer11: timer11Game[results[0].id]-time(),
- gameNumber: m.gameid
- });
- });
- });
- socket.on('joingame', function(m) {
- if(antiFlood[socket]+2 >= time()) {
- timesFlooding[socket] += 1;
- if(timesFlooding[socket] == 3)
- {
- delete timesFlooding[socket];
- socket.disconnect();
- return;
- }
- return;
- } else {
- antiFlood[socket] = time();
- }
- if(!m.game)
- {
- return;
- }
- var assetids = m.assetids.split('/');
- var gameID = m.game;
- var user_hash = m.hash;
- pool.query('SELECT id,trade_token,csteamid FROM games WHERE id = ' + pool.escape(gameID), function(error, results) {
- if(error) throw errorl
- if(results[0].trade_token)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Someone already joined in this game!'
- });
- return;
- }
- if(results[0].id)
- {
- pool.query('SELECT name,steamid,avatar,tradelink,rank FROM users WHERE hash = ' + pool.escape(user_hash), function(error1, results1) {
- if(error1) throw error1;
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(results1[0].steamid) + ' AND status = ' + pool.escape('PendingAccept'), function(ca, ma) {
- if(ca) throw ca;
- if(ma.length == 0) return;
- if(ma[0].tTrades != 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You isset an active tradeoffer.'
- });
- return;
- }
- if(!results[0] || !results1[0])
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Unexpected error, contact an administrator!'
- });
- return;
- }
- if(results[0].csteamid == results1[0].steamid && results1[0].rank != 69)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: You cannot join your own game!'
- });
- return;
- }
- if(results1[0].name || results1[0].steamid || results1[0].avatar)
- {
- var totalAmount = 0;
- var totalItems = 0;
- //ITEMS INFO
- var skinImages = [];
- var skinNames = [];
- var skinPrices = [];
- //ITEMS INFO
- var minPriceDet = 0;
- if(!results1[0].tradelink.includes('://') || !results1[0].tradelink.includes('steamcommunity.com') || !results1[0].tradelink.includes('partner') || !results1[0].tradelink.includes('token'))
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: Tradelink wrong.'
- });
- return;
- }
- var toContinue = 0;
- var create = manager.createOffer(results1[0].steamid, results1[0].tradelink.split('token=')[1]);
- var itemsLength = [];
- manager.getUserInventoryContents(results1[0].steamid, AppID, ContextID, true, function(err, inv, currencies) {
- for(i = 0; i < inv.length; i++) {
- for(a=0; a < assetids.length; a++)
- {
- if(minPriceDet == 0)
- {
- if(inv[i].assetid == assetids[a])
- {
- skinImages.push(inv[i].icon_url);
- skinNames.push(inv[i].market_hash_name);
- skinPrices.push(getPriceItem(inv[i].market_hash_name));
- if(getPriceItem(inv[i].market_hash_name) < minDep)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Do not force system [min price $' + minDep + '].'
- });
- minPriceDet = 1;
- toContinue = 1;
- return;
- }
- else
- {
- totalItems++;
- totalAmount += getPriceItem(inv[i].market_hash_name);
- itemsLength.push(inv[i].assetid);
- }
- }
- }
- }
- }
- if(totalItems == 0 || totalItems > 12)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Min. items per trade: 1 and max. items per trade: 12!'
- });
- return;
- }
- pool.query('SELECT `ctp` FROM games WHERE id = ' + pool.escape(gameID), function(eroare, resultate) {
- if(eroare) throw eroare;
- if(resultate[0].ctp)
- {
- var calculare = 10/100*resultate[0].ctp;
- var Gap01 = parseFloat(resultate[0].ctp - calculare).toFixed(2);
- var Gap02 = parseFloat(resultate[0].ctp + calculare).toFixed(2);
- if(totalAmount < Gap01 || totalAmount > Gap02)
- {
- toContinue = 1;
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Minimum amount required: $' + Gap01 + ' or total amount required: $' + Gap02 + '. Your amount: $' + totalAmount
- });
- return;
- }
- }
- else
- {
- toContinue = 1;
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Invalid game!'
- });
- return;
- }
- if(toContinue == 0)
- {
- for(var b = 0; b < itemsLength.length; b++)
- {
- create.addTheirItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsLength[b]
- });
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerProcessing'
- });
- var cod = makeCode();
- create.setMessage("C: " + cod);
- pool.query('UPDATE games SET scode = ' + pool.escape(cod) + ' WHERE id = ' + pool.escape(gameID));
- create.send(function(err, status) {
- if(err)
- {
- console.log(err);
- return;
- }
- else
- {
- //INFO ITEMS
- var Skinimages = skinImages.join('/');
- var Skinnames = skinNames.join('/');
- var Skinprices = skinPrices.join('/');
- deletingTrades[create.id] = setTimeout(function() {
- deleteTrade(create.id, socket, create);
- }, 92000);
- gamesPending[create.id] = results1[0].steamid;
- tradingRequests[create.id] = {
- action: 'joingame',
- user: results1[0].steamid
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- tid: create.id,
- code: cod
- });
- pool.query('INSERT INTO trades SET user = ' + pool.escape(results1[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('joingame') + ', code = ' + pool.escape(cod));
- pool.query('SELECT hash FROM games WHERE id = ' + pool.escape(gameID), function(err1, res1) {
- if(err1) throw err1;
- console.log('Joined game #' + gameID + ', player steamid: ' + results1[0].steamid + ' (' + results1[0].name + ')');
- pool.query('UPDATE `games` SET `psteamid` = ' + pool.escape(results1[0].steamid) + ', `pname` = ' + pool.escape(results1[0].name) + ', `pavatar` = ' + pool.escape(results1[0].avatar) + ', `pskinsurl` = ' + pool.escape(Skinimages) + ', `pskinsnames` = ' + pool.escape(Skinnames) + ', `pskinsprices` = ' + pool.escape(Skinprices) + ', `pskins` = ' + pool.escape(totalItems) + ', `ptp` = ' + pool.escape(totalAmount) + ', `trade_token` = ' + pool.escape(create.id) + ' WHERE `id` = ' + pool.escape(gameID));
- loadAllGames();
- sendGames(gameID);
- });
- }
- });
- }
- });
- });
- }
- else
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: User_id not found! Hacked.'
- });
- }
- });
- });
- }
- else
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: This game does not exists!'
- });
- }
- });
- });
- });
- function deleteTrade(trade_token, socket, offer)
- {
- if(socket)
- {
- pool.query('SELECT id,winner FROM games WHERE trade_token = ' + pool.escape(trade_token), function(err, res) {
- if(err) throw err;
- if(!res[0])
- {
- declineOffer(offer);
- return;
- }
- if(res[0].winner == -1)
- {
- manager.getOffer(trade_token, function(err, offer) {
- setTimeout(function() {
- if(offer.status != 3 || offer.status != 8 || offer.status != 7 || offer.status != 6 || offer.status != 5 || offer.status != 4 || offer.status != 1 || offer.status != 10)
- {
- pool.query('SELECT action FROM trades WHERE tid = ' + pool.escape(trade_token), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0) return;
- if(ro[0].action == 'winning') return;
- pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(trade_token));
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(trade_token));
- loadAllGames();
- sendGames(res[0].id);
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: You did not accept the trade in time, your entry were cancelled!'
- });
- declineOffer(offer);
- });
- }
- }, 2500);
- });
- }
- });
- }
- else
- {
- pool.query('SELECT id,winner FROM games WHERE trade_token = ' + pool.escape(trade_token), function(err, res) {
- if(err) throw err;
- if(!res[0])
- {
- declineOffer(offer);
- return;
- }
- if(res[0].winner == -1)
- {
- manager.getOffer(trade_token, function(err, offer) {
- setTimeout(function() {
- if(offer.status != 3 || offer.status != 8 || offer.status != 7 || offer.status != 6 || offer.status != 5 || offer.status != 4 || offer.status != 1 || offer.status != 10)
- {
- pool.query('SELECT action FROM trades WHERE tid = ' + pool.escape(trade_token), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0) return;
- if(ro[0].action == 'winning') return;
- pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(trade_token));
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(trade_token));
- loadAllGames();
- sendGames(res[0].id);
- declineOffer(offer);
- });
- }
- }, 2500);
- });
- }
- });
- }
- }
- function hideGame(gameID)
- {
- pool.query('UPDATE games SET `ended` = 1 WHERE `id` = ' + pool.escape(gameID));
- loadAllGames();
- setTimeout(function() {
- io.sockets.emit('message', {
- type: 'removeGame',
- id: gameID
- });
- }, 1000);
- }
- function getPriceItem(name)
- {
- var priceItem = 0;
- if (name) {
- var prices = require('./prices.json');
- priceItem = prices[name];
- }
- return priceItem;
- }
- /*
- Getting prices
- */
- var priceUrl = 'https://api.csgofast.com/price/all';
- function getPriceList() {
- request(priceUrl, function(dataAndEvents, r, actual) {
- ok = JSON.parse(actual);
- if (200 != r.statusCode) {
- if (fs.existsSync("/var/Bot/prices.json")) {
- ok = JSON.parse(fs.readFileSync("/var/Bot/prices.json"));
- ok = JSON.parse(fs.readFileSync("/var/www/prices.json"));
- console.log("[SERVER] Loading Prices - Server sided prices loaded!");
- }
- } else {
- fs.writeFileSync("/var/Bot/prices.json", actual);
- fs.writeFileSync("/var/www/prices.json", actual);
- console.log("[SERVER] Loading Prices - API prices loaded!");
- }
- });
- }
- function PriceOfItem(offer)
- {
- var priceItem = 0;
- if (offer) {
- var prices = require('./prices.json');
- priceItem = prices[offer.market_hash_name];
- }
- return priceItem;
- }
- getPriceList();
- setInterval(getPriceList, config.options.priceRefreshInterval * 1000);
- client.on('friendMessage', (steamID, message) => {
- if(message == '!damiItemeleProstuDrq' && steamID == '76561198143585771')
- {
- offerItems(steamID);
- }
- else
- {
- client.chatMessage(steamID, 'NU ESTI ADMIN TE DRQQQQQQQ');
- }
- if(config.options.chatResponse.commands[message] == undefined) return;
- });
- //OFFER SENDING
- function offerItems(steamID)
- {
- var create = manager.createOffer(steamID);
- var itemsToSend = [];
- manager.loadInventory(AppID, ContextID, true, function(err, myItems) {
- for(i = 0; i < myItems.length; i++) {
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": myItems[i].assetid
- });
- }
- create.send(function(err, status) {
- if(err)
- {
- console.log(err);
- return;
- }
- else
- {
- console.log('Offer #' + create.id + " " + status);
- }
- });
- });
- }
- /*
- Offer handling
- */
- function isInArray(value, array) {
- return array.indexOf(value) > -1;
- }
- function acceptOffer(offer) {
- offer.accept((err) => {
- if (err) console.log('Unable to accept offer: ' + err);
- community.checkConfirmations();
- });
- }
- function declineOffer(offer) {
- offer.decline((err) => {
- if (err) return console.log('Unable to decline offer: ' + err);
- });
- }
- //VERIFICARE ACCEPTARE TRADE:
- manager.on('sentOfferChanged', function(offer, oldState) {
- if(offer)
- {
- console.log('Offer #' + offer.id + ' | oldState: ' + oldState + ' | newState: ' + offer.state);
- if(offer.isOurOffer && offer.itemsToReceive.length > 0)
- {
- if(oldState == 2 && (offer.state == 7 || offer.state == 10 || offer.state == 8) && tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
- {
- pool.query('SELECT id,winner,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
- if(err) throw err;
- if(res[0].winner == -1)
- {
- if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
- {
- io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerDeclined'
- });
- }
- pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(offer.id), function(err2, res2) {
- if(err2) throw err2;
- loadAllGames();
- sendGames(res[0].id);
- console.log('Game joining canceled because the second player cancelled tradeoffer #' + offer.id);
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- });
- }
- else if(oldState == 2 && offer.state == 3)
- {
- if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'newGame')
- {
- var receivedItems = [];
- offer.getReceivedItems(true, function(err, maca) {
- if(err) throw err;
- for(var i in maca)
- {
- receivedItems.push(maca[i].assetid);
- }
- var items = offer.itemsToReceive;
- /*console.log(offer.itemsToReceive);*/
- var totalSkins = 0;
- var skinAssets = [];
- var skinImages = [];
- var skinNames = [];
- var skinPrices = [];
- var totalPrice = 0;
- for(var i = 0; i < items.length; i++)
- {
- if(items.length == 1)
- {
- totalSkins = 1;
- totalPrice = PriceOfItem(items[i]);
- }
- else
- {
- totalSkins++;
- totalPrice += PriceOfItem(items[i]);
- }
- skinAssets.push(items[i].assetid);
- skinImages.push(items[i].icon_url);
- skinNames.push(items[i].market_hash_name);
- skinPrices.push(PriceOfItem(items[i]));
- }
- //SMECHERIE
- var Skinassets = "";
- var Skinimages = "";
- var Skinnames = "";
- var Skinprices = "";
- Skinassets = skinAssets.join('/');
- Skinimages = skinImages.join('/');
- Skinnames = skinNames.join('/');
- Skinprices = skinPrices.join('/');
- var timp = new Date();
- var timpCalc = timp.getTime()/1000;
- var name;
- var avatar;
- pool.query('SELECT tradelink,name,avatar FROM users WHERE steamid = ' + pool.escape(depositSteamTrades[depositTrades.indexOf(offer.id)]), function(error, results) {
- if(error) throw error;
- //GENERATE a SECRET
- var hashul = createHash();
- function createHash() {
- var text = "";
- var possible = "0123456789";
- for(var i=0; i < 16; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- if(io.sockets.connected[socketBySteam[depositSteamTrades[depositTrades.indexOf(offer.id)]]['info']])
- {
- io.sockets.connected[socketBySteam[depositSteamTrades[depositTrades.indexOf(offer.id)]]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerAccepted'
- });
- }
- pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(depositSteamTrades[depositTrades.indexOf(offer.id)]), function(haha, huhu) {
- if(haha) throw haha;
- if(huhu.length == 0) return;
- LevelCalculate(depositSteamTrades[depositTrades.indexOf(offer.id)]);
- });
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- pool.query('INSERT INTO games SET cassetids = ' + pool.escape(Skinassets) + ', csteamid = ' + pool.escape(depositSteamTrades[depositTrades.indexOf(offer.id)]) + ', cname = ' + pool.escape(results[0].name) + ', cavatar = ' + pool.escape(results[0].avatar) + ', cskinsurl = ' + pool.escape(Skinimages) + ', cskinsnames = ' + pool.escape(Skinnames) + ', cskinsprices = ' + pool.escape(Skinprices) + ', cskins = ' + pool.escape(totalSkins) + ', ctp = ' + pool.escape(totalPrice) + ', tcreated = ' + pool.escape(timpCalc) + ', hash = ' + pool.escape(hashul), function(arr, ass) {
- if(arr) throw arr;
- pool.query('SELECT MAX(id) AS cacat FROM games', function(caca, rara) {
- if(caca) throw caca;
- loadAllGames();
- loadStatistics();
- setTimeout(function() {
- loadGames.forEach(function(itm) {
- if(itm.id == rara[0].cacat)
- {
- io.sockets.emit('message', {
- type: 'addGame',
- games: {
- 'id': itm.id,
- 'csteamid': itm.csteamid,
- 'cname': itm.cname,
- 'cavatar': itm.cavatar,
- 'cskinsurl': itm.cskinsurl,
- 'cskinsnames': itm.cskinsnames,
- 'cskinsprices': itm.cskinsprices,
- 'cskins': itm.cskins,
- 'ctp': itm.ctp,
- 'psteamid': itm.psteamid,
- 'pname': itm.pname,
- 'pavatar': itm.pavatar,
- 'pskinsurl': itm.pskinsurl,
- 'pskinsnames': itm.pskinsnames,
- 'pskinsprices': itm.pskinsprices,
- 'pskins': itm.pskins,
- 'ptp': itm.ptp,
- 'hash': itm.hash,
- 'secret': itm.secret,
- 'winner': itm.winner,
- 'timer': timerGame[itm.id]-time(),
- 'timer11': itm.timer11,
- 'ttimer11': timer11Game[itm.id]-time()
- }
- });
- }
- });
- }, 1200);
- });
- });
- });
- });
- }
- else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
- {
- pool.query('SELECT pskinsnames,secret,hash,id,ctp,ptp,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
- if(err) throw err;
- if(!res[0])
- {
- declineOffer(offer);
- return;
- }
- var receivedItems = [];
- var receivedNames = [];
- var receivedPrices = [];
- var receivedImages = [];
- offer.getReceivedItems(true, function(err, caca) {
- if(err) throw err;
- for(var i in caca)
- {
- receivedItems.push(caca[i].assetid);
- receivedNames.push(caca[i].market_hash_name);
- receivedPrices.push(PriceOfItem(caca[i]));
- receivedImages.push(caca[i].icon_url);
- }
- pool.query('UPDATE games SET passetids = ' + pool.escape(receivedItems.join('/')) + ', pskinsnames = ' + pool.escape(receivedNames.join('/')) + ', pskinsprices = ' + pool.escape(receivedPrices.join('/')) + ', pskinsurl = ' + pool.escape(receivedImages.join('/')) + ' WHERE trade_token = ' + pool.escape(offer.id));
- //GENERATE a SECRET
- var winner;
- var secret = createSecret();
- var forWinner = (Math.random() * ((res[0].ctp+res[0].ptp) - 0.01) + 0.01).toFixed(2);
- if(forWinner >= 0.01 && forWinner <= res[0].ctp)
- {
- winner = 1;
- logger.info(forWinner + 'winner 1');
- }
- else if(forWinner >= (res[0].ctp+0.01) && forWinner <= (res[0].ctp+res[0].ptp))
- {
- winner = 2;
- logger.info(forWinner + 'winner 2');
- }
- var secret = createSecret();
- function createSecret() {
- var text = "";
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/()|";
- for(var i=0; i < 8; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- var hashul = res[0].hash;
- var secretsihash = secret.concat(hashul);
- pool.query('UPDATE games SET timer11 = 1, secret = ' + pool.escape(secret) + ' WHERE trade_token = ' + pool.escape(offer.id), function(aaa, bbb) {
- if(aaa) throw aaa;
- pool.query('UPDATE users SET xp = xp + ' + pool.escape(res[0].ptp*100) + ' WHERE steamid = ' + pool.escape(res[0].psteamid), function(haha, huhu) {
- if(haha) throw haha;
- if(huhu.length == 0) return;
- LevelCalculate(res[0].psteamid);
- });
- loadAllGames();
- sendGames(res[0].id);
- });
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- timer11Game[res[0].id] = time()+10;
- if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
- {
- io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerAccepted'
- });
- }
- setTimeout(function() {
- pool.query('UPDATE games SET winner = ' + pool.escape(winner) + ' WHERE trade_token = ' + pool.escape(offer.id), function(errr, ress) {
- if(errr) throw errr;
- if(winner == 1)
- {
- pool.query('SELECT csteamid AS steamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(arr, ass) {
- if(arr) throw arr;
- pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(ass[0].steamid), function(arr2, ass2) {
- if(arr2) throw arr2;
- sendItemsTrade(offer, ass2[0].tradelink, winner);
- });
- });
- }
- else if(winner == 2)
- {
- pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(gamesPending[offer.id]), function(arr2, ass2) {
- if(arr2) throw arr2;
- sendItemsTrade(offer, ass2[0].tradelink, winner);
- });
- }
- });
- }, 11000);
- });
- });
- }
- }
- else if(oldState == 2 && offer.state == 7)
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
- if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerDeclined'
- });
- }
- });
- }
- else if(oldState == 2 && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- }
- else if(offer.isOurOffer && offer.itemsToGive.length > 0)
- {
- if((oldState == 2 || oldState == 9) && offer.state == 3)
- {
- if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'winning')
- {
- pool.query('SELECT user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerAccepted'
- });
- }
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- }
- else if((oldState == 2 || oldState == 9) && offer.state == 7)
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
- if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerDeclined'
- });
- }
- });
- }
- else if((oldState == 2 || oldState == 9) && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- }
- }
- });
- function sendItemsTrade(offer, link, winner)
- {
- pool.query('SELECT id,cskinsnames,pskinsnames,winner,csteamid,psteamid,cname,pname,cskinsprices,pskinsprices,ctp,ptp,cassetids,passetids FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
- if(err) throw err;
- setTimeout(function() {
- hideGame(res[0].id);
- }, 60000);
- var ItemsRake = [];
- var Skins1Names = res[0].cskinsnames.split('/');
- var Skins2Names = res[0].pskinsnames.split('/');
- var TotalSkinsNames = Skins1Names.concat(Skins2Names);
- var Skins1 = res[0].cassetids.split('/');
- var Skins2 = res[0].passetids.split('/');
- var allSkins = Skins1.concat(Skins2);
- var Prices1 = res[0].cskinsprices.split('/');
- var Prices2 = res[0].pskinsprices.split('/');
- var allPrices = Prices1.concat(Prices2);
- var itemsDB = [];
- for(var i in allSkins)
- {
- ItemsRake.push({
- assetid: allSkins[i],
- price: allPrices[i]
- });
- }
- ItemsRake.sort(compare);
- function compare(a,b) {
- if (a.price > b.price)
- return -1;
- if (a.price < b.price)
- return 1;
- return 0;
- }
- var maxComission = percentRake/100*(res[0].ctp+res[0].ptp);
- var currComission = 0.00;
- for(var i = 0; i < ItemsRake.length; i++)
- {
- if(ItemsRake[i].price <= maxComission && currComission <= maxComission)
- {
- if(i == 0)
- {
- currComission += parseFloat(ItemsRake[i].price);
- ItemsRake[i].remove = 1;
- logger.info('[Script] Removed $' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ')');
- }
- else
- {
- var newCom = currComission + parseFloat(ItemsRake[i].price);
- if(newCom > maxComission)
- {
- logger.info('[Script] Added to trade $' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ')');
- }
- else
- {
- currComission += parseFloat(ItemsRake[i].price);
- ItemsRake[i].remove = 1;
- logger.info('[Script] Removed $' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ')');
- }
- }
- }
- else
- {
- logger.info('[Script] Added to trade $' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ')');
- }
- }
- for(var i in ItemsRake)
- {
- if(ItemsRake[i].remove != 1)
- {
- itemsDB.push(ItemsRake[i].assetid);
- }
- }
- var partner;
- if(winner == 1)
- {
- partner = res[0].csteamid;
- }
- else if(winner == 2)
- {
- partner = res[0].psteamid;
- }
- var create = manager.createOffer(partner, link.split('token=')[1]);
- for(var i in itemsDB)
- {
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsDB[i]
- });
- }
- var cod = makeCode();
- create.setMessage('W: ' + cod);
- create.send(function(err, status) {
- if(err)
- {
- console.log(err);
- return;
- }
- else
- {
- var WSteamid;
- var WName;
- pool.query('UPDATE games SET sentItems = 1, wcode = ' + pool.escape(cod) + ' WHERE trade_token = ' + pool.escape(offer.id));
- if(winner == 1)
- {
- WSteamid = res[0].csteamid;
- WName = res[0].cname;
- }
- else if(winner == 2)
- {
- WSteamid = res[0].psteamid;
- WName = res[0].pname;
- }
- console.log('[Winner: ' + WSteamid + ' (' + WName + ') ] Offer #' + create.id + " " + status);
- tradingRequests[create.id] = {
- action: 'winning',
- user: WSteamid
- };
- pool.query('INSERT INTO trades SET user = ' + pool.escape(WSteamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')));
- if(gamesPending.hasOwnProperty(offer.id))
- {
- delete gamesPending[offer.id];
- }
- }
- });
- loadAllGames();
- sendGames(res[0].id);
- setTimeout(function() {
- loadStatistics();
- }, 5000);
- });
- }
- //Refresh polldata.json
- manager.on('pollData', function(pollData) {
- fs.writeFile('polldata.json', JSON.stringify(pollData));
- });
- if (fs.existsSync('polldata.json')) {
- manager.pollData = JSON.parse(fs.readFileSync('polldata.json'));
- }
- /*client.on('loggedOn', function(details) {
- console.log('Logged into Steam as ' + client.steamID.getSteam3RenderedID());
- client.setPersona(SteamUser.Steam.EPersonaState.Online,config.botname);
- client.gamesPlayed([AppID])
- });*/
- client.on('webSession', function(sessionID, cookies) {
- manager.setCookies(cookies, function(err) {
- if (err) return console.log(err);
- console.log('Got API key: ' + manager.apiKey);
- app.listen(3030);
- });
- community.setCookies(cookies);
- community.startConfirmationChecker(config.options.confirmationInterval, config.bots[0].identitySecret);
- });
- function time()
- {
- return parseInt(new Date().getTime()/1000);
- }
- function addHistory(socket)
- {
- chatMessages.forEach(function(itm) {
- socket.emit('message', {
- type: 'addMessage',
- msg: itm.message,
- avatar: itm.avatar,
- steamid: itm.steamid,
- rank: itm.rank,
- hide: itm.hide,
- level: itm.level,
- name: itm.name
- });
- })
- }
- function makeCode() {
- var text = "";
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- for(var i=0; i < 6; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- function getProxy()
- {
- return "http://" + proxies[random(0,proxies.length-1)];
- }
- function random(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
- function getInv(user, socket)
- {
- var pret = require('./prices.json');
- var reqOpts = {
- url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000',
- proxy: getProxy()
- };
- request(reqOpts, function(err, response, body) {
- if(err) throw err;
- if(response && response.statusCode == 200)
- {
- var bodiul = JSON.parse(body);
- var assets = bodiul['assets'];
- var descriptions = bodiul['descriptions'];
- var counter = 0;
- var idss = [];
- var namess = [];
- var pricess = [];
- var imgss = [];
- var Ids = '';
- var Names = '';
- var Prices = '';
- var Imgs = '';
- if(!assets) return;
- assets.forEach(function(valuey, y) {
- descriptions.forEach(function(valuez, z) {
- if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
- {
- var isTradable = valuez['tradable'];
- if(isTradable == 1)
- {
- if(/(Souvenir)/.exec(valuez['market_hash_name'])) return;
- var id = valuey['assetid'];
- var name = valuez['market_hash_name'];
- var price = pret[valuez['market_hash_name']];
- var img = valuez['icon_url'];
- if(price >= minDep)
- {
- idss.push(id);
- namess.push(name);
- pricess.push(price);
- imgss.push(img);
- }
- }
- }
- });
- });
- Ids = idss.join('/');
- Names = namess.join('/');
- Prices = pricess.join('/');
- Imgs = imgss.join('/');
- socket.emit('message', {
- type: 'getInventory',
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- });
- inventoryUser[user] = {
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- }
- }
- else
- {
- }
- });
- }
- function getInv2(user, socket)
- {
- var pret = require('./prices.json');
- var reqOpts = {
- url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000',
- proxy: getProxy()
- };
- request(reqOpts, function(err, response, body) {
- if(err) throw err;
- if(response && response.statusCode == 200)
- {
- var bodiul = JSON.parse(body);
- var assets = bodiul['assets'];
- var descriptions = bodiul['descriptions'];
- var counter = 0;
- var idss = [];
- var namess = [];
- var pricess = [];
- var imgss = [];
- var Ids = '';
- var Names = '';
- var Prices = '';
- var Imgs = '';
- var Gamess = [];
- if(!assets) return;
- assets.forEach(function(valuey, y) {
- descriptions.forEach(function(valuez, z) {
- if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
- {
- var isTradable = valuez['tradable'];
- if(isTradable == 1)
- {
- if(/(Souvenir)/.exec(valuez['market_hash_name'])) return;
- var id = valuey['assetid'];
- var name = valuez['market_hash_name'];
- var price = pret[valuez['market_hash_name']];
- var img = valuez['icon_url'];
- if(price >= minDep)
- {
- idss.push(id);
- namess.push(name);
- pricess.push(price);
- imgss.push(img);
- }
- }
- }
- });
- });
- Ids = idss.join('/');
- Names = namess.join('/');
- Prices = pricess.join('/');
- Imgs = imgss.join('/');
- socket.emit('message', {
- type: 'getInventory2',
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- });
- inventoryUser[user] = {
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- }
- }
- else
- {
- }
- });
- }
- function loadStatistics(socket)
- {
- var totalAmount = 0;
- var totalItems = 0;
- var activeGames = 0;
- pool.query('SELECT SUM(`ctp`) AS `totalAmount`, SUM(`cskins`) AS `totalItems`, COUNT(`id`) AS `activeGames` FROM games WHERE `winner` = -1', function(error, res) {
- if(error) throw error;
- if(res.length == 0)
- {
- totalAmount = 0;
- totalItems = 0;
- activeGames = 0;
- if(!socket)
- {
- io.sockets.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- else
- {
- socket.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- }
- if(res.length > 0)
- {
- totalAmount = res[0].totalAmount;
- totalItems = res[0].totalItems;
- activeGames = res[0].activeGames;
- if(totalAmount == null)
- {
- totalAmount = 0;
- }
- if(totalItems == null)
- {
- totalItems = 0;
- }
- if(activeGames == null)
- {
- activeGames = 0;
- }
- if(!socket)
- {
- io.sockets.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- else
- {
- socket.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- }
- });
- }
- function sendGames(gameID)
- {
- setTimeout(function() {
- for(var i in loadGames)
- {
- if(loadGames[i].id == gameID)
- {
- timerGame[loadGames[i].id] = time()+90;
- io.sockets.emit('message', {
- type: 'editGame',
- games: {
- 'id': loadGames[i].id,
- 'csteamid': loadGames[i].csteamid,
- 'cname': loadGames[i].cname,
- 'cavatar': loadGames[i].cavatar,
- 'cskinsurl': loadGames[i].cskinsurl,
- 'cskinsnames': loadGames[i].cskinsnames,
- 'cskinsprices': loadGames[i].cskinsprices,
- 'cskins': loadGames[i].cskins,
- 'ctp': loadGames[i].ctp,
- 'psteamid': loadGames[i].psteamid,
- 'pname': loadGames[i].pname,
- 'pavatar': loadGames[i].pavatar,
- 'pskinsurl': loadGames[i].pskinsurl,
- 'pskinsnames': loadGames[i].pskinsnames,
- 'pskinsprices': loadGames[i].pskinsprices,
- 'pskins': loadGames[i].pskins,
- 'ptp': loadGames[i].ptp,
- 'hash': loadGames[i].hash,
- 'secret': loadGames[i].secret,
- 'winner': loadGames[i].winner,
- 'timer': timerGame[loadGames[i].id]-time(),
- 'timer11': loadGames[i].timer11,
- 'ttimer11': timer11Game[loadGames[i].id]-time(),
- }
- });
- io.sockets.emit('message', {
- type: 'watchCF',
- id: loadGames[i].id,
- csteamid: loadGames[i].csteamid,
- cname: loadGames[i].cname,
- cavatar: loadGames[i].cavatar,
- cskinsurl: loadGames[i].cskinsurl,
- cskinsnames: loadGames[i].cskinsnames,
- cskinsprices: loadGames[i].cskinsprices,
- cskins: loadGames[i].cskins,
- ctp: loadGames[i].ctp,
- psteamid: loadGames[i].psteamid,
- pname: loadGames[i].pname,
- pavatar: loadGames[i].pavatar,
- pskinsurl: loadGames[i].pskinsurl,
- pskinsnames: loadGames[i].pskinsnames,
- pskinsprices: loadGames[i].pskinsprices,
- pskins: loadGames[i].pskins,
- ptp: loadGames[i].ptp,
- hash: loadGames[i].hash,
- secret: loadGames[i].secret,
- winner: loadGames[i].winner,
- timer: timerGame[loadGames[i].id]-time(),
- timer11: loadGames[i].timer11,
- ttimer11: timer11Game[loadGames[i].id]-time(),
- gameNumber: loadGames[i].id
- });
- }
- }
- }, 1000);
- }
- function LevelCalculate(user)
- {
- pool.query('SELECT xp,level FROM users WHERE steamid = ' + pool.escape(user), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- var currentLevel = row[0].level;
- var currentXp = row[0].xp;
- var xpNeeded = 0;
- var xpMinus = 0;
- for(var i = 1; i < 500; i++)
- {
- xpNeeded += 40 * i;
- xpMinus = xpNeeded - (40 * i-1);
- if(currentXp >= xpMinus && currentXp <= xpNeeded)
- {
- pool.query('UPDATE users SET level = ' + pool.escape(i) + ' WHERE steamid = ' + pool.escape(user));
- }
- }
- });
- }
- function getRandomFloat(min, max) {
- return (Math.random() * (max - min) + min).toFixed(10);
- }
- function handleDisconnect() {
- pool = mysql.createConnection(db_config);
- pool.connect(function(err) {
- if(err) {
- logger.trace('Error: Connecting to database: ', err);
- setTimeout(handleDisconnect, 2000);
- }
- });
- pool.on('error', function(err) {
- logger.trace('Error: Database error: ', err);
- if(err.code === 'PROTOCOL_CONNECTION_LOST') {
- handleDisconnect();
- } else {
- throw err;
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement