diff --git a/.gitignore b/.gitignore index 1033fee..ec1ae03 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.gitignore/ data/config.js node_modules/ package-lock.json diff --git a/src/commands/command.js b/src/commands/command.js index 9a18626..bb4d343 100644 --- a/src/commands/command.js +++ b/src/commands/command.js @@ -1,10 +1,10 @@ /* Just random command info */ -module.exports = class Comamnd { +module.exports = class Command { /* * @param {String} description Description of command - * @param {String} example Example useage of command + * @param {String} example Example usage of command * @param {String or function(MessageInfo)} action Command action */ constructor (description, example, action) { @@ -12,4 +12,4 @@ module.exports = class Comamnd { this.example = example; this.action = action; } -} \ No newline at end of file +}; diff --git a/src/commands/command_handler.js b/src/commands/command_handler.js index 02b0ac3..2af41bd 100644 --- a/src/commands/command_handler.js +++ b/src/commands/command_handler.js @@ -33,8 +33,10 @@ module.exports = class CommandHandlerBase { if (this.simpleCommands.has(command)) { message.channel.send(this.simpleCommands.get(command).action); + return; } - else if (this.commands.has(command)) { + + if (this.commands.has(command)) { args.splice(0, 1);//remove command name const cmd = this.commands.get(command); cmd.action(message, args, client); @@ -76,8 +78,11 @@ module.exports = class CommandHandlerBase { .setColor("#09f228"); function addOutput(m) { - m.forEach(function(command, commandName, _) { - if (commandName === "help") return; + m.forEach((command, commandName, _) => { + if (commandName === "help") { + return; + } + output.addField(`**__${commandName}__**`, `Description: ${command.description}\nExample: *${command.example}*`); }); @@ -86,4 +91,4 @@ module.exports = class CommandHandlerBase { addOutput(this.commands); msgInfo.channel.send(output); } -} \ No newline at end of file +}; diff --git a/src/commands/default_command_handler.js b/src/commands/default_command_handler.js index 9836313..1e31279 100644 --- a/src/commands/default_command_handler.js +++ b/src/commands/default_command_handler.js @@ -1,5 +1,5 @@ const CommandHandler = require('./command_handler'); -const Util = require('../util') +const Util = require('../util'); module.exports = class DefaultCommands extends CommandHandler { constructor() { @@ -17,11 +17,10 @@ module.exports = class DefaultCommands extends CommandHandler { )*/ } - getCommands() { return new Map([...this.simpleCommands, ...this.commands]) } -} +}; //8-ball command const BALL_RESULTS = ["Yes.", "Reply hazy, try again.", "Without a doubt.", @@ -50,4 +49,4 @@ function eightball(message, args) // Get result const RESPONSE_INDEX = Util.getRandomInt(0, BALL_RESULTS.length); message.channel.send(`🎱 The Magic 8-Ball says: "${BALL_RESULTS[RESPONSE_INDEX]}" 🎱`); -} \ No newline at end of file +} diff --git a/src/commands/poll_command_handler.js b/src/commands/poll_command_handler.js index c42fb72..d0f0f1a 100644 --- a/src/commands/poll_command_handler.js +++ b/src/commands/poll_command_handler.js @@ -26,7 +26,7 @@ module.exports = class PollCommandHandler extends CommandHandler { pollOptions ); } -} +}; /** * Sends a poll message for a yes/no question @@ -35,6 +35,7 @@ module.exports = class PollCommandHandler extends CommandHandler { */ function pollYesno(message, args) { const question = args.join(" "); + if (question == "" || question == " ") { createHopsonPollingStationEmbed(message.channel, "Please add a question."); return; @@ -57,7 +58,7 @@ function pollYesno(message, args) { * @param {[String]} args List of string, the command arguments */ function pollOptions(message, args) { - // Make sure there's at least two choises + // Make sure there's at least two choices const channel = message.channel; if (validationDoesNotPass(args.length < 1, 'Not enough known to create a poll, please provide a question with options eg `">poll option "How many stars is my food?" 1 2 3 4 5"`', channel)) { return; @@ -65,10 +66,11 @@ function pollOptions(message, args) { if (validationDoesNotPass(!args[0].startsWith("\""), 'The question should be wrapped between two " characters.', channel)) { return; - } + } + //Extract question let question = ""; - let full = args.join(" ").slice(1) + let full = args.join(" ").slice(1); let isQuestion = false; for (const c of full) { full = full.slice(1); @@ -125,6 +127,7 @@ function validationDoesNotPass(validation, errorMessage, channel) { ); return true; } + return false; } @@ -134,7 +137,7 @@ function validationDoesNotPass(validation, errorMessage, channel) { * @param {Number} n The emoji to send, number from the array above */ function delayedReactWithNumber(message, n) { - // 0.5s timeout seems to be the best when theres a large number of options + // 0.5s timeout seems to be the best when there's a large number of options setTimeout(function() { message.react(NUM_EMOJIS[n]); }, 500*n); diff --git a/src/commands/ref_command_handler.js b/src/commands/ref_command_handler.js index 77020a6..44ba0b7 100644 --- a/src/commands/ref_command_handler.js +++ b/src/commands/ref_command_handler.js @@ -13,7 +13,7 @@ module.exports = class ReferenceCommandHandler extends CommandHandler { cppReference ); } -} +}; function cppReference(message, args) { const channel = message.channel; @@ -69,16 +69,16 @@ function cppReference(message, args) { } channel.send(msg); + return; } - else { - channel.send({embed: { - color: 16525315, - fields: [{ - name: "Error", - value: `I cannot find anything in C++ with ${args[0]}` - }] - }}); - } + + channel.send({embed: { + color: 16525315, + fields: [{ + name: "Error", + value: `I cannot find anything in C++ with ${args[0]}` + }] + }}); }) .catch((error) => { console.log(`Error: ${error}`); diff --git a/src/commands/role_command_handler.js b/src/commands/role_command_handler.js index 28228b5..26a5650 100644 --- a/src/commands/role_command_handler.js +++ b/src/commands/role_command_handler.js @@ -30,7 +30,7 @@ module.exports = class RoleEventHandler extends CommandHandler { removeRoles ) } -} +}; /** * Outpus number of members to a single discord role @@ -50,6 +50,7 @@ function listRoles(message) { break; } } + message.channel.send(output); } @@ -66,12 +67,14 @@ function countRole(message, args) { return role.name.toLowerCase() === args[0]; }); + let output = ''; + if (role === null) { - var output = `Role '${args[0]} does not exist.`; - } - else { - var output = `Number of users with role "**${args[0].toUpperCase()}**": ${role.members.size}`; + output = `Role '${args[0]} does not exist.`; + } else { + output = `Number of users with role "**${args[0].toUpperCase()}**": ${role.members.size}`; } + message.channel.send(output); } @@ -98,22 +101,27 @@ function modifyRoles(message, args, action) { } if (roleLists.validRoles.length > 0) { + let verb = ''; + let dir = ''; + //Add/ Remove the roles if (action === "add") { for (const role of roleLists.validRoles) { member.addRole(role) .then (console.log("Role add successful")); } - var verb = "added"; - var dir = "to"; + + verb = "added"; + dir = "to"; } else if (action === "remove") { for (role of roleLists.validRoles) { member.removeRole(role) .then (console.log("Role remove successful")); } - var verb = "removed"; - var dir = "from"; + + verb = "removed"; + dir = "from"; } //Send result const output = createOutput(roleLists.validRoles, message.author.id.toString(), verb, dir); @@ -132,15 +140,18 @@ function createOutput(rolesAdded, userID, verb, dir) { if (rolesAdded.length === 0) { return; } - const sp = rolesAdded.length == 1 ? "role" : "roles"; + + const sp = rolesAdded.length === 1 ? "role" : "roles"; const roleNames = rolesAdded.map((role) => { return role.name; }); + let output = `I have **${verb}** the following ${sp} ${dir} **<@${userID}>**:\n> ${roleNames.join("\n>")}\n\n`; - if (rolesAdded.length == 1) { + if (rolesAdded.length === 1) { output += `Psst... Are you aware you can have multiple roles ${verb} at once? Give it a go!\n`; output += `Example: \`>role add/remove C++ Java Rust\``; } + return output; } @@ -153,23 +164,26 @@ function extractRoles(guild, roleList) { const result = { validRoles: [], invalidRoles: [] - } + }; + const modifiableRoles = Config.modifiableRoles.map(val => val.toLowerCase()); for (const roleName of roleList) { if (modifiableRoles.indexOf(roleName) > -1) { const role = guild.roles.find((roleToFind) => { return roleToFind.name.toLowerCase() === roleName; }); + if (role !== null) { result.validRoles.push(role); - } - else { - result.invalidRoles.push(roleName); + continue; } - } - else { + result.invalidRoles.push(roleName); + continue; } + + result.invalidRoles.push(roleName); } + return result; } diff --git a/src/deprecated/game_command_handler.js b/src/deprecated/game_command_handler.js index 14f85e8..edaa1c9 100644 --- a/src/deprecated/game_command_handler.js +++ b/src/deprecated/game_command_handler.js @@ -1,4 +1,4 @@ -const CommandHandler = require ("./command_handler") +const CommandHandler = require ("./command_handler"); const GuessingGame = require ('../games/guessing_game'); const GAME_GUESS_NUM = 0; @@ -6,7 +6,7 @@ const GAME_GUESS_NUM = 0; module.exports = class GameCommandHandler extends CommandHandler { constructor(gameSessions) { super('game'); - this.games = [] + this.games = []; this.initCommands(); this.gameSessions = gameSessions } @@ -21,13 +21,13 @@ module.exports = class GameCommandHandler extends CommandHandler { ) } - guessNumber(message, args) { + guessNumber(message) { if (!this.games[GAME_GUESS_NUM]) { this.games[GAME_GUESS_NUM] = true; this.gameSessions.push(new GuessingGame(message.channel, this.gameSessions)); + return; } - else { - message.channel.send("Sorry but guessing number game is already active."); - } + + message.channel.send("Sorry but guessing number game is already active."); } -} \ No newline at end of file +}; diff --git a/src/deprecated/games/guessing_game.js b/src/deprecated/games/guessing_game.js index 60ec1a6..c5f4ddc 100644 --- a/src/deprecated/games/guessing_game.js +++ b/src/deprecated/games/guessing_game.js @@ -1,5 +1,3 @@ - - module.exports = class GuessingGame { constructor(channel, sessions) { this.channel = channel; @@ -11,19 +9,27 @@ module.exports = class GuessingGame { update(message) { const channel = message.channel; - if (channel === this.channel) { - if (!isNaN(message.content)) { - const n = Number(message.content); - if (n === this.number) { - channel.send(`${message.author} guessed correct! The number was ${this.number}`); - } - else if (n > this.number) { - channel.send(`${n} guessed, but it is too big!`) - } - else { - channel.send(`${n} guessed, but it is too small!`) - } - } + + if (channel !== this.channel) { + return; } + + if (isNaN(message.content)) { + return; + } + + const n = Number(message.content); + + if (n === this.number) { + channel.send(`${message.author} guessed correct! The number was ${this.number}`); + return; + } + + if (n > this.number) { + channel.send(`${n} guessed, but it is too big!`); + return; + } + + channel.send(`${n} guessed, but it is too small!`); } -} \ No newline at end of file +}; diff --git a/src/deprecated/mine_command_handler.js b/src/deprecated/mine_command_handler.js index 077ba66..ad35565 100644 --- a/src/deprecated/mine_command_handler.js +++ b/src/deprecated/mine_command_handler.js @@ -19,7 +19,7 @@ module.exports = class MineCommandHandler extends CommandHandler { mineGen ); } -} +}; /** * @@ -31,24 +31,26 @@ function mineGen(message, args, client) { const mx = args[0]; const my = args[1]; const mines = args[2]; - var str0 = ""; + let str0 = ""; + if (mx > 15 || my > 15 || mines >= mx*my*(2/3)){ message.channel.send("Invalid parameters"); - } else { - message.channel.send("Sending minefield"); - var grid = generateMap(mx, my, mines); - var str0 = createView(grid); - str0 = message.author.username + " here is your mine field :triangular_flag_on_post: \n" + str0; - message.author.send(str0); + return; } + + message.channel.send("Sending minefield"); + let grid = generateMap(mx, my, mines); + str0 = createView(grid); + str0 = message.author.username + " here is your mine field :triangular_flag_on_post: \n" + str0; + message.author.send(str0); } function generateMap(mx, my, mines) { - var grid = []; - for (var y=0; y= mx || ny >= my) - continue; + if (nx < 0 || ny < 0 || nx >= mx || ny >= my) { + continue; + } if (grid[ny][nx] == 'x') { nmines += 1; @@ -100,23 +104,23 @@ function generateMap(mx, my, mines) { } function createView(grid) { - var str0 = ""; - - var mx = grid.length; - var my = grid[0].length; + let str0 = ""; + let mx = grid.length; + let my = grid[0].length; - var str0 = ""; + for (let y = 0; y < my; y++) { - for (var y=0; yquiz help"); return; } + let quizChnnels = Config.quizChannels; if (quizChnnels.indexOf(channel.name) === -1) { Bot.sendMessage(message.channel, `To avoid spam, quizzes only work in the following channels:\n>${quizChnnels.join("\n>")}`); @@ -48,13 +49,12 @@ module.exports = class QuizEventHandler extends CommandHandlerBase tryStartQuiz(message, args) { if (this.quizActive) { - Bot.sendMessage(message.channel, - `Sorry, a quiz is currently active in ${this.session.channel.name}`); - } - else { - this.quizActive = true; - this.session = new QuizSession(message.channel); + Bot.sendMessage(message.channel, `Sorry, a quiz is currently active in ${this.session.channel.name}`); + return; } + + this.quizActive = true; + this.session = new QuizSession(message.channel); } endQuiz() @@ -72,34 +72,41 @@ module.exports = class QuizEventHandler extends CommandHandlerBase if (!this.quizActive) { Bot.sendMessage(channel, `Sorry, a quiz is not active.`); + return; } - else if (!channelHasQuizSession(message.channel)) { //Cannot end a quiz from a different channel + + if (!channelHasQuizSession(message.channel)) { //Cannot end a quiz from a different channel Bot.sendMessage(channel, `Sorry, you can not end a quiz from a different channel from which is currently active, which is **'${this.session.channel.name}'**.`); + return; } - else { - this.endQuiz(); - Bot.sendMessage(channel, `Quiz has been stopped manually by <@${user.id}>`) - } + + this.endQuiz(); + Bot.sendMessage(channel, `Quiz has been stopped manually by <@${user.id}>`) } submitAnswer(message, answer) { - if (!this.quizActive) return; - if (!channelHasQuizSession(message.channel)) return; + if (!this.quizActive) { + return; + } + + if (!channelHasQuizSession(message.channel)) { + return; + } this.session.submitAnswer(message.member, answer); } - printQuestion(message, args) + printQuestion() { - if(this.quizActive) { + if (this.quizActive) { this.session.printQuestion("Question reminder"); } } - trySkip(message, args) + trySkip(message) { - if(this.quizActive) { + if (this.quizActive) { this.session.addSkip(message.member); } } @@ -115,7 +122,7 @@ module.exports = class QuizEventHandler extends CommandHandlerBase `Quiz Categories:\n>${QuizJSON.categories.join("\n>")}`, "Shows a list of quiz catergories.", "quiz cats" - ) + ); super.addFunctionCommand( "start", @@ -130,7 +137,7 @@ module.exports = class QuizEventHandler extends CommandHandlerBase this.tryEndQuiz.bind(this), "Ends the quiz session.", "quiz end" - ) + ); super.addFunctionCommand( "add", @@ -138,77 +145,82 @@ module.exports = class QuizEventHandler extends CommandHandlerBase "Adds a new question to the quiz log, requies a quiz category, question, and answer.", `quiz add Maths "What is 5 + 5?" "10"`, true - ) + ); super.addFunctionCommand( "skip", this.trySkip.bind(this), "Skips the question; but requirs 1/2 of the quiz participants to do so.", "quiz skip", - ) + ); super.addFunctionCommand( "remind", this.printQuestion.bind(this), "Resends the question to remind you what it was.", "quiz remind", - ) + ); super.addFunctionCommand( "cat-count", countQuestions, "Counts the number of questions in each category, and outputs the results.", "quiz cat-count", - ) + ); super.addFunctionCommand( "author-count", countAuthors, "Says how many questions the authors have submitted", "quiz author-count" - ) + ); } -} +}; //Adds a question to the JSON file function addQuestion(category, qu, ans, authorID) { //Open the JSON file - fs.readFile(questionsFile, 'utf8', function read(err, data){ - if(err) { - console.log(err) - } - else { - let qFile = JSON.parse(data); //Read file into a json object - qFile.questions.push({ //Add question to the questions array - cat: category, - question: qu, - answer: ans, - author: authorID - }); - let qOut = JSON.stringify(qFile, null, 4); //Rewrite the file - fs.writeFile(questionsFile, qOut, function(err){console.log(err);}); + fs.readFile(questionsFile, 'utf8', (err, data) => { + if (err) { + console.log(err); + return; } + + let qFile = JSON.parse(data); //Read file into a json object + qFile.questions.push({ //Add question to the questions array + cat: category, + question: qu, + answer: ans, + author: authorID + }); + let qOut = JSON.stringify(qFile, null, 4); //Rewrite the file + fs.writeFile(questionsFile, qOut, console.log); }); } + //on tin function tryAddQuestion(message, args) { let channel = message.channel; let user = message.member; + console.log(args); + //Check question length let inFile = JSONFile.readFileSync(questionsFile); - if (args.length == 0 || args.length < 3) { + if (args.length === 0 || args.length < 3) { Bot.sendMessage(channel, "You have not provided me with enough information to add a question; I must know the category, question, and the answer to the question."); return; } + //Check if the category input is valid let category = args[0]; if (inFile.categories.indexOf(category) === -1) { Bot.sendMessage(channel, `Category "${category}" doesn't exist. To see the list, use __*>quiz cats*__, and use correct casing.`) return; } + //Outputs a message for when the parsing of the strings fails function parseFail() { Bot.sendMessage(channel, `For me to recognise a question/ answer, you must start and end your question with"`); @@ -221,12 +233,14 @@ function tryAddQuestion(message, args) parseFail(); return; } + //Get answer let [res2, answer, f] = Util.extractStringFromArray(newArgs); if (!res2) { parseFail(); return; } + //Finally if all validations passed, add the question addQuestion(category, question, answer, user.id); Bot.sendMessage(channel, new Discord.RichEmbed() @@ -239,26 +253,31 @@ function tryAddQuestion(message, args) } //Outputs the number of questions created by people who have created questions. -function countAuthors(message, args) +function countAuthors(message) { let inFile = JSONFile.readFileSync(questionsFile); let questions = inFile.questions; let result = new Map(); + //Count the authors - for (var question of questions) { + for (let question of questions) { let author = question.author; - if(result.has(author)) { + + if (result.has(author)) { let currentCount = result.get(author); result.set(author, currentCount + 1); - } else { - result.set(author, 1); + continue; } + + result.set(author, 1); } + let output = new Discord.RichEmbed() .setTitle("Total Questions for each Author") .setColor(embedColour); + this.count = 0; - result.forEach(function(val, key, map) { + result.forEach(function(val, key) { output.addField(`${val.toString()} questions by:`,`<@${key}>`, true); this.count++; if (this.count % 3 == 0) { @@ -270,27 +289,30 @@ function countAuthors(message, args) } //Creates a count of how many questions are in each category -function countQuestions(message, args) +function countQuestions(message) { let inFile = JSONFile.readFileSync(questionsFile); let cats = inFile.categories; let questions = inFile.questions; let result = new Map(); let total = 0; - for (var category of cats) { + + for (let category of cats) { result.set(category, 0); } - for (var question of questions) { - var val = result.get(question.cat); + + for (let question of questions) { + let val = result.get(question.cat); result.set(question.cat, val + 1); total++; } + let output = new Discord.RichEmbed() .setTitle("Total Questions in each Category") .setColor(embedColour) .addField("Total", total.toString(), true); - result.forEach(function(val, key, map) { + result.forEach((val, key, map) => { output.addField(key, val.toString(), true); }); Bot.sendMessage(message.channel, output); -} \ No newline at end of file +} diff --git a/src/deprecated/quiz/quiz_session.js b/src/deprecated/quiz/quiz_session.js index f8dd7a9..284ba02 100644 --- a/src/deprecated/quiz/quiz_session.js +++ b/src/deprecated/quiz/quiz_session.js @@ -1,9 +1,9 @@ -const questionsFile = "data/quiz_questions.json"; +const questionsFile = 'data/quiz_questions.json'; -const Bot = require("../main"); -const Util = require("../util"); +const Bot = require('../main'); +const Util = require('../util'); const JSONFile = require('jsonfile'); -const Discord = require('discord.js') +const Discord = require('discord.js'); const embedColour = 0x28abed; const MAX_USERS = 24; @@ -54,7 +54,7 @@ module.exports = class QuizSession //Initiates the next question for the quiz nextQuestion() { - this.users.forEach(function(user, key, map) { + this.users.forEach(function(user) { user.hasSkipped = false; }.bind(this)); this.skipVotes = 0; @@ -65,7 +65,7 @@ module.exports = class QuizSession //Adds a member to this quiz session if they have not yet been added tryAddUser(member) { - if(!this.users.has(member) && this.users.size < MAX_USERS) { + if (!this.users.has(member) && this.users.size < MAX_USERS) { this.users.set(member, new QuizUser()); } } @@ -75,29 +75,29 @@ module.exports = class QuizSession { this.tryAddUser(member); //A user cannot skip twice - if(this.users.get(member).hasSkipped) { + if (this.users.get(member).hasSkipped) { this.sendMessage(new Discord.RichEmbed() - .setTitle(`You cannot vote to skip twice, ${member.displayName}, sorry.`)) + .setTitle(`You cannot vote to skip twice, ${member.displayName}, sorry.`)); + return; } - else { - this.users.get(member).hasSkipped = true - this.skipVotes++; - let skipsNeeded = Math.floor(this.users.size / 2); - //Check if the current question is able to be skipped - if (this.skipVotes >= skipsNeeded) { - this.sendMessage(new Discord.RichEmbed() - .setTitle("Question Skipped!") - .addField("Question", this.question.question) - .addField("Answer", this.question.answer)); - this.nextQuestion(); - } - else { - this.sendMessage(new Discord.RichEmbed() - .setTitle("Skip Vote Registered") - .addField("Current Votes", this.skipVotes.toString(), true) - .addField("Votes Needed", skipsNeeded.toString(), true)); - } + + this.users.get(member).hasSkipped = true; + this.skipVotes++; + let skipsNeeded = Math.floor(this.users.size / 2); + //Check if the current question is able to be skipped + if (this.skipVotes >= skipsNeeded) { + this.sendMessage(new Discord.RichEmbed() + .setTitle("Question Skipped!") + .addField("Question", this.question.question) + .addField("Answer", this.question.answer)); + this.nextQuestion(); + return; } + + this.sendMessage(new Discord.RichEmbed() + .setTitle("Skip Vote Registered") + .addField("Current Votes", this.skipVotes.toString(), true) + .addField("Votes Needed", skipsNeeded.toString(), true)); } //Gets a random question from the main JSON file @@ -105,8 +105,7 @@ module.exports = class QuizSession { let inFile = JSONFile.readFileSync(questionsFile); let qIndex = Util.getRandomInt(0, inFile.questions.length); - let question = new Question(inFile.questions[qIndex]); - return question; + return new Question(inFile.questions[qIndex]); } //Displays the question @@ -152,13 +151,15 @@ module.exports = class QuizSession //Submits an answer to current question, and if the question is answered correctly, then it gets the next question submitAnswer(member, answer) { - if (answer.toLowerCase() == this.question.answer.toLowerCase()) { - this.sendMessage(new Discord.RichEmbed() - .setTitle("Answered sucessfully!") - .addField("Answered By", `<@${member.id}>`)); - this.addPointTo(member); - this.outputScores("Current"); - this.nextQuestion(); + if (answer.toLowerCase() !== this.question.answer.toLowerCase()) { + return; } + + this.sendMessage(new Discord.RichEmbed() + .setTitle("Answered successfully!") + .addField("Answered By", `<@${member.id}>`)); + this.addPointTo(member); + this.outputScores("Current"); + this.nextQuestion(); } -} \ No newline at end of file +}; diff --git a/src/deprecated/quiz_command_handler.js b/src/deprecated/quiz_command_handler.js index 71109b4..3cfbcf5 100644 --- a/src/deprecated/quiz_command_handler.js +++ b/src/deprecated/quiz_command_handler.js @@ -21,9 +21,9 @@ module.exports = class PollCommandHandler extends CommandHandler { ) } -} +}; -function addQuizQuestion(message, args) { - const channel = message.channel; - const author = message.author; -} \ No newline at end of file +// function addQuizQuestion(message, args) { +// const channel = message.channel; +// const author = message.author; +// } diff --git a/src/deprecated/words_command_handler.js b/src/deprecated/words_command_handler.js index 8dffb3a..4a647b3 100644 --- a/src/deprecated/words_command_handler.js +++ b/src/deprecated/words_command_handler.js @@ -25,7 +25,7 @@ module.exports = class WordCommandHandler extends CommandHandler { countWords ); } -} +}; function doAction(callback) { fs.readFile("data/words_db.json", 'utf8', (err, data) => { @@ -33,6 +33,7 @@ function doAction(callback) { console.log("Error reading file: " + err); return; } + const words = JSON.parse(data); callback(words); }); @@ -44,16 +45,20 @@ function topNWords(message, args, client) { } doAction(words => { const n = parseInt(args[0]); + if (n != NaN) { const topWords = words.slice(0, Math.min(Math.min(words.length, n), 10)); + const output = new Discord.RichEmbed() .setTitle(`Top ${n} Words`); + for (const idx in topWords) { output.addField( `Rank ${(parseInt(idx) + 1)}`, `***${topWords[idx].w}***, said ***${topWords[idx].c}*** times` ); } + message.channel.send(output); } @@ -64,9 +69,11 @@ function countWords(message, args, client) { if (args.length < 1) { return; } + console.log("Seratrching"); doAction(words => { const search = args[0]; + for (const word of words) { if (word.w == search) { console.log("Found"); @@ -74,6 +81,7 @@ function countWords(message, args, client) { return; } } + message.channel.send(`${search} has never been said`); }); } diff --git a/src/events/member_join_handler.js b/src/events/member_join_handler.js index 73b9d81..40f3ae3 100644 --- a/src/events/member_join_handler.js +++ b/src/events/member_join_handler.js @@ -1,5 +1,5 @@ -const Config = require("../../data/config.json"); -const Discord = require('discord.js') +const Config = require('../../data/config.json'); +const Discord = require('discord.js'); const dateFormat = require('dateformat'); //TODO @@ -22,7 +22,7 @@ Enjoy! :)` ); */ } -} +}; function checkAccountAge(member, client) { const channelName = Config.memberJoinChannel; @@ -39,17 +39,12 @@ function checkAccountAge(member, client) { .addField("**Join Date**", join) .addField("**Time Between Create and Join (est)**", diff.regularDiff) .addField("**Milliseconds Difference**", diff.unixTimeDiff); - - if (diff.notify) { - embed.setColor(16711680); - } else { - embed.setColor(65280); - } + + embed.setColor(diff.notify ? 16711680 : 65280); channel.send(embed); } - function getTimeDifference(join, create) { const diff = join - create; const diffDate = new Date(diff); diff --git a/src/events/member_leave_handler.js b/src/events/member_leave_handler.js index 4ebd37e..cbe7cea 100644 --- a/src/events/member_leave_handler.js +++ b/src/events/member_leave_handler.js @@ -1,4 +1,4 @@ -const Config = require("../../data/config.json"); +const Config = require('../../data/config.json'); /** * Event handler for leaving and that @@ -13,4 +13,4 @@ module.exports = { //cya channel.send(`"${user}" has left the server. ID: <@${id}> - ${id}`); } -} \ No newline at end of file +}; diff --git a/src/events/member_update_event.js b/src/events/member_update_event.js index c5c2d6d..a4bdfdf 100644 --- a/src/events/member_update_event.js +++ b/src/events/member_update_event.js @@ -1,12 +1,11 @@ const Discord = require('discord.js'); module.exports = { - handleUserUpdate: function (client, oldUser, newUser) - { + handleUserUpdate: (client, oldUser, newUser) => { let botlog = client.channels.get("362124431801450526"); let time = (new Date()).toLocaleString('en-GB'); - if (oldUser.username != newUser.username){ + if (oldUser.username != newUser.username) { let embed = new Discord.RichEmbed() .setDescription(`Username Change at ${time}`) .setColor(9699539) @@ -16,4 +15,4 @@ module.exports = { botlog.send(embed); } } -} +}; diff --git a/src/events/message_mod_handler.js b/src/events/message_mod_handler.js index 5f71b3d..d5970b9 100644 --- a/src/events/message_mod_handler.js +++ b/src/events/message_mod_handler.js @@ -15,19 +15,21 @@ module.exports = { const botLog = getBotLogChannel(client); const time = (new Date()).toLocaleString('en-GB'); const content = sliceLongMessage(message.content); - if (content.length == 0) { + + if (content.length === 0) { return; } + botLog.send(new Discord.RichEmbed() .setDescription(`${message.author} in ${message.channel} at ${time}`) .setColor(16711680) .addField("Deleted Message", content)); - }, handleMessageUpdate: (client, oldMessage, newMessage) => { - if (isChannelBlacklisted(oldMessage.channel)) return; - if(oldMessage.content === newMessage.content) return; + if (oldMessage.content === newMessage.content || isChannelBlacklisted(oldMessage.channel)) { + return; + } const botLog = getBotLogChannel(client); const time = (new Date()).toLocaleString('en-GB'); @@ -42,22 +44,26 @@ module.exports = { botLog.send(embed); } -} +}; function sliceLongMessage(message) { - if (message.length > 1000) message = message.slice(0,1000) + " ..."; - return message + if (message.length > 1000) { + message = `${message.slice(0, 1000)} ...`; + } + + return message; } function isChannelBlacklisted(channel) { - for (var blacklistedChannel of Config.logBlacklistedChannels) { + for (let blacklistedChannel of Config.logBlacklistedChannels) { if (channel.id == blacklistedChannel) { return true; } } + return false; } function getBotLogChannel(client) { - return client.channels.get("362124431801450526"); + return client.channels.get('362124431801450526'); } diff --git a/src/events/message_sent_handler.js b/src/events/message_sent_handler.js index e716269..d7f8b55 100644 --- a/src/events/message_sent_handler.js +++ b/src/events/message_sent_handler.js @@ -3,7 +3,7 @@ const RoleCommandHandler = require('../commands/role_command_handler'); const DefaultCommandHandler = require('../commands/default_command_handler'); const RefCommandHandler = require('../commands/ref_command_handler'); const Config = require('../../data/config.json'); -const Discord = require('discord.js') +const Discord = require('discord.js'); /** * Class to handle messages sent by the user @@ -20,6 +20,7 @@ module.exports = class MessageSentHandler { new RefCommandHandler(), ] } + /** * Entry point for handling messages * @param {Discord.TextMessage} message The raw message sent by a user @@ -35,13 +36,15 @@ module.exports = class MessageSentHandler { (message.author.bot)) { return; } - else if (message.channel.name === Config.newMemberChannel) { + if (message.channel.name === Config.newMemberChannel) { let newMemberRole = message.member.guild.roles.find('name', Config.newMemberRole); let introduceRole = message.member.guild.roles.find('name', Config.introRole); message.member.removeRole(newMemberRole); message.member.addRole(introduceRole); + return; } - else if (message.content.startsWith('>')) { + + if (message.content.startsWith('>')) { this.handleCommand(message, client); } } @@ -74,24 +77,28 @@ module.exports = class MessageSentHandler { return; } } - if(commandCategory === "help") { + + if (commandCategory === "help") { this._sendHelpList(message.channel); + return; } - else { - args.unshift(commandCategory); - this.defaultCommandHandler.handleCommand(message, args, client); - } + + args.unshift(commandCategory); + this.defaultCommandHandler.handleCommand(message, args, client); } _sendHelpList(channel) { let defaultCommands = this.defaultCommandHandler.getCommands(); let output = new Discord.RichEmbed() .setTitle("HopsonBot Command List") - .setColor("#09f228");; + .setColor("#09f228"); defaultCommands.forEach((command, commandName, _) => { - if (commandName === "help") return; - output.addField(`**__${commandName}__**`, + if (commandName === "help") { + return; + } + + output.addField(`**__${commandName}__**`, `Description: ${command.description}\nExample: *${command.example}*`); }); @@ -102,14 +109,14 @@ module.exports = class MessageSentHandler { } channel.send(output); } -} +}; function logMessageInfo(message) { const ch = message.channel.name; - const user = message.member ? message.member.displayName : "No name"; + const user = message.member ? message.member.displayName : 'No name'; const msg = message.content; - console.log("============") + console.log("============"); console.log(`Message Sent\nChannel: ${ch}\nUser: ${user}\nContent: ${msg}\n`); console.log("============\n") -} \ No newline at end of file +} diff --git a/src/hopson_bot.js b/src/hopson_bot.js index 6a14c4c..7dc2e4f 100644 --- a/src/hopson_bot.js +++ b/src/hopson_bot.js @@ -1,6 +1,6 @@ const MessageSentHandler = require('./events/message_sent_handler'); const MessageModifyHandler = require('./events/message_mod_handler'); -const MemeberJoinHandler = require('./events/member_join_handler'); +const MemberJoinHandler = require('./events/member_join_handler'); const MemberUpdateHandler = require('./events/member_update_event'); const MemberLeaveHandler = require('./events/member_leave_handler'); @@ -19,7 +19,7 @@ module.exports = class HopsonBot { .catch(console.error); }); - //Event for when bot is dissconnected + //Event for when bot is disconnected this.client.on("disconnect", event => { console.log(`Client has closed with status code ${event.code} and reason ${event.reason}`) }); @@ -49,16 +49,16 @@ module.exports = class HopsonBot { //Event for people joining the server this.client.on("guildMemberAdd", member => { - MemeberJoinHandler.handleJoin(member, this.client); + MemberJoinHandler.handleJoin(member, this.client); }); this.client.on("guildMemberRemove", member => { MemberLeaveHandler.handleLeave(member, this.client); - }) + }); - //Event for a user update (eg changing their usernem) + //Event for a user update (eg changing their username) this.client.on("userUpdate", (oldUser, newUser) => { MemberUpdateHandler.handleUserUpdate(this.client, oldUser, newUser); }); } -} +}; diff --git a/src/main.js b/src/main.js index 39559c2..8298402 100644 --- a/src/main.js +++ b/src/main.js @@ -1,10 +1,10 @@ const Discord = require('discord.js'); const Config = require('../data/config'); -const HopsonBot = require('./hopson_bot') +const HopsonBot = require('./hopson_bot'); const client = new Discord.Client(); //Entry point of the bot itself new HopsonBot(client).runBot(); -client.login(Config.getToken()); \ No newline at end of file +client.login(Config.getToken()); diff --git a/src/util.js b/src/util.js index 9e60360..b1b5b26 100644 --- a/src/util.js +++ b/src/util.js @@ -1,36 +1,38 @@ - module.exports = { - getRandomInt : function(min, max) - { - return Math.floor((Math.random() * (max - min) + min)); - }, - - extractStringFromArray : function(args) - { - if(!args[0].startsWith("\"")) { + getRandomInt: (min, max) => Math.floor((Math.random() * (max - min) + min)), + extractStringFromArray : args => { + if (!args[0].startsWith('"')) { return [false, "", null]; } + let str = args[0].slice(1); //remove the starting " from the string - args = args.slice(1); //remove first word as it has already been added + args = args.slice(1); //remove first word as it has already been added + let endFound = false; - //Iterate through the array passed in, and search for the end of a string - var wordCount = 0; - for (var word of args) { + + // Iterate through the array passed in, and search for the end of a string + let wordCount = 0; + for (let word of args) { if (word.endsWith("\"")) { endFound = true; word = word.slice(0, -1); } + str += " " + word; wordCount++; - if (endFound) break; - + if (endFound) { + break; + } } - if(!endFound && args.length > 0) { + + if (!endFound && args.length > 0) { return [false, "", null]; } - if (args.length == 0) { + + if (args.length === 0) { str = str.slice(0, -1); //For single word answers, this will remove the trailing " at the end of a word } + return [true, str, args.slice(wordCount)]; } -} \ No newline at end of file +}; diff --git a/test/commands/default_command_handler.test.js b/test/commands/default_command_handler.test.js index 66a94a0..975de6f 100644 --- a/test/commands/default_command_handler.test.js +++ b/test/commands/default_command_handler.test.js @@ -1,6 +1,6 @@ const MessageHandler = require('../../src/events/message_sent_handler'); -const MockMessage = require('../discord_mocks/mock_message') -const MockChannel = require('../discord_mocks/mock_channel') +const MockMessage = require('../discord_mocks/mock_message'); +const MockChannel = require('../discord_mocks/mock_channel'); QUnit.test( "Default command handler tests", @@ -17,4 +17,4 @@ QUnit.test( "The source command should return the GitHub link of the bot." ); } -) +); diff --git a/test/commands/poll_command_handler.test.js b/test/commands/poll_command_handler.test.js index eec5492..0fc47f0 100644 --- a/test/commands/poll_command_handler.test.js +++ b/test/commands/poll_command_handler.test.js @@ -1,6 +1,6 @@ const MessageHandler = require('../../src/events/message_sent_handler'); -const MockMessage = require('../discord_mocks/mock_message') -const MockChannel = require('../discord_mocks/mock_channel') +const MockMessage = require('../discord_mocks/mock_message'); +const MockChannel = require('../discord_mocks/mock_channel'); const POLL_STATION_NAME = "*Hopson Polling Station*"; @@ -141,7 +141,7 @@ QUnit.test( "Providing a question with more than 9 options should error" ); } -) +); QUnit.test( "Poll options: Correct args", @@ -174,4 +174,4 @@ QUnit.test( done(); }, 5000); } -); \ No newline at end of file +); diff --git a/test/commands/role_command_handler.test.js b/test/commands/role_command_handler.test.js index 45f8a35..be698c8 100644 --- a/test/commands/role_command_handler.test.js +++ b/test/commands/role_command_handler.test.js @@ -1,11 +1,11 @@ -const djs = require('discord.js') +const djs = require('discord.js'); const MessageHandler = require('../../src/events/message_sent_handler'); -const MockMessage = require('../discord_mocks/mock_message') -const MockChannel = require('../discord_mocks/mock_channel') -const MockMember = require('../discord_mocks/mock_guild_member') -const MockGuild = require('../discord_mocks/mock_guild') +const MockMessage = require('../discord_mocks/mock_message'); +const MockChannel = require('../discord_mocks/mock_channel'); +const MockMember = require('../discord_mocks/mock_guild_member'); +const MockGuild = require('../discord_mocks/mock_guild'); const MockRoles = require('../discord_mocks/mock_role'); -const MockUser = require('../discord_mocks/mock_user') +const MockUser = require('../discord_mocks/mock_user'); const roles = new djs.Collection(); roles.set(0, new MockRoles("C++")); @@ -33,4 +33,4 @@ QUnit.test( assert.equal(true, true); } -); \ No newline at end of file +); diff --git a/test/discord_mocks/mock_channel.js b/test/discord_mocks/mock_channel.js index 933ffde..fd59537 100644 --- a/test/discord_mocks/mock_channel.js +++ b/test/discord_mocks/mock_channel.js @@ -30,4 +30,4 @@ module.exports = class { lastMessage() { return this.messages[this.messages.length - 1]; } -} \ No newline at end of file +} diff --git a/test/discord_mocks/mock_guild.js b/test/discord_mocks/mock_guild.js index 3feb1b3..f71b9c9 100644 --- a/test/discord_mocks/mock_guild.js +++ b/test/discord_mocks/mock_guild.js @@ -1,4 +1,3 @@ - module.exports = class { /** * @@ -7,4 +6,4 @@ module.exports = class { constructor(roles) { this.roles = roles } -} \ No newline at end of file +} diff --git a/test/discord_mocks/mock_guild_member.js b/test/discord_mocks/mock_guild_member.js index 3cc6bab..ee8fc82 100644 --- a/test/discord_mocks/mock_guild_member.js +++ b/test/discord_mocks/mock_guild_member.js @@ -27,4 +27,4 @@ module.exports = class { const index = this.roles.indexOf(role); if (index !== -1) this.roles.splice(index, 1); } -} \ No newline at end of file +} diff --git a/test/discord_mocks/mock_message.js b/test/discord_mocks/mock_message.js index 13191ce..3422f3e 100644 --- a/test/discord_mocks/mock_message.js +++ b/test/discord_mocks/mock_message.js @@ -1,6 +1,7 @@ -const MockGuildMember = require('./mock_guild_member') -const MockUser = require('./mock_user') -const MockGuild = require('./mock_guild') +const MockGuildMember = require('./mock_guild_member'); +const MockUser = require('./mock_user'); +const MockGuild = require('./mock_guild'); + module.exports = class { /** * Creates a mock message @@ -25,4 +26,4 @@ module.exports = class { react(reaction) { this.reactions.push(reaction); } -} \ No newline at end of file +} diff --git a/test/discord_mocks/mock_role.js b/test/discord_mocks/mock_role.js index ae495bc..76d5794 100644 --- a/test/discord_mocks/mock_role.js +++ b/test/discord_mocks/mock_role.js @@ -1,6 +1,5 @@ - module.exports = class { constructor(name) { this.name = name; } -} \ No newline at end of file +} diff --git a/test/discord_mocks/mock_user.js b/test/discord_mocks/mock_user.js index bba8ff0..b996c30 100644 --- a/test/discord_mocks/mock_user.js +++ b/test/discord_mocks/mock_user.js @@ -1,4 +1,3 @@ - module.exports = class { -} \ No newline at end of file +} diff --git a/test/events/message_delete.test.js b/test/events/message_delete.test.js index 502f4b9..a0c6131 100644 --- a/test/events/message_delete.test.js +++ b/test/events/message_delete.test.js @@ -1,2 +1 @@ const MessageModHandle = require("../../src/events/message_mod_handler"); - diff --git a/test/test_start.js b/test/test_start.js index cfa5f36..19bd80c 100644 --- a/test/test_start.js +++ b/test/test_start.js @@ -1,8 +1,7 @@ - //Command handler tests require("./commands/default_command_handler.test"); require("./commands/poll_command_handler.test"); -require("./commands/role_command_handler.test") +require("./commands/role_command_handler.test"); //Event handler test -require("./events/message_delete.test"); \ No newline at end of file +require("./events/message_delete.test");