Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mysql = require('mysql')
- var SteamUser = require("steam-user")
- var TradeOfferManager = require('steam-tradeoffer-manager');
- var SteamTotp = require('steam-totp')
- var fs = require('fs')
- var url = require('url');
- var SteamCommunity = require('steamcommunity');
- var market = require('steam-market-pricing');
- var request = require('request');
- var Slack = require('node-slack');
- var config = require('./config.json');
- var SteamID = TradeOfferManager.SteamID;
- var shared_secret = config.shared_secret || null;
- var identity_secret = config.identity_secret || null;
- var donated_message = fs.readFileSync('donated_message.txt');
- var vipexpired_message = fs.readFileSync('vipexpired_message.txt');
- var vipwarn_message = fs.readFileSync('vipwarn_message.txt');
- var database = mysql.createConnection(config.mysql);
- var slack = new Slack(config.hookurl);
- var client = new SteamUser();
- var community = new SteamCommunity();
- var manager = new TradeOfferManager({
- "steam": client, // Polling every 30 seconds is fine since we get notifications from Steam
- "domain": "aliasservernetwork.com",// Our domain is example.com
- "language": "en", // We want English item descriptions
- "pollInterval": 20 * 1000, // Poll interval
- "cancelTime": 60 * 60 * 1000, // Cancel sent offer in 60 minutes.
- });
- if(fs.existsSync('polldata.json'))
- {
- manager.pollData = JSON.parse(fs.readFileSync('polldata.json'));
- }
- client.setSentry(fs.readFileSync('sentry/' + config.username + ".sentry"));
- slack.send({ text: "[Donation Bot]: NOW ONLINE", username: "Donation Bot" });
- client.logOn({
- accountName: config.username,
- password: config.password
- });
- client.on('loggedOn', function(code)
- {
- console.log("[Donation Bot]: Logged into Steam %s, %s", code.eresult, client.steamID.toString());
- slack.send({ text: "[Donation Bot]: Logged on to steam " + code.eresult, username: "Donation Bot" });
- client.getSteamGuardDetails(function(enabled, enabledTime, machineTime, canTrade)
- {
- if(canTrade)
- {
- console.log("[Donation Bot]: SteamGuard says we can trade!");
- client.setPersona(SteamUser.Steam.EPersonaState.Online, "AliasServerNetwork Donation Bot");
- }
- else
- {
- // Update DB?
- console.log("[Donation Bot]: Unable to trade. Exiting. (Steamguard) En: %s, Time En: %s, Mach time: %s, canTrade: %s", enabled, enabledTime, machineTime, canTrade);
- process.exit(1);
- }
- });
- });
- client.on('steamGuard', function(domain, callback, lastCodeWrong)
- {
- // Needs steamguard.
- console.log("[Donation Bot]: SteamGuard requires a code!");
- if(domain)
- {
- console.log("[Donation Bot]: Please enter email code in the code.");
- process.exit(0);
- }
- if(!shared_secret)
- {
- return process.exit(0);
- }
- if(lastCodeWrong)
- {
- setTimeout(function(callback, shared_secret)
- {
- var code = SteamTotp.generateAuthCode(shared_secret)
- console.log("[Donation Bot]: Attempting to authorize login with %s", code)
- callback(code)
- }, 20000, callback, config.shared_secret);
- }
- });
- client.on('error', function(eresult)
- {
- console.log("[Donation Bot]: Unable to login: %j", eresult);
- slack.send({ text: "[Donation Bot]: Unable to login to steam " + eresult, username: "Donation Bot" });
- process.exit(1);
- });
- client.on('accountLimitations', function(limited, communityBanned, locked, canInvite)
- {
- if(limited || communityBanned || locked)
- {
- console.log("[Donation Bot]: The account is limited in some way. (L: %j, C: %j, L:%j)", limited, communityBanned, locked);
- process.exit(1);
- }
- });
- client.on('webSession', function(sessionID, cookies)
- {
- manager.setCookies(cookies, function(err)
- {
- if(err)
- {
- console.log("[Donation Bot]: Fatal error getting API key ", err);
- process.exit(1); // Fatal error since we couldn't get our API key
- return;
- }
- console.log("[Donation Bot]: Got API key: %s (TradeOfferManager Ready)", manager.apiKey);
- if(config.playGame)
- {
- client.gamesPlayed(config.playGame);
- }
- manager.doPoll();
- });
- community.setCookies(cookies);
- // Auto confirm trades.
- if (config.shared_secret && SteamTotp && config.identity_secret)
- {
- community.startConfirmationChecker(1000 * 20, client.identity_secret);
- }
- slack.send({ text: "[Donation Bot]: We are ready for trading!", username: "Donation Bot" });
- client.sessionID = sessionID;
- client.cookies = cookies;
- warnVIPs();
- setInterval(warnVIPs, 1000 * 60 * 60 * 24);
- deleteVIPs();
- setInterval(deleteVIPs, 1000 * 60 * 60 * 24);
- });
- manager.on('pollData', function(pollData)
- {
- console.log("[Donation Bot]: Brand spanking new poll data");
- fs.writeFile('polldata.json', JSON.stringify(pollData), function(err)
- {
- console.log("[Donation Bot]: Written poll data. (E: %s)", err);
- });
- });
- manager.on('pollFailure', function(err)
- {
- console.log("[Donation Bot]: There was an error polling %s", err.message);
- });
- manager.on('pollSuccess', function()
- {
- // console.log("Polled steam!");
- });
- manager.on('newOffer', function(offer)
- {
- console.log("[Donation Bot]: New offer #" + offer.id + " from " + offer.partner.toString());
- slack.send({ text:
- "[Donation Bot]: New offer ("+ offer.id +") from " + offer.partner.toString() +
- " they want our " + offer.itemsToGive.map(function(item)
- { return item.market_hash_name; }).join(', ') +
- " for their " + offer.itemsToReceive.map(function(item)
- { return item.market_hash_name; }).join(', ')
- , username: "Donation Bot" });
- if(isAdmin(offer.partner.toString()))
- {
- offer.data('admin', true);
- offer.accept(true);
- slack.send({ text: "[Donation Bot]: Accepted offer (admin).", username: "Donation Bot" });
- return console.log("[Donation Bot]: Accepted admin offer.");
- }
- if (offer.itemsToGive && offer.itemsToGive.length > 0)
- {
- console.log("[Donation Bot]: Declining offer, wants my items.")
- return offer.decline();
- }
- var items = offer.itemsToReceive; // alias
- var keys = items.filter(function(item)
- {
- return (item.market_hash_name.indexOf('Case Key') > -1) || (item.market_hash_name.indexOf('eSports Key') > -1);
- });
- if(keys.length == items.length)
- {
- console.log("[Donation Bot]: Keys only offer.");
- if (keys.length == 3)
- {
- console.log("[Donation Bot]: User %s donated 3 keys accepting and giving vip", offer.partner.toString());
- offer.data('vip', 30);
- slack.send({ text: "[Donation Bot]: User donated 3 keys giving vip 1 month", username: "Donation Bot" });
- return offer.accept();
- }
- else if (keys.length == 13)
- {
- console.log("[Donation Bot]: User %s donated 13 keys accepting and giving vip", offer.partner.toString());
- offer.data('vip', 90);
- slack.send({ text: "[Donation Bot]: User donated 13 keys giving vip 3 month", username: "Donation Bot" });
- return offer.accept();
- }
- else if (keys.length == 25)
- {
- console.log("[Donation Bot]: User %s donated 25 keys accepting and giving vip", offer.partner.toString());
- offer.data('vip', 182);
- slack.send({ text: "[Donation Bot]: User donated 25 keys giving vip 6 month", username: "Donation Bot" });
- return offer.accept();
- }
- else if (keys.length == 45)
- {
- console.log("[Donation Bot]: User %s donated 45 keys accepting and giving vip", offer.partner.toString());
- offer.data('vip', 365);
- slack.send({ text: "[Donation Bot]: User donated 45 keys giving vip lifetime", username: "Donation Bot" });
- return offer.accept();
- }
- offer.data('donation', keys.length * 2);
- console.log("[Donation Bot]: User %s donated pure keys totalling $%s", offer.partner.toString(), offer.data('donation'));
- slack.send({ text: "[Donation Bot]: User donated keys only accepting", username: "Donation Bot" });
- return offer.accept();
- }
- console.log("[Donation Bot]: Its a donation of items/(keys)");
- var totalDonation = 0;
- totalDonation += keys.length * 2;
- var weapons = items.filter(function(item)
- {
- return (item.market_hash_name.indexOf('Case Key') == -1) && (item.market_hash_name.indexOf('eSports Key') == -1);
- });
- market.getItemsPrice(730, weapons.map(function(item)
- { return item.market_hash_name; }), function(marketdata)
- {
- if(!marketdata)
- {
- console.log("[Donation Bot]: Unable to get pricing information from market.");
- process.exit(1);
- }
- weapons.forEach(function(item)
- {
- var marketitem = marketdata[item.market_hash_name];
- if(!marketitem || !marketitem.success)
- {
- console.log("[Donation Bot]: unable to get data about an item!");
- return offer.decline();
- }
- console.log("[Donation Bot]: Got item price for %s is $%s")
- marketitem.median_price = marketitem.median_price * 0.7;
- if(marketitem.median_price < 1)
- {
- console.log("[Donation Bot]: Item is below $1 (%s)", marketitem.median_price);
- return offer.decline();
- }
- totalDonation += marketitem.median_price;
- });
- if(totalDonation < 1)
- {
- console.log("[Donation Bot]: Total donation amount is less than 1 declining");
- return offer.decline();
- }
- offer.data('donation', totalDonation);
- console.log("[Donation Bot]: User is trying to donate $%s amount, accepting.", totalDonation);
- offer.accept();
- slack.send({ text: "[Donation Bot]: User is trying to donate $" + totalDonation +" amount, accepting.", username: "Donation Bot" });
- });
- });
- manager.on('receivedOfferChanged', function(offer, oldState)
- {
- if(offer.state !== TradeOfferManager.ETradeOfferState.Accepted)
- {
- return console.log("An offer entered an unknown state");
- }
- console.log("[Donation Bot]: An offer was accepted, lets check the price and add them to donator status");
- if(offer.data('admin'))
- {
- return;
- }
- getOrCreateUser(offer.partner, function(id, name, balance)
- {
- postComment(offer.partner.toString(), donated_message);
- if(offer.data('donation'))
- {
- console.log("[Donation Bot]: Got user, updating donator with " + offer.data('donation'))
- return updateDonator(id, balance, offer.data('donation'));
- }
- if(offer.data('vip'))
- {
- console.log("[Donation Bot]: Got user updating vip with " + offer.data('vip'))
- return updateVIP(id, offer.data('vip'));
- }
- });
- });
- function getOrCreateUser(steamid, callback)
- {
- database.query("SELECT * FROM `sb_admins` WHERE `authid` = ?", [ steamid.getSteam2RenderedID() ], function(err, rows)
- {
- if(err)
- {
- console.log("[Donation Bot]: There was an error communicating with the database. (Selecting user %s) %j", steamid.getSteam2RenderedID(), err);
- process.exit(1);
- }
- if(!rows || rows.length == 0)
- {
- community.getSteamUser(steamid, function(err, user)
- {
- user.name = user.name
- .replace('[', '')
- .replace(']', '')
- .replace('/', '')
- .replace('|', '')
- .replace('\\', '')
- .replace('*', '')
- .replace('^', '')
- .replace('(', '')
- .replace(')', '')
- .replace('&', '')
- .replace('%', '')
- .replace('$', '')
- .replace('@', '')
- .replace('#', '')
- database.query("INSERT INTO `sb_admins` (`user`, `authid`) VALUES (?, ?);", [ user.name, steamid.getSteam2RenderedID() ], function(err, result)
- {
- if(err)
- {
- console.log("[Donation Bot]: There was an error communicating with the database. (Inserting user %s)", steamid);
- process.exit(1);
- }
- return callback(result.insertId, user.name, 0);
- });
- });
- }
- else
- {
- return callback(rows[0].aid, rows[0].user, (rows[0].donated ? rows[0].donated : 0));
- }
- });
- }
- function updateVIP(userid, length)
- {
- console.log("[Donation Bot]: Updating VIP %s %s days", userid, length)
- database.query("SELECT `vip_time` FROM `sb_admins` WHERE `aid` = ?", [ userid ], function(err, rows)
- {
- if(err)
- {
- return process.exit(1);
- }
- var futureDate = Math.floor(Date.now() / 1000);
- if(rows && rows.length > 0 && rows[0] > futureDate)
- {
- futureDate = rows[0]
- }
- futureDate = ((Date.now() / 1000) + (24 * length * 60 * 60) )
- database.query("UPDATE `sb_admins` SET `vip_time` = ?, `srv_group` = 'VIP' WHERE `aid` = ?", [ futureDate, userid ], function(err, rows)
- {
- console.log("[Donation Bot]: Updated user %s added vip", userid);
- });
- database.query("DELETE FROM `sb_admins_servers_groups` WHERE `admin_id` = ?" , [ userid ], function(e,r )
- {});
- var servers = config.servers;
- servers.forEach(function(server)
- {
- console.log("server " + server)
- 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)
- {});
- });
- });
- }
- function updateDonator(userid, balance, donated)
- {
- console.log("[Donation Bot]: Updating donation %s %s %s", userid, balance, donated)
- var total = balance + donated;
- var group = -1;
- var srv_group = "";
- if (total >= 12)
- {
- group = 8;
- srv_group = "Bronze"
- }
- else if (total >= 24)
- {
- group = 7;
- srv_group = "Silver"
- }
- else if (total >= 44)
- {
- group = 6;
- srv_group = "Gold"
- }
- else
- {
- return;
- }
- database.query("UPDATE `sb_admins` SET `donated` = `donated` + ?, `srv_group` = ? WHERE `aid` = ?", [ donated, srv_group, userid ], function(err, rows)
- {
- console.log("[Donation Bot]: Updated user %s donated amount", userid);
- });
- // Doesn't work with duplicates.
- database.query("DELETE FROM `sb_admins_servers_groups` WHERE `admin_id` = ?" , [ userid ], function(e,r )
- {});
- var insert = "INSERT INTO `sb_admins_servers_groups` (`admin_id`, `group_id`, `srv_group_id`, `server_id`) VALUES (?, ?, -1, ?) ";
- var servers = config.servers;
- servers.forEach(function(server)
- {
- console.log("[Donation Bot]: server " + server)
- database.query(insert, [ userid, group, server], function(e, r)
- {
- 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.
- });
- });
- }
- function isAdmin(steamid)
- {
- return config.admins.indexOf(steamid) > -1;
- }
- client.on('friendMessage', function(steamId, message)
- {
- console.log("%s: %s", steamId, message);
- if (isAdmin(steamId.toString()))
- {
- getOrCreateUser(steamId, function(id, name, donated)
- {
- console.log("[Donation Bot]: %s (id: %s) donated: $%s", name, id, donated);
- updateDonator(id, donated, 5);
- })
- }
- })
- var postComment = function(other, comment)
- {
- return request.post({
- url: "http://steamcommunity.com/comment/Profile/post/" + other + "/-1/",
- headers: {
- 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
- 'Cookie': client.cookies.join('; '),
- 'Accept': '/',
- 'Connection': 'keep-alive'
- },
- formData: {
- "comment": comment,
- "count": 6,
- "sessionid": client.sessionID
- }
- }, function(err, res, body)
- {
- return console.log("Ayy lmao posted comment");
- });
- };
- function deleteVIPs()
- {
- database.query("SELECT `aid`, `authid` FROM `sb_admins` WHERE `vip_time` < UNIX_TIMESTAMP() AND `vip_time` != NULL", function(err, res)
- {
- if(err || !res)
- {
- return console.log("[Donation Bot]: Error getting admin IDs of expired VIPs (%j)", err);
- }
- if(res.length == 0)
- {
- return;
- }
- res.forEach(function(admin)
- {
- database.query("DELETE FROM `sb_admins_servers_groups` WHERE `admin_id` = ?", [ admin.aid ], function()
- {
- postComment((new SteamID(admin.authid)).toString(), vipexpired_message)
- });
- });
- })
- }
- function warnVIPs()
- {
- database.query("SELECT `authid` FROM `sb_admins` WHERE `vip_time` < UNIX_TIMESTAMP() + (24 * 60 * 60) AND `vip_time` != NULL", function(err, res)
- {
- if(err || !res)
- {
- return console.log("[Donation Bot]: Error getting admin IDs of expired VIPs (%j)", err);
- }
- if(res.length == 0)
- {
- return;
- }
- console.log(res)
- res.forEach(function(admin)
- {
- postComment((new SteamID(admin.authid)).toString(), vipwarn_message)
- });
- })
- }
- function pingMysql()
- {
- database.query("SELECT 1+1", function()
- {
- });
- }
- setInterval(pingMysql, 1000 * 60);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement