Advertisement
Guest User

Untitled

a guest
Nov 12th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.12 KB | None | 0 0
  1. let steamData = require("./steam.js");
  2. let colors = require('colors');
  3. let mysql = require('mysql');
  4. let bp = require('./bp.js');
  5. let tradesCount = require('./tradesCount.js');
  6.  
  7. let config = require('./config.json');
  8. let func = require('./functions.js');
  9.  
  10. var connection = mysql.createConnection({
  11. host: config.db.host,
  12. user: config.db.user,
  13. password: config.db.pass,
  14. database: config.db.dbname
  15. });
  16. connection.connect((err) => { if (err) { throw err; return; } });
  17.  
  18. var keysDefaultPrice = 34;
  19. var traded = 0;
  20.  
  21.  
  22.  
  23. // Sends a heartbeat to backpack.tf to keep the lightening symbol
  24. // bp.startAutomatic(config.myID, config.bpToken, function(err){
  25. // if (err) {console.log(err);return;}
  26. // });
  27.  
  28. // Handling friends request
  29. steamData.clientUser.on('friendRelationship', (steamID, relationship) => {
  30. if (relationship === 2) {
  31. steamData.clientUser.addFriend(steamID);
  32. console.log("A friend request from "+steamID+" was accepted.\n".green);
  33. console.log("**************************************************************************************************\n");
  34. steamData.clientUser.chatMessage(steamID, config.addMessage);
  35. steamData.clientUser.inviteToGroup(steamID, config.groupID);
  36. }
  37. });
  38.  
  39. steamData.clientUser.on('webSession', (sessionid, cookies) => {
  40. steamData.manager.setCookies(cookies);
  41. steamData.community.setCookies(cookies);
  42. steamData.community.startConfirmationChecker(5000, config.identitySecret);
  43. });
  44.  
  45. steamData.clientUser.on("friendMessage", function(steamID, message) {
  46. var procmsg = func.proccessMsg(message, steamID, config);
  47. switch(procmsg) {
  48. case 'update':
  49. steamData.clientUser.chatMessage(steamID, "Updating stock......"); updateCurrentStock(1);
  50. break;
  51. case 'calc':
  52. steamData.clientUser.chatMessage(steamID, "Calculating inventory value....."); calculateValue(1);
  53. break;
  54. case 'show calc':
  55. connection.query('select * from stats where day = ?', tradesCount.date(), function(err, stat) {
  56. if (err) { console.error(err); return false; }
  57. if (stat.length == 0) {
  58. steamData.clientUser.chatMessage(steamID, "No stats for today !");
  59. } else {
  60. connection.query('select * from items where name = ?', 'Mann Co. Supply Crate Key', function(err, keyResult) {
  61. setTimeout(function() { steamData.clientUser.chatMessage(steamID, "Todays stats are as follows:"); }, 1000);
  62. setTimeout(function() { steamData.clientUser.chatMessage(steamID, "I accepted "+stat[0].accepted+" trades today,"); }, 2000);
  63. setTimeout(function() { steamData.clientUser.chatMessage(steamID, "I declined "+stat[0].declined+","); }, 3000);
  64. setTimeout(function() { steamData.clientUser.chatMessage(steamID, "And "+stat[0].leftTrades+" were left,"); }, 4000);
  65. setTimeout(function() { steamData.clientUser.chatMessage(steamID, "With a value of "+stat[0].value+" ref ("+func.convert(stat[0].value, keyResult[0].buy_ref)+") so far."); }, 5000);
  66. });
  67. }
  68. });
  69. break;
  70. case 'todays':
  71. connection.query('select * from stats', function(err, stats) {
  72. var stat = func.inStats(stats, tradesCount.date());
  73. if (stat == false) { steamData.clientUser.chatMessage(steamID, "0 successful trades today."); }
  74. else if(stat == "err") {steamData.clientUser.chatMessage(steamID, "an error has accured");}
  75. else { steamData.clientUser.chatMessage(steamID, stat.accepted+" successful trades today."); }
  76. });
  77. break;
  78. case 'sort':
  79. tf2.sortBackpack(4); steamData.clientUser.chatMessage(config.ownerID, "Sorted !");
  80. console.log("Sorted !"); console.log("--------------------------------------------------------------------------------------------------\n");
  81. case false:
  82. connection.query('select * from items', function(err, itemsResult) {
  83. if (err) { console.error(err); return false; }
  84. var msgItems= [];
  85. if (message.length > 3) { for(var i = 0; i < itemsResult.length; i++) { if (itemsResult[i].name.toLowerCase().indexOf(message.toLowerCase()) != -1 && (itemsResult[i].sell_key > 0 || itemsResult[i].sell_ref != 0.055)) { msgItems.push(itemsResult[i]); } } }
  86. if (msgItems.length == 0) {
  87. message = message.split(" ");
  88. var i = 0; while (i < message.length) { if (message[i] == "") { message.splice(i, 1); } else { i++; } }
  89. if (message[0] == "msg" && steamID == config.ownerID) {
  90. if (message[1] && message[2]) {
  91. var usrID = message[1];
  92. message.splice(0, 2); var msg = message.join(" ");
  93. steamData.clientUser.chatMessage(usrID, msg);
  94. }else {
  95. if (!message[1]) {
  96. console.log("No SteamID provided !");
  97. } else {
  98. if (message[1] != parseInt(message[1])) {
  99. console.log("User's steamID need to be given first");
  100. } else {
  101. if (!message[2]) {
  102. console.log("we can't send an empty message");
  103. }
  104. }
  105. }
  106. }
  107. console.log("--------------------------------------------------------------------------------------------------\n");
  108. }
  109. } else if(msgItems.length == 1) {
  110. steamData.clientUser.chatMessage(steamID, func.msgItemData(msgItems[0]));
  111. } else {
  112. for (var i = 0; i < msgItems.length; i++) {
  113. if (i < 6) {
  114. steamData.clientUser.chatMessage(steamID, func.msgItemData(msgItems[i]));
  115. } else if(i == 6) {
  116. steamData.clientUser.chatMessage(steamID, "5 items is the limit if the item you're looking for isn't shown then you need to be more precise in the name.");
  117. break;
  118. }
  119. }
  120. }
  121. });
  122. break;
  123. default:
  124. steamData.clientUser.chatMessage(steamID, procmsg);
  125. break;
  126. }
  127. });
  128.  
  129. function updateCurrentStock(line = 0) {
  130. console.log('Updating Current Stock.....');
  131. steamData.manager.loadUserInventory(config.myID, 440, 2, true, (err, inventory) => {
  132. var query = connection.query('select * from items', function(err, result) {
  133. if (err) { console.error(err); return false; }
  134. for (var i = 0; i < result.length; i++) {
  135. var stock = 0;
  136. for (var j in inventory) {
  137. if (func.craftable(inventory[j]) == result[i].name) {
  138. stock++;
  139. }
  140. }
  141. connection.query(`update items set currentStock = ${stock} where name = ?`, result[i].name, function(err, result) {
  142. if (err) { console.error(err); return false; }
  143. });
  144. if (i == (result.length -1)) {
  145. if (line) {
  146. console.log("--------------------------------------------------------------------------------------------------\n");
  147. }
  148. }
  149. }
  150. });
  151. });
  152. }
  153.  
  154. function calculateValue(line = 0) {
  155. console.log('Calculating inventory value.....');
  156. steamData.manager.loadUserInventory('76561198273595803', 440, 2, true, (err, inventory) => {
  157. tradesCount.calcValue(inventory);
  158. if (line) {
  159. console.log("--------------------------------------------------------------------------------------------------\n");
  160. }
  161. });
  162. }
  163.  
  164. function acceptOffer(offer, donate = 0) {
  165. offer.accept((err) => {
  166. if (err) {
  167. if (err.message.indexOf("Please try again later" == -1)) { steamData.clientUser.chatMessage(config.ownerID, "there was an error accepting an offer"); }
  168. console.log(("Error: "+err.message+"\n").red);
  169. return false;
  170. } else {
  171. steamData.community.checkConfirmations();
  172. tradesCount.plus("accepted");
  173. if (donate) {
  174. console.log("the donation have been accepted\n".green);
  175. } else {
  176. console.log("the offer have been accepted\n".green);
  177. }
  178. traded = 1;
  179. }
  180. console.log("**************************************************************************************************");
  181. console.log("**************************************************************************************************\n");
  182. });
  183. return true;
  184. }
  185.  
  186. function declineOffer(offer) {
  187. offer.decline((err) => {
  188. console.log("the offer have been declined\n".red);
  189. tradesCount.plus("declined");
  190. console.log("**************************************************************************************************");
  191. console.log("**************************************************************************************************\n");
  192. if (err) console.log(("Error: "+err.message+"\n").red);
  193. });
  194. }
  195.  
  196. function processOffer(offer) {
  197. connection.query('select * from items', function(err, result) {
  198. if (err) { console.error(err); return false; }
  199. var notyet = 0, keysPrice = func.inItems(result, "Mann Co. Supply Crate Key");
  200. if (offer.isGlitched() || offer.state === 11) {
  201. console.log("Offer was glitched, declining.".red);
  202. notyet = 1;
  203. declineOffer(offer);
  204. } else if (offer.partner.getSteamID64() === config.ownerID) {
  205. console.log("The Owner sent a trade".blue);
  206. notyet = 1;
  207. acceptOffer(offer);
  208. } else {
  209. var ourItems = offer.itemsToGive;
  210. var theirItems = offer.itemsToReceive;
  211. var ourValue = 0, theirValue = 0, ourItemsList = {}, ourItemsNames = "", theirItemsList = {}, theirItemsNames = "";
  212. for (var i in ourItems) {
  213. var item = func.craftable(ourItems[i]);
  214. if (!ourItemsList[item]) { ourItemsList[item] = 1; } else { ourItemsList[item] += 1; }
  215. var itemData = func.inItems(result, item);
  216. if (itemData == false) {
  217. if (!notyet) {
  218. console.log("User has chosen an item that isn't in the database yet.\n".yellow);
  219. notyet = 1;
  220. }
  221. } else {
  222. if (itemData.sell_key > 0) {
  223. for (var i = 0; i < itemData.sell_key; i++) {
  224. ourValue = func.fixFloat(ourValue + keysPrice.sell_ref);
  225. }
  226. }
  227. ourValue = func.fixFloat(ourValue + itemData.sell_ref);
  228. }
  229. }
  230. for(var i in theirItems) {
  231. var item = func.craftable(theirItems[i]),
  232. itemType = theirItems[i].type;
  233. if (!theirItemsList[item]) { theirItemsList[item] = 1; } else { theirItemsList[item] += 1; }
  234. var itemData = func.inItems(result, item);
  235. if (itemData == false) {
  236. if (!notyet) {
  237. console.log("User offered an item that isn't in the database yet.\n".yellow);
  238. console.log("named: "+item);
  239. notyet = 1;
  240. }
  241. } else {
  242. if ((itemData.currentStock + theirItemsList[item]) > itemData.maxStock) {
  243. console.log("User offered an overstocked item.\n");
  244. console.log("named: "+item);
  245. notyet = 1;
  246. } else {
  247. if (itemData.buy_key > 0) {
  248. for (var i = 0; i < itemData.buy_key; i++) {
  249. if (func.overpay(theirItems, result, [])) { theirValue = func.fixFloat(theirValue + keysPrice.sell_ref); }
  250. else { theirValue = func.fixFloat(theirValue + keysPrice.buy_ref); }
  251. }
  252. }
  253. theirValue = func.fixFloat(theirValue + itemData.buy_ref);
  254. }
  255. }
  256. }
  257.  
  258. for (var i in ourItemsList) { ourItemsNames += i+" x"+ourItemsList[i]+", "; }
  259. for (var i in theirItemsList) { theirItemsNames += i+" x"+theirItemsList[i]+", "; }
  260.  
  261. if (ourItems.length === 0) {
  262. console.log(("A user donated: "+ theirItemsNames +"\n").green);
  263. acceptOffer(offer, 1);
  264. notyet = 1;
  265. }
  266. }
  267.  
  268. if (!notyet) {
  269. ourValue = parseFloat(func.fixFloat(parseFloat(ourValue).toFixed(3)));
  270. theirValue = parseFloat(func.fixFloat(parseFloat(theirValue).toFixed(3)));
  271.  
  272. if (func.overpay(theirItems, result, []) && func.overpay(ourItems, result, [])) {
  273. console.log(("A user offered: "+ theirItemsNames).blue);
  274. console.log("\tTheir value: "+func.convert(theirValue, keysPrice.buy_ref)+ " ("+theirValue+" ref)");
  275. console.log(("for our: "+ ourItemsNames).blue);
  276. var ourv = parseFloat((ourValue+config.overpayBy)).toFixed(2);
  277. console.log("\tOur value: "+ func.convert(ourValue, keysPrice.sell_ref) + " + "+config.overpayBy+" ref = "+ func.convert(ourv, keysPrice.sell_ref)+ " ("+ourv+" ref)");
  278. if ((theirValue - ourv) >= 0) {
  279. acceptOffer(offer);
  280. } else {
  281. declineOffer(offer);
  282. }
  283. } else{
  284. console.log(("A user offered: "+ theirItemsNames).blue);
  285. console.log("\tTheir value: "+ func.convert(theirValue, keysPrice.sell_ref)+ " ("+theirValue+" ref)");
  286. console.log(("for our: "+ ourItemsNames).blue);
  287. console.log("\tOur value: "+ func.convert(ourValue, keysPrice.sell_ref)+ " ("+ourValue+" ref)");
  288. if ((theirValue - ourValue) >= 0) {
  289. acceptOffer(offer);
  290. } else {
  291. declineOffer(offer);
  292. }
  293. }
  294. }
  295. });
  296. }
  297.  
  298. steamData.clientUser.setOption("promptSteamGuardCode", false);
  299.  
  300. // setInterval(function(){
  301. // bp.startAutomatic(config.myID, config.bpToken, function(err){
  302. // if (err) {console.log("Error while sending bp.tf heartbeat");return;}
  303. // if (traded) {
  304. // console.log('Heartbeat sent to backpack.tf');
  305. // updateCurrentStock(1);
  306. // traded = 0;
  307. // }
  308. // });
  309. // }, 1000 * 60 * 5);
  310.  
  311. steamData.manager.on('newOffer', (offer) => {
  312. processOffer(offer);
  313. });
  314.  
  315. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  316. ////////////// //////////////
  317. ////////////// //////////////
  318. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  319.  
  320.  
  321. let express = require('express');
  322. let bodyParser = require('body-parser');
  323. let app = express();
  324. let error = '', success = '';
  325.  
  326. app.set('view engine', 'ejs');
  327.  
  328. app.use('/assets', express.static('public'));
  329. app.use(bodyParser.urlencoded({extended: false}));
  330. app.use(bodyParser.json());
  331.  
  332. app.get('/', (req, res) => {
  333. connection.query('select * from items', function(err, result) {
  334. if (err) { console.error(err); return false; }
  335. for(var i=0; i<result.length;i++){
  336. var firstWord = (result[i].name).split(' ')[0].toLowerCase();
  337. var qualities = ['strange', 'genuine', 'unusual', 'vintage', 'hunted', 'collectors'];
  338. if(qualities.indexOf(firstWord) == -1){ result[i].quality = 'unique'; } else { result[i].quality = firstWord; }
  339. }
  340. res.render('pages/index', {prices: result, count: 2, error: error, success: success});
  341. error = '';success = "";
  342. });
  343. });
  344.  
  345. app.get('/history', (req, res) => {
  346. steamData.community.getInventoryHistory({resolveVanityURLs: true}, function(err, history) {
  347. if (err) {
  348. if (String(err).indexOf("Not Logged In") != -1) {
  349. res.render("pages/error", {message: "You need to wait a moment before requesting your trades history, Reload the page in a bit."});
  350. } else {
  351. console.error("damn it",err);
  352. res.render("pages/error", {message: "An error has accured please try in a moment."});
  353. }
  354. } else {
  355. res.render('pages/history', {jumbo: {title: "Trades", message: "Latest accepted trades"}, history: history});
  356. }
  357. });
  358. });
  359.  
  360. app.get('/update', (req, res) => { res.redirect('/'); });
  361. app.get('/add', (req, res) => { res.redirect('/'); });
  362.  
  363. app.post('/add', (req, res) => {
  364. if (req.body.itemName == '' ||req.body.bpurl == '' || req.body.maxStock == '' || req.body.buy_key == '' || req.body.sell_key == '' || req.body.buy_ref == '' || req.body.sell_ref == '' || req.body.img == '') {
  365. res.send({result: 'error', message: 'All fields most have a value'});
  366. } else {
  367. var itemData = { name: req.body.itemName, maxStock: req.body.maxStock, buy_key: req.body.buy_key, buy_ref: req.body.buy_ref, sell_key: req.body.sell_key, sell_ref: req.body.sell_ref, img: req.body.img, bpurl: req.body.bpurl };
  368. connection.query('insert into items set ?', itemData, function(err, result) {
  369. if (err) { console.error(err); return false; }
  370. res.send({result: 'success', message: "Item added successfully"});
  371. });
  372. }
  373. });
  374.  
  375. app.post('/update', (req, res) => {
  376. if (req.body.itemName == '' || req.body.maxStock == '' || req.body.buy_key == '' || req.body.sell_key == '' || req.body.buy_ref == '' || req.body.sell_ref == '') {
  377. res.send({result: 'error', message: 'All fields most have a value'});
  378. } else {
  379. var item = req.body;
  380. var query1 = connection.query(`update items set maxStock = ${item.maxStock}, buy_key = ${item.buy_key}, buy_ref = ${item.buy_ref}, sell_key =${item.sell_key}, sell_ref = ${item.sell_ref} where name = ?`, item.itemName, function(err, result) {
  381. if (err) { console.error(err); return false; }
  382. res.send({result: 'success', message: "Item updated successfully"});
  383. });
  384. }
  385. });
  386.  
  387. app.get('/delete/:id', (req, res) => {
  388. if (req.params.id != parseInt(req.params.id)) {
  389. res.send({result: 'error', message: 'the id must be an integer !'});
  390. } else {
  391. var query1 = connection.query(`delete from items where itemId = ?`, req.params.id, function(err, result) {
  392. if (err) { console.error(err); res.send({result: 'error', message: 'there was an error deleting the item'}); }
  393. else { res.send({result: 'success', message: "item deleted successfully"}); }
  394. });
  395. }
  396. });
  397.  
  398. app.listen(config.port, function() { console.log('Listening on port '+config.port); });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement