Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var fs = require('fs');
- var crypto = require('crypto');
- var config = require('config');
- var moment = require('moment');
- var SteamWeb = require('./steamweb');
- var Steam = require('steam');
- var getSteamAPIKey = require('steam-web-api-key');
- var SteamWebLogOn = require('steam-weblogon');
- var steamClient = new Steam.SteamClient();
- var steamUser = new Steam.SteamUser(steamClient);
- var steamFriends = new Steam.SteamFriends(steamClient);
- var steamWebLogOn = new SteamWebLogOn(steamClient, steamUser);
- var sw;
- if (!config.get('steam.username')) {
- console.log('Either you have not set your steam username in the config or you are using default.json!');
- console.log('You\'ll need to go into /config and create the file production.json');
- console.log('Copy all of default.json and paste it in production.json and then fill it out.');
- console.log('');
- console.log('Finally you\'ll need to type in your console:');
- console.log('')
- console.log('export NODE_ENV=production');
- console.log('');
- console.log('Then trying running it again.');
- process.exit(0);
- }
- // Login, self explanatory
- var logOnOptions = {
- account_name: config.get('steam.username'),
- password: config.get('steam.password')
- };
- var authCode = process.argv[2];
- // Check if sentry exists
- if (authCode == '2fa') logOnOptions.two_factor_code = process.argv[3]
- else {
- try {
- logOnOptions.sha_sentryfile = getSHA1(fs.readFileSync('sentry'));
- } catch (e) {
- if (authCode !== '') {
- logOnOptions.auth_code = authCode;
- }
- }
- }
- // If we've said a server list, use it
- if (fs.existsSync('servers')) {
- Steam.servers = JSON.parse(fs.readFileSync('servers'));
- }
- // Login
- steamClient.connect();
- steamClient.on('connected', function() {
- steamUser.logOn(logOnOptions);
- });
- // Logged in response
- steamClient.on('logOnResponse', function(logonResp) {
- if (logonResp.eresult === Steam.EResult.OK) {
- console.log('Logged In!');
- steamFriends.setPersonaState(Steam.EPersonaState.Online);
- steamFriends.setPersonaName(config.get('name'));
- steamWebLogOn.webLogOn(function(sessionID, newCookie) {
- getSteamAPIKey({
- sessionID: sessionID,
- webCookie: newCookie
- }, function(err, APIKey) {
- if (err) console.log('[ERR STEAM API]',err);
- sw = SteamWeb(APIKey);
- console.log('Connected to Steam Web API');
- steamFriends.joinChat(config.get('groupId'));
- });
- });
- } else {
- if (logonResp.eresult == 85) {
- console.log('You need 2FA for this account!');
- } else if (logonResp.eresult == 63) {
- console.log('Code sent to your email (XXXXXX.'+logonResp.email_domain+').');
- console.log('You\'ll need to run:');
- console.log('node index <code>');
- console.log('Once in order to save the computer');
- console.log('IF YOU\'VE DONE ALL THIS: You may need to delete your "sentry" file.');
- } else {
- console.log('Houston, we have a problem! Info:',logonResp);
- }
- process.exit(0);
- }
- });
- steamFriends.on('chatEnter', (chatId) => {
- console.log('Entered chat ('+chatId+')');
- Object.keys(roomUsers()).forEach(id => uniqueUsers.push(id));
- });
- steamFriends.on('chatStateChange', (state, id, chatId, actionId) => { // Join/leave/kick/etc messages
- getName(id, (name) => {
- getName(actionId, (actionName) => {
- if (state == Steam.EChatMemberStateChange.Entered) {
- console.log(name + ' entered');
- chatLogs.push({ msg: name + ' entered' });
- if (uniqueUsers.indexOf(id) == -1) uniqueUsers.push(id);
- } else if (state = Steam.EChatMemberStateChange.Left) {
- console.log(name + ' left');
- chatLogs.push({ msg: name + ' left' });
- } else if (state = Steam.EChatMemberStateChange.Disconnected) {
- console.log(name + ' disconnected');
- chatLogs.push({ msg: name + ' disconnected' });
- } else if (state = Steam.EChatMemberStateChange.Kicked) {
- console.log(name + ' kicked by ' + actionName);
- chatLogs.push({ msg: name + ' kicked by ' + actionName });
- } else if (state = Steam.EChatMemberStateChange.Banned) {
- console.log(name + ' banned by ' + actionName);
- chatLogs.push({ msg: name + ' banned by ' + actionName });
- }
- });
- })
- });
- var cacheNames = {}; // Cache names so we don't always have to ask the steam api
- var kickCount = {}; // Numbers of times kicked (track for 3 kick = ban)
- var chatLogs = []; // Stores logs, compiled in saveLog()
- var uniqueUsers = []; // Unique users, added to end of log
- var messageCount = {}; // Keeps track of messages in last 3 seconds (for spam kick)
- steamFriends.on('chatMsg', (roomId, msg, type, id) => {
- if (roomId != config.get('groupId')) return;
- getName(id, (name) => {
- parseMessage(msg, id, name);
- });
- });
- ////// BASIC ACTIONS
- function roomUsers() { return steamFriends.chatRooms[config.get('groupId')]; }
- function chat(msg) { steamFriends.sendMessage(config.get('groupId'), msg); }
- function kick(id, reason) {
- if (isAdmin(id)) return;
- console.log('Kicking '+id+' ('+reason+')');
- steamFriends.kick(config.get('groupId'), id);
- getName(id, (name) => {
- chatLogs.push({ msg: '*KICKED ' + name + ' (Reason: ' + reason + ')'});
- });
- kickCount[id] = (kickCount[id] || 0) + 1;
- if (kickCount[id] >= 3) ban(id, 'Three kicks');
- }
- function ban(id, reason) {
- if (isAdmin(id)) return;
- console.log('Banning '+id+' ('+reason+')')
- steamFriends.ban(config.get('groupId'), id);
- getName(id, (name) => {
- chatLogs.push({ msg: '***BANNED ' + name + ' (Reason: ' + reason + ')'});
- });
- }
- function unban(id) { steamFriends.unban(config.get('groupId'), id); }
- function lock() { steamFriends.lockChat(config.get('groupId')); }
- function unlock() { steamFriends.unlockChat(config.get('groupId')); }
- function moderated() { steamFriends.setModerated(config.get('groupId')); }
- function unmoderated() { steamFriends.setUnmoderated(config.get('groupId')); }
- function isAdmin(id) { return config.get('admins').indexOf(id) > -1 }
- //////////
- function getName(id, cb) { // Either instantly (cached) or a long time (steam api to get name)
- if (!id) {
- cb(null);
- return;
- } else if (cacheNames[id]) {
- cb(cacheNames[id]);
- } else {
- sw.summary([id], (err, resp) => { // Get their data + name
- if (err) console.log('[STEAM API ERR]',err);
- else {
- if (!resp || !resp.players || !resp.players[0]) cb(null);
- else cb(resp.players[0].personaname);
- }
- });
- }
- }
- function saveLog(cb) { // Called at end when closing bot
- var fileName = 'logs/log-'+moment().format('MMM[-]Do[-]h[_]mma')+'.txt';
- var userCount = {};
- uniqueUsers.forEach(u => userCount[u] = 0);
- var str = 'Logs - Saved at '+moment().format('LLLL');
- str += '\n\n';
- for (var c in chatLogs) {
- if (!chatLogs[c].msg) continue;
- if (chatLogs[c].name) {
- str += chatLogs[c].name + ': ' + chatLogs[c].msg + '\n';
- if (userCount[chatLogs[c].id] != undefined) userCount[chatLogs[c].id]++;
- } else {
- str += chatLogs[c].msg + '\n';
- }
- }
- str += '\n\n\nUsers:\n\n';
- var userCountArr = Object.keys(userCount).map(k => { return { id: k, count: userCount[k] } });
- userCountArr = userCountArr.sort((a, b) => a.count < b.count);
- var done = () => {
- totalDone++;
- if (totalDone == userCountArr.length) finish();
- else {
- var user = userCountArr[totalDone];
- getName(user.id, (name) => {
- str += name + ' - ' + user.id + ' (' + user.count + ')' + '\n';
- setTimeout(done, 0);
- });
- }
- };
- var totalDone = -1;
- var finish = () => fs.writeFile(fileName, str, cb);
- setTimeout(finish, 5*1000);
- done();
- }
- setInterval(() => { // Check every 3 seconds, user said >= 5 messages? Kick
- Object.keys(messageCount).forEach(id => {
- if (messageCount[id] >= 5) kick(id, 'Spam');
- });
- messageCount = {};
- }, 3*1000);
- function parseMessage(msg, id, name) { // Deal with message
- console.log(name+': '+msg);
- chatLogs.push({
- name: name,
- id: id,
- msg: msg
- });
- messageCount[id] = (messageCount[id] || 0) + 1;
- var penalty = parseLanguage(msg, id);
- parseCommands(msg, id);
- }
- function parseLanguage(msg, id) { // parse language or links
- if (isAdmin(id)) return;
- var urlChecker = /[^ ]+ ?(?:dot|\.) ?(?:com|org|net)/gi;
- if (msg.match(urlChecker)) { // Check to make sure not an illegal URL
- var m;
- do {
- m = urlChecker.exec(msg);
- if (!m) return;
- var url = m[0].replace(/(https?:\/\/)?(.+\.)?(?=.+\..+)/g, '');
- if (config.get('options.sites').split(',').indexOf(url) == -1) {
- kick(id, 'Unapproved Website');
- return;
- }
- } while (m);
- } else if (config.get('options.keywords').split(',').hasSame(msg.split(' '))) { // Keywords = inappropriate language
- kick(id, 'Language');
- }
- }
- function parseCommands(msg, id) { // Parse commands (only one atm)
- if (msg.match(/!random/) && !isAdmin(id)) {
- var userList = Object.keys(roomUsers()).filter(user => !isAdmin(user));
- var rand = userList[Math.floor(Math.random() * userList.length)];
- getName(rand, (name) => {
- chat('Random User: ' + name + '!');
- });
- }
- }
- // Save server list
- steamClient.on('servers', function(servers) {
- fs.writeFile('servers', JSON.stringify(servers));
- });
- // Save sentry
- steamUser.on('updateMachineAuth', function(sentry, callback) {
- fs.writeFileSync('sentry', sentry.bytes);
- callback({ sha_file: getSHA1(sentry.bytes) });
- });
- function getSHA1(bytes) { // Convert sentry
- var shasum = crypto.createHash('sha1');
- shasum.end(bytes);
- return shasum.read();
- }
- steamFriends.on('relationships', () => { // "node index id" to see this
- if (process.argv[2] == 'id') {
- for (var g in steamFriends.groups) {
- console.log(g);
- }
- }
- });
- Array.prototype.hasSame = function(arr2) {
- for (var i = 0; i < arr2.length; i++) {
- if (this.indexOf(arr2[i]) != -1) return true;
- }
- return false;
- }
- process.on('SIGINT', function() { // When closing, save (or don't if no logs)
- console.log('');
- if (!chatLogs.length) {
- console.log('No chat logs to save!');
- process.exit(0);
- }
- console.log('Saving Log (If this takes more than 20 seconds it will end early)');
- steamFriends.leaveChat(config.get('groupId'));
- saveLog(() => {
- console.log('Saved Log!');
- process.exit(0);
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement