<commit_before>/*
	MSS-Discord
	Copyright (C) 2017 moustacheminer.com

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

//Get the Discord API Key.
console.log(process.argv[2]);
if (process.argv[2]) {
	var api = process.argv[2];
} else {
	console.log("Usage:\nnode bot.js <Discord API Key>");
	process.exit(1);
}

//Declare the Discord and client constants used to set up the Discord bot
const Discord = require("discord.js");
const client = new Discord.Client();

//ytdl-core for !play
const yt = require('ytdl-core');

//fs to open the wav file
const fs = require('fs');

//exec for the DECtalk API
const child_process = require('child_process');

//Login to Discord's Bot API Service
client.login(api);

//Declare the playlist and stream variables
//playlist[guild][position in playlist]
var playlist = [];
//stream[guild]
var stream = [];

//Set the running game and the avatar for the bot.
client.on('ready', function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame("ask for >>   !help");
	client.user.setAvatar("http://moustacheminer.com/dickbutt.jpg");
});

client.on('message', message => {

	try {
		//Stop checking if the message is from a bot - Don't repeat the !ping Pong!
		if(message.author.bot) return;

		let input = message.content.replace( /\n/g, " " ).split(" ");

		//Set the username of the bot as MSS
		if (message.guild.id) {
			message.guild.member(client.user).setNickname('MSS');
		} else {
			//If the bot is not in the server, stop doing shit - It's too dangerous.
			return richSend(message, "Error", "You are not allowed to send commands via Direct Messaging.", "#FF0000");
		}

		//Send help detials. Need to use the E-zed richSend someday
		if (input[0] === '!help') {
			richSend(message, "Moustacheminer Server Services", "Help is at hand, at the official MSS Discord Server @ https://discord.gg/hPw5gEt", "#FF9999", "http://i.imgur.com/h2JkYGm.jpg", "https://discord.gg/hPw5gEt");
		} else if (input[0] === '!play') {
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel) return richSend(message, input[0], "Please be in a voice channel before using the " + input[0] + " command", "#FFFF00");
			if (!input[1]) return richSend(message, input[0], "Please insert a VALID url.", "#FF0000");

			if (youtubeCheck(input[1])) {
				yt.getInfo(input[1], function(err, info) {
					if (!info) return richSend(message, "!play", "Please send a valid YouTube URL", "#FF0000");
					if (info["length_seconds"] > 3600 && !isAdmin(message)) return;
					playlistAdd(message, "youtube", input[1], info["title"], info["thumbnail_url"]);
				});
			} else {
				console.log(input[1]);
				richSend(message, input[0], "The URL is currently NOT supported by Moustacheminer Server Services.", "#FF0000");
			}
		} else if (input[0] === '!skip') {
			if (!isAdmin(message)) return;
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel.connection) {
				return richSend(message, "!stop", "There is no bot running in your current voice channel", "#FF0000");
			}

			stream[message.guild.id].destroy();
		} else if (input[0] === '!stop') {
			if (!isAdmin(message)) return;
			playlistClear(message);
		} else if (input[0] === '!error') {
			if (!isAdmin(message)) return;
			throw new Error("A error was PURPOSELY thrown for the excitement of mathematicians.");
		}
	} catch(err) {
		console.log(err.stack);
		//Catch those errors!
		richSend(message, "This is a Parker Square of an error.", "A fatal error was encountered:\n```\n" + err.stack + "\n```\nA singing banana has been deployed to fix the error. In the meantime, try folding a piece of A4 paper 8 times.", "#FF0000", "http://moustacheminer.com/home/img/ffs.jpg", "https://discord.gg/hPw5gEt");
	}

});

//Provide an easy wrapper for Discord and Discord API's and Discord.js' RichEmbed feature
function richSend(message, subheading, description, colour, img, url) {
	if (!url) {
		var url = "http://moustacheminer.com/w/mss";
	}

	var embed = new Discord.RichEmbed()
		.setTitle(subheading)
		.setAuthor("MSS", 'http://moustacheminer.com/dickbutt.jpg')
		.setColor(colour)
		.setDescription(description)
		.setFooter('moustacheminer.com server services', '')
		.setTimestamp()
		.setURL(url)
		.setImage(img);

	message.channel.sendEmbed(embed, "", { disableEveryone: true });
}

function playlistAdd(message, type, url, title, thumb_url) {
	if (!thumb_url) {
		thumb_url = "http://i48.tinypic.com/260v86c.png";
	}

	richSend(message, "!play", "Added " + title + " to playlist", "#00FF00");
	playlist[message.guild.id] = playlist[message.guild.id] || [];
	playlist[message.guild.id].push(JSON.stringify({type: type, url: url, title: title, thumb_url: thumb_url}));
	if (!message.member.voiceChannel.connection) {
		playSound(message);
	}
}

function playlistClear(message) {
	//Get the voice channel
	let voiceChannel = message.member.voiceChannel;

	//If the person is in the voice channel, stop the bot in that channel
	if (voiceChannel && voiceChannel.connection) {
		richSend(message, "!stop", "Stopped playing music in the channel.", "#00FF00");
		voiceChannel.leave();
		playlist[message.guild.id] = [];
		stream[message.guild.id].destroy();
		return;
	} else {
		return richSend(message, "!stop", "There is no bot running in your current voice channel", "#FF0000");
	}
}

function playSound(message) {
	var voiceChannel = message.member.voiceChannel;
	var current;

	voiceChannel.join()
	.then(connnection => {
		var looper = function() {
			playlistPlay(message);
			const dispatcher = connnection.playStream(stream[message.guild.id]);
			dispatcher.on('end', () => {
				looper();
			});
		}
		looper();
	});
}

function playlistPlay(message) {
	var voiceChannel = message.member.voiceChannel;
	if (playlist[message.guild.id].length > 0) {
		current = JSON.parse(playlist[message.guild.id].shift());
		richSend(message, "Now playing:", current["title"], "#00FF00", current["thumb_url"], current["url"]);
		if (current["type"] === "youtube") {
			stream[message.guild.id] = yt(current["url"], {audioonly: true});
		} else if (current["type"] === "file") {
			stream[message.guild.id] = fs.createReadStream(current["url"]);
		}
	} else {
		voiceChannel.leave();
		playlist[message.guild.id] = [];
		stream[message.guild.id].destroy();
		return;
	}
}

/**
 * JavaScript function to match (and return) the video Id
 * of any valid Youtube Url, given as input string.
 * @author: Stephan Schmitz <eyecatchup@gmail.com>
 * @url: http://stackoverflow.com/a/10315969/624466
 */
function youtubeCheck(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp.$1 : false;
}

function isAdmin(message) {
	if (message.channel.permissionsFor(message.member).hasPermission("ADMINISTRATOR") || message.author.id === "190519304972664832") {
		return true;
	} else {
		richSend(message, "MSS", "You do not have permission to run this command.", "#FF0000");
		return false;
	}
}
<commit_msg>Changed ID and added some lists<commit_after>/*
	MSS-Discord
	Copyright (C) 2017 moustacheminer.com

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

//Get the Discord API Key.
console.log(process.argv[2]);
if (process.argv[2]) {
	var api = process.argv[2];
} else {
	console.log("Usage:\nnode bot.js <Discord API Key>");
	process.exit(1);
}

//Declare the Discord and client constants used to set up the Discord bot
const Discord = require("discord.js");
const client = new Discord.Client();

//ytdl-core for !play
const yt = require('ytdl-core');

//fs to open the wav file
const fs = require('fs');

//exec for the DECtalk API
const child_process = require('child_process');

//Login to Discord's Bot API Service
client.login(api);

//Declare the playlist and stream variables
//playlist[guild][position in playlist]
var playlist = [];
//stream[guild]
var stream = [];

//Set the running game and the avatar for the bot.
client.on('ready', function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame("ask for >>   !help");
	client.user.setAvatar("http://moustacheminer.com/dickbutt.jpg");
});

client.on('message', message => {

	try {

		if(message.author.id === "81026656365453312" && message.content.startsWith("Pong!")) {
			setTimeout(function(){
				return message.channel.send("!ping");
			}, 1000);
		}
		if(message.author.bot) return;

		let input = message.content.replace( /\n/g, " " ).split(" ");

		//Set the username of the bot as MSS
		if (message.guild) {
			message.guild.member(client.user).setNickname('MSS');
		} else {
			//If the bot is not in the server, stop doing shit - It's too dangerous.
			return richSend(message, "Error", "You are not allowed to send commands via Direct Messaging.", "#FF0000");
		}

		//Send help detials. Need to use the E-zed richSend someday
		if (input[0] === '!help') {
			richSend(message, "Moustacheminer Server Services", "Help is at hand, at the official MSS Discord Server @ https://discord.gg/hPw5gEt", "#FF9999", "http://i.imgur.com/h2JkYGm.jpg", "https://discord.gg/hPw5gEt");
		} else if (input[0] === '!play') {
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel) return richSend(message, "MSS Music Player", "Please be in a voice channel before using the " + input[0] + " command", "#FFFF00");
			if (!input[1]) return richSend(message, "MSS Music Player", "Please insert a VALID url.", "#FF0000");

			if (youtubeCheck(input[1])) {
				yt.getInfo(input[1], function(err, info) {
					if (!info) return richSend(message, "MSS Music Player", "Please send a valid YouTube URL", "#FF0000");
					if (info["length_seconds"] > 3600 && !isAdmin(message)) return;
					playlistAdd(message, "youtube", input[1], info["title"], info["thumbnail_url"]);
				});
			} else {
				console.log(input[1]);
				richSend(message, "MSS Music Player", "The URL is currently NOT supported by Moustacheminer Server Services.", "#FF0000");
			}
		} else if (input[0] === '!skip') {
			if (!isAdmin(message)) return;
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel.connection) {
				return richSend(message, "MSS Music Player", "There is no bot running in your current voice channel", "#FF0000");
			}

			stream[message.guild.id].destroy();
		} else if (input[0] === '!stop') {
			if (!isAdmin(message)) return;
			playlistClear(message);
		} else if (input[0] === '!list') {
			if (playlist[message.guild.id].length > 0) {
				return richSend(message, "MSS Music Player", playlist[message.guild.id].map(function(sound){return JSON.parse(sound).title;}).join("\n"), "#00FF00");
			} else {
				return richSend(message, "MSS Music Player", "There is no music remaining in the playlist.", "#FF0000");
			}
		} else if (input[0] === '!error') {
			if (!isAdmin(message)) return;
			throw new Error("A error was PURPOSELY thrown for the excitement of mathematicians.");
		} else if (input[0] === '!eval') {
			if (message.author.id === "190519304972664832") {
				eval(message.content.substring(6));
			} else {
				richSend(message, "!eval", "You do not have permission to run this command.", "#FF0000", "http://i.imgur.com/Uz6Xq1v.png");
			}
		} else if (input[0] === '!invite') {
			message.reply("Invite me into your server!\nhttps://discordapp.com/oauth2/authorize?&client_id=257547382277931009&scope=bot&permissions=0");
		}
	} catch(err) {
		console.log(err.stack);
		//Catch those errors!
		richSend(message, "This is a Parker Square of an error.", "A fatal error was encountered:\n```\n" + err.stack + "\n```\nA singing banana has been deployed to fix the error. In the meantime, try folding a piece of A4 paper 8 times.", "#FF0000", "http://moustacheminer.com/home/img/ffs.jpg", "https://discord.gg/hPw5gEt");
	}

});

/**
 * Function to send a rich embed to the server the message was sent by.
 * @author: 7coil <admin@moustacheminer.com>
 * @url: http://moustacheminer.com/
 * @param: {Object[]} message
 * @param: {string} subheading
 * @param: {string} description
 * @param: {string} colour
 * @param: {string} img
 * @param: {string} url
 */
function richSend(message, subheading, description, colour, img, url) {
	if (!url) {
		var url = "http://moustacheminer.com/w/mss";
	}

	var embed = new Discord.RichEmbed()
		.setTitle(subheading)
		.setAuthor("MSS", 'http://moustacheminer.com/dickbutt.jpg')
		.setColor(colour)
		.setDescription(description)
		.setFooter('moustacheminer.com server services', '')
		.setTimestamp()
		.setURL(url)
		.setImage(img);

	message.channel.sendEmbed(embed, "", { disableEveryone: true });
}

/**
 * Function to add things into the playlist, and play it if it needs to.
 * @author: 7coil <admin@moustacheminer.com>
 * @url: http://moustacheminer.com/
 * @param: {Object[]} message
 * @param: {string} type
 * @param: {string} url
 * @param: {string} title
 * @param: {string} thumb_url
 */
function playlistAdd(message, type, url, title, thumb_url) {
	if (!thumb_url) {
		thumb_url = "http://i48.tinypic.com/260v86c.png";
	}

	richSend(message, "MSS Music Player", "Added " + title + " to playlist", "#00FF00");
	playlist[message.guild.id] = playlist[message.guild.id] || [];
	playlist[message.guild.id].push(JSON.stringify({type: type, url: url, title: title, thumb_url: thumb_url}));
	if (!message.member.voiceChannel.connection) {
		playSound(message);
	}
}

/**
 * Function to clear the playlist in a channel.
 * @author: 7coil <admin@moustacheminer.com>
 * @url: http://moustacheminer.com/
 * @param: {Object[]} message
 */
function playlistClear(message) {
	//Get the voice channel
	let voiceChannel = message.member.voiceChannel;

	//If the person is in the voice channel, stop the bot in that channel
	if (voiceChannel && voiceChannel.connection) {
		voiceChannel.leave();
		playlist[message.guild.id] = [];
		stream[message.guild.id].destroy();
		return;
	} else {
		return richSend(message, "MSS Music Player", "There is no bot running in your current voice channel", "#FF0000");
	}
}

/**
 * Function to start playing through the playlist
 * @author: 7coil <admin@moustacheminer.com>
 * @url: http://moustacheminer.com/
 * @param: {Object[]} message
 */
function playSound(message) {
	var voiceChannel = message.member.voiceChannel;
	var current;

	voiceChannel.join()
	.then(connnection => {
		var looper = function() {
			playlistPlay(message);
			const dispatcher = connnection.playStream(stream[message.guild.id]);
			dispatcher.on('end', () => {
				looper();
			});
		}
		looper();
	});
}

/**
 * Function to start a stream based on what is next on the playlist.
 * @author: 7coil <admin@moustacheminer.com>
 * @url: http://moustacheminer.com/
 * @param: {Object[]} message
 */
function playlistPlay(message) {
	var voiceChannel = message.member.voiceChannel;
	if (playlist[message.guild.id].length > 0) {
		current = JSON.parse(playlist[message.guild.id].shift());
		richSend(message, "Now playing:", current["title"], "#00FF00", current["thumb_url"], current["url"]);
		if (current["type"] === "youtube") {
			stream[message.guild.id] = yt(current["url"], {audioonly: true});
		} else if (current["type"] === "file") {
			stream[message.guild.id] = fs.createReadStream(current["url"]);
		}
	} else {
		if (voiceChannel.connection) voiceChannel.leave();
		playlist[message.guild.id] = [];
		if (stream[message.guild.id]) stream[message.guild.id].destroy();
		richSend(message, "MSS Music Player", "The playlist has ended.", "#00FF00");
		return;
	}
}

/**
 * JavaScript function to match (and return) the video Id of any valid Youtube Url, given as input string.
 * @author: Stephan Schmitz <eyecatchup@gmail.com>
 * @url: http://stackoverflow.com/a/10315969/624466
 * @param: {string} url
 * @return: {Boolean} isYouTube
 */
function youtubeCheck(url) {
	if (url.startsWith("https://m.youtube.com/watch?v=")) return true;

  	var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  	return (url.match(p)) ? RegExp.$1 : false;
}

/**
 * Function to check if the user is an admin.
 * @author: 7coil <admin@moustacheminer.com>
 * @url: http://moustacheminer.com/
 * @param: {Object[]} message
 * @return {Boolean} isAdmin
 */
function isAdmin(message) {
	if (message.channel.permissionsFor(message.member).hasPermission("ADMINISTRATOR") || message.author.id === "190519304972664832") {
		return true;
	} else {
		richSend(message, "!stop", "You do not have permission to run this command.", "#FF0000");
		return false;
	}
}<|endoftext|>


<commit_before>// Dependencies
const Discordie = require('discordie');
const readline = require('readline');

// Handlers
const consoleHandler = require('./handler/consoleHandler');
const messageHandler = require('./handler/messageHandler');
const vcHandler = require('./handler/vcHandler');
const { logToBoth } = require('./plugins/logger');

// Utility
const { ensureFoldersExist, log } = require('./util/botUtil');

/** @type {{ prefix: string, hide: boolean }} */
const config = require('./config');

const Events = Discordie.Events;
const client = new Discordie({
	autoReconnect: true
});
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

process.on('unhandledRejection', (reason, promise) =>
	log(`Unhandled Promise:\n${promise}\n\n${reason.stack}`));

rl.on('line', c =>
	consoleHandler.respond(c, client));

client.connect({ token: process.env.BOT_TOKEN || require('./auth').loginToken });

function getCurrentTime () {
	return new Date(Date.now()).toLocaleString('en-US');
}

// Connection-related

client.Dispatcher.on(Events.GATEWAY_READY, e => { // eslint-disable-line no-unused-vars
	client.User.setStatus(config.hide ? 'invisible' : 'online');
	if (client.User.status === 'online') client.User.setGame('the usual stuff');
	log(`[${getCurrentTime()}] Checking music folders...`);
	ensureFoldersExist(client);
	log(`[${getCurrentTime()}] Connected.`);
});

client.Dispatcher.on(Events.DISCONNECTED, e =>
	log(`[${getCurrentTime()}] Connection interrupted. (${e.error})`));

client.Dispatcher.on(Events.GATEWAY_RESUMED, () => {
	client.User.setStatus(config.hide ? 'invisible' : 'online');
	log(`[${getCurrentTime()}] Connection resumed.`);
});

// Guild-related

client.Dispatcher.on(Events.GUILD_CREATE, e => {
	logToBoth('[GUILD_CREATE] ' + e.guild.name);
	ensureFoldersExist(client);
});

// TODO: Make it cuztomizable, per guild
client.Dispatcher.on(Events.GUILD_MEMBER_ADD, e =>
	e.guild.generalChannel.sendMessage(`Welcome, **${e.member.name}** to **${e.guild.name}**.`));

client.Dispatcher.on(Events.GUILD_MEMBER_REMOVE, e =>
	e.guild.generalChannel.sendMessage(`**${e.user.username}** has left **${e.guild.name}**.`));

// Message related

client.Dispatcher.on(Events.MESSAGE_CREATE, e =>
	messageHandler.handle(e, client));

/* client.Dispatcher.on(Events.MESSAGE_REACTION_ADD, e => {
	// if (e.user.id !== botUser.id)
	console.log('Reacted!');
}); */

// Voice related

client.Dispatcher.on(Events.VOICE_CHANNEL_JOIN, e =>
	vcHandler.handle(e));
<commit_msg>Fix join/leave message attempt crashing on recent servers.<commit_after>// Dependencies
const Discordie = require('discordie');
const readline = require('readline');

// Handlers
const consoleHandler = require('./handler/consoleHandler');
const messageHandler = require('./handler/messageHandler');
const vcHandler = require('./handler/vcHandler');
const { logToBoth } = require('./plugins/logger');

// Utility
const { ensureFoldersExist, log } = require('./util/botUtil');

/** @type {{ prefix: string, hide: boolean }} */
const config = require('./config');

const Events = Discordie.Events;
const client = new Discordie({
	autoReconnect: true
});
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

process.on('unhandledRejection', (reason, promise) =>
	log(`Unhandled Promise:\n${promise}\n\n${reason.stack}`));

rl.on('line', c =>
	consoleHandler.respond(c, client));

client.connect({ token: process.env.BOT_TOKEN || require('./auth').loginToken });

function getCurrentTime () {
	return new Date(Date.now()).toLocaleString('en-US');
}

// Connection-related

client.Dispatcher.on(Events.GATEWAY_READY, e => { // eslint-disable-line no-unused-vars
	client.User.setStatus(config.hide ? 'invisible' : 'online');
	if (client.User.status === 'online') client.User.setGame('the usual stuff');
	log(`[${getCurrentTime()}] Checking music folders...`);
	ensureFoldersExist(client);
	log(`[${getCurrentTime()}] Connected.`);
});

client.Dispatcher.on(Events.DISCONNECTED, e =>
	log(`[${getCurrentTime()}] Connection interrupted. (${e.error})`));

client.Dispatcher.on(Events.GATEWAY_RESUMED, () => {
	client.User.setStatus(config.hide ? 'invisible' : 'online');
	log(`[${getCurrentTime()}] Connection resumed.`);
});

// Guild-related

client.Dispatcher.on(Events.GUILD_CREATE, e => {
	logToBoth('[GUILD_CREATE] ' + e.guild.name);
	ensureFoldersExist(client);
});

client.Dispatcher.on(Events.GUILD_MEMBER_ADD, e => {
	const channel = e.guild.generalChannel || e.guild.textChannels.find(tc => tc.name === 'general');
	channel && channel.sendMessage(`Welcome, **${e.member.name}** to **${e.guild.name}**.`);
});

client.Dispatcher.on(Events.GUILD_MEMBER_REMOVE, e => {
	const channel = e.guild.generalChannel || e.guild.textChannels.find(tc => tc.name === 'general');
	channel && channel.sendMessage(`**${e.user.username}** has left **${e.guild.name}**.`)
});

// Message related

client.Dispatcher.on(Events.MESSAGE_CREATE, e =>
	messageHandler.handle(e, client));

/* client.Dispatcher.on(Events.MESSAGE_REACTION_ADD, e => {
	// if (e.user.id !== botUser.id)
	console.log('Reacted!');
}); */

// Voice related

client.Dispatcher.on(Events.VOICE_CHANNEL_JOIN, e =>
	vcHandler.handle(e));
<|endoftext|>


<commit_before>console.log('[INFO] I\'m starting up! Please wait until the next message!')

const botConfig = require('./botconfig.json')
const Discord = require('discord.js')
const fs = require('fs')
const schedule = require('node-schedule')
var express = require('express')
var path = require('path')
var filter = require('leo-profanity')

var app = express()
const bot = new Discord.Client()

var helpInfo = require('./help.json')
var messageReactions = require('./messageReactions.json');
var dbAccess = require('./dbAccess.js')
var commandsPath = require(`path`).join(__dirname, 'cmds')
var cmds = []
var startupTime = Date.now()

// Reading Commands
fs.readdirSync(commandsPath).forEach(function (file) { // For each file read, create a function
  let cmd = require('./cmds/' + file)
  console.log('[COMMANDS] Loaded ' + file)
  cmds[file.slice(0, -3).toUpperCase()] = cmd
  cmd.info.aliases.forEach(function (alias) {
    cmds[alias.toUpperCase()] = cmd
  })
  if (cmd.info.helpInfo.show) {
    helpInfo[cmd.info.helpInfo.category.toUpperCase()].commands.push(cmd.info.helpInfo)
  }
})

JSON.parse(fs.readFileSync('./events.json')).forEach((data) => { // Reading Events from events.json
  schedule.scheduleJob(data.date, () => {
    let color
    if (data.color) {
      color = data.color
    } else {
      color = 'RANDOM'
    }

    bot.channels.get(botConfig.channelID.event).send(new Discord.RichEmbed()
    .setTitle(data.name)
    .setColor(color)
    .setDescription(data.info)
    .setFooter(`Current Server Time: ${new Date().toString()}`)
    )
    console.log(`[EVENTS] Running ${data.name} on ${new Date()}`)
  })
  console.log(`[EVENTS] Loaded ${data.name}`)
})

// Launching bot
bot.on('ready', async () => {
  console.log(`[INFO] I'm logged on as ${bot.user.username}!`)
  console.log('[INFO] I\'m ready!')
  try {
    let link = await bot.generateInvite(['READ_MESSAGES', 'SEND_MESSAGES'])
    console.log('[INFO] Here is my invite link: ' + link)
  } catch (e) {
    console.log('[ERROR] Can\'t create invite link! Am I a normal user?')
    console.log(e.stack)
  }
})

// on message

bot.on('message', async message => {

  if (message.author.bot) return

  Object.keys(messageReactions).forEach(key => {
    if (new RegExp(key, 'g').test(message.content)) {
      message.react(messageReactions[key])
    }
  })

  if (filter.check(message.content.trim())) {
    console.log(`[FILTER] ${message.author.username}#${message.author.discriminator} cursed. Message: ${filter.clean(message.content, '*')}`)
    message.delete()
    bot.channels.get(botConfig.channelID.log).send(new Discord.RichEmbed()
    .setColor('ORANGE')
    .setAuthor(message.author.username + '#' + message.author.discriminator, message.author.avatarURL)
    .setDescription(`Message sent by <@${message.author.id}> has been replaced in #${message.channel.name}`)
    .addField('Message', filter.clean(message.content, '*'))
    .setFooter(`ID: ${message.author.id} | ${new Date()}`))
    message.channel.send(`${message.author.username} said \`${filter.clean(message.content, '*')}\``)
    return
  }

  // bot message or not start with prefix = return
  if (!message.content.startsWith(botConfig.prefix)) return

  let messageArray = message.content.trim().split(' ')
  let command = messageArray[0].replace(botConfig.prefix, '')
  let args = messageArray.slice(1)
  let data = {
    user: message.author,
    command: command,
    args: args,
    message: message,
    bot: bot.user,
    botVar: bot,
    startup: startupTime
  }
  let cmd = cmds[command.toUpperCase()]

  if (cmd != null) {
    let result = cmd.Command(data) // Send data to each handler. Returns with var `result`

    if (result != null) { // There should be always a result on each command.
      message.channel.send(result)
    } else {
      message.channel.send(new Discord.RichEmbed()
      .setTitle('❌ Something isn\'t looking right...')
      .setURL('https://github.com/rey2952/RoverBot/issues')
      .setDescription('Your command returned something weird! 😱')
      .setColor('DARK_RED')
      .addField(`Returned Value`, `\`${result}\``)
      .addField('What should I do?', 'If you see this, please report this to the bot developer or create an issue on GitHub by clicking the title of this text!'))
    }
  } else {
    message.channel.send('The command is invalid! Do `!help` if you need help.')
  }
})

bot.on('messageReactionAdd', (reaction, user) => {
  if (user.bot) return
  if (reaction.emoji.name == '💾') {
    if (reaction.message.embeds.length == 0) {
      let embed = new Discord.RichEmbed()
      .setTitle(`Saved message from ${reaction.message.author.username}#${reaction.message.author.discriminator}`)
      .setDescription(reaction.message.content)
      .setFooter('Just your friendly neighborhood bot here')
      .setTimestamp()
      user.send(embed).then( message => {
        message.pin()
      })
    } else {
      reaction.message.channel.send('I don\'t support saving embeds yet 😞');
    }
  }
})

bot.on('presenceUpdate', (oldMember, newMember) => { // Set town Offline
  if (newMember.presence.status === 'offline' && dbAccess.setOfflineTown(newMember.id) === 'deleted') {
    bot.channels.get(botConfig.channelID.townAnnouncement).send(`<@${newMember.id}>'s Town has been set offline automatically! *(The user is offline on Discord) \n @here*`)
    console.log(`[AUTOOFFLINE] ${newMember.user.username}#${newMember.user.discriminator}'s town has been set offline automatically (Discord offline)`)
  }
})

/*
Logging things should start from here. Send to channel `logs` please
*/

bot.on('guildMemberAdd', async guildMember => { // When someone joins a guild that Bot joins
  if (!botConfig.log) return

  let user = guildMember.user
  let sendData = new Discord.RichEmbed()
  .setColor([35, 209, 96])
  .setAuthor('Member Joined', user.displayAvatarURL)
  .setDescription(`<@${user.id}> ${user.username}#${user.discriminator}`)
  .setFooter(`UserID: ${user.id} | ${new Date()}`)

  bot.channels.get(botConfig.channelID.log).send(sendData)
})

bot.on('guildBanAdd', async (guild, user) => {
  if (!botConfig.log) return

  let sendData = new Discord.RichEmbed()
  .setColor(`RED`)
  .setAuthor('Member Banned', user.displayAvatarURL)
  .setDescription(`<@${user.id}> ${user.username}#${user.discriminator}`)
  .setFooter(`UserID: ${user.id} | ${new Date()}`)

  bot.channels.get(botConfig.channelID.log).send(sendData)
})

bot.on('guildMemberUpdate', async (oldMember, newMember) => {
  // TODO: Detect Changes between old and new, Output the corresponding RichEmbed.
})

/*
EXPRESS STUFF STARTS HERE
*/

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', require('./routes/index'))
app.use('/edituserinfo', require('./routes/edituserinfo'))
app.use('/github/update', require('./routes/githubupdate'))

// Initalize!
app.listen(3000) // Auto Update GitHub
bot.login(botConfig.token) // Bot Itself

// On exit

process.on('exit', (code) => {
  console.log(`[EXIT] About to exit with code ${code}`)
})
<commit_msg>Changed rexex g to i<commit_after>console.log('[INFO] I\'m starting up! Please wait until the next message!')

const botConfig = require('./botconfig.json')
const Discord = require('discord.js')
const fs = require('fs')
const schedule = require('node-schedule')
var express = require('express')
var path = require('path')
var filter = require('leo-profanity')

var app = express()
const bot = new Discord.Client()

var helpInfo = require('./help.json')
var messageReactions = require('./messageReactions.json');
var dbAccess = require('./dbAccess.js')
var commandsPath = require(`path`).join(__dirname, 'cmds')
var cmds = []
var startupTime = Date.now()

// Reading Commands
fs.readdirSync(commandsPath).forEach(function (file) { // For each file read, create a function
  let cmd = require('./cmds/' + file)
  console.log('[COMMANDS] Loaded ' + file)
  cmds[file.slice(0, -3).toUpperCase()] = cmd
  cmd.info.aliases.forEach(function (alias) {
    cmds[alias.toUpperCase()] = cmd
  })
  if (cmd.info.helpInfo.show) {
    helpInfo[cmd.info.helpInfo.category.toUpperCase()].commands.push(cmd.info.helpInfo)
  }
})

JSON.parse(fs.readFileSync('./events.json')).forEach((data) => { // Reading Events from events.json
  schedule.scheduleJob(data.date, () => {
    let color
    if (data.color) {
      color = data.color
    } else {
      color = 'RANDOM'
    }

    bot.channels.get(botConfig.channelID.event).send(new Discord.RichEmbed()
    .setTitle(data.name)
    .setColor(color)
    .setDescription(data.info)
    .setFooter(`Current Server Time: ${new Date().toString()}`)
    )
    console.log(`[EVENTS] Running ${data.name} on ${new Date()}`)
  })
  console.log(`[EVENTS] Loaded ${data.name}`)
})

// Launching bot
bot.on('ready', async () => {
  console.log(`[INFO] I'm logged on as ${bot.user.username}!`)
  console.log('[INFO] I\'m ready!')
  try {
    let link = await bot.generateInvite(['READ_MESSAGES', 'SEND_MESSAGES'])
    console.log('[INFO] Here is my invite link: ' + link)
  } catch (e) {
    console.log('[ERROR] Can\'t create invite link! Am I a normal user?')
    console.log(e.stack)
  }
})

// on message

bot.on('message', async message => {

  if (message.author.bot) return

  Object.keys(messageReactions).forEach(key => {
    if (new RegExp(key, 'i').test(message.content)) {
      message.react(messageReactions[key])
    }
  })

  if (filter.check(message.content.trim())) {
    console.log(`[FILTER] ${message.author.username}#${message.author.discriminator} cursed. Message: ${filter.clean(message.content, '*')}`)
    message.delete()
    bot.channels.get(botConfig.channelID.log).send(new Discord.RichEmbed()
    .setColor('ORANGE')
    .setAuthor(message.author.username + '#' + message.author.discriminator, message.author.avatarURL)
    .setDescription(`Message sent by <@${message.author.id}> has been replaced in #${message.channel.name}`)
    .addField('Message', filter.clean(message.content, '*'))
    .setFooter(`ID: ${message.author.id} | ${new Date()}`))
    message.channel.send(`${message.author.username} said \`${filter.clean(message.content, '*')}\``)
    return
  }

  // bot message or not start with prefix = return
  if (!message.content.startsWith(botConfig.prefix)) return

  let messageArray = message.content.trim().split(' ')
  let command = messageArray[0].replace(botConfig.prefix, '')
  let args = messageArray.slice(1)
  let data = {
    user: message.author,
    command: command,
    args: args,
    message: message,
    bot: bot.user,
    botVar: bot,
    startup: startupTime
  }
  let cmd = cmds[command.toUpperCase()]

  if (cmd != null) {
    let result = cmd.Command(data) // Send data to each handler. Returns with var `result`

    if (result != null) { // There should be always a result on each command.
      message.channel.send(result)
    } else {
      message.channel.send(new Discord.RichEmbed()
      .setTitle('❌ Something isn\'t looking right...')
      .setURL('https://github.com/rey2952/RoverBot/issues')
      .setDescription('Your command returned something weird! 😱')
      .setColor('DARK_RED')
      .addField(`Returned Value`, `\`${result}\``)
      .addField('What should I do?', 'If you see this, please report this to the bot developer or create an issue on GitHub by clicking the title of this text!'))
    }
  } else {
    message.channel.send('The command is invalid! Do `!help` if you need help.')
  }
})

bot.on('messageReactionAdd', (reaction, user) => {
  if (user.bot) return
  if (reaction.emoji.name == '💾') {
    if (reaction.message.embeds.length == 0) {
      let embed = new Discord.RichEmbed()
      .setTitle(`Saved message from ${reaction.message.author.username}#${reaction.message.author.discriminator}`)
      .setDescription(reaction.message.content)
      .setFooter('Just your friendly neighborhood bot here')
      .setTimestamp()
      user.send(embed).then( message => {
        message.pin()
      })
    } else {
      reaction.message.channel.send('I don\'t support saving embeds yet 😞');
    }
  }
})

bot.on('presenceUpdate', (oldMember, newMember) => { // Set town Offline
  if (newMember.presence.status === 'offline' && dbAccess.setOfflineTown(newMember.id) === 'deleted') {
    bot.channels.get(botConfig.channelID.townAnnouncement).send(`<@${newMember.id}>'s Town has been set offline automatically! *(The user is offline on Discord) \n @here*`)
    console.log(`[AUTOOFFLINE] ${newMember.user.username}#${newMember.user.discriminator}'s town has been set offline automatically (Discord offline)`)
  }
})

/*
Logging things should start from here. Send to channel `logs` please
*/

bot.on('guildMemberAdd', async guildMember => { // When someone joins a guild that Bot joins
  if (!botConfig.log) return

  let user = guildMember.user
  let sendData = new Discord.RichEmbed()
  .setColor([35, 209, 96])
  .setAuthor('Member Joined', user.displayAvatarURL)
  .setDescription(`<@${user.id}> ${user.username}#${user.discriminator}`)
  .setFooter(`UserID: ${user.id} | ${new Date()}`)

  bot.channels.get(botConfig.channelID.log).send(sendData)
})

bot.on('guildBanAdd', async (guild, user) => {
  if (!botConfig.log) return

  let sendData = new Discord.RichEmbed()
  .setColor(`RED`)
  .setAuthor('Member Banned', user.displayAvatarURL)
  .setDescription(`<@${user.id}> ${user.username}#${user.discriminator}`)
  .setFooter(`UserID: ${user.id} | ${new Date()}`)

  bot.channels.get(botConfig.channelID.log).send(sendData)
})

bot.on('guildMemberUpdate', async (oldMember, newMember) => {
  // TODO: Detect Changes between old and new, Output the corresponding RichEmbed.
})

/*
EXPRESS STUFF STARTS HERE
*/

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', require('./routes/index'))
app.use('/edituserinfo', require('./routes/edituserinfo'))
app.use('/github/update', require('./routes/githubupdate'))

// Initalize!
app.listen(3000) // Auto Update GitHub
bot.login(botConfig.token) // Bot Itself

// On exit

process.on('exit', (code) => {
  console.log(`[EXIT] About to exit with code ${code}`)
})
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();
const weather = require('weather-js');
const sql = require("sqlite");
//const mysql = require('mysql');

//----------------------------------------------------------------------------------------------------------------------------------

sql.open("./score.sqlite");

//----------------------------------------------------------------------------------------------------------------------------------

client.config = require('./config.json');
client.log = require('./functions/log.js');
client.commands = new Discord.Collection();

//----------------------------------------------------------------------------------------------------------------------------------

//COMANDOS
client.commands.set('ping', require('./commands/ping.js'));
client.commands.set('falar', require('./commands/falar.js'));
client.commands.set('ajuda', require('./commands/ajuda.js'));
client.commands.set('limpar', require('./commands/limpar.js'));
client.commands.set('ban', require('./commands/ban.js'));
client.commands.set('kick', require('./commands/kick.js'));
client.commands.set('unban', require('./commands/unban.js'));
client.commands.set('roll', require('./commands/roll.js'));
client.commands.set('bot', require('./commands/conversaBot.js'));
client.commands.set('morra', require('./commands/conversaMorra.js'));
client.commands.set('soma', require('./commands/calcularSoma.js'));
client.commands.set('sub', require('./commands/calcularSub.js'));
client.commands.set('mult', require('./commands/calcularMult.js'));
client.commands.set('div', require('./commands/calcularDiv.js'));
client.commands.set('fsalvos', require('./commands/canalSalvos.js'));
client.commands.set('fprincipal', require('./commands/canalPrincipal.js'));
client.commands.set('resp', require('./commands/resp.js'));
client.commands.set('playinitiald', require('./commands/radioPlayInitialD.js'));
client.commands.set('playmoe', require('./commands/radioPlayMoe.js'));
client.commands.set('playanimenfo', require('./commands/radioPlayAnimeNfo.js'));
client.commands.set('stop', require('./commands/radioStop.js'));
client.commands.set('userinfo', require('./commands/userinfo.js'));
client.commands.set('serverinfo', require('./commands/serverinfo.js'));
client.commands.set('tempo', require('./commands/tempo.js'));
client.commands.set('afk', require('./commands/joinAway.js'));
client.commands.set('level', require('./commands/levelXp.js'));
client.commands.set('pontos', require('./commands/levelPoints.js'));

//----------------------------------------------------------------------------------------------------------------------------------

//MENSAGEM
client.on('messageReactionAdd', (reaction, user) => require('./events/messageReactionAdd.js')(client, reaction, user));
//----------------------------------------------------------------------------------------------------------------------------------
client.on('message', message => {
  //BANCO DE DADOS
  sql.get(`SELECT * FROM scores WHERE userId ="${message.author.id}"`).then(row =>
  { if (!row) { sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
  } else {  let curLevel = Math.floor(0.1 * Math.sqrt(row.points + 1));
    if (curLevel > row.level) { row.level = curLevel;  sql.run(`UPDATE scores SET points = ${row.points + 1}, level = ${row.level} WHERE userId = ${message.author.id}`);  message.reply(`Ding! Parabéns! Você subiu de level. O seu level atual é **${curLevel}**!`);    }
  sql.run(`UPDATE scores SET points = ${row.points + 1} WHERE userId = ${message.author.id}`);  }
  }).catch(() => { console.error;
  sql.run("CREATE TABLE IF NOT EXISTS scores (userId TEXT, points INTEGER, level INTEGER)").then(() => {
  sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);   });  });
  //FILTRO DE PALAVRÃO
  const msgbanida = message.content.toUpperCase();
  if (msgbanida.includes('PPPPP','NNNNN')) { message.delete(); message.channel.send('Por favor... **'+message.author.username+'**, não diga palavrões!!! Rhrumnn!!!').then(msg => {msg.delete(60000)}); }
  //MENSAGEM REQUIRE
  require('./events/message.js')(client, message, sql) });
//----------------------------------------------------------------------------------------------------------------------------------

//READY
client.on('ready', () => { var channel = client.channels.get('167715230082662401'); channel.sendMessage("**O BoT está online!**").then(msg => {msg.delete(60000)}); require('./events/ready.js')(client) });

//GUILD
client.on('guildCreate', guild => require('./events/guildCreate.js')(client, guild));
client.on('guildMemberAdd', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Seja bem vindo(a) **'+member.user.username+'**!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberRemove', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Adeus **'+member.user.username+'**!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberUpdate', (oldMember, newMember) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário **'+oldMember+'** **atualizou** os seus dados!').then(msg => {msg.delete(60000)}) } );
client.on('guildUpdate', (guild, oldGuild, newGuild) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O servidor **'+oldGuild+'** foi **atualizado**!').then(msg => {msg.delete(60000)}) } );
client.on('guildBanAdd', (guild, user) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário **'+user+'** foi **banido**!').then(msg => {msg.delete(60000)}) } );
client.on('guildBanRemove', (guild, user) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário **'+user+'** foi **desbanido**!').then(msg => {msg.delete(60000)}) } );

//EMOJI
client.on('emojiCreate', (emoji) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O **Emoji** '+emoji+' foi adicionado!').then(msg => {msg.delete(60000)}) } );
client.on('emojiDelete', (emoji) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O **Emoji** '+emoji+' foi deletado!!').then(msg => {msg.delete(60000)}) } );
client.on('emojiUpdate', (emoji, oldEmoji, newEmoji) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O **Emoji** '+oldEmoji+' foi **atualizado**!').then(msg => {msg.delete(60000)}) } );

//ROLES
client.on('roleCreate', (role) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A nova **Role** '+role+' foi adicionada!').then(msg => {msg.delete(60000)}) } );
client.on('roleDelete', (role) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A **Role** '+role+' foi deletada!!').then(msg => {msg.delete(60000)}) } );
client.on('roleUpdate', (role, oldRole, newRole) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A **Role** '+oldRole+' foi **atualizada**!').then(msg => {msg.delete(60000)}) } );

//CANAL
client.on('channelCreate', (channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova **sala de conversa** foi **criada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelDelete', (channel, guild) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma **sala de conversa** foi **deletada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelPinsUpdate', (channel, time) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova mensagem foi **fixada** em **'+time+'**!').then(msg => {msg.delete(60000)}) } );
client.on('channelUpdate', (channel, oldChannel, newChannel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A sala de conversa **'+oldChannel+'** foi atualizada!').then(msg => {msg.delete(60000)}) } );

//----------------------------------------------------------------------------------------------------------------------------------
//-----Nao usado por causa de spam
/*client.on('voiceStateUpdate', (oldMember, newMember) => { let newUserChannel = newMember.voiceChannel; let oldUserChannel = oldMember.voiceChannel;
if(oldUserChannel === undefined && newUserChannel !== undefined) { entra no canal --- CODIGO de msg aqui } else if(newUserChannel === undefined){ sai no canal --- CODIGO de msg aqui }}); */
//----------------------------------------------------------------------------------------------------------------------------------
//-----mysql Heroku connect database
/*var con;
if(process.env.DATABASE_URL) { con = mysql.createConnection(process.env.DATABASE_URL); } */

//client.login(config.token)
client.login(process.env.BOT_TOKEN);<commit_msg><commit_after>const Discord = require('discord.js');
const client = new Discord.Client();
const weather = require('weather-js');
const sql = require("sqlite");
//const mysql = require('mysql');

//----------------------------------------------------------------------------------------------------------------------------------

sql.open("./score.sqlite");

//----------------------------------------------------------------------------------------------------------------------------------

client.config = require('./config.json');
client.log = require('./functions/log.js');
client.commands = new Discord.Collection();

//----------------------------------------------------------------------------------------------------------------------------------

//COMANDOS
client.commands.set('ping', require('./commands/ping.js'));
client.commands.set('falar', require('./commands/falar.js'));
client.commands.set('ajuda', require('./commands/ajuda.js'));
client.commands.set('limpar', require('./commands/limpar.js'));
client.commands.set('ban', require('./commands/ban.js'));
client.commands.set('kick', require('./commands/kick.js'));
client.commands.set('unban', require('./commands/unban.js'));
client.commands.set('roll', require('./commands/roll.js'));
client.commands.set('bot', require('./commands/conversaBot.js'));
client.commands.set('morra', require('./commands/conversaMorra.js'));
client.commands.set('soma', require('./commands/calcularSoma.js'));
client.commands.set('sub', require('./commands/calcularSub.js'));
client.commands.set('mult', require('./commands/calcularMult.js'));
client.commands.set('div', require('./commands/calcularDiv.js'));
client.commands.set('fsalvos', require('./commands/canalSalvos.js'));
client.commands.set('fprincipal', require('./commands/canalPrincipal.js'));
client.commands.set('resp', require('./commands/resp.js'));
client.commands.set('playinitiald', require('./commands/radioPlayInitialD.js'));
client.commands.set('playmoe', require('./commands/radioPlayMoe.js'));
client.commands.set('playanimenfo', require('./commands/radioPlayAnimeNfo.js'));
client.commands.set('stop', require('./commands/radioStop.js'));
client.commands.set('userinfo', require('./commands/userinfo.js'));
client.commands.set('serverinfo', require('./commands/serverinfo.js'));
client.commands.set('tempo', require('./commands/tempo.js'));
client.commands.set('afk', require('./commands/joinAway.js'));
client.commands.set('level', require('./commands/levelXp.js'));
client.commands.set('pontos', require('./commands/levelPoints.js'));

//----------------------------------------------------------------------------------------------------------------------------------

//MENSAGEM
client.on('messageReactionAdd', (reaction, user) => require('./events/messageReactionAdd.js')(client, reaction, user));
//----------------------------------------------------------------------------------------------------------------------------------
client.on('message', message => {
  //BANCO DE DADOS
  sql.get(`SELECT * FROM scores WHERE userId ="${message.author.id}"`).then(row =>
  { if (!row) { sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
  } else {  let curLevel = Math.floor(0.1 * Math.sqrt(row.points + 1));
    if (curLevel > row.level) { row.level = curLevel;  sql.run(`UPDATE scores SET points = ${row.points + 1}, level = ${row.level} WHERE userId = ${message.author.id}`);  message.reply(`Ding! Parabéns! Você subiu de level. O seu level atual é **${curLevel}**!`);    }
  sql.run(`UPDATE scores SET points = ${row.points + 1} WHERE userId = ${message.author.id}`);  }
  }).catch(() => { console.error;
  sql.run("CREATE TABLE IF NOT EXISTS scores (userId TEXT, points INTEGER, level INTEGER)").then(() => {
  sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);   });  });
  //FILTRO DE PALAVRÃO
  const msgbanida = message.content.toUpperCase();
  if (msgbanida.includes('PPPPP','NNNNN')) { message.delete(); message.channel.send('**'+message.author.username+'**, A sua mensagem foi deletada. Por favor não diga palavrões!!! Rhrumnn!!!').then(msg => {msg.delete(60000)}); }
  //MENSAGEM REQUIRE
  require('./events/message.js')(client, message, sql) });
//----------------------------------------------------------------------------------------------------------------------------------

//READY
client.on('ready', () => { var channel = client.channels.get('167715230082662401'); channel.sendMessage("**O BoT está online!**").then(msg => {msg.delete(60000)}); require('./events/ready.js')(client) });

//GUILD
client.on('guildCreate', guild => require('./events/guildCreate.js')(client, guild));
client.on('guildMemberAdd', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Seja bem vindo(a) **'+member.user.username+'**!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberRemove', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Adeus **'+member.user.username+'**!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberUpdate', (oldMember, newMember) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário **'+oldMember+'** **atualizou** os seus dados!').then(msg => {msg.delete(60000)}) } );
client.on('guildUpdate', (guild, oldGuild, newGuild) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O servidor **'+oldGuild+'** foi **atualizado**!').then(msg => {msg.delete(60000)}) } );
client.on('guildBanAdd', (guild, user) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário **'+user+'** foi **banido**!').then(msg => {msg.delete(60000)}) } );
client.on('guildBanRemove', (guild, user) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário **'+user+'** foi **desbanido**!').then(msg => {msg.delete(60000)}) } );

//EMOJI
client.on('emojiCreate', (emoji) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O **Emoji** '+emoji+' foi adicionado!').then(msg => {msg.delete(60000)}) } );
client.on('emojiDelete', (emoji) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O **Emoji** '+emoji+' foi deletado!!').then(msg => {msg.delete(60000)}) } );
client.on('emojiUpdate', (emoji, oldEmoji, newEmoji) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O **Emoji** '+oldEmoji+' foi **atualizado**!').then(msg => {msg.delete(60000)}) } );

//ROLES
client.on('roleCreate', (role) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A nova **Role** '+role+' foi adicionada!').then(msg => {msg.delete(60000)}) } );
client.on('roleDelete', (role) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A **Role** '+role+' foi deletada!!').then(msg => {msg.delete(60000)}) } );
client.on('roleUpdate', (role, oldRole, newRole) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A **Role** '+oldRole+' foi **atualizada**!').then(msg => {msg.delete(60000)}) } );

//CANAL
client.on('channelCreate', (channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova **sala de conversa** foi **criada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelDelete', (channel, guild) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma **sala de conversa** foi **deletada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelPinsUpdate', (channel, time) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova mensagem foi **fixada** em **'+time+'**!').then(msg => {msg.delete(60000)}) } );
client.on('channelUpdate', (channel, oldChannel, newChannel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A sala de conversa **'+oldChannel+'** foi atualizada!').then(msg => {msg.delete(60000)}) } );

//----------------------------------------------------------------------------------------------------------------------------------
//-----Nao usado por causa de spam
/*client.on('voiceStateUpdate', (oldMember, newMember) => { let newUserChannel = newMember.voiceChannel; let oldUserChannel = oldMember.voiceChannel;
if(oldUserChannel === undefined && newUserChannel !== undefined) { entra no canal --- CODIGO de msg aqui } else if(newUserChannel === undefined){ sai no canal --- CODIGO de msg aqui }}); */
//----------------------------------------------------------------------------------------------------------------------------------
//-----mysql Heroku connect database
/*var con;
if(process.env.DATABASE_URL) { con = mysql.createConnection(process.env.DATABASE_URL); } */

//client.login(config.token)
client.login(process.env.BOT_TOKEN);<|endoftext|>


<commit_before>var Bot = require('ttapi');
var AUTH= process.env.PRABBAUTH;
var USERID= process.env.PRABBUSERID;
var ROOM= process.env.PRABBROOM;

var bot = new Bot(AUTH, USERID, ROOM);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Dj = mongoose.model("Dj", require("./models/dj").Dj);
var Track = mongoose.model("Track", require("./models/track").Track);
var Artist = mongoose.model("Artist", require("./models/artist").Artist);
var Play = mongoose.model("Play", require("./models/play").Play);

var twitter = require('./tweets').twitter;

var currentSong;

bot.on('newsong', function(data){
  setCurrentSong(data);
  show_link(data.room.metadata.current_song.metadata.artist);
  tweet_song(data.room.metadata.current_song.metadata.artist);
});
show_link = function(artist){
    var response = artist + ' Info: ';
    response+="http://www.postrockandbeyond.com/artists/";
    response+=escape(artist);
    bot.speak(response);
};
bot.on('ready', function(data){
  bot.roomInfo(function(data){
    setCurrentSong(data);
  });
});

bot.on('update_votes', function(data){
  currentSong.upvotes= data.room.metadata.upvotes;
  currentSong.downvotes= data.room.metadata.downvotes;
  currentSong.listeners= data.room.metadata.listeners;
  currentSong.save(function(err){log_error(err);});
});

bot.on('endsong', function(){
  updatePlayInfo();
});
bot.on('add_dj', function(data){
  Dj.find_or_create_by_userid(data.user[0].userid, data.user[0].name, new Dj(), function(err, docs){
        log_error(err);
  });
});

bot.on('speak', function(data){
  Dj.isAdmin(data.userid, function(err, res){
    log_error(err);
    if(res){
      var result = data.text.match(/^\/(.*?)( .*)?$/);
      if(result){
        var command = result[1].trim().toLowerCase();
        var param = '';
        if (result.length == 3 && result[2]){
          param = result[2].trim().toLowerCase();
        }

        switch(command){
          case 'sa':
          case 'setadmin':
            setAdmin(param);
            break;
          case 'da':
          case 'deladmin':
            deleteAdmin(param);
            break;

          case 'sb':
          case 'setbandcamp':
            setLink('bandcamp', param);
            break;
          case 'db':
          case 'delbandcamp':
            deleteLink('bandcamp');
            break;
          case 'sf':
          case 'setfacebook':
            setLink('facebook', param);
            break;
          case 'df':
          case 'delfacebook':
            deleteLink('facebook');
            break;
          case 'sw':
          case 'setwebsite':
            setLink('website', param);
            break;
          case 'dw':
          case 'delwebsite':
            deleteLink('website');
            break;
          case 'sfm':
          case 'setlast':
            setLink('lastfm', param);
            break;
          case 'dfm':
          case 'dellast':
            deleteLink('lastfm');
            break;
          case 'sl':
            show_link(currentSong.artist.name);
            break;
          case 'tweet':
            tweet_song(currentSong.artist.name);
            break;
        }
      }
    }
  });
});

tweet_song = function(artist){
  var status = "Now playing #"+artist.toLowerCase().replace(/\ /gi,"")+" in http://turntable.fm/postrock_beyond #turntablefm"
  twitter.verifyCredentials(function(){}).updateStatus(status, function(){});
};

deleteAdmin = function(name){
  bot.getProfile(name, function(data){
    Dj.update({userid: data.userid},{admin: false},function(err, docs){
      log_error();
      bot.speak(name + ' is no longer an admin.');
    });
  });
};

setAdmin = function(name){
  bot.getProfile(name, function(data){
    Dj.update({userid: data.userid},{admin: true},function(err, docs){
      bot.speak(name + ' added as an admin.');
    });
  });
};

deleteLink = function(key){
  if(key && currentSong){
    currentSong.artist.links[key] = '';
    artist = currentSong.artist;
    artist.save(function(err){log_error();});
    bot.speak("Removed "+key+" link");
  }else{console.log(key,currentSong);}
};

setLink = function(key, value){
  if(key && value && currentSong){
    currentSong.artist.links[key] = value;
    artist = currentSong.artist;
    artist.save(function(err){log_error();});
    bot.speak("Added "+key+" link: "+value);
  }else{console.log(key, value, currentSong);}
};

setCurrentSong = function(data){
  if(data.room.metadata.current_song){
  song = data.room.metadata.current_song;
  dj = data.room.metadata.current_dj;
  upvotes = data.room.metadata.upvotes;
  downvotes = data.room.metadata.downvotes;
  listeners = data.room.metadata.listeners;

  bot.getProfile(dj, function(data){
    Dj.find_or_create_by_userid(dj,data.name,new Dj(), function(err, docs){
      log_error(err);
      var dj = docs;
      Artist.find_or_create_by_name(song.metadata.artist, song, new Artist(), function(err, docs){
        log_error(err);
        var artist = docs;
        Track.find_or_create_by_name(song.metadata.song, song.metadata.album, artist.id, new Track(), function(err, docs){
          log_error(err);
          var track = docs;
          artist.tracks.push(track.id);
          artist.save(function(err){log_error(err);});
          Play.find_or_create_by_timestamp(song.starttime, dj.id, artist.id, track.id, new Play(), function(err, docs){
            currentSong = docs;
            currentSong.upvotes = upvotes;
            currentSong.downvotes = downvotes;
            currentSong.listeners = listeners;
          });
        });
      });
    });
  });
  }
};

updatePlayInfo = function(){
  currentSong.dj.plays++;
  currentSong.dj.upvotes = currentSong.dj.upvotes ? currentSong.dj.upvotes+currentSong.upvotes : currentSong.upvotes;
  currentSong.dj.downvotes = currentSong.dj.downvotes ? currentSong.dj.downvotes+currentSong.downvotes : currentSong.downvotes;
  dj = currentSong.dj;
  dj.save(function(err){log_error(err);});

  currentSong.artist.plays = currentSong.artist.plays ? currentSong.artist.plays+1 : 1;
  currentSong.artist.upvotes = currentSong.artist.upvotes ? currentSong.artist.upvotes+currentSong.upvotes : currentSong.upvotes;
  currentSong.artist.downvotes = currentSong.artist.downvotes ? currentSong.artist.downvotes+currentSong.downvotes : currentSong.downvotes;
  artist = currentSong.artist;
  artist.save(function(err){log_error(err);});

  currentSong.track.plays = currentSong.track.plays ? currentSong.track.plays+1:1;
  currentSong.track.upvotes = currentSong.track.upvotes ? currentSong.track.upvotes+currentSong.upvotes : currentSong.upvotes;
  currentSong.track.downvotes = currentSong.track.downvotes ? currentSong.track.downvotes+currentSong.downvotes : currentSong.downvotes;
  track = currentSong.track;
  track.save(function(err){log_error(err);});
  currentSong.save(function(err){log_error(err);});
};
log_error = function(err){
  if(err){
    console.log(err);
  }
};
exports.bot = bot;
<commit_msg>removing hash tag<commit_after>var Bot = require('ttapi');
var AUTH= process.env.PRABBAUTH;
var USERID= process.env.PRABBUSERID;
var ROOM= process.env.PRABBROOM;

var bot = new Bot(AUTH, USERID, ROOM);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Dj = mongoose.model("Dj", require("./models/dj").Dj);
var Track = mongoose.model("Track", require("./models/track").Track);
var Artist = mongoose.model("Artist", require("./models/artist").Artist);
var Play = mongoose.model("Play", require("./models/play").Play);

var twitter = require('./tweets').twitter;

var currentSong;

bot.on('newsong', function(data){
  setCurrentSong(data);
  show_link(data.room.metadata.current_song.metadata.artist);
  tweet_song(data.room.metadata.current_song.metadata.artist);
});
show_link = function(artist){
    var response = artist + ' Info: ';
    response+="http://www.postrockandbeyond.com/artists/";
    response+=escape(artist);
    bot.speak(response);
};
bot.on('ready', function(data){
  bot.roomInfo(function(data){
    setCurrentSong(data);
  });
});

bot.on('update_votes', function(data){
  currentSong.upvotes= data.room.metadata.upvotes;
  currentSong.downvotes= data.room.metadata.downvotes;
  currentSong.listeners= data.room.metadata.listeners;
  currentSong.save(function(err){log_error(err);});
});

bot.on('endsong', function(){
  updatePlayInfo();
});
bot.on('add_dj', function(data){
  Dj.find_or_create_by_userid(data.user[0].userid, data.user[0].name, new Dj(), function(err, docs){
        log_error(err);
  });
});

bot.on('speak', function(data){
  Dj.isAdmin(data.userid, function(err, res){
    log_error(err);
    if(res){
      var result = data.text.match(/^\/(.*?)( .*)?$/);
      if(result){
        var command = result[1].trim().toLowerCase();
        var param = '';
        if (result.length == 3 && result[2]){
          param = result[2].trim().toLowerCase();
        }

        switch(command){
          case 'sa':
          case 'setadmin':
            setAdmin(param);
            break;
          case 'da':
          case 'deladmin':
            deleteAdmin(param);
            break;

          case 'sb':
          case 'setbandcamp':
            setLink('bandcamp', param);
            break;
          case 'db':
          case 'delbandcamp':
            deleteLink('bandcamp');
            break;
          case 'sf':
          case 'setfacebook':
            setLink('facebook', param);
            break;
          case 'df':
          case 'delfacebook':
            deleteLink('facebook');
            break;
          case 'sw':
          case 'setwebsite':
            setLink('website', param);
            break;
          case 'dw':
          case 'delwebsite':
            deleteLink('website');
            break;
          case 'sfm':
          case 'setlast':
            setLink('lastfm', param);
            break;
          case 'dfm':
          case 'dellast':
            deleteLink('lastfm');
            break;
          case 'sl':
            show_link(currentSong.artist.name);
            break;
          case 'tweet':
            tweet_song(currentSong.artist.name);
            break;
        }
      }
    }
  });
});

tweet_song = function(artist){
  var status = "Now playing #"+artist.toLowerCase().replace(/\ /gi,"")+" in http://turntable.fm/postrock_beyond"
  twitter.verifyCredentials(function(){}).updateStatus(status, function(){});
};

deleteAdmin = function(name){
  bot.getProfile(name, function(data){
    Dj.update({userid: data.userid},{admin: false},function(err, docs){
      log_error();
      bot.speak(name + ' is no longer an admin.');
    });
  });
};

setAdmin = function(name){
  bot.getProfile(name, function(data){
    Dj.update({userid: data.userid},{admin: true},function(err, docs){
      bot.speak(name + ' added as an admin.');
    });
  });
};

deleteLink = function(key){
  if(key && currentSong){
    currentSong.artist.links[key] = '';
    artist = currentSong.artist;
    artist.save(function(err){log_error();});
    bot.speak("Removed "+key+" link");
  }else{console.log(key,currentSong);}
};

setLink = function(key, value){
  if(key && value && currentSong){
    currentSong.artist.links[key] = value;
    artist = currentSong.artist;
    artist.save(function(err){log_error();});
    bot.speak("Added "+key+" link: "+value);
  }else{console.log(key, value, currentSong);}
};

setCurrentSong = function(data){
  if(data.room.metadata.current_song){
  song = data.room.metadata.current_song;
  dj = data.room.metadata.current_dj;
  upvotes = data.room.metadata.upvotes;
  downvotes = data.room.metadata.downvotes;
  listeners = data.room.metadata.listeners;

  bot.getProfile(dj, function(data){
    Dj.find_or_create_by_userid(dj,data.name,new Dj(), function(err, docs){
      log_error(err);
      var dj = docs;
      Artist.find_or_create_by_name(song.metadata.artist, song, new Artist(), function(err, docs){
        log_error(err);
        var artist = docs;
        Track.find_or_create_by_name(song.metadata.song, song.metadata.album, artist.id, new Track(), function(err, docs){
          log_error(err);
          var track = docs;
          artist.tracks.push(track.id);
          artist.save(function(err){log_error(err);});
          Play.find_or_create_by_timestamp(song.starttime, dj.id, artist.id, track.id, new Play(), function(err, docs){
            currentSong = docs;
            currentSong.upvotes = upvotes;
            currentSong.downvotes = downvotes;
            currentSong.listeners = listeners;
          });
        });
      });
    });
  });
  }
};

updatePlayInfo = function(){
  currentSong.dj.plays++;
  currentSong.dj.upvotes = currentSong.dj.upvotes ? currentSong.dj.upvotes+currentSong.upvotes : currentSong.upvotes;
  currentSong.dj.downvotes = currentSong.dj.downvotes ? currentSong.dj.downvotes+currentSong.downvotes : currentSong.downvotes;
  dj = currentSong.dj;
  dj.save(function(err){log_error(err);});

  currentSong.artist.plays = currentSong.artist.plays ? currentSong.artist.plays+1 : 1;
  currentSong.artist.upvotes = currentSong.artist.upvotes ? currentSong.artist.upvotes+currentSong.upvotes : currentSong.upvotes;
  currentSong.artist.downvotes = currentSong.artist.downvotes ? currentSong.artist.downvotes+currentSong.downvotes : currentSong.downvotes;
  artist = currentSong.artist;
  artist.save(function(err){log_error(err);});

  currentSong.track.plays = currentSong.track.plays ? currentSong.track.plays+1:1;
  currentSong.track.upvotes = currentSong.track.upvotes ? currentSong.track.upvotes+currentSong.upvotes : currentSong.upvotes;
  currentSong.track.downvotes = currentSong.track.downvotes ? currentSong.track.downvotes+currentSong.downvotes : currentSong.downvotes;
  track = currentSong.track;
  track.save(function(err){log_error(err);});
  currentSong.save(function(err){log_error(err);});
};
log_error = function(err){
  if(err){
    console.log(err);
  }
};
exports.bot = bot;
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

const ciJobNumber = require('ci-job-number')
const readPkg = require('read-pkg-up')
const globby = require('globby')
const yargs = require('yargs')
const chalk = require('chalk')
const bytes = require('bytes')
const path = require('path')

const getSize = require('.')

const argv = yargs
  .usage('$0')
  .option('why', {
    alias: 'w',
    describe: 'Show package content',
    type: 'boolean'
  })
  .option('no-webpack', {
    describe: 'Disable webpack',
    type: 'boolean'
  })
  .version()
  .help()
  .alias('help', 'h')
  .alias('version', 'v')
  .epilog('Usage:\n' +
          '  $0\n' +
          '    Read configuration from package.json and check limit.\n' +
          '  $0 --why\n' +
          '    Show reasons why project have this size.\n' +
          '  $0 index.js\n' +
          '    Check specific file size with all file dependencies.\n' +
          '\n' +
          'Size Limit will read size-limit section from package.json.\n' +
          'Configuration example:\n' +
          '\n' +
          '  "size-limit": [\n' +
          '    {\n' +
          '      "path": "index.js",\n' +
          '      "limit": "9 KB"\n' +
          '    }\n' +
          '  ]')
  .locale('en')
  .argv

function ownError (msg) {
  const error = new Error(msg)
  error.sizeLimit = true
  return error
}

function formatBytes (size) {
  return chalk.bold(bytes.format(size, { unitSeparator: ' ' }))
}

function warn (messages) {
  const prefix = `${ chalk.bgYellow.black(' WARN ') } `
  process.stderr.write(prefix + messages.map((message, index) => {
    const highlighted = message.replace(/`([^`]*)`/g, chalk.bold('$1'))
    const str = `${ chalk.yellow(highlighted) }\n`
    return index === 0 ? str : `       ${ str }`
  }).join(''))
}

if (ciJobNumber() !== 1) {
  process.stdout.write(
    chalk.yellow('Size Limits run only on first CI job, to save CI resources'))
  process.stdout.write('\n')
  process.exit(0)
}

let getOptions
if (argv['_'].length === 0) {
  getOptions = readPkg().then(result => {
    if (!result.pkg) {
      throw ownError(
        'Can not find `package.json`. ' +
        'Be sure that you run Size Limit inside project dir.'
      )
    } else if (!result.pkg['size-limit'] && !result.pkg['sizeLimit']) {
      throw ownError(
        'Can not find `"size-limit"` section in `package.json`. ' +
        'Add it according Size Limit docs.'
      )
    }

    if (result.pkg.sizeLimit) {
      warn([
        'Section name `"sizeLimit"` in package.json was deprecated.',
        'Use `"size-limit"` for section name.'
      ])
    }

    const limits = result.pkg['size-limit'] || result.pkg['sizeLimit']
    return Promise.all(limits.map(limit => {
      const cwd = path.dirname(result.path)
      return globby(limit.path, { cwd }).then(files => {
        if (files.length === 0) {
          files = limit.path
          if (typeof files === 'string') files = [files]
        }
        if (limit.babili) {
          warn([
            'Option `"babili": true` was deprecated.',
            'Size Limit now supports ES2016 out of box.',
            'You can remove this option.'
          ])
        }
        return {
          webpack: limit.webpack !== false,
          bundle: result.pkg.name,
          ignore: result.pkg.peerDependencies,
          limit: limit.limit,
          full: files.map(i => path.join(cwd, i)),
          files
        }
      })
    }))
  })
} else {
  const files = argv['_'].slice(0)

  let limit
  if (/^\d+(\.\d+|)$/.test(files[0]) && /^[kKMGT]?B$/.test(files[1])) {
    limit = bytes.parse(`${ files.shift() } ${ files.shift() }`)
  } else if (/^\d+(\.\d+|)?([kKMGT]B|B)?$/.test(files[0])) {
    limit = bytes.parse(files.shift())
  }

  if (limit) {
    warn([
      'Limit argument in Size Limit CLi was deprecated.',
      'Use `size-limit` section in `package.json` to specify limit.'
    ])
  }
  if (argv.babili) {
    warn([
      'Argument `--babili` was deprecated.',
      'Size Limit now supports ES2016 out of box.',
      'You can remove this argument.'
    ])
  }

  const full = files.map(i => {
    if (path.isAbsolute(i)) {
      return i
    } else {
      return path.join(process.cwd(), i)
    }
  })

  getOptions = Promise.resolve([
    {
      webpack: argv.webpack !== false,
      path: files,
      limit,
      full
    }
  ])
}

getOptions.then(files => {
  return Promise.all(files.map(file => {
    const opts = { bundle: file.bundle, webpack: file.webpack }
    if (file.ignore) {
      opts.ignore = Object.keys(file.ignore)
    }
    if (argv.why && files.length === 1) {
      opts.analyzer = process.env['NODE_ENV'] === 'test' ? 'static' : 'server'
    }
    return getSize(file.full, opts).then(size => {
      file.size = size
      return file
    })
  }))
}).then(files => {
  process.stdout.write('\n')

  const checks = files.map(file => {
    const limit = bytes.parse(file.limit)
    file.passed = true

    if (files.length > 1) {
      process.stdout.write(chalk.gray(`  ${ file.files }\n`))
    }

    if (limit && file.size <= limit) {
      process.stdout.write(
        `  Package size: ${ chalk.green(formatBytes(file.size)) }\n` +
        `  Size limit:   ${ formatBytes(limit) }\n`)
    } else if (limit) {
      process.stdout.write(
        `  ${ chalk.red('Package has exceeded the size limit') }\n` +
        `  Package size: ${ chalk.red(formatBytes(file.size)) }\n` +
        `  Size limit:   ${ formatBytes(limit) }\n`)
      file.passed = false
    } else {
      process.stdout.write(
        `  Package size: ${ formatBytes(file.size) }\n`)
    }

    if (files.length > 1) process.stdout.write('\n')
    return file
  })

  process.stdout.write(
    chalk.gray('  With all dependencies, minified and gzipped\n\n'))

  return checks
}).then(files => {
  if (argv.why && files.length > 1) {
    const opts = {
      analyzer: process.env['NODE_ENV'] === 'test' ? 'static' : 'server',
      bundle: files[0].bundle
    }
    const full = files.reduce((all, i) => all.concat(i.full), [])
    return getSize(full, opts).then(() => files)
  } else {
    return files
  }
}).then(files => {
  if (!argv.why) {
    if (files.some(i => !i.passed)) {
      process.exit(3)
    } else {
      process.exit(0)
    }
  }
}).catch(e => {
  let msg
  if (e.sizeLimit) {
    msg = e.message
      .split('. ')
      .map(i => i.replace(/`([^`]*)`/g, chalk.bold('$1')))
      .join('.\n        ')
  } else if (e.message.indexOf('Module not found:') !== -1) {
    const first = e.message.match(/Module not found:[^\n]*/)[0]
    msg = `Size Limit c${ first.replace('Module not found: Error: C', '') }`
      .replace(/resolve '(.*)' in '(.*)'/,
        `resolve\n        ${ chalk.bold('$1') }` +
        `\n        in ${ chalk.bold('$2') }`
      )
  } else {
    msg = e.stack
  }

  process.stderr.write(`${ chalk.bgRed(' ERROR ') } ${ chalk.red(msg) }\n`)
  process.exit(1)
})
<commit_msg>Better error for missed files in legacy API<commit_after>#!/usr/bin/env node
'use strict'

const ciJobNumber = require('ci-job-number')
const readPkg = require('read-pkg-up')
const globby = require('globby')
const yargs = require('yargs')
const chalk = require('chalk')
const bytes = require('bytes')
const path = require('path')

const getSize = require('.')

const argv = yargs
  .usage('$0')
  .option('why', {
    alias: 'w',
    describe: 'Show package content',
    type: 'boolean'
  })
  .option('no-webpack', {
    describe: 'Disable webpack',
    type: 'boolean'
  })
  .version()
  .help()
  .alias('help', 'h')
  .alias('version', 'v')
  .epilog('Usage:\n' +
          '  $0\n' +
          '    Read configuration from package.json and check limit.\n' +
          '  $0 --why\n' +
          '    Show reasons why project have this size.\n' +
          '  $0 index.js\n' +
          '    Check specific file size with all file dependencies.\n' +
          '\n' +
          'Size Limit will read size-limit section from package.json.\n' +
          'Configuration example:\n' +
          '\n' +
          '  "size-limit": [\n' +
          '    {\n' +
          '      "path": "index.js",\n' +
          '      "limit": "9 KB"\n' +
          '    }\n' +
          '  ]')
  .locale('en')
  .argv

function ownError (msg) {
  const error = new Error(msg)
  error.sizeLimit = true
  return error
}

function formatBytes (size) {
  return chalk.bold(bytes.format(size, { unitSeparator: ' ' }))
}

function warn (messages) {
  const prefix = `${ chalk.bgYellow.black(' WARN ') } `
  process.stderr.write(prefix + messages.map((message, index) => {
    const highlighted = message.replace(/`([^`]*)`/g, chalk.bold('$1'))
    const str = `${ chalk.yellow(highlighted) }\n`
    return index === 0 ? str : `       ${ str }`
  }).join(''))
}

if (ciJobNumber() !== 1) {
  process.stdout.write(
    chalk.yellow('Size Limits run only on first CI job, to save CI resources'))
  process.stdout.write('\n')
  process.exit(0)
}

let getOptions
if (argv['_'].length === 0) {
  getOptions = readPkg().then(result => {
    if (!result.pkg) {
      throw ownError(
        'Can not find `package.json`. ' +
        'Be sure that you run Size Limit inside project dir.'
      )
    } else if (!result.pkg['size-limit'] && !result.pkg['sizeLimit']) {
      throw ownError(
        'Can not find `"size-limit"` section in `package.json`. ' +
        'Add it according Size Limit docs.'
      )
    }

    if (result.pkg.sizeLimit) {
      warn([
        'Section name `"sizeLimit"` in package.json was deprecated.',
        'Use `"size-limit"` for section name.'
      ])
    }

    const limits = result.pkg['size-limit'] || result.pkg['sizeLimit']
    return Promise.all(limits.map(limit => {
      const cwd = path.dirname(result.path)
      return globby(limit.path, { cwd }).then(files => {
        if (files.length === 0) {
          files = limit.path
          if (typeof files === 'string') files = [files]
        }
        if (limit.babili) {
          warn([
            'Option `"babili": true` was deprecated.',
            'Size Limit now supports ES2016 out of box.',
            'You can remove this option.'
          ])
        }
        return {
          webpack: limit.webpack !== false,
          bundle: result.pkg.name,
          ignore: result.pkg.peerDependencies,
          limit: limit.limit,
          full: files.map(i => path.join(cwd, i)),
          files
        }
      })
    }))
  })
} else {
  const files = argv['_'].slice(0)

  let limit
  if (/^\d+(\.\d+|)$/.test(files[0]) && /^[kKMGT]?B$/.test(files[1])) {
    limit = bytes.parse(`${ files.shift() } ${ files.shift() }`)
  } else if (/^\d+(\.\d+|)?([kKMGT]B|B)?$/.test(files[0])) {
    limit = bytes.parse(files.shift())
  }

  if (limit) {
    warn([
      'Limit argument in Size Limit CLi was deprecated.',
      'Use `size-limit` section in `package.json` to specify limit.'
    ])
  }
  if (argv.babili) {
    warn([
      'Argument `--babili` was deprecated.',
      'Size Limit now supports ES2016 out of box.',
      'You can remove this argument.'
    ])
  }

  if (files.length === 0) {
    getOptions = Promise.reject(
      ownError(
        'Specify file for Size Limit. ' +
        `For example, \`size-limit ${ argv['_'] } index.js\`.`
      )
    )
  } else {
    const full = files.map(i => {
      if (path.isAbsolute(i)) {
        return i
      } else {
        return path.join(process.cwd(), i)
      }
    })

    getOptions = Promise.resolve([
      {
        webpack: argv.webpack !== false,
        path: files,
        limit,
        full
      }
    ])
  }
}

getOptions.then(files => {
  return Promise.all(files.map(file => {
    const opts = { bundle: file.bundle, webpack: file.webpack }
    if (file.ignore) {
      opts.ignore = Object.keys(file.ignore)
    }
    if (argv.why && files.length === 1) {
      opts.analyzer = process.env['NODE_ENV'] === 'test' ? 'static' : 'server'
    }
    return getSize(file.full, opts).then(size => {
      file.size = size
      return file
    })
  }))
}).then(files => {
  process.stdout.write('\n')

  const checks = files.map(file => {
    const limit = bytes.parse(file.limit)
    file.passed = true

    if (files.length > 1) {
      process.stdout.write(chalk.gray(`  ${ file.files }\n`))
    }

    if (limit && file.size <= limit) {
      process.stdout.write(
        `  Package size: ${ chalk.green(formatBytes(file.size)) }\n` +
        `  Size limit:   ${ formatBytes(limit) }\n`)
    } else if (limit) {
      process.stdout.write(
        `  ${ chalk.red('Package has exceeded the size limit') }\n` +
        `  Package size: ${ chalk.red(formatBytes(file.size)) }\n` +
        `  Size limit:   ${ formatBytes(limit) }\n`)
      file.passed = false
    } else {
      process.stdout.write(
        `  Package size: ${ formatBytes(file.size) }\n`)
    }

    if (files.length > 1) process.stdout.write('\n')
    return file
  })

  process.stdout.write(
    chalk.gray('  With all dependencies, minified and gzipped\n\n'))

  return checks
}).then(files => {
  if (argv.why && files.length > 1) {
    const opts = {
      analyzer: process.env['NODE_ENV'] === 'test' ? 'static' : 'server',
      bundle: files[0].bundle
    }
    const full = files.reduce((all, i) => all.concat(i.full), [])
    return getSize(full, opts).then(() => files)
  } else {
    return files
  }
}).then(files => {
  if (!argv.why) {
    if (files.some(i => !i.passed)) {
      process.exit(3)
    } else {
      process.exit(0)
    }
  }
}).catch(e => {
  let msg
  if (e.sizeLimit) {
    msg = e.message
      .split('. ')
      .map(i => i.replace(/`([^`]*)`/g, chalk.bold('$1')))
      .join('.\n        ')
  } else if (e.message.indexOf('Module not found:') !== -1) {
    const first = e.message.match(/Module not found:[^\n]*/)[0]
    msg = `Size Limit c${ first.replace('Module not found: Error: C', '') }`
      .replace(/resolve '(.*)' in '(.*)'/,
        `resolve\n        ${ chalk.bold('$1') }` +
        `\n        in ${ chalk.bold('$2') }`
      )
  } else {
    msg = e.stack
  }

  process.stderr.write(`${ chalk.bgRed(' ERROR ') } ${ chalk.red(msg) }\n`)
  process.exit(1)
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

var path = require('path')
var Dat = require('./')
var minimist = require('minimist')
var EOL = require('os').EOL
var url = require('url')
var stdout = require('stdout-stream')
var fs = require('fs')
var path = require('path')
var debug = require('debug')('dat.cli')

var onerror = function(err) {
  console.error('Error: ' + err.message)
  process.exit(2)
}

// rules:
// a 1 part command and a 2 part command can't share the same first part
// e.g. if 'dat cat' exists you can't add 'dat cat dog'

var bin = {
  "cat": './bin/cat',
  "export": './bin/cat',
  "import": './bin/import',
  "init": './bin/init',
  "help": './bin/help',
  "version": './bin/version',
  "pull": './bin/pull',
  "push": './bin/push',
  "clone": './bin/clone',
  "listen": './bin/listen',
  "blobs get": "./bin/blobs-get",
  "blobs put": "./bin/blobs-put"
}

var argv = minimist(process.argv.slice(2), {boolean: true})
var first = argv._[0] || ''
var second = argv._[1] || ''

var cmd = first
if (!bin.hasOwnProperty(first)) cmd = first + ' ' + second

var defaultMessage = "Usage: dat <command> [<args>]" + EOL + EOL + "Enter 'dat help' for help"
var badMessage = ['Command not found: ' + cmd, '', defaultMessage].join(EOL)

if (!bin.hasOwnProperty(first) && !bin.hasOwnProperty(cmd)) {
  console.error(badMessage)
  process.exit(1)
}

var dir = (cmd === 'clone' && argv._[2]) || argv.path || '.' // leaky
var initing = (cmd === 'init' || cmd === 'clone')

var dat = Dat(dir, {init: false}, function(err) {
  if (err) return onerror(err)

  var execCommand = function(err) {
    if (err) return onerror(err)
    require(bin[cmd])(dat, argv, function(err) {
      if (err) return onerror(err)
      setImmediate(close)
    })
  }

  if (!dat.db && !initing) return onerror(new Error('There is no dat here'))
  if (first !== 'listen' && !dat.rpcClient) return dat.listen(argv.port, argv, execCommand)
  execCommand()
})

function close() {
  // if _server exists it means dat is the rpc server
  if (dat._server) {
    // since the server process can't exit yet we must manually close stdout
    stdout.end()

    // if there aren't any active connections then we can close the server
    if (dat.connections.sockets.length === 0) dat.close()

    // otherwise wait for the current connections to close
    dat.connections.on('idle', function() {
      debug('dat close due to idle')
      dat.close()
    })

  } else {
    dat.close()
  }
}<commit_msg>clone always creates folder. fixes #179<commit_after>#!/usr/bin/env node

var path = require('path')
var Dat = require('./')
var minimist = require('minimist')
var EOL = require('os').EOL
var url = require('url')
var stdout = require('stdout-stream')
var fs = require('fs')
var path = require('path')
var debug = require('debug')('dat.cli')

var onerror = function(err) {
  console.error('Error: ' + err.message)
  process.exit(2)
}

// rules:
// a 1 part command and a 2 part command can't share the same first part
// e.g. if 'dat cat' exists you can't add 'dat cat dog'

var bin = {
  "cat": './bin/cat',
  "export": './bin/cat',
  "import": './bin/import',
  "init": './bin/init',
  "help": './bin/help',
  "version": './bin/version',
  "pull": './bin/pull',
  "push": './bin/push',
  "clone": './bin/clone',
  "listen": './bin/listen',
  "blobs get": "./bin/blobs-get",
  "blobs put": "./bin/blobs-put"
}

var argv = minimist(process.argv.slice(2), {boolean: true})
var first = argv._[0] || ''
var second = argv._[1] || ''

var cmd = first
if (!bin.hasOwnProperty(first)) cmd = first + ' ' + second

var defaultMessage = "Usage: dat <command> [<args>]" + EOL + EOL + "Enter 'dat help' for help"
var badMessage = ['Command not found: ' + cmd, '', defaultMessage].join(EOL)

if (!bin.hasOwnProperty(first) && !bin.hasOwnProperty(cmd)) {
  console.error(badMessage)
  process.exit(1)
}

var dir = (first === 'clone' && (argv._[2] || toFolder(argv._[1]))) || argv.path || '.' // leaky
var initing = (first === 'init' || first === 'clone')

var dat = Dat(dir, {init: false}, function(err) {
  if (err) return onerror(err)

  var execCommand = function(err) {
    if (err) return onerror(err)
    require(bin[cmd])(dat, argv, function(err) {
      if (err) return onerror(err)
      setImmediate(close)
    })
  }

  if (!dat.db && !initing) return onerror(new Error('There is no dat here'))
  if (first !== 'listen' && !dat.rpcClient) return dat.listen(argv.port, argv, execCommand)
  execCommand()
})

function toFolder(dir) {
  if (!dir) return dir
  return dir.replace(/^.*\/\//, '').replace(/[\/:].*$/, '')
}

function close() {
  // if _server exists it means dat is the rpc server
  if (dat._server) {
    // since the server process can't exit yet we must manually close stdout
    stdout.end()

    // if there aren't any active connections then we can close the server
    if (dat.connections.sockets.length === 0) dat.close()

    // otherwise wait for the current connections to close
    dat.connections.on('idle', function() {
      debug('dat close due to idle')
      dat.close()
    })

  } else {
    dat.close()
  }
}<|endoftext|>


<commit_before>#! /usr/bin/env node

/**
 * Copyright 2015 Mozilla
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var configure = require('./lib/configure');
var packageJson = require('./package.json');
var program = require('commander');

program
  .version(packageJson.version)
  .command('configure')
  .description('configure repository to auto-deploy to GitHub Pages using Travis CI')
  .action(function(env, options) {
    configure()
    .catch(function(err) {
      console.error(err);
    });
  });

program.parse(process.argv);

if (!process.argv.slice(2).length) {
  program.outputHelp();
}
<commit_msg>include program.parse in chain<commit_after>#! /usr/bin/env node

/**
 * Copyright 2015 Mozilla
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var configure = require('./lib/configure');
var packageJson = require('./package.json');
var program = require('commander');

program
  .version(packageJson.version)
  .command('configure')
  .description('configure repository to auto-deploy to GitHub Pages using Travis CI')
  .action(function(env, options) {
    configure()
    .catch(function(err) {
      console.error(err);
    });
  })
  .parse(process.argv);

if (!process.argv.slice(2).length) {
  program.outputHelp();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var path = require('path')
var Dat = require('./')
var minimist = require('minimist')
var EOL = require('os').EOL
var url = require('url')
var stdout = require('stdout-stream')
var fs = require('fs')
var path = require('path')
var rimraf = require('rimraf')
var debug = require('debug')('dat.cli')

var onerror = function(err) {
  console.error('Error: ' + err.message)
  process.exit(2)
}

// rules:
// a 1 part command and a 2 part command can't share the same first part
// e.g. if 'dat cat' exists you can't add 'dat cat dog'

var bin = {
  "cat": './bin/cat',
  "export": './bin/cat',
  "import": './bin/import',
  "init": './bin/init',
  "help": './bin/help',
  "version": './bin/version',
  "pull": './bin/pull',
  "push": './bin/push',
  "clean": './bin/clean',
  "clone": './bin/clone',
  "serve": './bin/listen',
  "listen": './bin/listen',
  "blobs get": "./bin/blobs-get",
  "blobs put": "./bin/blobs-put",
  "rows get": "./bin/rows-get",
  "rows delete": "./bin/rows-delete"
}

var argv = minimist(process.argv.slice(2), {boolean: true})
var first = argv._[0] || ''
var second = argv._[1] || ''

var cmd = first
if (!bin.hasOwnProperty(first)) cmd = first + ' ' + second

var defaultMessage = "Usage: dat <command> [<args>]" + EOL + EOL + "Enter 'dat help' for help"
var badMessage = ['Command not found: ' + cmd, '', defaultMessage].join(EOL)

if (!bin.hasOwnProperty(first) && !bin.hasOwnProperty(cmd)) {
  console.error(badMessage)
  process.exit(1)
}

var dir = (first === 'clone' && (argv._[2] || toFolder(argv._[1]))) || argv.path || '.' // leaky
var initing = (first === 'init' || first === 'clone')

var dat = Dat(dir, {init: false}, function(err) {
  if (err) return onerror(err)

  var execCommand = function(err) {
    if (err) return onerror(err)
    require(bin[cmd])(dat, argv, function(err) {
      if (err) return onerror(err)
      setImmediate(close)
    })
  }

  if (!dat.db && !initing) return onerror(new Error('There is no dat here'))
  if (first !== 'listen' && !dat.rpcClient) return dat.listen(argv.port, argv, execCommand)
  execCommand()
})

function toFolder(dir) {
  if (!dir) return dir
  return dir.replace(/^.*\/\//, '').replace(/[\/:].*$/, '')
}

function close() {
  // if _server exists it means dat is the rpc server
  if (dat._server) {
    // since the server process can't exit yet we must manually close stdout
    stdout.end()

    // if there aren't any active connections then we can close the server
    if (dat.connections.sockets.length === 0) dat.close()

    // otherwise wait for the current connections to close
    dat.connections.on('idle', function() {
      debug('dat close due to idle')
      dat.close()
    })

  } else {
    dat.close()
  }
}<commit_msg>fix various cli commands when not in a dat<commit_after>#!/usr/bin/env node

var path = require('path')
var Dat = require('./')
var minimist = require('minimist')
var EOL = require('os').EOL
var url = require('url')
var stdout = require('stdout-stream')
var fs = require('fs')
var path = require('path')
var rimraf = require('rimraf')
var debug = require('debug')('dat.cli')

var onerror = function(err) {
  console.error('Error: ' + err.message)
  process.exit(2)
}

// rules:
// a 1 part command and a 2 part command can't share the same first part
// e.g. if 'dat cat' exists you can't add 'dat cat dog'

var bin = {
  "cat": './bin/cat',
  "export": './bin/cat',
  "import": './bin/import',
  "init": './bin/init',
  "help": './bin/help',
  "version": './bin/version',
  "pull": './bin/pull',
  "push": './bin/push',
  "clean": './bin/clean',
  "clone": './bin/clone',
  "serve": './bin/listen',
  "listen": './bin/listen',
  "blobs get": "./bin/blobs-get",
  "blobs put": "./bin/blobs-put",
  "rows get": "./bin/rows-get",
  "rows delete": "./bin/rows-delete"
}

var argv = minimist(process.argv.slice(2), {boolean: true})
var first = argv._[0] || ''
var second = argv._[1] || ''

var cmd = first
if (!bin.hasOwnProperty(first)) cmd = first + ' ' + second

var defaultMessage = "Usage: dat <command> [<args>]" + EOL + EOL + "Enter 'dat help' for help"
var badMessage = ['Command not found: ' + cmd, '', defaultMessage].join(EOL)

if (!bin.hasOwnProperty(first) && !bin.hasOwnProperty(cmd)) {
  console.error(first ? badMessage : defaultMessage)
  process.exit(1)
}

var dir = (first === 'clone' && (argv._[2] || toFolder(argv._[1]))) || argv.path || '.' // leaky
var noDat = (first === 'init' || first === 'clone' || first === 'version' || first === 'help')

var dat = Dat(dir, {init: false}, function(err) {
  if (err) return onerror(err)

  var execCommand = function(err) {
    if (err) return onerror(err)
    require(bin[cmd])(dat, argv, function(err) {
      if (err) return onerror(err)
      setImmediate(close)
    })
  }

  if (!dat.db && !noDat) return onerror(new Error('There is no dat here'))
  if (first !== 'listen' && !dat.rpcClient) return dat.listen(argv.port, argv, execCommand)
  execCommand()
})

function toFolder(dir) {
  if (!dir) return dir
  return dir.replace(/^.*\/\//, '').replace(/[\/:].*$/, '')
}

function close() {
  // if _server exists it means dat is the rpc server
  if (dat._server) {
    // since the server process can't exit yet we must manually close stdout
    stdout.end()

    // if there aren't any active connections then we can close the server
    if (dat.connections.sockets.length === 0) dat.close()

    // otherwise wait for the current connections to close
    dat.connections.on('idle', function() {
      debug('dat close due to idle')
      dat.close()
    })

  } else {
    dat.close()
  }
}<|endoftext|>


<commit_before>var argv = require('minimist')(process.argv.slice(2))

if (!argv.length || argv.h || argv.help) {
  console.log(help())
}

function help () {
  return [
    'Usage:',
    '  matrix-bundler [entry] [opts]',
    '',
    'Options:',
    '  --help, -h           show help message',
    '  --entry, -e          the enrty point for bundler, default "."',
    '  --output, -o         the exported file bundle, default "./export.tgz"',
    '  --parent, -p         an asset id to import the files under, default "1"',
    '  --link, -l           the link type all assets will be imported as, default "TYPE_1"',
    '  --unrestricted, -u   whether unrestricted access is allowed, default "false"',
    '',
    'Examples:',
    '  matrix-bundler --entry ./files --link 2 --unrestricted --output ./files.tgz'
  ].join('\n')
}
<commit_msg>Add output variable to CLI<commit_after>var Bundler = require('../')
var argv = require('minimist')(process.argv.slice(2))
var fs = require('fs')

var bundle = Bundler()
var entry = argv.entry || argv.e || '.'
var output = argv.output || argv.o || './export.tgz'

if (!argv.length || argv.h || argv.help) {
  console.log(help())
}

bundle.createBundle()
  .pipe(fs.createWriteStream(output))

function help () {
  return [
    'Usage:',
    '  matrix-bundler [entry] [opts]',
    '',
    'Options:',
    '  --help, -h           show help message',
    '  --entry, -e          the enrty point for bundler, default "."',
    '  --output, -o         the exported file bundle, default "./export.tgz"',
    '  --parent, -p         an asset id to import the files under, default "1"',
    '  --link, -l           the link type all assets will be imported as, default "TYPE_1"',
    '  --unrestricted, -u   whether unrestricted access is allowed, default "false"',
    '',
    'Examples:',
    '  matrix-bundler --entry ./files --link 2 --unrestricted --output ./files.tgz'
  ].join('\n')
}
<|endoftext|>