Advertisement
Guest User

Untitled

a guest
Feb 11th, 2018
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.55 KB | None | 0 0
  1. var mysql = require('mysql')
  2. var SteamUser = require("steam-user")
  3. var TradeOfferManager = require('steam-tradeoffer-manager');
  4. var SteamTotp = require('steam-totp')
  5. var fs = require('fs')
  6. var url = require('url');
  7. var SteamCommunity = require('steamcommunity');
  8. var market = require('steam-market-pricing');
  9. var request = require('request');
  10. var Slack = require('node-slack');
  11.  
  12. var config = require('./config.json');
  13. var SteamID = TradeOfferManager.SteamID;
  14.  
  15. var shared_secret = config.shared_secret || null;
  16. var identity_secret = config.identity_secret || null;
  17.  
  18. var donated_message = fs.readFileSync('donated_message.txt');
  19. var vipexpired_message = fs.readFileSync('vipexpired_message.txt');
  20. var vipwarn_message = fs.readFileSync('vipwarn_message.txt');
  21.  
  22. var database = mysql.createConnection(config.mysql);
  23.  
  24. var slack = new Slack(config.hookurl);
  25.  
  26. var client = new SteamUser();
  27. var community = new SteamCommunity();
  28. var manager = new TradeOfferManager({
  29. "steam": client, // Polling every 30 seconds is fine since we get notifications from Steam
  30. "domain": "aliasservernetwork.com",// Our domain is example.com
  31. "language": "en", // We want English item descriptions
  32. "pollInterval": 20 * 1000, // Poll interval
  33. "cancelTime": 60 * 60 * 1000, // Cancel sent offer in 60 minutes.
  34. });
  35.  
  36. if(fs.existsSync('polldata.json'))
  37. {
  38. manager.pollData = JSON.parse(fs.readFileSync('polldata.json'));
  39. }
  40.  
  41. client.setSentry(fs.readFileSync('sentry/' + config.username + ".sentry"));
  42.  
  43. slack.send({ text: "[Donation Bot]: NOW ONLINE", username: "Donation Bot" });
  44.  
  45. client.logOn({
  46. accountName: config.username,
  47. password: config.password
  48. });
  49.  
  50. client.on('loggedOn', function(code)
  51. {
  52. console.log("[Donation Bot]: Logged into Steam %s, %s", code.eresult, client.steamID.toString());
  53. slack.send({ text: "[Donation Bot]: Logged on to steam " + code.eresult, username: "Donation Bot" });
  54.  
  55. client.getSteamGuardDetails(function(enabled, enabledTime, machineTime, canTrade)
  56. {
  57. if(canTrade)
  58. {
  59. console.log("[Donation Bot]: SteamGuard says we can trade!");
  60. client.setPersona(SteamUser.Steam.EPersonaState.Online, "AliasServerNetwork Donation Bot");
  61. }
  62. else
  63. {
  64. // Update DB?
  65. console.log("[Donation Bot]: Unable to trade. Exiting. (Steamguard) En: %s, Time En: %s, Mach time: %s, canTrade: %s", enabled, enabledTime, machineTime, canTrade);
  66. process.exit(1);
  67. }
  68. });
  69. });
  70.  
  71. client.on('steamGuard', function(domain, callback, lastCodeWrong)
  72. {
  73. // Needs steamguard.
  74. console.log("[Donation Bot]: SteamGuard requires a code!");
  75. if(domain)
  76. {
  77. console.log("[Donation Bot]: Please enter email code in the code.");
  78. process.exit(0);
  79. }
  80.  
  81. if(!shared_secret)
  82. {
  83. return process.exit(0);
  84. }
  85.  
  86. if(lastCodeWrong)
  87. {
  88. setTimeout(function(callback, shared_secret)
  89. {
  90. var code = SteamTotp.generateAuthCode(shared_secret)
  91. console.log("[Donation Bot]: Attempting to authorize login with %s", code)
  92. callback(code)
  93. }, 20000, callback, config.shared_secret);
  94. }
  95. });
  96.  
  97. client.on('error', function(eresult)
  98. {
  99. console.log("[Donation Bot]: Unable to login: %j", eresult);
  100. slack.send({ text: "[Donation Bot]: Unable to login to steam " + eresult, username: "Donation Bot" });
  101. process.exit(1);
  102. });
  103.  
  104. client.on('accountLimitations', function(limited, communityBanned, locked, canInvite)
  105. {
  106. if(limited || communityBanned || locked)
  107. {
  108. console.log("[Donation Bot]: The account is limited in some way. (L: %j, C: %j, L:%j)", limited, communityBanned, locked);
  109. process.exit(1);
  110. }
  111. });
  112.  
  113. client.on('webSession', function(sessionID, cookies)
  114. {
  115. manager.setCookies(cookies, function(err)
  116. {
  117. if(err)
  118. {
  119. console.log("[Donation Bot]: Fatal error getting API key ", err);
  120. process.exit(1); // Fatal error since we couldn't get our API key
  121. return;
  122. }
  123. console.log("[Donation Bot]: Got API key: %s (TradeOfferManager Ready)", manager.apiKey);
  124. if(config.playGame)
  125. {
  126. client.gamesPlayed(config.playGame);
  127. }
  128. manager.doPoll();
  129. });
  130.  
  131. community.setCookies(cookies);
  132. // Auto confirm trades.
  133. if (config.shared_secret && SteamTotp && config.identity_secret)
  134. {
  135. community.startConfirmationChecker(1000 * 20, client.identity_secret);
  136. }
  137.  
  138. slack.send({ text: "[Donation Bot]: We are ready for trading!", username: "Donation Bot" });
  139.  
  140. client.sessionID = sessionID;
  141. client.cookies = cookies;
  142.  
  143. warnVIPs();
  144. setInterval(warnVIPs, 1000 * 60 * 60 * 24);
  145. deleteVIPs();
  146. setInterval(deleteVIPs, 1000 * 60 * 60 * 24);
  147.  
  148. });
  149.  
  150. manager.on('pollData', function(pollData)
  151. {
  152. console.log("[Donation Bot]: Brand spanking new poll data");
  153. fs.writeFile('polldata.json', JSON.stringify(pollData), function(err)
  154. {
  155. console.log("[Donation Bot]: Written poll data. (E: %s)", err);
  156. });
  157. });
  158.  
  159. manager.on('pollFailure', function(err)
  160. {
  161. console.log("[Donation Bot]: There was an error polling %s", err.message);
  162. });
  163.  
  164. manager.on('pollSuccess', function()
  165. {
  166. // console.log("Polled steam!");
  167. });
  168.  
  169. manager.on('newOffer', function(offer)
  170. {
  171. console.log("[Donation Bot]: New offer #" + offer.id + " from " + offer.partner.toString());
  172.  
  173. slack.send({ text:
  174. "[Donation Bot]: New offer ("+ offer.id +") from " + offer.partner.toString() +
  175. " they want our " + offer.itemsToGive.map(function(item)
  176. { return item.market_hash_name; }).join(', ') +
  177. " for their " + offer.itemsToReceive.map(function(item)
  178. { return item.market_hash_name; }).join(', ')
  179. , username: "Donation Bot" });
  180.  
  181. if(isAdmin(offer.partner.toString()))
  182. {
  183. offer.data('admin', true);
  184. offer.accept(true);
  185. slack.send({ text: "[Donation Bot]: Accepted offer (admin).", username: "Donation Bot" });
  186. return console.log("[Donation Bot]: Accepted admin offer.");
  187. }
  188.  
  189. if (offer.itemsToGive && offer.itemsToGive.length > 0)
  190. {
  191. console.log("[Donation Bot]: Declining offer, wants my items.")
  192. return offer.decline();
  193. }
  194.  
  195. var items = offer.itemsToReceive; // alias
  196.  
  197. var keys = items.filter(function(item)
  198. {
  199. return (item.market_hash_name.indexOf('Case Key') > -1) || (item.market_hash_name.indexOf('eSports Key') > -1);
  200. });
  201.  
  202. if(keys.length == items.length)
  203. {
  204. console.log("[Donation Bot]: Keys only offer.");
  205.  
  206. if (keys.length == 3)
  207. {
  208. console.log("[Donation Bot]: User %s donated 3 keys accepting and giving vip", offer.partner.toString());
  209. offer.data('vip', 30);
  210. slack.send({ text: "[Donation Bot]: User donated 3 keys giving vip 1 month", username: "Donation Bot" });
  211. return offer.accept();
  212. }
  213. else if (keys.length == 13)
  214. {
  215. console.log("[Donation Bot]: User %s donated 13 keys accepting and giving vip", offer.partner.toString());
  216. offer.data('vip', 90);
  217. slack.send({ text: "[Donation Bot]: User donated 13 keys giving vip 3 month", username: "Donation Bot" });
  218. return offer.accept();
  219. }
  220. else if (keys.length == 25)
  221. {
  222. console.log("[Donation Bot]: User %s donated 25 keys accepting and giving vip", offer.partner.toString());
  223. offer.data('vip', 182);
  224. slack.send({ text: "[Donation Bot]: User donated 25 keys giving vip 6 month", username: "Donation Bot" });
  225. return offer.accept();
  226. }
  227. else if (keys.length == 45)
  228. {
  229. console.log("[Donation Bot]: User %s donated 45 keys accepting and giving vip", offer.partner.toString());
  230. offer.data('vip', 365);
  231. slack.send({ text: "[Donation Bot]: User donated 45 keys giving vip lifetime", username: "Donation Bot" });
  232. return offer.accept();
  233. }
  234.  
  235. offer.data('donation', keys.length * 2);
  236. console.log("[Donation Bot]: User %s donated pure keys totalling $%s", offer.partner.toString(), offer.data('donation'));
  237. slack.send({ text: "[Donation Bot]: User donated keys only accepting", username: "Donation Bot" });
  238. return offer.accept();
  239. }
  240.  
  241. console.log("[Donation Bot]: Its a donation of items/(keys)");
  242. var totalDonation = 0;
  243. totalDonation += keys.length * 2;
  244.  
  245. var weapons = items.filter(function(item)
  246. {
  247. return (item.market_hash_name.indexOf('Case Key') == -1) && (item.market_hash_name.indexOf('eSports Key') == -1);
  248. });
  249.  
  250. market.getItemsPrice(730, weapons.map(function(item)
  251. { return item.market_hash_name; }), function(marketdata)
  252. {
  253. if(!marketdata)
  254. {
  255. console.log("[Donation Bot]: Unable to get pricing information from market.");
  256. process.exit(1);
  257. }
  258.  
  259. weapons.forEach(function(item)
  260. {
  261. var marketitem = marketdata[item.market_hash_name];
  262. if(!marketitem || !marketitem.success)
  263. {
  264. console.log("[Donation Bot]: unable to get data about an item!");
  265. return offer.decline();
  266. }
  267.  
  268. console.log("[Donation Bot]: Got item price for %s is $%s")
  269.  
  270. marketitem.median_price = marketitem.median_price * 0.7;
  271.  
  272. if(marketitem.median_price < 1)
  273. {
  274. console.log("[Donation Bot]: Item is below $1 (%s)", marketitem.median_price);
  275. return offer.decline();
  276. }
  277.  
  278. totalDonation += marketitem.median_price;
  279. });
  280.  
  281. if(totalDonation < 1)
  282. {
  283. console.log("[Donation Bot]: Total donation amount is less than 1 declining");
  284. return offer.decline();
  285. }
  286.  
  287. offer.data('donation', totalDonation);
  288. console.log("[Donation Bot]: User is trying to donate $%s amount, accepting.", totalDonation);
  289. offer.accept();
  290. slack.send({ text: "[Donation Bot]: User is trying to donate $" + totalDonation +" amount, accepting.", username: "Donation Bot" });
  291.  
  292. });
  293. });
  294.  
  295. manager.on('receivedOfferChanged', function(offer, oldState)
  296. {
  297. if(offer.state !== TradeOfferManager.ETradeOfferState.Accepted)
  298. {
  299. return console.log("An offer entered an unknown state");
  300. }
  301.  
  302. console.log("[Donation Bot]: An offer was accepted, lets check the price and add them to donator status");
  303.  
  304. if(offer.data('admin'))
  305. {
  306. return;
  307. }
  308.  
  309. getOrCreateUser(offer.partner, function(id, name, balance)
  310. {
  311. postComment(offer.partner.toString(), donated_message);
  312.  
  313. if(offer.data('donation'))
  314. {
  315. console.log("[Donation Bot]: Got user, updating donator with " + offer.data('donation'))
  316. return updateDonator(id, balance, offer.data('donation'));
  317. }
  318.  
  319. if(offer.data('vip'))
  320. {
  321. console.log("[Donation Bot]: Got user updating vip with " + offer.data('vip'))
  322. return updateVIP(id, offer.data('vip'));
  323. }
  324. });
  325. });
  326.  
  327. function getOrCreateUser(steamid, callback)
  328. {
  329. database.query("SELECT * FROM `sb_admins` WHERE `authid` = ?", [ steamid.getSteam2RenderedID() ], function(err, rows)
  330. {
  331. if(err)
  332. {
  333. console.log("[Donation Bot]: There was an error communicating with the database. (Selecting user %s) %j", steamid.getSteam2RenderedID(), err);
  334. process.exit(1);
  335. }
  336.  
  337. if(!rows || rows.length == 0)
  338. {
  339. community.getSteamUser(steamid, function(err, user)
  340. {
  341.  
  342. user.name = user.name
  343. .replace('[', '')
  344. .replace(']', '')
  345. .replace('/', '')
  346. .replace('|', '')
  347. .replace('\\', '')
  348. .replace('*', '')
  349. .replace('^', '')
  350. .replace('(', '')
  351. .replace(')', '')
  352. .replace('&', '')
  353. .replace('%', '')
  354. .replace('$', '')
  355. .replace('@', '')
  356. .replace('#', '')
  357.  
  358. database.query("INSERT INTO `sb_admins` (`user`, `authid`) VALUES (?, ?);", [ user.name, steamid.getSteam2RenderedID() ], function(err, result)
  359. {
  360. if(err)
  361. {
  362. console.log("[Donation Bot]: There was an error communicating with the database. (Inserting user %s)", steamid);
  363. process.exit(1);
  364. }
  365. return callback(result.insertId, user.name, 0);
  366. });
  367. });
  368. }
  369. else
  370. {
  371. return callback(rows[0].aid, rows[0].user, (rows[0].donated ? rows[0].donated : 0));
  372. }
  373. });
  374. }
  375.  
  376. function updateVIP(userid, length)
  377. {
  378. console.log("[Donation Bot]: Updating VIP %s %s days", userid, length)
  379.  
  380. database.query("SELECT `vip_time` FROM `sb_admins` WHERE `aid` = ?", [ userid ], function(err, rows)
  381. {
  382. if(err)
  383. {
  384. return process.exit(1);
  385. }
  386.  
  387. var futureDate = Math.floor(Date.now() / 1000);
  388.  
  389. if(rows && rows.length > 0 && rows[0] > futureDate)
  390. {
  391. futureDate = rows[0]
  392. }
  393.  
  394. futureDate = ((Date.now() / 1000) + (24 * length * 60 * 60) )
  395.  
  396. database.query("UPDATE `sb_admins` SET `vip_time` = ?, `srv_group` = 'VIP' WHERE `aid` = ?", [ futureDate, userid ], function(err, rows)
  397. {
  398. console.log("[Donation Bot]: Updated user %s added vip", userid);
  399. });
  400.  
  401. database.query("DELETE FROM `sb_admins_servers_groups` WHERE `admin_id` = ?" , [ userid ], function(e,r )
  402. {});
  403.  
  404. var servers = config.servers;
  405. servers.forEach(function(server)
  406. {
  407. console.log("server " + server)
  408. database.query("INSERT INTO `sb_admins_servers_groups` (`admin_id`, `group_id`, `srv_group_id`, `server_id`) VALUES (?, ?, -1, ?)", [ userid, 5, server ], function(e, r)
  409. {});
  410. });
  411. });
  412. }
  413.  
  414. function updateDonator(userid, balance, donated)
  415. {
  416. console.log("[Donation Bot]: Updating donation %s %s %s", userid, balance, donated)
  417. var total = balance + donated;
  418.  
  419. var group = -1;
  420. var srv_group = "";
  421.  
  422. if (total >= 12)
  423. {
  424. group = 8;
  425. srv_group = "Bronze"
  426. }
  427. else if (total >= 24)
  428. {
  429. group = 7;
  430. srv_group = "Silver"
  431. }
  432. else if (total >= 44)
  433. {
  434. group = 6;
  435. srv_group = "Gold"
  436. }
  437. else
  438. {
  439. return;
  440. }
  441.  
  442. database.query("UPDATE `sb_admins` SET `donated` = `donated` + ?, `srv_group` = ? WHERE `aid` = ?", [ donated, srv_group, userid ], function(err, rows)
  443. {
  444. console.log("[Donation Bot]: Updated user %s donated amount", userid);
  445. });
  446.  
  447. // Doesn't work with duplicates.
  448. database.query("DELETE FROM `sb_admins_servers_groups` WHERE `admin_id` = ?" , [ userid ], function(e,r )
  449. {});
  450.  
  451. var insert = "INSERT INTO `sb_admins_servers_groups` (`admin_id`, `group_id`, `srv_group_id`, `server_id`) VALUES (?, ?, -1, ?) ";
  452. var servers = config.servers;
  453. servers.forEach(function(server)
  454. {
  455. console.log("[Donation Bot]: server " + server)
  456. database.query(insert, [ userid, group, server], function(e, r)
  457. {
  458. console.log("[Donation Bot]: Added %s to group %s for donating %s (server %s)", userid, group, total, server); // Async with a sync for loop so cant serverid.
  459. });
  460. });
  461. }
  462.  
  463. function isAdmin(steamid)
  464. {
  465. return config.admins.indexOf(steamid) > -1;
  466. }
  467.  
  468. client.on('friendMessage', function(steamId, message)
  469. {
  470. console.log("%s: %s", steamId, message);
  471.  
  472. if (isAdmin(steamId.toString()))
  473. {
  474. getOrCreateUser(steamId, function(id, name, donated)
  475. {
  476. console.log("[Donation Bot]: %s (id: %s) donated: $%s", name, id, donated);
  477. updateDonator(id, donated, 5);
  478. })
  479. }
  480. })
  481.  
  482. var postComment = function(other, comment)
  483. {
  484. return request.post({
  485. url: "http://steamcommunity.com/comment/Profile/post/" + other + "/-1/",
  486. headers: {
  487. 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
  488. 'Cookie': client.cookies.join('; '),
  489. 'Accept': '/',
  490. 'Connection': 'keep-alive'
  491. },
  492. formData: {
  493. "comment": comment,
  494. "count": 6,
  495. "sessionid": client.sessionID
  496. }
  497. }, function(err, res, body)
  498. {
  499. return console.log("Ayy lmao posted comment");
  500. });
  501. };
  502.  
  503.  
  504. function deleteVIPs()
  505. {
  506. database.query("SELECT `aid`, `authid` FROM `sb_admins` WHERE `vip_time` < UNIX_TIMESTAMP() AND `vip_time` != NULL", function(err, res)
  507. {
  508. if(err || !res)
  509. {
  510. return console.log("[Donation Bot]: Error getting admin IDs of expired VIPs (%j)", err);
  511. }
  512.  
  513. if(res.length == 0)
  514. {
  515. return;
  516. }
  517.  
  518. res.forEach(function(admin)
  519. {
  520. database.query("DELETE FROM `sb_admins_servers_groups` WHERE `admin_id` = ?", [ admin.aid ], function()
  521. {
  522. postComment((new SteamID(admin.authid)).toString(), vipexpired_message)
  523. });
  524. });
  525. })
  526. }
  527.  
  528. function warnVIPs()
  529. {
  530. database.query("SELECT `authid` FROM `sb_admins` WHERE `vip_time` < UNIX_TIMESTAMP() + (24 * 60 * 60) AND `vip_time` != NULL", function(err, res)
  531. {
  532. if(err || !res)
  533. {
  534. return console.log("[Donation Bot]: Error getting admin IDs of expired VIPs (%j)", err);
  535. }
  536.  
  537. if(res.length == 0)
  538. {
  539. return;
  540. }
  541. console.log(res)
  542. res.forEach(function(admin)
  543. {
  544. postComment((new SteamID(admin.authid)).toString(), vipwarn_message)
  545. });
  546. })
  547. }
  548.  
  549. function pingMysql()
  550. {
  551. database.query("SELECT 1+1", function()
  552. {
  553.  
  554. });
  555. }
  556.  
  557. setInterval(pingMysql, 1000 * 60);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement