Skip to content

Commit

Permalink
Merge pull request #30 from muricans/mbot-testing
Browse files Browse the repository at this point in the history
7.5.1
  • Loading branch information
muricans authored Jun 3, 2019
2 parents 6f97e7e + 162be26 commit 43206e7
Show file tree
Hide file tree
Showing 12 changed files with 408 additions and 200 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# mbot
<!--- [![Build Status](https://travis-ci.org/muricans/mbot.svg?branch=master)](https://travis-ci.org/muricans/mbot) -->
<!--- commented out for now -->

[mbot](https://github.com/muricans/mbot) is a discord bot created by [muricans](https://www.twitch.tv/muricanslol)
and edited by [felanbird](https://www.twitch.tv/felanbird)
Expand Down Expand Up @@ -48,3 +46,10 @@ Should you want to update the bot, simply run the update script.
```sh
$ ./update.sh
```

## Console Commands

| Command | Descriotion |
| ------- | ------------------------------- |
| stop | Stops the bot. |
| version | Gets version data from the bot. |
10 changes: 10 additions & 0 deletions commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const tools = new tls.Tools();
const fs = require('fs');
const Discord = require('discord.js');
const mute = require('./commands/mod/mute');
const timer = require('./commands/util/timer');

const cooldowns = new Discord.Collection();
module.exports.getCooldowns = (key) => {
Expand Down Expand Up @@ -233,6 +234,15 @@ module.exports.registerCommands = async (client, mbot) => {
if (!mute.guilds.has(message.guild.id)) {
mute.guilds.set(message.guild.id, new Discord.Collection());
}
if (!timer.users.has(message.author.id)) {
timer.users.set(message.author.id, new Discord.Collection());
const user = timer.users.get(message.author.id);
user.set('timers', new Discord.Collection());
user.set('dates', new Discord.Collection());
user.set('timeouts', new Discord.Collection());
user.set('names', new Discord.Collection());
user.set('ids', new Discord.Collection());
}
const muted = mute.guilds.get(message.guild.id);
if (muted.has(message.author.id)) {
message.delete();
Expand Down
83 changes: 63 additions & 20 deletions commands/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,71 @@ module.exports = {
description: 'Returns a random article with specified category if one is provided.',
async execute(message, args) {
const options = {
country: 'us',
language: 'en',
};
if (args[0] !== null) {
options.category = args[0];
if (args[0]) {
if (args[0].startsWith('c:')) {
const category = args[0].slice(2);
if (!category) {
return message.channel.send('Please define a category');
}
options.category = category;
} else if (args[0].startsWith('q:')) {
const query = args[0].slice(2).replace('_', ' ');
if (!query) {
return message.channel.send('Please define a query');
}
options.q = query;
} else {
return message.channel.send(`${message.author} Allowed params: 'q:', 'c:'`);
}
}
newsapi.v2.topHeadlines(options).then(body => {
const article = body.articles[Math.floor(Math.random() * body.articles.length)];
if (!article) {
return message.channel.send('No articles were found!');
if (args[1]) {
if (args[1].startsWith('c:')) {
const category = args[1].slice(2);
if (!category) {
return message.channel.send('Please define a category');
}
options.category = category;
} else if (args[1].startsWith('q:')) {
const query = args[1].slice(2).replace('_', ' ');
if (!query) {
return message.channel.send('Please define a query');
}
options.q = query;
} else {
return message.channel.send(`${message.author} Allowed params: 'q:', 'c:'`);
}
const embed = new Discord.RichEmbed()
.setTitle(article.title)
.setDescription(article.description)
.setAuthor(article.author)
.setURL(article.url)
.setThumbnail(article.urlToImage)
.setFooter('mbot uses News API to fetch articles.')
.setTimestamp(article.publishedAt);
return message.channel.send(embed);
}).catch(reason => {
console.log(reason);
});
}
if (args[0] && !options.category) {
newsapi.v2.everything(options).then(body => {
handleArticle(message, body);
}).catch(reason => {
console.log(reason);
});
} else {
options.country = 'us';
newsapi.v2.topHeadlines(options).then(body => {
handleArticle(message, body);
}).catch(reason => {
console.log(reason);
});
}
},
};
};

function handleArticle(message, body) {
const article = body.articles[Math.floor(Math.random() * body.articles.length)];
if (!article) {
return message.channel.send('No articles were found!');
}
const embed = new Discord.RichEmbed()
.setTitle(article.title)
.setDescription(article.description)
.setAuthor(article.author)
.setURL(article.url)
.setThumbnail(article.urlToImage)
.setFooter('mbot uses News API to fetch articles.')
.setTimestamp(article.publishedAt);
return message.channel.send(embed);
}
2 changes: 1 addition & 1 deletion commands/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ module.exports = {
case 4:
embed = new Discord.RichEmbed()
.setTitle('Commands')
.addField(prefix + `timer <time?'min','hour'> [name]`, 'Set a timer for the bot to remind you on when it completes.')
.addField(prefix + `timer <time?'min','hour'|cancel|list> [name]`, 'Set a timer for the bot to remind you on when it completes.')
.addField(prefix + 'unmute <user>', 'Unmute a muted user')
.addField(prefix + 'userinfo [user]', "Returns the designated user's info")
.addField(prefix + 'set <user> <points>', 'Sets the users points [admin only]')
Expand Down
70 changes: 65 additions & 5 deletions commands/util/timer.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,64 @@ const hourAlias = ['hour', 'hours', 'h', 'hr', 'hrs'];
module.exports = {
users: new Discord.Collection(),
name: 'timer',
usage: `<time?'min','hour'> [name]`,
usage: `<time?'min','hour'|cancel|list> [name]`,
description: 'Set a timer for the bot to remind you on when it completes.',
args: true,
minArgs: 1,
execute(message, args) {
if (args[0].toLowerCase() === "cancel") {
const user = this.users.get(message.author.id);
if (!user) {
return message.channel.send(`You don't have any timers set up right now!`);
}
if (!args[1]) {
return message.channel.send(`${message.author} Please provide your timers name!`);
}
const timerName = args.slice(1, args.length).join(' ');
const timerId = user.get('names').get(timerName.toLowerCase());
if (!timerId) {
return message.channel.send('Could not find a timer by that name!');
}
tools.deleteTimer(message.author.id, timerId, timerName);
return message.channel.send(`${message.author} Timer ${timerName} deleted successfully!`);
} else if (args[0].toLowerCase() === "list") {
const user = this.users.get(message.author.id);
const names = user.get('names').array();
const ids = user.get('ids');
let send = [];
for (let i = 0; i < names.length; i++) {
const exp = user.get('dates').get(names[i]) + user.get('timers').get(names[i]);
const left = (exp - Date.now()) / 1000;
let timeLeft = Math.floor(left);
if (timeLeft >= 3600) {
const mins = Math.floor((left / 60) % 60);
timeLeft = Math.floor(timeLeft / 3600);
timeLeft += ` hour(s) and ${mins} minute(s)`;
} else if (timeLeft >= 60) {
const secs = Math.floor(left % 60);
timeLeft = Math.floor(timeLeft / 60);
timeLeft += ` minute(s) and ${secs} second(s)`;
} else {
timeLeft += ` second(s)`;
}
send.push(`${ids.get(names[i])} - ${timeLeft}`);
}
send = send.join('\n');
if (send !== '') {
return message.channel.send(send).catch();
} else {
return message.channel.send(`${message.author} Could not find any timers!`);
}
}
if (!this.users.has(message.author.id)) {
this.users.set(message.author.id, new Discord.Collection());
}
const time = parseInt(args[0]);
if (!time) {
if (!time && !args[0].startsWith('t:')) {
return message.channel.send(`${message.author} Please use numbers!`);
}
let out = "Error occured";
const mil = tools.parseTime(args[0]);
let mil = tools.parseTime(args[0]);
if (hasMin(args[0]) && !hasHour(args[0])) {
const minutes = parseInt(args[0]);
if (minutes >= 60) {
Expand All @@ -37,10 +81,23 @@ module.exports = {
const sec = parseInt(args[0]);
if (sec >= 60) {
out = `${Math.floor(sec / 60)} minute(s)`;
} else if (sec >= 3600) {
out = `${Math.floor(sec / 3600)} hour(s)`;
} else {
out = `${sec} second(s)`;
}
}
if (args[0].startsWith('t:')) {
const timeArray = args[0].split(':').slice(1);
if (timeArray.length < 3 || timeArray.length > 3) {
return message.channel.send(`${message.author} Please follow the time format! hh:mm:ss`);
}
const hours = tools.parseTime(timeArray[0] + 'hour');
const minutes = tools.parseTime(timeArray[1] + 'min');
const seconds = tools.parseTime(timeArray[2]);
mil = hours + minutes + seconds;
out = `${timeArray[0]}:${timeArray[1]}:${timeArray[2]}`;
}
let wordNumbers = 'timer:';
wordNumbers += Math.floor(Math.random() * 15231).toString();
wordNumbers += Math.random() * 10;
Expand All @@ -50,10 +107,13 @@ module.exports = {
if (args[1] !== null) {
wordNumbers += name.split(' ').join('_');
}
console.log(wordNumbers);
const timerId = crypto.createHash('md5').update(wordNumbers).digest('hex');
const timerName = name === '' ? 'No name provided' : name;
tools.createTimer(message.author.id, mil, timerId, timerName);
if (this.users.get(message.author.id).get('names').has(timerName)) {
return message.channel.send('A timer with that name already exists!');
}
require('../../logger').debug(wordNumbers);
tools.createTimer(message.author.id, mil, timerId, timerName.toLowerCase());
return message.channel.send(`${message.author} Successfully created timer that will go off in ${out}\nName: ${timerName}`);
},
};
Expand Down
23 changes: 14 additions & 9 deletions commands/util/version.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
const pkg = require('../../package.json');
const Discord = require('discord.js');
const fs = require('fs');

module.exports = {
name: 'version',
usage: 'No usage data',
description: 'Gets the current version of the bot',
cooldown: 3,
execute(message) {
const embed = new Discord.RichEmbed()
.setTitle('mbot info')
.setThumbnail('https://hotemoji.com/images/dl/v/robot-face-emoji-by-twitter.png')
.setColor('#e9225f')
.addField('Version', `v${pkg.version}`, true)
.addField('Author', 'muricans', true)
.addField('Repository', '[GitHub](https://github.com/muricans/mbot)', true)
.addField('Documentation', '[Here](https://muricans.github.io/)', true);
message.channel.send(embed);
fs.readFile('./version.txt', 'utf8', (err, data) => {
if (err) return console.log(err);
const embed = new Discord.RichEmbed()
.setTitle('mbot info')
.setThumbnail('https://hotemoji.com/images/dl/v/robot-face-emoji-by-twitter.png')
.setColor('#e9225f')
.addField('Version', `v${pkg.version}`, true)
.addField('Author', 'muricans', true)
.addField('Repository', '[GitHub](https://github.com/muricans/mbot)', true)
.addField('Documentation', '[Here](https://muricans.github.io/)', true)
.setFooter(`Git commit: ${data}`, 'https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png');
message.channel.send(embed);
});
},
};
2 changes: 2 additions & 0 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ npm install snekfetch
npm install sqlite3
npm install newsapi
npm install crypto
npm install chalk
npm install figlet

chmod +x update.sh
chmod +x start.sh
Expand Down
6 changes: 5 additions & 1 deletion logger.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const fs = require('fs');
const settings = require('./settings.json');
const chalk = require('chalk');

const mbotLogStream = fs.createWriteStream('logs/mbot.log');
const isFileLogging = settings.fileLogging;
Expand Down Expand Up @@ -69,7 +70,10 @@ class Logger {
}

function rawLog(message, type) {
console.log(`[${time()} LEVEL-${type}]: ${message}`);
const open = chalk.yellow('[');
const close = chalk.yellow(']');
type = chalk.blue('LEVEL-' + type);
console.log(`${open}${chalk.green(time())} ${type}${close}: ${message}`);
if (isFileLogging) {
mbotLogStream.write(writeLog(message, type));
}
Expand Down
27 changes: 26 additions & 1 deletion mbot.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const Discord = require('discord.js');
const client = new Discord.Client();
const sqlite = require('sqlite3').verbose();
const Logger = require('./logger');
const figlet = require('figlet');
const chalk = require('chalk');

if (settings.token === "YOURTOKEN" || !settings.token.length) {
Logger.error('Please add your token to the bot!');
Expand Down Expand Up @@ -99,7 +101,7 @@ event.on('ready', () => {
event.on('timerFinished', (userId, timerId, timerName) => {
Logger.debug(`Timer ${timerId} has finished.`);
client.fetchUser(userId).then(user => {
user.send(`Your timer ${timerName} has finsihed!`);
user.send(`Your timer '${timerName}' has finished!`);
}).catch();
});
});
Expand Down Expand Up @@ -255,8 +257,31 @@ event.on('editCommand', (command, msg) => {
Logger.debug(`Command ${command.name}'s message was updated to ${msg}`);
});

console.log(chalk.magenta(figlet.textSync('mbot', {
font: "Doom",
horizontalLayout: "full",
})));

commands.registerCommands(client, this);

process.openStdin().on('data', (val) => {
const command = val.toString().trim();
switch (command.toLowerCase()) {
case "stop":
Logger.info('Stopping mbot...');
process.exit(0);
break;
case "version":
require('fs').readFile('./version.txt', 'utf8', (err, data) => {
if (err) return Logger.error(err.stack);
Logger.info(
`Application: mbot\n Version: ${pkg.version}\n Author: Muricans\n Git repo: https://github.com/muricans/mbot\n Git commit: ${data}\n Website: https://muricans.github.io/mbot`
);
});
break;
}
});

//login to the client
client.login(settings.token).catch(err => {
if (err) {
Expand Down
Loading

0 comments on commit 43206e7

Please sign in to comment.