<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();
const figlet = require('figlet');

process.argv.forEach((t) => console.log(t));

token = process.argv[2];
console.log('Using token: ' + token);

client.on('ready', () => {
        figlet('BOT IS READY', (err, data) => {
                if (err) {
                        console.log('figlet broke?');
                }
                console.log(data);
        });
});

client.login(token);
<commit_msg>removed args debug<commit_after>const Discord = require('discord.js');
const client = new Discord.Client();
const figlet = require('figlet');

//process.argv.forEach((t) => console.log(t));

token = process.argv[2];
//console.log('Using token: ' + token);

client.on('ready', () => {
        figlet('BOT IS READY', (err, data) => {
                if (err) {
                        console.log('figlet broke?');
                }
                console.log(data);
        });
});

client.login(token);
<|endoftext|>


<commit_before>var kss = require('kss');
var path = require('path');

function KssPlugin(options) {
  if (!options) {
    throw 'kss webpack plugin: options is not defined. should be an object with at least "source"';
  }
  if (!options.source) {
    throw 'kss webpack plugin: source is not defined';
  }
  this.options = options;
}

KssPlugin.prototype.apply = function (compiler) {
  if (!options.chunks) {
    compiler.plugin('done', function() {
      kss(self.options, function (error) {
        if (error) throw error;
      });
    });
  } else {
    compiler.plugin('emit', (compilation, callback) => {
      this.render(compilation, callback);
    });
  }
};

KssPlugin.prototype.render = function (compilation, callback) {
  var self = this;
  new Promise(function(resolve, reject) {
    var assets = this._buildAssets(compilation);

    kss(Object.assign({}, self.options, assets), function (error) {
      if (error) throw error;
    });
    resolve();
  }).then(() => {
      callback();
    }
  )
};

KssPlugin.prototype._buildAssets = function (compilation) {
  const assets = {
    css: [],
    js: []
  };

  this.options.chunks.forEach(function(key) {
    var pushAsset = function(file) {
      const ext = path.extname(file);

      if (ext === '.css') {
          assets.css.push(path.join('/', file))
      } else if (ext === '.js') {
          assets.js.push(path.join('/', file));
      }
    }

    const asset = compilation.getStats().toJson().assetsByChunkName[key];

    if(typeof asset === 'string') {
      pushAsset(asset)
    } else {
      asset.forEach((file) => {
        pushAsset(file)
      })
    }
  });

  return assets;
};

module.exports = KssPlugin;
<commit_msg>Fixes unknown ref to self<commit_after>var kss = require('kss');
var path = require('path');

function KssPlugin(options) {
  if (!options) {
    throw 'kss webpack plugin: options is not defined. should be an object with at least "source"';
  }
  if (!options.source) {
    throw 'kss webpack plugin: source is not defined';
  }
  this.options = options;
}

KssPlugin.prototype.apply = function (compiler) {
  var self = this;
  if (!self.options.chunks) {
    compiler.plugin('done', function() {
      kss(self.options, function (error) {
        if (error) throw error;
      });
    });
  } else {
    compiler.plugin('emit', (compilation, callback) => {
      this.render(compilation, callback);
    });
  }
};

KssPlugin.prototype.render = function (compilation, callback) {
  var self = this;
  new Promise(function(resolve, reject) {
    var assets = this._buildAssets(compilation);

    kss(Object.assign({}, self.options, assets), function (error) {
      if (error) throw error;
    });
    resolve();
  }).then(() => {
      callback();
    }
  )
};

KssPlugin.prototype._buildAssets = function (compilation) {
  const assets = {
    css: [],
    js: []
  };

  this.options.chunks.forEach(function(key) {
    var pushAsset = function(file) {
      const ext = path.extname(file);

      if (ext === '.css') {
          assets.css.push(path.join('/', file))
      } else if (ext === '.js') {
          assets.js.push(path.join('/', file));
      }
    }

    const asset = compilation.getStats().toJson().assetsByChunkName[key];

    if(typeof asset === 'string') {
      pushAsset(asset)
    } else {
      asset.forEach((file) => {
        pushAsset(file)
      })
    }
  });

  return assets;
};

module.exports = KssPlugin;
<|endoftext|>


<commit_before>var YattaIRC = require('yattairc');
var CommandManager = require('./CommandManager');
var PluginManager = require('./PluginManager')
var Storage = require('./Storage');
var IRC = new YattaIRC;
// User levels
global['USER_LEVEL_NORMAL'] = 0;
global['USER_LEVEL_MODERATOR'] = 1;
global['USER_LEVEL_ADMIN'] = 2;
global['USER_LEVEL_OWNER'] = 3;
var Bot = function(config){
	var self = this;
	var session = self.session = IRC.connect(config.server, config.port);

	self.startTime = (new Date).getTime();

	if(config.nick){
		self.nick = config.nick;
		IRC.nick(session, config.nick);
	}
	if(config.user && config.realname){
		IRC.user(session, config.user, 8, config.realname);
	}
	if(channels = config.channels){
		if(typeof channels == 'object'){
			channels.forEach(function(channel){
				IRC.join(session, channel);
			});
		}
	}
	if(config.auth && config.auth.user && config.auth.pass){
		IRC.message(session, 'NickServ', 'IDENTIFY ' + config.auth.user + ' ' + config.auth.pass);
	}

	self.event = IRC.event;
	self.UserStorage = self.UserStorage = new Storage('users');
	self.PluginConfigs = self.PluginConfigs = new Storage('pluginconfigs');

	CommandManager = self.CommandManager = new CommandManager(self, config.prefix);
	CommandManager.addListeners();
	PluginManager = self.PluginManager = new PluginManager(self);
	PluginManager.loadPlugins(config.plugins || './plugins/');
};
Bot.prototype = {
	on: function(event, callback){
		var self = this;
		self.event.on(event, callback);
	},
	raw: function(message){
		var self = this;
		IRC.raw(self.session, message);
	},
	message: function(target, message){
		var self = this;
		IRC.message(self.session, target, message || '');
	},
	op: function(channel, user){
		var self = this;
		IRC.op(self.session, channel, user);
	},
	deop: function(channel, user){
		var self = this;
		IRC.deop(self.session, channel, user);
	},
	join: function(channel){
		var self = this;
		IRC.join(self.session, channel);
	},
	part: function(channel){
		var self = this;
		IRC.part(self.session, channel);
	},
	kick: function(channel, user, message){
		var self = this;
		IRC.kick(self.session, channel, user, message || user);
	},
	ban: function(channel, user){
		var self = this;
		IRC.ban(self.session, channel, user);
	},
	addCommand: function(){
		var self = this;
		self.CommandManager.addCommand.apply(self.CommandManager, arguments);
	},
	getLevel: function(host){
		var self = this,
			level = self.UserStorage.get(host).level;
		return level ? level : USER_LEVEL_NORMAL;
	}
};
module.exports = Bot;<commit_msg>Fix crash when using nick command<commit_after>var YattaIRC = require('yattairc');
var CommandManager = require('./CommandManager');
var PluginManager = require('./PluginManager')
var Storage = require('./Storage');
var IRC = new YattaIRC;
// User levels
global['USER_LEVEL_NORMAL'] = 0;
global['USER_LEVEL_MODERATOR'] = 1;
global['USER_LEVEL_ADMIN'] = 2;
global['USER_LEVEL_OWNER'] = 3;
var Bot = function(config){
	var self = this;
	var session = self.session = IRC.connect(config.server, config.port);

	self.startTime = (new Date).getTime();

	if(config.nick){
		self.nick = config.nick;
		IRC.nick(session, config.nick);
	}
	if(config.user && config.realname){
		IRC.user(session, config.user, 8, config.realname);
	}
	if(channels = config.channels){
		if(typeof channels == 'object'){
			channels.forEach(function(channel){
				IRC.join(session, channel);
			});
		}
	}
	if(config.auth && config.auth.user && config.auth.pass){
		IRC.message(session, 'NickServ', 'IDENTIFY ' + config.auth.user + ' ' + config.auth.pass);
	}

	self.event = IRC.event;
	self.UserStorage = self.UserStorage = new Storage('users');
	self.PluginConfigs = self.PluginConfigs = new Storage('pluginconfigs');

	CommandManager = self.CommandManager = new CommandManager(self, config.prefix);
	CommandManager.addListeners();
	PluginManager = self.PluginManager = new PluginManager(self);
	PluginManager.loadPlugins(config.plugins || './plugins/');
};
Bot.prototype = {
	on: function(event, callback){
		var self = this;
		self.event.on(event, callback);
	},
	raw: function(message){
		var self = this;
		IRC.raw(self.session, message);
	},
	message: function(target, message){
		var self = this;
		IRC.message(self.session, target, message || '');
	},
	op: function(channel, user){
		var self = this;
		IRC.op(self.session, channel, user);
	},
	deop: function(channel, user){
		var self = this;
		IRC.deop(self.session, channel, user);
	},
	join: function(channel){
		var self = this;
		IRC.join(self.session, channel);
	},
	part: function(channel){
		var self = this;
		IRC.part(self.session, channel);
	},
	kick: function(channel, user, message){
		var self = this;
		IRC.kick(self.session, channel, user, message || user);
	},
	ban: function(channel, user){
		var self = this;
		IRC.ban(self.session, channel, user);
	},
	nick: function(channel, nick){
		var self = this;
		IRC.nick(self.session, nick);
	},
	addCommand: function(){
		var self = this;
		self.CommandManager.addCommand.apply(self.CommandManager, arguments);
	},
	getLevel: function(host){
		var self = this,
			level = self.UserStorage.get(host).level;
		return level ? level : USER_LEVEL_NORMAL;
	}
};
module.exports = Bot;<|endoftext|>


<commit_before>var API = require('./api-functions'),
	RATE_LIMIT_EXCEEDED_TIMEOUT = 1000 * 60 * 10, 	// 10 minutes
	RETWEET_TIMEOUT = 1000 * 5; 					// 5 * 1.2 seconds

// Main self-initializing function
(function() {
	var last_tweet_id = 0,
		searchResultsArr = [],
		blockedUsers = [];

	/** The Callback function for the Search API */
	var searchCallback = function (response) {
		var payload = JSON.parse(response);

		// Iterating through tweets returned by the Search
		payload.statuses.forEach(function (searchItem) {

			// Further filtering out the retweets and tweets from blocked users
			if (!searchItem.retweeted_status && blockedUsers.indexOf(searchItem.user.id) === -1) {

				// Save the search item in the Search Results array
				searchResultsArr.push(searchItem);
			}
		});

		// If we have the next_results, search again for the rest (sort of a pagination)
		if (payload.search_metadata.next_results) {
			API.searchByStringParam(payload.search_metadata.next_results, searchCallback);
		}
  	};

  	/** The error callback for the Search API */
  	var errorHandler = function (err) {
  		console.error("Error!", err.message);

  		// If the error is "Rate limit exceeded", code 88 - try again after 10 minutes
  		if (JSON.parse(err.error).errors[0].code === 88) {
  			console.log("After " + RATE_LIMIT_EXCEEDED_TIMEOUT / 60000 + " minutes, I will try again to fetch some results...");
  			setTimeout(function () {
  				search();
  			}, RATE_LIMIT_EXCEEDED_TIMEOUT);
	  	}
  	};

  	/** The Search function */
  	var search = function () {
  		API.search({
  			// Without having the word "vote", and filtering out retweets - as much as possible
			text: "retweet to win -vote -filter:retweets OR RT to win -vote -filter:retweets",
			result_type: "recent",
			callback: searchCallback,
			error_callback: errorHandler,
			since_id: last_tweet_id
		});
  	};

  	/** The Retweet worker - also performs Favorite and Follow actions if necessary */
  	var retweetWorker = function () {

  		setTimeout(function () {

  			// Check if we have elements in the Result Array
  			if (searchResultsArr.length) {

  				// Pop the first element (by doing a shift() operation)
  				var searchItem = searchResultsArr[0];
  				searchResultsArr.shift();

  				// Retweet
				API.retweet(searchItem.id_str);
				console.log("Retweet", searchItem.id);

  				// Check if we also need to Favorite
  				if (searchItem.text.toLowerCase().indexOf("fav") > -1) {
  					API.favorite(searchItem.id_str);
  					console.log("Favorite", searchItem.id);
  				}

  				if (searchItem.text.toLowerCase().indexOf("follow") > -1) {
  					API.follow(searchItem.user.id_str);
  					console.log("Follow", searchItem.user.screen_name);
  				}
  			}

  			retweetWorker();
  		}, RETWEET_TIMEOUT);
  	}

  	// First, get the blocked users
  	API.getBlockedUsers(function (blockedList) {

  		blockedUsers = blockedList;

  		// Start the Retweet worker
  		retweetWorker();

  		// Start searching (the Search is in itself a worked, as the callback continues to fetch data)
  		search();
  	});
}());<commit_msg>something<commit_after>var API = require('./api-functions'),
	RATE_LIMIT_EXCEEDED_TIMEOUT = 1000 * 60 * 50, 	// 50 minutes
	RETWEET_TIMEOUT = 1000 * 5; 					// 5 seconds

// Main self-initializing function
(function() {
	var last_tweet_id = 0,
		searchResultsArr = [],
		blockedUsers = [];

	/** The Callback function for the Search API */
	var searchCallback = function (response) {
		var payload = JSON.parse(response);

		// Iterating through tweets returned by the Search
		payload.statuses.forEach(function (searchItem) {

			// Further filtering out the retweets and tweets from blocked users
			if (!searchItem.retweeted_status && blockedUsers.indexOf(searchItem.user.id) === -1) {

				// Save the search item in the Search Results array
				searchResultsArr.push(searchItem);
			}
		});

		// If we have the next_results, search again for the rest (sort of a pagination)
		if (payload.search_metadata.next_results) {
			API.searchByStringParam(payload.search_metadata.next_results, searchCallback);
		}
  	};

  	/** The error callback for the Search API */
  	var errorHandler = function (err) {
  		console.error("Error!", err.message);

  		// If the error is "Rate limit exceeded", code 88 - try again after 10 minutes
  		if (JSON.parse(err.error).errors[0].code === 88) {
  			console.log("After " + RATE_LIMIT_EXCEEDED_TIMEOUT / 60000 + " minutes, I will try again to fetch some results...");
  			setTimeout(function () {
  				search();
  			}, RATE_LIMIT_EXCEEDED_TIMEOUT);
	  	}
  	};

  	/** The Search function */
  	var search = function () {
  		API.search({
  			// Without having the word "vote", and filtering out retweets - as much as possible
			text: "retweet to win -vote -filter:retweets OR RT to win -vote -filter:retweets",
			result_type: "recent",
			callback: searchCallback,
			error_callback: errorHandler,
			since_id: last_tweet_id
		});
  	};

  	/** The Retweet worker - also performs Favorite and Follow actions if necessary */
  	var retweetWorker = function () {

  		setTimeout(function () {

  			// Check if we have elements in the Result Array
  			if (searchResultsArr.length) {

  				// Pop the first element (by doing a shift() operation)
  				var searchItem = searchResultsArr[0];
  				searchResultsArr.shift();

  				// Retweet
				API.retweet(searchItem.id_str);
				console.log("Retweet", searchItem.id);

  				// Check if we also need to Favorite
  				if (searchItem.text.toLowerCase().indexOf("fav") > -1) {
  					API.favorite(searchItem.id_str);
  					console.log("Favorite", searchItem.id);
  				}

  				if (searchItem.text.toLowerCase().indexOf("follow") > -1) {
  					API.follow(searchItem.user.id_str);
  					console.log("Follow", searchItem.user.screen_name);
  				}
  			}

  			retweetWorker();
  		}, RETWEET_TIMEOUT);
  	}

  	// First, get the blocked users
  	API.getBlockedUsers(function (blockedList) {

  		blockedUsers = blockedList;

  		// Start the Retweet worker
  		retweetWorker();

  		// Start searching (the Search is in itself a worked, as the callback continues to fetch data)
  		search();
  	});
}());<|endoftext|>


<commit_before>// This code is awful, and I know it.

var config = Config.ircconfig;

exports.report = function report(message) {
	if (!config) {
		return;
	}
	var room = config.reportroom;
	if (room) {
		say(room, message);
	}
};

if (!config) {
	return;
}

var irc = require('irc');
var Pool = require('generic-pool').Pool;
var Client = require('pg-native');

var pool = Pool({
	create: function (callback) {
		var client = new Client();
		client.connect(function (err) {
			if (err) {
				callback(err, null);
			} else {
				callback(null, client);
			}
		});
	},
	destroy: function (client) {
		client.end();
	},
	max: 5,
	idleTimeoutMillis: 30000
});

var connection = exports.connection = new irc.Client(config.server, config.nickname, config);

function say(room, message) {
	connection.say(room, message);
	if (!config.loggerid) return;
	var messages = message.split("\n");
	for (var i = 0; i < messages.length; i++) {
		log(config.loggerid, 1, config.nickname, messages[i]);
	}
}

function log(bufferid, type, user, message) {
	pool.acquire(function (err, client) {
		if (err) throw err;
		client.query('SELECT insert_row($1, $2, $3, $4)', [bufferid, type, user, message], function (err, result) {
			pool.release(client);
			if (err) throw err;
		});
	});
}

function listenForLogs(socket, channel, bufferid) {
	socket.on('join' + channel, function join(nick, message) {
		log(bufferid, 32, message.prefix, channel);
	});

	socket.on('part' + channel, function part(nick, reason, message) {
		log(bufferid, 64, message.prefix, reason);
	});

	socket.on('quit', function quit(nick, reason, channels, message) {
		if (channels.indexOf(channel) === -1) return;

		log(bufferid, 128, message.prefix, reason);
	});

	socket.on('kick' + channel, function kick(nick, by, reason, message) {
		log(bufferid, 256, message.prefix, nick + ' ' + reason);
	});

	socket.on('action', function action(nick, to, actionMessage, message) {
		log(bufferid, 4, message.prefix, actionMessage);
	});

	socket.on('notice', function notice(nick, to, text, message) {
		if (to !== channel) return;
		log(bufferid, 2, message.prefix, text);
	});

	socket.on('nick', function nick(oldnick, newnick, channels, message) {
		if (channels.indexOf(channel) === -1) return;

		log(bufferid, 8, message.prefix, newnick);
	});

	socket.on('topic', function topic(to, newTopic, nick, message) {
		if (to !== channel) return;
		// Initial message
		if (/!/.test(nick)) {
			log(bufferid, 16384, "", 'Topic for ' + to + ' is "' + newTopic + '"');
		} else {
			log(bufferid, 16384, "", nick + ' has changed topic for ' + to + ' to: "' + newTopic + '"');
		}
	});

	// Mode messages in IRC framework are way too clever.
	socket.on('raw', function (message) {
		if (message.command !== 'MODE' || message.args[0] !== channel) return;
		log(bufferid, 16, message.prefix, message.args.join(' '));
	});
}

function identity(value) {
	return function identityFunction() {
		return value;
	};
}

function parseRaw(message) {
	return message
		.replace(/Super Effective<\/font><\/b>/g, "\x033Super Effective\x0F")
		.replace(/]*room=[^>]*>(.*?)<\/a>/g, "$1")
		.replace(/(.*?)<\/a>/g, "[$2]($1)")
		.replace(/
/g, "\n  • ")
		.replace(/<\/?(?:ul|font size|div)[^>]*?>/g, "")
		.replace(/.*?<\/small>/g, "")
		.replace(/<\/?(?:b|strong)(?: class="username")?>/g, "\x02")
		.replace(/<\/?em>/g, "\x1D")
		.replace(/<(?:\/span|\/font|font color=black)>/g, "\x0F")
		.replace(//g, "\x02\x034")
		.replace(//g, "\x02\x0312")
		.replace(//g, "\x02\x0314")
		.replace(//g, "\x02\x1F\x033")
		.replace(//g, "\x02\x1F\x034")
		.replace(//g, "\x0314")
		.replace(//g, "\x0314")
		.replace(/ |  | +/g, " ")
		.replace(/✓/g, "✓")
		.replace(/</g, "<")
		.replace(/>/g, ">")
		.replace(/"/g, '"')
		.replace(/'/g, "'")
		.replace(///g, "/")
		.replace(/é/g, "é")
		.replace(/&/g, "&")
		.split(/
/);
}

function verifyParts(parts) {
	if (parts.length > 6) {
		return false;
	}
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		if (part.length > 440) {
			return false;
		}
	}
	return true;
}

var dataParsers = {
	pokemon: function (specie) {
		var specieData = Tools.getTemplate(specie);
		var result = [];
		var tier = specieData.tier;
		if (!require('./data/tpp').BattleTPP[specieData.id] && !specieData.isNonstandard && !specieData.isUnreleased) {
			tier = 'T-Rule ' + tier;
		}
		result.push(tier);
		result.push(specieData.species);
		result.push(specieData.types.join("/") + '-type');

		var baseStats = [];
		var bst = 0;
		var stats = ['HP', 'Atk', 'Def', 'SpA', 'SpD', 'Spe'];
		var statsLength = stats.length;
		var i;
		for (i = 0; i < statsLength; i++) {
			var stat = stats[i];
			var statValue = specieData.baseStats[toId(stat)];
			bst += statValue;
			baseStats.push('\x0314' + stat + ':\x0F ' + statValue);
		}
		baseStats.push('\x0314BST:\x0F ' + bst);
		result.push(baseStats.join(', '));

		var abilityData = specieData.abilities;
		var abilityOrder = [0, 1, 'H'];
		var abilityOrderLength = abilityOrder.length;
		var abilities = [];

		for (i = 0; i < abilityOrderLength; i++) {
			var abilityPosition = abilityOrder[i];
			var ability = abilityData[abilityPosition];
			if (ability) {
				if (abilityPosition === 'H') {
					ability = '\x1D' + ability + '\x1D';
				}
				abilities.push(ability);
			}
		}
		result.push('\x0314Abilities:\x0F ' + abilities.join(', '));

		return result.join(' | ');
	},
	item: function (item) {
		var itemData = Tools.getItem(item);
		return [itemData.name, itemData.desc].join(' | ');
	},
	ability: function (ability) {
		var abilityData = Tools.getAbility(ability);
		return [abilityData.name, abilityData.shortDesc].join(' | ');
	},
	move: function (move) {
		var moveData = Tools.getMove(move);

		var result = [];
		result.push(moveData.name);
		result.push(moveData.category);
		result.push(moveData.type + '-type');

		if (moveData.category !== 'Status') {
			if (moveData.basePower) {
				result.push('\x0314Power:\x0F ' + moveData.basePower + ' BP');
			} else {
				result.push('\x0314Power:\x0F —');
			}
		}

		if (moveData.accuracy === true) {
			result.push('\x0314Accuracy:\x0F —');
		} else {
			result.push('\x0314Accuracy:\x0F ' + moveData.accuracy + '%');
		}

		result.push('\x0314PP:\x0F ' + moveData.pp * 8 / 5);
		result.push(moveData.shortDesc);

		return result.join(' | ');
	}
};

function filter(rawMessage) {
	var parts = rawMessage.split(/\n/);
	var rawSignal = '|raw|';
	var dataSignal = '|c|~|/data-';
	var errorSignal = '|html|
';
	var finalParts = [];
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		var message;
		if (part.slice(0, rawSignal.length) === rawSignal) {
			message = part.slice(rawSignal.length);
			Array.prototype.push.apply(finalParts, parseRaw(message));
		} else if (part.slice(0, dataSignal.length) === dataSignal) {
			message = part.slice(dataSignal.length);
			var splitter = message.indexOf(' ');
			var type = message.slice(0, splitter);
			var what = message.slice(splitter + 1);
			finalParts.push(dataParsers[type](what));
		} else if (part.slice(0, errorSignal.length) !== errorSignal) {
			finalParts.push(part);
		}
	}
	if (!verifyParts(finalParts)) return "Response too long.";
	return finalParts.join("\n");
}

function FakeRoom(id) {
	this.id = id;
}
FakeRoom.prototype.isMuted = identity(false);
FakeRoom.prototype.users = {};

var ircUser = {
	named: false,
	can: identity(false),
	resetName: identity(),
	tryJoinRoom: identity(null),
	leaveRoom: identity(),
	group: ' '
};

var ircConnection = {
	sendTo: function (room, message) {
		say(room.id, filter(message));
	},
	popup: identity()
};

connection.on('message', function parseMessage(from, to, text, message) {
	if (config.loggerid && to === (config.reportroom || config.channels[0])) {
		log(config.loggerid, 1, message.prefix, text);
	}
	if (to.charAt(0) !== '#') {
		to = from;
	}
	if (/\byay\b/i.test(text)) {
		connection.say(to, 'Y+A+Y');
	}
	// DootBot conflict
	if (text.slice(0, 2) === '!?') return;
	if (text.charAt(0) !== '!' && text.charAt(0) !== '/') return;
	CommandParser.parse('/' + text.slice(1), new FakeRoom(to), ircUser, ircConnection);
});

if (config.loggerid) {
	listenForLogs(connection, config.reportroom || config.channels[0], config.loggerid);
}

if (!Config.irclog) {
	Config.irclog = [];
}

for (var i = 0; i < Config.irclog.length; i++) {
	var server = Config.irclog[i];
	var channels = server.channels;
	server.channels = server.channels.map(function (channel) {
		return channel.name;
	});
	var logConnection = new irc.Client(server.server, server.nickname, server);
	for (var j = 0; j < channels.length; j++) {
		var channel = channels[j];
		listenForLogs(logConnection, channel.name, channel.loggerid);
		logConnection.on('message' + channel.name, function (nick, text, message) {
			log(channel.loggerid, 1, message.prefix, text);
		});
	}
}
<commit_msg>Don't output empty messages into logs.<commit_after>// This code is awful, and I know it.

var config = Config.ircconfig;

exports.report = function report(message) {
	if (!config) {
		return;
	}
	var room = config.reportroom;
	if (room) {
		say(room, message);
	}
};

if (!config) {
	return;
}

var irc = require('irc');
var Pool = require('generic-pool').Pool;
var Client = require('pg-native');

var pool = Pool({
	create: function (callback) {
		var client = new Client();
		client.connect(function (err) {
			if (err) {
				callback(err, null);
			} else {
				callback(null, client);
			}
		});
	},
	destroy: function (client) {
		client.end();
	},
	max: 5,
	idleTimeoutMillis: 30000
});

var connection = exports.connection = new irc.Client(config.server, config.nickname, config);

function say(room, message) {
	if (!message) return;
	connection.say(room, message);
	if (!config.loggerid) return;
	var messages = message.split("\n");
	for (var i = 0; i < messages.length; i++) {
		log(config.loggerid, 1, config.nickname, messages[i]);
	}
}

function log(bufferid, type, user, message) {
	pool.acquire(function (err, client) {
		if (err) throw err;
		client.query('SELECT insert_row($1, $2, $3, $4)', [bufferid, type, user, message], function (err, result) {
			pool.release(client);
			if (err) throw err;
		});
	});
}

function listenForLogs(socket, channel, bufferid) {
	socket.on('join' + channel, function join(nick, message) {
		log(bufferid, 32, message.prefix, channel);
	});

	socket.on('part' + channel, function part(nick, reason, message) {
		log(bufferid, 64, message.prefix, reason);
	});

	socket.on('quit', function quit(nick, reason, channels, message) {
		if (channels.indexOf(channel) === -1) return;

		log(bufferid, 128, message.prefix, reason);
	});

	socket.on('kick' + channel, function kick(nick, by, reason, message) {
		log(bufferid, 256, message.prefix, nick + ' ' + reason);
	});

	socket.on('action', function action(nick, to, actionMessage, message) {
		log(bufferid, 4, message.prefix, actionMessage);
	});

	socket.on('notice', function notice(nick, to, text, message) {
		if (to !== channel) return;
		log(bufferid, 2, message.prefix, text);
	});

	socket.on('nick', function nick(oldnick, newnick, channels, message) {
		if (channels.indexOf(channel) === -1) return;

		log(bufferid, 8, message.prefix, newnick);
	});

	socket.on('topic', function topic(to, newTopic, nick, message) {
		if (to !== channel) return;
		// Initial message
		if (/!/.test(nick)) {
			log(bufferid, 16384, "", 'Topic for ' + to + ' is "' + newTopic + '"');
		} else {
			log(bufferid, 16384, "", nick + ' has changed topic for ' + to + ' to: "' + newTopic + '"');
		}
	});

	// Mode messages in IRC framework are way too clever.
	socket.on('raw', function (message) {
		if (message.command !== 'MODE' || message.args[0] !== channel) return;
		log(bufferid, 16, message.prefix, message.args.join(' '));
	});
}

function identity(value) {
	return function identityFunction() {
		return value;
	};
}

function parseRaw(message) {
	return message
		.replace(/Super Effective<\/font><\/b>/g, "\x033Super Effective\x0F")
		.replace(/]*room=[^>]*>(.*?)<\/a>/g, "$1")
		.replace(/(.*?)<\/a>/g, "[$2]($1)")
		.replace(/
/g, "\n  • ")
		.replace(/<\/?(?:ul|font size|div)[^>]*?>/g, "")
		.replace(/.*?<\/small>/g, "")
		.replace(/<\/?(?:b|strong)(?: class="username")?>/g, "\x02")
		.replace(/<\/?em>/g, "\x1D")
		.replace(/<(?:\/span|\/font|font color=black)>/g, "\x0F")
		.replace(//g, "\x02\x034")
		.replace(//g, "\x02\x0312")
		.replace(//g, "\x02\x0314")
		.replace(//g, "\x02\x1F\x033")
		.replace(//g, "\x02\x1F\x034")
		.replace(//g, "\x0314")
		.replace(//g, "\x0314")
		.replace(/ |  | +/g, " ")
		.replace(/✓/g, "✓")
		.replace(/</g, "<")
		.replace(/>/g, ">")
		.replace(/"/g, '"')
		.replace(/'/g, "'")
		.replace(///g, "/")
		.replace(/é/g, "é")
		.replace(/&/g, "&")
		.split(/
/);
}

function verifyParts(parts) {
	if (parts.length > 6) {
		return false;
	}
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		if (part.length > 440) {
			return false;
		}
	}
	return true;
}

var dataParsers = {
	pokemon: function (specie) {
		var specieData = Tools.getTemplate(specie);
		var result = [];
		var tier = specieData.tier;
		if (!require('./data/tpp').BattleTPP[specieData.id] && !specieData.isNonstandard && !specieData.isUnreleased) {
			tier = 'T-Rule ' + tier;
		}
		result.push(tier);
		result.push(specieData.species);
		result.push(specieData.types.join("/") + '-type');

		var baseStats = [];
		var bst = 0;
		var stats = ['HP', 'Atk', 'Def', 'SpA', 'SpD', 'Spe'];
		var statsLength = stats.length;
		var i;
		for (i = 0; i < statsLength; i++) {
			var stat = stats[i];
			var statValue = specieData.baseStats[toId(stat)];
			bst += statValue;
			baseStats.push('\x0314' + stat + ':\x0F ' + statValue);
		}
		baseStats.push('\x0314BST:\x0F ' + bst);
		result.push(baseStats.join(', '));

		var abilityData = specieData.abilities;
		var abilityOrder = [0, 1, 'H'];
		var abilityOrderLength = abilityOrder.length;
		var abilities = [];

		for (i = 0; i < abilityOrderLength; i++) {
			var abilityPosition = abilityOrder[i];
			var ability = abilityData[abilityPosition];
			if (ability) {
				if (abilityPosition === 'H') {
					ability = '\x1D' + ability + '\x1D';
				}
				abilities.push(ability);
			}
		}
		result.push('\x0314Abilities:\x0F ' + abilities.join(', '));

		return result.join(' | ');
	},
	item: function (item) {
		var itemData = Tools.getItem(item);
		return [itemData.name, itemData.desc].join(' | ');
	},
	ability: function (ability) {
		var abilityData = Tools.getAbility(ability);
		return [abilityData.name, abilityData.shortDesc].join(' | ');
	},
	move: function (move) {
		var moveData = Tools.getMove(move);

		var result = [];
		result.push(moveData.name);
		result.push(moveData.category);
		result.push(moveData.type + '-type');

		if (moveData.category !== 'Status') {
			if (moveData.basePower) {
				result.push('\x0314Power:\x0F ' + moveData.basePower + ' BP');
			} else {
				result.push('\x0314Power:\x0F —');
			}
		}

		if (moveData.accuracy === true) {
			result.push('\x0314Accuracy:\x0F —');
		} else {
			result.push('\x0314Accuracy:\x0F ' + moveData.accuracy + '%');
		}

		result.push('\x0314PP:\x0F ' + moveData.pp * 8 / 5);
		result.push(moveData.shortDesc);

		return result.join(' | ');
	}
};

function filter(rawMessage) {
	var parts = rawMessage.split(/\n/);
	var rawSignal = '|raw|';
	var dataSignal = '|c|~|/data-';
	var errorSignal = '|html|
';
	var finalParts = [];
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		var message;
		if (part.slice(0, rawSignal.length) === rawSignal) {
			message = part.slice(rawSignal.length);
			Array.prototype.push.apply(finalParts, parseRaw(message));
		} else if (part.slice(0, dataSignal.length) === dataSignal) {
			message = part.slice(dataSignal.length);
			var splitter = message.indexOf(' ');
			var type = message.slice(0, splitter);
			var what = message.slice(splitter + 1);
			finalParts.push(dataParsers[type](what));
		} else if (part.slice(0, errorSignal.length) !== errorSignal) {
			finalParts.push(part);
		}
	}
	if (!verifyParts(finalParts)) return "Response too long.";
	return finalParts.join("\n");
}

function FakeRoom(id) {
	this.id = id;
}
FakeRoom.prototype.isMuted = identity(false);
FakeRoom.prototype.users = {};

var ircUser = {
	named: false,
	can: identity(false),
	resetName: identity(),
	tryJoinRoom: identity(null),
	leaveRoom: identity(),
	group: ' '
};

var ircConnection = {
	sendTo: function (room, message) {
		say(room.id, filter(message));
	},
	popup: identity()
};

connection.on('message', function parseMessage(from, to, text, message) {
	if (config.loggerid && to === (config.reportroom || config.channels[0])) {
		log(config.loggerid, 1, message.prefix, text);
	}
	if (to.charAt(0) !== '#') {
		to = from;
	}
	if (/\byay\b/i.test(text)) {
		connection.say(to, 'Y+A+Y');
	}
	// DootBot conflict
	if (text.slice(0, 2) === '!?') return;
	if (text.charAt(0) !== '!' && text.charAt(0) !== '/') return;
	CommandParser.parse('/' + text.slice(1), new FakeRoom(to), ircUser, ircConnection);
});

if (config.loggerid) {
	listenForLogs(connection, config.reportroom || config.channels[0], config.loggerid);
}

if (!Config.irclog) {
	Config.irclog = [];
}

for (var i = 0; i < Config.irclog.length; i++) {
	var server = Config.irclog[i];
	var channels = server.channels;
	server.channels = server.channels.map(function (channel) {
		return channel.name;
	});
	var logConnection = new irc.Client(server.server, server.nickname, server);
	for (var j = 0; j < channels.length; j++) {
		var channel = channels[j];
		listenForLogs(logConnection, channel.name, channel.loggerid);
		logConnection.on('message' + channel.name, function (nick, text, message) {
			log(channel.loggerid, 1, message.prefix, text);
		});
	}
}
<|endoftext|>


<commit_before>var registerSystem = require('../core/system').registerSystem;
var utils = require('../utils');

/**
 * Tracked controls system.
 * Maintain list with available tracked controllers.
 */
module.exports.System = registerSystem('tracked-controls', {
  init: function () {
    var self = this;

    this.controllers = [];

    this.updateControllerList(navigator.getGamepads && navigator.getGamepads());
    this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);

    if (!navigator.getVRDisplays) { return; }

    this.sceneEl.addEventListener('enter-vr', function () {
      navigator.getVRDisplays().then(function (displays) {
        if (displays.length) { self.vrDisplay = displays[0]; }
      });
    });
  },

  tick: function () {
    var gamepads;
    // Call getGamepads for Chrome.
    gamepads = navigator.getGamepads && navigator.getGamepads();
    this.throttledUpdateControllerList(gamepads);
  },

  /**
   * Update controller list.
   */
  updateControllerList: function (gamepads) {
    var controllers = this.controllers;
    var gamepad;
    var i;
    var prevCount;

    if (!gamepads) { return; }

    prevCount = controllers.length;
    controllers.length = 0;
    for (i = 0; i < gamepads.length; ++i) {
      gamepad = gamepads[i];
      if (gamepad && gamepad.pose) {
        controllers.push(gamepad);
      }
    }

    if (controllers.length !== prevCount) {
      this.el.emit('controllersupdated', undefined, false);
    }
  }
});
<commit_msg>remove spamming getGamepad calls to reduce GC (#3816)<commit_after>var registerSystem = require('../core/system').registerSystem;
var utils = require('../utils');

/**
 * Tracked controls system.
 * Maintain list with available tracked controllers.
 */
module.exports.System = registerSystem('tracked-controls', {
  init: function () {
    var self = this;

    this.controllers = [];

    this.updateControllerList();
    this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);

    if (!navigator.getVRDisplays) { return; }

    this.sceneEl.addEventListener('enter-vr', function () {
      navigator.getVRDisplays().then(function (displays) {
        if (displays.length) { self.vrDisplay = displays[0]; }
      });
    });
  },

  tick: function () {
    if (navigator.userAgent.indexOf('Chrome') !== -1) {
      // Call getGamepads for Chrome for it to update. Not sure if needed in future.
      navigator.getGamepads && navigator.getGamepads();
    }
    this.throttledUpdateControllerList();
  },

  /**
   * Update controller list.
   */
  updateControllerList: function () {
    var controllers = this.controllers;
    var gamepad;
    var gamepads;
    var i;
    var prevCount;

    gamepads = navigator.getGamepads && navigator.getGamepads();
    if (!gamepads) { return; }

    prevCount = controllers.length;
    controllers.length = 0;
    for (i = 0; i < gamepads.length; ++i) {
      gamepad = gamepads[i];
      if (gamepad && gamepad.pose) {
        controllers.push(gamepad);
      }
    }

    if (controllers.length !== prevCount) {
      this.el.emit('controllersupdated', undefined, false);
    }
  }
});
<|endoftext|>


<commit_before>var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000

app.use(express.static(__dirname + '/site'));

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

 app.get('/test', function(request, response) {
 response.send('Hello World!');
 });

var server = http.createServer(app)
server.listen(port)

console.log("http server listening on %d", port)

var wss = new WebSocketServer({server: server})
console.log("websocket server created")

//connections
var gCon = [];

var curID = 0;

var WsProtocol =
{
	//operation code
	wsOP_cliHello:0,
	wsOP_servHello:1,
	wsOP_cliLogin:2,
	wsOP_msgRelay:3,
	wsOP_msgSpecial:4,
	wsOP_positiveAck:5,
	wsOP_negativeAck:6,

	//subopCodes
	wsOP_srvDebugConn:0,

	//message keys
	wsKey_clientType:0,

	//message values
	wsValue_homeBase:0,
	wsValue_webBrowser:1,
	wsValue_mobileApp:2,
	wsValue_unknown:3,

	//connection states
	wsState_new:0,
	wsState_hello:1,
	wsState_conn:2,
	wsState_inval:3,

};

wss.on("connection", function(ws)
{
  var id = curID++;
  var conIdx = gCon.length;

  gCon.push({ws:ws, id:-1, ws:ws, state:WsProtocol.wsState_new, type:WsProtocol.wsValue_unknown});

  /*setInterval(function() {
    ws.send(JSON.stringify(new Date()), function() {  })
  }, 1000)*/

  //ws.send("{conID:"+id+"}", function() {  })

  console.log("ws open "+id);

  ws.on("message", function(msg)
  {
    console.log("ws msg "+msg)

	var m = JSON.parse(msg);
	var reply = {};

	if(typeof m.op === 'undefined')
	{
		console.log("[E] ws msg: nop")
		return;
	}

	switch(m.op)
	{
		case WsProtocol.wsOP_cliHello:
			if(gCon[conIdx].state == WsProtocol.wsState_new)
			{
				reply.op = WsProtocol.wsOP_servHello;
				ws.send(JSON.stringify(reply), function() {  })

				gCon[conIdx].state = WsProtocol.wsState_hello;
			}
			else console.log("[E] ws msg: cliHello, state "+gCon[conIdx].state);
		break;

		case WsProtocol.wsOP_cliLogin:
			if(gCon[conIdx].state == WsProtocol.wsState_hello)
			{
				if((m.type >= WsProtocol.wsValue_homeBase && m.type < WsProtocol.wsValue_unknown) &&
					(m.id > -1))
				{
					gCon[conIdx].type = m.type;
					gCon[conIdx].id = m.id;

					reply.op = WsProtocol.wsOP_positiveAck;
					reply.conID = id;
					gCon[conIdx].state = WsProtocol.wsState_conn;
				}
				else
				{
					reply.op = WsProtocol.wsOP_negativeAck;
					reply.err = "badParams";

				}

				ws.send(JSON.stringify(reply), function() {  })
			}
			else console.log("[E] ws msg: cliLogin, state "+gCon[conIdx].state);
		break;

		case WsProtocol.wsOP_msgRelay:
			if(gCon[conIdx].state == WsProtocol.wsState_conn)
			{
				var dest = m.dest;
				var destType = m.type;
				var i=0;
				reply.op = WsProtocol.wsOP_negativeAck;

				for(; i< conIdx+1;i++)
				{
					if(gCon[i].type == destType && gCon[i].id == dest)
					{
						var proxy={}
						proxy.op = WsProtocol.wsOP_msgRelay;
						proxy.msg = m.msg;
						proxy.from = gCon[conIdx].id;

						gCon[i].ws.send(JSON.stringify(proxy), function() {  })
						reply.op = WsProtocol.wsOP_positiveAck;
						break;
					}
				}

				//only send reply for negative responses
				if(reply.op == WsProtocol.wsOP_negativeAck)
				{
					ws.send(JSON.stringify(reply), function() {  })
				}
			}
			else console.log("[E] ws msg: msgToBase, state "+gCon[conIdx].state);
		break;

		case WsProtocol.wsOP_msgSpecial:
			if(gCon[conIdx].state == WsProtocol.wsState_conn)
			{
				switch(m.subOp)
				{
					case WsProtocol.wsOP_srvDebugConn:

						reply.op = WsProtocol.wsOP_msgSpecial;
						reply.subOp = WsProtocol.wsOP_srvDebugConn;

						reply.message = gCon;

						ws.send(JSON.stringify(reply), function() {  })

					break;

					default:
						console.log("[E] ws msg: unknown op" + m.op)
					break;
				}
			}
			else console.log("[E] ws msg: msgToServer, state "+gCon[conIdx].state);
		break;

		default:
			console.log("[E] ws msg: unknown op" + m.op)
			break;
	};

  });

  ws.on("close", function()
  {
    console.log("ws close "+id)
    //clearInterval(id);
  });
});
<commit_msg>improve parse<commit_after>var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000

app.use(express.static(__dirname + '/site'));

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

 app.get('/test', function(request, response) {
 response.send('Hello World!');
 });

var server = http.createServer(app)
server.listen(port)

console.log("http server listening on %d", port)

var wss = new WebSocketServer({server: server})
console.log("websocket server created")

//connections
var gCon = [];

var curID = 0;

var WsProtocol =
{
	//operation code
	wsOP_cliHello:0,
	wsOP_servHello:1,
	wsOP_cliLogin:2,
	wsOP_msgRelay:3,
	wsOP_msgSpecial:4,
	wsOP_positiveAck:5,
	wsOP_negativeAck:6,

	//subopCodes
	wsOP_srvDebugConn:0,

	//message keys
	wsKey_clientType:0,

	//message values
	wsValue_homeBase:0,
	wsValue_webBrowser:1,
	wsValue_mobileApp:2,
	wsValue_unknown:3,

	//connection states
	wsState_new:0,
	wsState_hello:1,
	wsState_conn:2,
	wsState_inval:3,

};

wss.on("connection", function(ws)
{
  var id = curID++;
  var conIdx = gCon.length;

  gCon.push({ws:ws, id:-1, state:WsProtocol.wsState_new, type:WsProtocol.wsValue_unknown});

  /*setInterval(function() {
    ws.send(JSON.stringify(new Date()), function() {  })
  }, 1000)*/

  //ws.send("{conID:"+id+"}", function() {  })

  console.log("ws open "+id);

  ws.on("message", function(msg)
  {
    console.log("ws msg "+msg)

	var m = {};
	var reply = {};

	try{
		m = JSON.parse(msg);
	}
	catch(e)
	{
		console.log("ws parse exc: "+e.message)
		m = {op:-1};
	}

	if(typeof m.op === 'undefined')
	{
		console.log("[E] ws msg: nop")
		return;
	}

	switch(m.op)
	{
		case WsProtocol.wsOP_cliHello:
			if(gCon[conIdx].state == WsProtocol.wsState_new)
			{
				reply.op = WsProtocol.wsOP_servHello;
				ws.send(JSON.stringify(reply), function() {  })

				gCon[conIdx].state = WsProtocol.wsState_hello;
			}
			else console.log("[E] ws msg: cliHello, state "+gCon[conIdx].state);
		break;

		case WsProtocol.wsOP_cliLogin:
			if(gCon[conIdx].state == WsProtocol.wsState_hello)
			{
				if((m.type >= WsProtocol.wsValue_homeBase && m.type < WsProtocol.wsValue_unknown) &&
					(m.id > -1))
				{
					gCon[conIdx].type = m.type;
					gCon[conIdx].id = m.id;

					reply.op = WsProtocol.wsOP_positiveAck;
					reply.conID = id;
					gCon[conIdx].state = WsProtocol.wsState_conn;
				}
				else
				{
					reply.op = WsProtocol.wsOP_negativeAck;
					reply.err = "badParams";

				}

				ws.send(JSON.stringify(reply), function() {  })
			}
			else console.log("[E] ws msg: cliLogin, state "+gCon[conIdx].state);
		break;

		case WsProtocol.wsOP_msgRelay:
			if(gCon[conIdx].state == WsProtocol.wsState_conn)
			{
				var dest = m.dest;
				var destType = m.type;
				var i=0;
				reply.op = WsProtocol.wsOP_negativeAck;

				for(; i< conIdx+1;i++)
				{
					if(gCon[i].type == destType && gCon[i].id == dest)
					{
						var proxy={}
						proxy.op = WsProtocol.wsOP_msgRelay;
						proxy.msg = m.msg;
						proxy.from = gCon[conIdx].id;

						gCon[i].ws.send(JSON.stringify(proxy), function() {  })
						reply.op = WsProtocol.wsOP_positiveAck;
						break;
					}
				}

				//only send reply for negative responses
				if(reply.op == WsProtocol.wsOP_negativeAck)
				{
					ws.send(JSON.stringify(reply), function() {  })
				}
			}
			else console.log("[E] ws msg: msgToBase, state "+gCon[conIdx].state);
		break;

		case WsProtocol.wsOP_msgSpecial:
			if(gCon[conIdx].state == WsProtocol.wsState_conn)
			{
				switch(m.subOp)
				{
					case WsProtocol.wsOP_srvDebugConn:

						reply.op = WsProtocol.wsOP_msgSpecial;
						reply.subOp = WsProtocol.wsOP_srvDebugConn;

						reply.message = gCon;

						ws.send(JSON.stringify(reply), function() {  })

					break;

					default:
						console.log("[E] ws msg: unknown op" + m.op)
					break;
				}
			}
			else console.log("[E] ws msg: msgToServer, state "+gCon[conIdx].state);
		break;

		default:
			console.log("[E] ws msg: unknown op" + m.op)
			break;
	};

  });

  ws.on("close", function()
  {
    console.log("ws close "+id)
    //clearInterval(id);
  });
});
<|endoftext|>


<commit_before>var dotenv = require('dotenv').config()
var _ = require('lodash');
var Client      = require('node-rest-client').Client;
var Twit        = require('twit');
var async       = require('async');
var emoji       = require('node-emoji');
var lyrics = [
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special"],
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special (special)"],
["Once bitten and twice shy I keep my distance but you still catch my eye"],
["Tell me baby do you recognize me? Well it's been a year, it doesn't surprise me"],
["I wrapped it up and sent it With a note saying 'I Love You' I meant it"],
["Now I know what a fool I've been But if you kissed me now I know you'd fool me again"],
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special (special)"],
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special (special)"],
["A face on a lover with a fire in his heart A man undercover but you tore him apart"],
["Maybe next year, I'll give it to someone, I'll give it to someone special"],
["Special, someone, someone I'll give it to someone, I'll give it to someone special"],
["Who'll give me something in return I'll give it to someone, hold my heart and watch it burn"],
["I'll give it to someone, I'll give it to someone special I thought you were here to stay"],
["How can love be for a day? I thought you were someone special, gave you my heart"],
["I'll give it to someone, I'll give it to someone"],
["Last Christmas I gave you my heart You gave it away"],
["I'll give it to someone, I'll give it to someone"]
];
console.log(process.env)
var t = new Twit({
  consumer_key:          process.env['12DAYSOFWHAM_TWIT_CONSUMER_KEY'],
  consumer_secret:      process.env['12DAYSOFWHAM_TWIT_CONSUMER_SECRET'],
  access_token          : process.env['12DAYSOFWHAM_TWIT_ACCESS_TOKEN'],
  access_token_secret   : process.env['12DAYSOFWHAM_TWIT_ACCESS_TOKEN_SECRET']
});

var ref_index = -1;

var printLine = function(){
  if (ref_index < 20) {
  ref_index += 1;
  }
  else{
    ref_index = 0;
  };
  var emojify1 = emoji.random().emoji
  var emojify2 = emoji.random().emoji
  var tweet = {
    status: (emojify1 + "  " + lyrics[ref_index].toString() + ' ' + emojify2)
  };
  return tweet
};

var post = function() {
  t.post('statuses/update', printLine(), function(err, data, response){
  console.log(data);
});
}

setInterval(post, 180000);

<commit_msg>change timer<commit_after>var dotenv = require('dotenv').config()
var _ = require('lodash');
var Client      = require('node-rest-client').Client;
var Twit        = require('twit');
var async       = require('async');
var emoji       = require('node-emoji');
var lyrics = [
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special"],
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special (special)"],
["Once bitten and twice shy I keep my distance but you still catch my eye"],
["Tell me baby do you recognize me? Well it's been a year, it doesn't surprise me"],
["I wrapped it up and sent it With a note saying 'I Love You' I meant it"],
["Now I know what a fool I've been But if you kissed me now I know you'd fool me again"],
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special (special)"],
["Last Christmas, I gave you my heart But the very next day, you gave it away"],
["This year, to save me from tears I'll give it to someone special (special)"],
["A face on a lover with a fire in his heart A man undercover but you tore him apart"],
["Maybe next year, I'll give it to someone, I'll give it to someone special"],
["Special, someone, someone I'll give it to someone, I'll give it to someone special"],
["Who'll give me something in return I'll give it to someone, hold my heart and watch it burn"],
["I'll give it to someone, I'll give it to someone special I thought you were here to stay"],
["How can love be for a day? I thought you were someone special, gave you my heart"],
["I'll give it to someone, I'll give it to someone"],
["Last Christmas I gave you my heart You gave it away"],
["I'll give it to someone, I'll give it to someone"]
];
console.log(process.env)
var t = new Twit({
  consumer_key:          process.env['12DAYSOFWHAM_TWIT_CONSUMER_KEY'],
  consumer_secret:      process.env['12DAYSOFWHAM_TWIT_CONSUMER_SECRET'],
  access_token          : process.env['12DAYSOFWHAM_TWIT_ACCESS_TOKEN'],
  access_token_secret   : process.env['12DAYSOFWHAM_TWIT_ACCESS_TOKEN_SECRET']
});

var ref_index = -1;

var printLine = function(){
  if (ref_index < 20) {
  ref_index += 1;
  }
  else{
    ref_index = 0;
  };
  var emojify1 = emoji.random().emoji
  var emojify2 = emoji.random().emoji
  var tweet = {
    status: (emojify1 + "  " + lyrics[ref_index].toString() + ' ' + emojify2)
  };
  return tweet
};

var post = function() {
  t.post('statuses/update', printLine(), function(err, data, response){
  console.log(data);
});
}

setInterval(post, 60000 * 60);

<|endoftext|>


<commit_before>/* Licensed under the MIT License. See the accompanying LICENSE file for terms. */

var repl = require('repl'), // https://github.com/joyent/node/blob/master/lib/repl.js
    util = require('util'),
    vm = require('vm'),
    fs = require('fs'),
    async = require('async'),
    http = require('http'),
    libUrl = require('url'),
    serialport = require('serialport'),
    SerialPort = serialport.SerialPort,
    version = require('./package').version,
    espruinoStub = require('./data/stub'),
    resultMatch = /^=(.+)$/m,
    receiveCallback,
    receiveBuffer = '',
    boardInfo = {},
    connected = false,
    candidates = [],
    context,
    buffer = '',
    input,
    env = {},
    esp;

function readPorts(err, ports) {
    ports.forEach(eachPort);
    attempt();
}

function eachPort(port) {
    candidates.push(function candidate(cb) {
        analyze(port, cb);
    });
}

function attempt() {
    async.series(candidates, function done(err) {
        if (!connected) {
            var msg = candidates.length ? 'Espruino not found!' : 'No connected devices found!';
            console.log(msg + ' Make sure Espruino is plugged in.');
        }
    });
}

function analyze(port, cb) {
    if (!connected) {
        var dev = port.comName,
            id = port.pnpId;

        console.log('Analyzing ' + dev + ' (' + id + ')');
        if (id.match('Espruino') || id.match('STM32')) {
            console.log('Found compatible Espruino device! --^');
            console.log('Connecting...');
            connect(dev);
        } else {
            console.log('No Espruino found, continuing. --^');
        }
    }

    cb(null);
}

function connect(dev) {
    // connect to espruino
    esp = new SerialPort(dev, {});
    esp.on('open', init);
    esp.on('data', receive);
    esp.on('close', exit);
    connected = true;
}

function init() {
    // start repl ui
    input = repl.start({prompt: ">", useGlobal: true, useColors: true, ignoreUndefined: true, eval: evalLine});
    input.on('exit', exit);
    input.defineCommand('module', {
        help: 'Add a module for require.',
        action: loadModule
    });

    // replace context to get closer to espruino environment
    context = vm.createContext(espruinoStub);
    input.context = context;

    // set up queue interval
    setInterval(flush, 5);

    // get board info
    query('process.env', function (e, details) {
        if (!e) {
            env = details || {};
            loadBoardInfo(env.BOARD);
        }
    });
}

function exit(e) {
    console.log('Disconnecting...');
    process.exit();
}

function loadBoardInfo(board) {
    if (board) {
        try {
            boardInfo = require('./data/boards/' + board);
            // populate pins for autocomplete
            (boardInfo.pins || []).forEach(function eachPin(pin) {
                context[pin.name] = 1;
            });
        } catch(e) {
            receive('Unable to load board info for ' + board);
        }
    }
}

function query(code, cb) {
    receiveCallback = cb;
    send(code);
}

function send(code) {
    buffer += code + '\n';
}

function flush() {
    if (buffer.length) {
        var chunk = buffer.substr(0, 32);
        buffer = buffer.substr(32);
        esp.write(chunk);
    }
}

function receive(data) {
    data = data.toString();
    if (receiveCallback) {
        receiveBuffer += data;
        var match = data.match(/\r>$/m) ? resultMatch.exec(receiveBuffer) : null;
        if (match) {
            try {
                var result = JSON.parse(match[1]);
                receiveCallback(null, result);
            } catch (e) {
                // buffer isn't finished so continue
                if (isRecoverableError(e)) {
                    return;
                }
                receiveCallback(e);
            }
            receiveCallback = null;
            receiveBuffer = '';
        }
    } else {
        process.stdout.write(data);
    }
}

function evalLine(code, context, file, cb) {
    var err,
        result;

    // strip repl's wrapping bs
    code = code.replace(/^\(|\n\)$/g, '');

    // first, create the script object to check the syntax
    try {
        var script = vm.createScript(code, {
            filename: file,
            displayErrors: false
        });
    } catch (e) {
        // pass through unexpected end of input to handle multiline
        if (isRecoverableError(e)) {
           err = e;
        }
    }

    if (code) {
        if (!err) {
            try {
                // this retains a rough approximation of the board state
                result = script.runInContext(context, {displayErrors: false});
            } catch (e) {
            }

            // let autocomplete pass thru w/o write
            result = context[code];
            if (!result) {
                send(code);
            }
        }
    }

    cb(err, result);
}

function loadModule(args) {
    var self = this,
        args = args && args.length ? args.split(' ') : [],
        base = 'http://www.espruino.com/modules/{mod}.min.js',
        mod = args[0],
        url, path, msg, code, body = '',
        log = function (msg, prompt) {
            console.log(msg);
            if (prompt !== false) {
                input.displayPrompt();
            }
        },
        add = function (body) {
            if (body) {
                send('echo(0);');
                // hack to work around Espruino buffer errors (introduces escaped line breaks to allow queueing)
                body = JSON.stringify(body).replace(/;/g, ';\\\n')
                var code = 'Modules.addCached("' + mod + '", ' + body + '); echo(1)';
                send(code);
            }
        };

    switch (args.length) {
        case 0:
            msg = 'Expected a module name and optional URL / file path.';
        break;
        case 1:
            url = base.replace('{mod}', args[0]);
        break;
        case 2:
            if (args[1].substr(0, 5) === 'http:') {
                url = args[1];
            } else {
                path = args[1];
            }
        break;
        default:
            msg = 'Unexpected number of arguments.';
        break;
    }

    if (url) {
        log('Attempting to fetch module "' + mod + '" from ' + url + '...', false);
        var options = libUrl.parse(url);
        options.headers = {'User-Agent': 'Espruino CLI/' + version};
        http.get(options, function(res) {
            res.on('data', function (chunk) {
                body += chunk;
            });
            res.on('end', function (chunk) {
                if (res.statusCode === 200) {
                    log('Module fetched, sending to Espruino...', false);
                    add(body);
                } else {
                    log('Error fetching module "' + mod + '"!');
                }
            });
        }).on('error', function(e) {
            log('Error fetching module "' + mod + '"!');
        });
    } else if (path) {
        log('Attempting to load module "' + mod + '" from ' + path + '...', false);
        try {
            body = fs.readFileSync(path, {encoding: 'utf-8'});
            add(body);
        } catch (e) {
            log('Error loading module "' + mod + '"!');
        }
    }

    if (msg) {
        log(msg);
    }
}

function isRecoverableError(e) {
    return e && e.name === 'SyntaxError' && /^Unexpected end of input/.test(e.message);
}

console.log('Searching for Espruino compatible device...');
serialport.list(readPorts);

<commit_msg>Tolerate illegal token for opening block comment<commit_after>/* Licensed under the MIT License. See the accompanying LICENSE file for terms. */

var repl = require('repl'), // https://github.com/joyent/node/blob/master/lib/repl.js
    util = require('util'),
    vm = require('vm'),
    fs = require('fs'),
    async = require('async'),
    http = require('http'),
    libUrl = require('url'),
    serialport = require('serialport'),
    SerialPort = serialport.SerialPort,
    version = require('./package').version,
    espruinoStub = require('./data/stub'),
    resultMatch = /^=(.+)$/m,
    receiveCallback,
    receiveBuffer = '',
    boardInfo = {},
    connected = false,
    candidates = [],
    context,
    buffer = '',
    input,
    env = {},
    esp;

function readPorts(err, ports) {
    ports.forEach(eachPort);
    attempt();
}

function eachPort(port) {
    candidates.push(function candidate(cb) {
        analyze(port, cb);
    });
}

function attempt() {
    async.series(candidates, function done(err) {
        if (!connected) {
            var msg = candidates.length ? 'Espruino not found!' : 'No connected devices found!';
            console.log(msg + ' Make sure Espruino is plugged in.');
        }
    });
}

function analyze(port, cb) {
    if (!connected) {
        var dev = port.comName,
            id = port.pnpId;

        console.log('Analyzing ' + dev + ' (' + id + ')');
        if (id.match('Espruino') || id.match('STM32')) {
            console.log('Found compatible Espruino device! --^');
            console.log('Connecting...');
            connect(dev);
        } else {
            console.log('No Espruino found, continuing. --^');
        }
    }

    cb(null);
}

function connect(dev) {
    // connect to espruino
    esp = new SerialPort(dev, {});
    esp.on('open', init);
    esp.on('data', receive);
    esp.on('close', exit);
    connected = true;
}

function init() {
    // start repl ui
    input = repl.start({prompt: ">", useGlobal: true, useColors: true, ignoreUndefined: true, eval: evalLine});
    input.on('exit', exit);
    input.defineCommand('module', {
        help: 'Add a module for require.',
        action: loadModule
    });

    // replace context to get closer to espruino environment
    context = vm.createContext(espruinoStub);
    input.context = context;

    // set up queue interval
    setInterval(flush, 5);

    // get board info
    query('process.env', function (e, details) {
        if (!e) {
            env = details || {};
            loadBoardInfo(env.BOARD);
        }
    });
}

function exit(e) {
    console.log('Disconnecting...');
    process.exit();
}

function loadBoardInfo(board) {
    if (board) {
        try {
            boardInfo = require('./data/boards/' + board);
            // populate pins for autocomplete
            (boardInfo.pins || []).forEach(function eachPin(pin) {
                context[pin.name] = 1;
            });
        } catch(e) {
            receive('Unable to load board info for ' + board);
        }
    }
}

function query(code, cb) {
    receiveCallback = cb;
    send(code);
}

function send(code) {
    buffer += code + '\n';
}

function flush() {
    if (buffer.length) {
        var chunk = buffer.substr(0, 32);
        buffer = buffer.substr(32);
        esp.write(chunk);
    }
}

function receive(data) {
    data = data.toString();
    if (receiveCallback) {
        receiveBuffer += data;
        var match = data.match(/\r>$/m) ? resultMatch.exec(receiveBuffer) : null;
        if (match) {
            try {
                var result = JSON.parse(match[1]);
                receiveCallback(null, result);
            } catch (e) {
                // buffer isn't finished so continue
                if (isRecoverableError(e)) {
                    return;
                }
                receiveCallback(e);
            }
            receiveCallback = null;
            receiveBuffer = '';
        }
    } else {
        process.stdout.write(data);
    }
}

function evalLine(code, context, file, cb) {
    var err,
        result;

    // strip repl's wrapping bs
    code = code.replace(/^\(|\n\)$/g, '');

    // first, create the script object to check the syntax
    try {
        var script = vm.createScript(code, {
            filename: file,
            displayErrors: false
        });
    } catch (e) {
        // pass through unexpected end of input to handle multiline
        if (isRecoverableError(e)) {
           err = e;
        }// else console.dir(e)
    }

    if (code) {
        if (!err) {
            if (script) {
                try {
                    // this retains a rough approximation of the board state
                    result = script.runInContext(context, {displayErrors: false});
                } catch (e) {
                    //console.dir(e)
                }
            }

            // let autocomplete pass thru w/o write
            result = context[code];
            if (!result) {
                send(code);
            }
        }
    }

    cb(err, result);
}

function loadModule(args) {
    var self = this,
        args = args && args.length ? args.split(' ') : [],
        base = 'http://www.espruino.com/modules/{mod}.min.js',
        mod = args[0],
        url, path, msg, code, body = '',
        log = function (msg, prompt) {
            console.log(msg);
            if (prompt !== false) {
                input.displayPrompt();
            }
        },
        add = function (body) {
            if (body) {
                send('echo(0);');
                // hack to work around Espruino buffer errors (introduces escaped line breaks to allow queueing)
                body = JSON.stringify(body).replace(/;/g, ';\\\n')
                var code = 'Modules.addCached("' + mod + '", ' + body + '); echo(1)';
                send(code);
            }
        };

    switch (args.length) {
        case 0:
            msg = 'Expected a module name and optional URL / file path.';
        break;
        case 1:
            url = base.replace('{mod}', args[0]);
        break;
        case 2:
            if (args[1].substr(0, 5) === 'http:') {
                url = args[1];
            } else {
                path = args[1];
            }
        break;
        default:
            msg = 'Unexpected number of arguments.';
        break;
    }

    if (url) {
        log('Attempting to fetch module "' + mod + '" from ' + url + '...', false);
        var options = libUrl.parse(url);
        options.headers = {'User-Agent': 'Espruino CLI/' + version};
        http.get(options, function(res) {
            res.on('data', function (chunk) {
                body += chunk;
            });
            res.on('end', function (chunk) {
                if (res.statusCode === 200) {
                    log('Module fetched, sending to Espruino...', false);
                    add(body);
                } else {
                    log('Error fetching module "' + mod + '"!');
                }
            });
        }).on('error', function(e) {
            log('Error fetching module "' + mod + '"!');
        });
    } else if (path) {
        log('Attempting to load module "' + mod + '" from ' + path + '...', false);
        try {
            body = fs.readFileSync(path, {encoding: 'utf-8'});
            add(body);
        } catch (e) {
            log('Error loading module "' + mod + '"!');
        }
    }

    if (msg) {
        log(msg);
    }
}

function isRecoverableError(e) {
    return e && e.name === 'SyntaxError' && (/^Unexpected end of input/.test(e.message) || /^Unexpected token ILLEGAL/.test(e.message));
}

console.log('Searching for Espruino compatible device...');
serialport.list(readPorts);

<|endoftext|>


<commit_before>"use strict";
const discord = require('discord.io');
const fs = require('fs');
const info = {};
info.config = require('./config.json');
const bot = new discord.Client({token: info.config.api.discord_token, autorun: true });
info.utility = require('./lib/utility.js')(bot, info);
info.commands = require('./commands/loader.js')(bot,info);
info.db = require('./lib/db.js')(bot, info);
info.web = require('./lib/portal.js')(bot,info);
info.time = require('./tz-pretty.json');
info.manualKill = false;
const utility = info.utility;
const config = info.config;
const commands = info.commands;
let db = info.db;
info.start = new Date();
//When the bot is ready
bot.on('ready', function() {
console.log(bot.username + " - (" + bot.id + ")");
    //Set the bot's "Playing" to the config file's playing
    bot.setPresence({
        game:{
        name: utility.filter(info.config.playing)
        }
    });
});
//When there is a message fired that the bot can see, process it
bot.on('message', function(user, userID, channelID, message, event) {
    const details = {
        user: user,
        userID: userID,
        channelID: channelID,
        message: message,
        event: event
    };
//was it a direct message?
  details.isDirectMessage = details.channelID in bot.directMessages ? true : false;
  if(details.isDirectMessage)
  {
    //checks to see if it started with the prefix(possibly a command)
    details.isCommandForm = utility.isCommandForm(message);
    if(details.isCommandForm)
    {
      details.prefix = config.prefix;
      details.isMod = false;
      details.isElevated = false;
      details.isAdministrator = utility.isAdministrator(details.userID);
      let cmd = utility.stripPrefix(message);
      let keyword = cmd.split(' ')[0];
      details.input = cmd.replace(keyword, '').trim();
      //split up the remaining into something similar to command line args
      details.args = cmd.split(' ');
      keyword = keyword.toLowerCase();
      if(commands[keyword] && typeof commands[keyword].action === 'function')
      {
        processCommand(keyword, details);
      }
      else
      {
        //didn't find command
        for(let index in commands)
        {
          if(commands[index] && typeof commands[index].alias === 'object')
          {
              //is the keyword an alias
            if(commands[index].alias.indexOf(keyword) > -1)
            {
              processCommand(index, details);
            }
          }
        }
      }
    }
  }
  else
  {
    if(bot.channels[channelID].guild_id != undefined)
    {
      //checks to see if it started with the Server defined prefix(possibly a command)
      utility.isServerCommandForm(message, bot.channels[channelID].guild_id).then((info) =>
      {
        details.isCommandForm = info.isCommand;
        //console.log(`This is COMMAND FORM ${isCommand}`);
        //if the message is in command form, process it
        if(details.isCommandForm)
        {
          details.prefix = info.prefix;
          //is the message sender listed as an administrator?
          details.isAdministrator = utility.isAdministrator(details.userID);
          if(details.isDirectMessage)
          {
            details.isMod = false;
            details.isElevated = false;
          }
          else
          {
            if(!details.isAdministrator)
            {
              details.serverID = utility.getServerID(details.channelID);
              //does the message sender have elevated priveleges?
              try{
                details.isMod = utility.checkModPerm(details.userID, details.serverID);
                if(!details.isMod)
                {
                  //if sender is not a mod, check to see if they are elevated
                  details.isElevated = utility.checkCommandPerm(details.userID, details.serverID);
                }
              }
              catch(err)
              {
                console.log(err);
                details.isMod = false;
                details.isElevated = false;
              }
            }
            details.serverID = utility.getServerID(details.channelID);
          }
          //separate the command from the rest of the string
          let cmd = utility.stripServerPrefix(message, info.prefix);
          let keyword = cmd.split(' ')[0];
          details.input = cmd.replace(keyword, '').trim();
          //split up the remaining into something similar to command line args
          details.args = cmd.split(' ');
          keyword = keyword.toLowerCase();
          //if the command exists, check the permissions.
          if(commands[keyword] && typeof commands[keyword].action === 'function')
          {
            db.checkEnabled(details.serverID, keyword).then((enabled) =>
            {
              if(enabled || keyword === 'help')
              {
                processCommand(keyword, details);
              }
              else
              {
                disabled(details);
              }
            }).catch((err) =>
            {
              console.log(err);
            });
          }
          else
          {
            //didn't find command
            for(let index in commands)
            {
              if(commands[index] && typeof commands[index].alias === 'object')
              {
                  //is the keyword an alias
                if(commands[index].alias.indexOf(keyword) > -1)
                {
                  db.checkEnabled(details.serverID, index).then((enabled) =>
                  {
                    if(enabled || index === 'help')
                    {
                      processCommand(index, details);
                    }
                    else
                    {
                      disabled(details);
                    }
                  }).catch((err) =>
                  {
                    console.log(err);
                  });
                }
              }
            }
          }
        }
      }).catch((info) =>
      {
        //console.log(info);
      });
    }
  }
});
//When the bot disconnects (may it be from code, or on Discord's end')
bot.on('disconnect',function(errMsg, code)
{
  //if you didn't manually kill the bot
  if(info.reload)
  {
    commands = require('./commands/loader.js')(bot, info);
    info.reload = false;
    bot.connect();
  }
  else if(!info.manualKill)
  {
    //reconnect and log the instance into log.txt
    bot.connect();
    fs.appendFile('log.txt', 'Error occured: Error Code ' + code +' - attempting to login ' + new Date() + '\n' , function (err) {});
  }
  else
  {
    console.log('Kill command used.');
    process.exit(0);
  }
});
function processCommand(command, details)
{
  if(commands[command].permissions == 'public')
  {
    commands[command].action(details);
  }
  else if(commands[command].permissions == 'elevated' && (details.isMod || details.isElevated || details.isAdministrator))
  {
    commands[command].action(details);
  }
  else if(commands[command].permissions == 'mod' && (details.isMod || details.isAdministrator))
  {
    commands[command].action(details);
  }
  else if(commands[command].permissions == 'private' && details.isAdministrator)
  {
    commands[command].action(details);
  }
}
function disabled(details)
{
  bot.sendMessage({
    to: details.channelID,
    embed: {
      title: 'Disabled',
      description: 'Looks like that command was disabled'
    }
  });
}<commit_msg>Minor Updates<commit_after>"use strict";
const discord = require('discord.io');
const fs = require('fs');
const info = {};
info.config = require('./config.json');
const bot = new discord.Client({token: info.config.api.discord_token, autorun: true });
info.utility = require('./lib/utility.js')(bot, info);
info.commands = require('./commands/loader.js')(bot,info);
info.db = require('./lib/db.js')(bot, info);
info.web = require('./lib/portal.js')(bot,info);
info.time = require('./tz-pretty.json');
info.manualKill = false;
const utility = info.utility;
const config = info.config;
const commands = info.commands;
let db = info.db;
info.start = new Date();
//When the bot is ready
bot.on('ready', function() {
  bot.getAllUsers((err) =>
  {
    if(err)
    {
      console.log(err);
    }
  });
  console.log(bot.username + " - (" + bot.id + ")");
  //Set the bot's "Playing" to the config file's playing
  function setPlaying()
  {
    bot.setPresence({
    game:{
    name: utility.filter(info.config.playing)
    }
    });
  }
  setTimeout(setPlaying, 5000);
});
//When there is a message fired that the bot can see, process it
bot.on('message', function(user, userID, channelID, message, event) {
    const details = {
        user: user,
        userID: userID,
        channelID: channelID,
        message: message,
        event: event
    };
//was it a direct message?
  details.isDirectMessage = details.channelID in bot.directMessages ? true : false;
  if(details.isDirectMessage)
  {
    //checks to see if it started with the prefix(possibly a command)
    details.isCommandForm = utility.isCommandForm(message);
    if(details.isCommandForm)
    {
      details.prefix = config.prefix;
      details.isMod = false;
      details.isElevated = false;
      details.isAdministrator = utility.isAdministrator(details.userID);
      let cmd = utility.stripPrefix(message);
      let keyword = cmd.split(' ')[0];
      details.input = cmd.replace(keyword, '').trim();
      //split up the remaining into something similar to command line args
      details.args = cmd.split(' ');
      keyword = keyword.toLowerCase();
      if(commands[keyword] && typeof commands[keyword].action === 'function')
      {
        processCommand(keyword, details);
      }
      else
      {
        //didn't find command
        for(let index in commands)
        {
          if(commands[index] && typeof commands[index].alias === 'object')
          {
              //is the keyword an alias
            if(commands[index].alias.indexOf(keyword) > -1)
            {
              processCommand(index, details);
            }
          }
        }
      }
    }
  }
  else
  {
    if(bot.channels[channelID].guild_id != undefined)
    {
      //checks to see if it started with the Server defined prefix(possibly a command)
      utility.isServerCommandForm(message, bot.channels[channelID].guild_id).then((info) =>
      {
        details.isCommandForm = info.isCommand;
        //console.log(`This is COMMAND FORM ${isCommand}`);
        //if the message is in command form, process it
        if(details.isCommandForm)
        {
          details.prefix = info.prefix;
          //is the message sender listed as an administrator?
          details.isAdministrator = utility.isAdministrator(details.userID);
          if(details.isDirectMessage)
          {
            details.isMod = false;
            details.isElevated = false;
          }
          else
          {
            if(!details.isAdministrator)
            {
              details.serverID = utility.getServerID(details.channelID);
              //does the message sender have elevated priveleges?
              try{
                details.isMod = utility.checkModPerm(details.userID, details.serverID);
                if(!details.isMod)
                {
                  //if sender is not a mod, check to see if they are elevated
                  details.isElevated = utility.checkCommandPerm(details.userID, details.serverID);
                }
              }
              catch(err)
              {
                console.log(err);
                details.isMod = false;
                details.isElevated = false;
              }
            }
            details.serverID = utility.getServerID(details.channelID);
          }
          //separate the command from the rest of the string
          let cmd = utility.stripServerPrefix(message, info.prefix);
          let keyword = cmd.split(' ')[0];
          details.input = cmd.replace(keyword, '').trim();
          //split up the remaining into something similar to command line args
          details.args = cmd.split(' ');
          keyword = keyword.toLowerCase();
          //if the command exists, check the permissions.
          if(commands[keyword] && typeof commands[keyword].action === 'function')
          {
            db.checkEnabled(details.serverID, keyword).then((enabled) =>
            {
              if(enabled || keyword === 'help')
              {
                processCommand(keyword, details);
              }
              else
              {
                disabled(details);
              }
            }).catch((err) =>
            {
              console.log(err);
            });
          }
          else
          {
            //didn't find command
            for(let index in commands)
            {
              if(commands[index] && typeof commands[index].alias === 'object')
              {
                  //is the keyword an alias
                if(commands[index].alias.indexOf(keyword) > -1)
                {
                  db.checkEnabled(details.serverID, index).then((enabled) =>
                  {
                    if(enabled || index === 'help')
                    {
                      processCommand(index, details);
                    }
                    else
                    {
                      disabled(details);
                    }
                  }).catch((err) =>
                  {
                    console.log(err);
                  });
                }
              }
            }
          }
        }
      }).catch((info) =>
      {
        //console.log(info);
      });
    }
  }
});
//When the bot disconnects (may it be from code, or on Discord's end')
bot.on('disconnect',function(errMsg, code)
{
  //if you didn't manually kill the bot
  if(info.reload)
  {
    commands = require('./commands/loader.js')(bot, info);
    info.reload = false;
    bot.connect();
  }
  else if(!info.manualKill)
  {
    //reconnect and log the instance into log.txt
    bot.connect();
    fs.appendFile('log.txt', 'Error occured: Error Code ' + code +' - attempting to login ' + new Date() + '\n' , function (err) {});
  }
  else
  {
    console.log('Kill command used.');
    process.exit(0);
  }
});
function processCommand(command, details)
{
  if(commands[command].permissions == 'public')
  {
    commands[command].action(details);
  }
  else if(commands[command].permissions == 'elevated' && (details.isMod || details.isElevated || details.isAdministrator))
  {
    commands[command].action(details);
  }
  else if(commands[command].permissions == 'mod' && (details.isMod || details.isAdministrator))
  {
    commands[command].action(details);
  }
  else if(commands[command].permissions == 'private' && details.isAdministrator)
  {
    commands[command].action(details);
  }
}
function disabled(details)
{
  bot.sendMessage({
    to: details.channelID,
    embed: {
      title: 'Disabled',
      description: 'Looks like that command was disabled'
    }
  });
}<|endoftext|>


<commit_before>var Neuter = require('neuter');
var path = require('path');
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var File = gutil.File;
var async = require('async');
var sourceMap = require('source-map');
var SourceMapConsumer = sourceMap.SourceMapConsumer;
var SourceMapGenerator = sourceMap.SourceMapGenerator;

var PLUGIN_NAME = 'gulp-neuter';

var MAPPING_INCLUDE = new Buffer('//@ sourceMappingURL=');

module.exports = function(outputFileName, mapFileName, options) {
	if (mapFileName && !outputFileName) {
		throw new PluginError(PLUGIN_NAME, 'Missing outputFileName parameter');
	}

	if (outputFileName && !mapFileName) {
		throw new PluginError(PLUGIN_NAME, 'Missing mapFileName parameter');
	}

	if (options !== undefined && typeof options !== 'object') {
		throw new PluginError(PLUGIN_NAME, 'Missing options parameter should be an object');
	}

	options = options || {};

	return through.obj(function (file, enc, done) {
		if (file.isNull()) {
			// ignore null files
			return done();
		}

		if (file.isStream()) {
			this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported'));
			return done();
		}

		if (options.basePath) {
			//
			// !! IMPORTANT !!
			// The basepath set in the passed file object must match the basepath
			// set in the neuter options. If not, requires relying on the basepath
			// might fail.
			//
			file.base = options.basePath;
			file.path = path.relative(options.basePath, file.path);
		}

		var neuter = new Neuter(options);
		neuter.parse(file, (function(err, sourceNode) {
			if (err) {
				this.emit('error', new PluginError(PLUGIN_NAME, err));
				return done();
			}

			var options = {};
			if (outputFileName) {
				options.file = outputFileName;
			} else {
				options.file = path.basename(file.path);
				console.log(options.file);
			}

			var codeMap = sourceNode.toStringWithSourceMap(options);

			var sourceFile = new File({
				cwd: file.cwd,
				base: file.base,
				path: path.join(file.base, options.file),
				contents: new Buffer(codeMap.code),
			});

			if (mapFileName) {
				var consumer = new SourceMapConsumer(codeMap.map.toJSON());
				var generator = SourceMapGenerator.fromSourceMap(consumer);
				var newSourceMap = generator.toJSON();
				newSourceMap.file = path.basename(newSourceMap.file);

				var sourceMap = JSON.stringify(newSourceMap, null, '  ');
				var mapFile = new File({
					cwd: file.cwd,
					base: file.base,
					path: path.join(file.base, mapFileName),
					contents: new Buffer(sourceMap),
				})

				this.push(mapFile);

				sourceFile.contents = Buffer.concat([
					sourceFile.contents,
					MAPPING_INCLUDE,
					new Buffer(path.relative(sourceFile.path, mapFile.path)),
				]);
			}

			this.push(sourceFile);

			done();
		}).bind(this));
	});
};
<commit_msg>Adding support for sourceRoot in source-map.<commit_after>var Neuter = require('neuter');
var path = require('path');
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var File = gutil.File;
var async = require('async');
var sourceMap = require('source-map');
var SourceMapConsumer = sourceMap.SourceMapConsumer;
var SourceMapGenerator = sourceMap.SourceMapGenerator;

var PLUGIN_NAME = 'gulp-neuter';

var MAPPING_INCLUDE = new Buffer('//@ sourceMappingURL=');

module.exports = function(outputFileName, mapFileName, options) {
	if (mapFileName && !outputFileName) {
		throw new PluginError(PLUGIN_NAME, 'Missing outputFileName parameter');
	}

	if (outputFileName && !mapFileName) {
		throw new PluginError(PLUGIN_NAME, 'Missing mapFileName parameter');
	}

	if (options !== undefined && typeof options !== 'object') {
		throw new PluginError(PLUGIN_NAME, 'Missing options parameter should be an object');
	}

	options = options || {};

	// Adding support to include a sourceRoot into source-map. Storing the var here since options obj gets overridden when it's needed.
	var sourceRoot = options.sourceRoot;

	return through.obj(function (file, enc, done) {
		if (file.isNull()) {
			// ignore null files
			return done();
		}

		if (file.isStream()) {
			this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported'));
			return done();
		}

		if (options.basePath) {
			//
			// !! IMPORTANT !!
			// The basepath set in the passed file object must match the basepath
			// set in the neuter options. If not, requires relying on the basepath
			// might fail.
			//
			file.base = options.basePath;
			file.path = path.relative(options.basePath, file.path);
		}

		var neuter = new Neuter(options);
		neuter.parse(file, (function(err, sourceNode) {
			if (err) {
				this.emit('error', new PluginError(PLUGIN_NAME, err));
				return done();
			}

			var options = {};
			if (outputFileName) {
				options.file = outputFileName;
			} else {
				options.file = path.basename(file.path);
				console.log(options.file);
			}

			// Including a sourceRoot if passed in
			if (sourceRoot) {
				options.sourceRoot = sourceRoot;
			}

			var codeMap = sourceNode.toStringWithSourceMap(options);

			var sourceFile = new File({
				cwd: file.cwd,
				base: file.base,
				path: path.join(file.base, options.file),
				contents: new Buffer(codeMap.code),
			});

			if (mapFileName) {
				var consumer = new SourceMapConsumer(codeMap.map.toJSON());
				var generator = SourceMapGenerator.fromSourceMap(consumer);
				var newSourceMap = generator.toJSON();
				newSourceMap.file = path.basename(newSourceMap.file);

				var sourceMap = JSON.stringify(newSourceMap, null, '  ');
				var mapFile = new File({
					cwd: file.cwd,
					base: file.base,
					path: path.join(file.base, mapFileName),
					contents: new Buffer(sourceMap),
				})

				this.push(mapFile);

				sourceFile.contents = Buffer.concat([
					sourceFile.contents,
					MAPPING_INCLUDE,
					new Buffer(path.relative(sourceFile.path, mapFile.path)),
				]);
			}

			this.push(sourceFile);

			done();
		}).bind(this));
	});
};
<|endoftext|>