From 2486f57e2b924786c8579be31e1df5e47fd867ee Mon Sep 17 00:00:00 2001 From: Julia Lange Date: Wed, 25 Dec 2019 00:58:54 -0800 Subject: [PATCH 1/4] Working on refactor --- main.ts | 278 ++++------------------------------- scripts/commands.ts | 214 +++++++++++++++++++++++++++ enums.ts => scripts/enums.ts | 2 +- scripts/functions.ts | 32 ++++ 4 files changed, 275 insertions(+), 251 deletions(-) create mode 100644 scripts/commands.ts rename enums.ts => scripts/enums.ts (99%) create mode 100644 scripts/functions.ts diff --git a/main.ts b/main.ts index 1e012fe..8841ddd 100644 --- a/main.ts +++ b/main.ts @@ -1,95 +1,25 @@ // Created by Julia Lange //===Requirements=== -const fs = require('fs'); -const Discord = require('discord.js'); +export const Discord = require('discord.js'); const client = new Discord.Client(); +export const fs = require('fs'); const info = JSON.parse(fs.readFileSync(`./data/info.json`)); -import { player } from "./enums"; -//===Data stored for use, such as class, race, and last names=== -const races: Array = ["tree", "ground", "chipmunk"]; -const classes: Array = ["rogue", "berserker", "knight", "ranger", "priest"]; -const lastNames: Array = ["Nutcrack", "Nutmeg", "Seedsower", "McScuiri", "Rodentia", "Arbora", "Patagi"]; -const COLOR: string = "#E81B47"; -const newPlayerTemplate: player = { - "name": "", - "race": "", - "class": "", - "weapon": { - "weaponName": "", - "attackStat": 0, - "defenseStat": 0, - "secondStat": 0 - }, - "level": 1, - "nuts": 0, - "staminaMax": 0, - "stamina": 0, - "dm": false, - "dm_points": 0 -} +import { player } from "./scripts/enums"; +import { processes, channels } from "./scripts/commands"; +import { encounterInProgress } from "./scripts/functions"; -//===Commands=== -const processes: any = { - "help": { - title: "Help", - description: "Show a description of a command", - args: "**command** - the command you'd like to know more about", - run: (msg: any, data: player, args: string[], file: any) => help(msg, args) - }, - "list": { - title: "List", - description: "List all commands", - args: "", - run: (msg: any, data: player, args: string[], file: any) => list(msg) - }, - "read": { - title: "Read", - description: "Read a description of your squirrel", - args: "", - run: (msg: any, data: player, args: string[], file: any) => read(msg, data) - }, - "namechange": { - title: "Namechange", - description: "Change the name of your squirrel, can only be used at level 1", - args: "**name** - the new name for your squirrel", - run: (msg: any, data: player, args: string[], file: any) => nameChange(msg, data, args, file) - }, - "races": { - title: "Races", - description: "List all the races", - args: "", - run: (msg: any, data: player, args: string[], file: any) => printRaces(msg) - }, - "classes": { - title: "Classes", - description: "List all the classes", - args: "", - run: (msg: any, data: player, args: string[], file: any) => printClasses(msg) - }, - "create": { - title: "Create", - description: "Create a squirrel, can only be used once", - args: "**name** - the name of the created squirrel\n**race** - The race of the created squirrel, type !races for race options\n**class** - The class of the created squirrel, type !classes for class options", - run: (msg: any, data: player, args: string[], file: any) => msg.reply(`You already have a squirrel silly.`) - }, -} //===Global editable variables=== -let encounterChannel; -let preparingChannel; -let generalChannel; -let barChannel; -// let encounterInProgress: boolean; + //===Initalization=== client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); - encounterChannel = client.channels.find(ch => ch.name === 'the-wild'); - preparingChannel = client.channels.find(ch => ch.name === 'preparing-for-expedition'); - generalChannel = client.channels.find(ch => ch.name === 'general-table'); - barChannel = client.channels.find(ch => ch.name === 'the-bar'); + channels.general = client.channels.find(ch => ch.id === info.channels.general); + channels.encounter = client.channels.find(ch => ch.id === info.channels.encounter); + channels.preparing = client.channels.find(ch => ch.id === info.channels.preparing); // const preparingCollector = new Discord.MessageCollector(preparingChannel); // preparingCollector.on('collect', msg => { // console.log(msg.content); @@ -102,13 +32,28 @@ client.on('ready', () => { client.on('message', msg => { //Reasons to exit if (!msg.content.split(" ")[0].startsWith(info.prefix)) return; // if the message doesn't start with the prefix + switch(msg.channel) { + case channels.encounter: + if(encounterInProgress) return; + encounterChannelMessage(msg); + break; + default: + defaultChannelMessage(msg); + } + +}); +// Log the bot in +client.login(info.key); + + +// Channel Cases +function defaultChannelMessage(msg: any): void { let messageContent: Array = msg.content.split(" "); // split message into an array on spaces let command: string = messageContent[0]; // This is the command they are using let args: Array = [""]; // arguments of the message if (messageContent.length > 1) args = messageContent.slice(1); - let authorId: number = msg.author.id; // Message Author let playerFile: string = `./data/playerdata/${authorId}.json`; @@ -124,7 +69,7 @@ client.on('message', msg => { } else { if(command === `${info.prefix}create`){ // if they are using the create command console.log(`Attempting to make a squirrel for ${authorId}`); - if (create(msg, args, playerFile)) + if (processes["create"]["create"].run(msg, null, args, playerFile)) console.log(`Squirrel made succesfully for ${authorId}`); else console.log(`Failed to create a squirrel for ${authorId}`); @@ -132,175 +77,8 @@ client.on('message', msg => { msg.reply(`Please make a squirrel before interacting with the bot. To do so please use the create command. For more information on creation type "!help create"`); } } -}); - -// Log the bot in -client.login(info.key); - -//===FUNCTIONS=== -/* -function encounter(encounterChannel: any): void { - if (!encounterInProgress) { // randomInt(1,60) === 60 && - console.log("Starting Encounter"); - encounterInProgress = true; - encounterChannel.send("An encounter is beginning!"); - - encounterChannel.send(`\`■■■ ■■■ ■■■ ■■■\`\n\`■■■ ■■■ ■■■ ■■■\`\n\`■■■ ■■■ ■■■ ■■■\``).then(msg => { - - - - console.log("Encounter finished"); - encounterInProgress = false; - }); - } -} -*/ -function randomInt(low: number, high: number): number { - return Math.floor(Math.random() * (high - low + 1) + low) } -function raceText(race: string): string { - if (race === races[2]) return capitalize(race); - else if (race === races[0] || race === races[1]) return `${capitalize(race)} Squirrel`; - else { - console.log(`Error ${race} is not a valid race`); - return ""; - } -} - -function capitalize(toCaps: string): string { - return toCaps.charAt(0).toUpperCase() + toCaps.slice(1).toLowerCase(); -} - -//===COMMAND FUNCTIONS== - -function help(msg: any, args: string[]): void { - let argument: string = args[0].toLowerCase(); - if(argument === "") { - msg.reply(`Please provide a command, like "!help help", or "!help races"\nAlternatively type "!list" for a list of commands`); - } else if(processes.hasOwnProperty(argument)){ - let embed = new Discord.RichEmbed() - .setTitle(processes[argument].title) - .setColor(COLOR) - .setDescription(processes[argument].description); - if(processes[argument].args === "") { - embed.addField("Arguments:", `This command has no arguments`); - } else { - embed.addField("Arguments:", processes[argument].args); - } - msg.channel.send(embed); - } else { - msg.reply(`That command does not exist`); - } -} - -function list(msg: any): void { - let embed = new Discord.RichEmbed() - .setTitle("List of Commands") - .setColor(COLOR); - let description: string = ""; - Object.keys(processes).forEach(process => { - description += `**${processes[process].title}:** ${processes[process].description}.\n`; - }); - embed.setDescription(description); - msg.author.send(embed); -} - -function read(msg: any, data: player): void { - let embed = new Discord.RichEmbed() - .setTitle(msg.author.username) - .setColor(COLOR) - .setThumbnail(msg.author.avatarURL) - .setDescription("Squirrel Info") - .addField("Name", data.name) - .addField("Race", raceText(data.race)) - .addField("Class", capitalize(data.class)) - .addField("Nuts", data.nuts) - .addField("Level", data.level); - if (data.dm === true) - embed.addField("DM Points", data.dm_points); - - msg.channel.send(embed); -} - -function create(msg: any, args: Array, file: any): boolean { - if (args.length === 3) { - let newPlayer: player = newPlayerTemplate; - let incorrect: string = ""; - - incorrect = " race"; - races.some(type => { - if (args[1].toLowerCase() == type) { - incorrect = ""; - return true; - } - }); - - if (incorrect == "") - incorrect = " class"; - else - incorrect += ", and class"; - classes.some(type => { - if (args[2].toLowerCase() == type) { - if (incorrect == " race, and class") - incorrect = " race"; - else - incorrect = ""; - return true; - } - }); - - if (incorrect === "") { - newPlayer.name = args[0] + " " + lastNames[randomInt(0, lastNames.length - 1)]; - newPlayer.race = args[1]; - newPlayer.class = args[2]; - fs.writeFileSync(file, JSON.stringify(newPlayer)); - msg.reply(`Squirrel ${newPlayer.name} has been created`); - return true; - } else { - msg.reply(`Some parameters were entered incorrectly. Remember the format is "create name race class". Your name can be whatever you want, but you have to choose from !race, and !class. You incorrectly entered your:${incorrect}.`); - return false; - } - } else { - msg.reply(`Too many or too few parameters were entered. The format is "create name race class". You only get to choose your first name, don't write a last name.`); - return false; - } -} - -function nameChange(msg: any, data: player, args: string[], file: any): void { - if (data.level == 1) { - if (args.length >= 1) { - data.name = capitalize(args[0]) + " " + data.name.split(' ')[1]; - fs.writeFileSync(file, JSON.stringify(data)); - msg.reply(`Name changed to ${data.name}`); - } else { - msg.reply(`Please provide a name`); - } - } else { - msg.reply(`Sorry, you have to be level 1 to change your name. You're stuck with ${data.name}`); - } -} - -function printRaces(msg: any): void { - let print = "The races are: "; - for (let i = 0; i < races.length; i++) { - if (i === races.length - 1) { - print += `& ${raceText(races[i])}s`; - } else { - print += `${raceText(races[i])}s, `; - } - } - msg.reply(print); -} - -function printClasses(msg: any): void { - let print = "The classes are: "; - for (let i = 0; i < classes.length; i++) { - if (i === classes.length - 1) { - print += `& ${capitalize(classes[i])}s`; - } else { - print += `${capitalize(classes[i])}s, `; - } - } - msg.reply(print); +function encounterChannelMessage(msg: any): void { + } \ No newline at end of file diff --git a/scripts/commands.ts b/scripts/commands.ts new file mode 100644 index 0000000..a48e526 --- /dev/null +++ b/scripts/commands.ts @@ -0,0 +1,214 @@ +import { Discord, fs} from "../main"; +import { player } from "./enums"; +import { raceText, capitalize, randomInt, encounter } from "./functions"; + +//===Data stored for use, such as class, race, and last names=== +export const races: Array = ["tree", "ground", "chipmunk"]; +const classes: Array = ["rogue", "berserker", "knight", "ranger", "priest"]; +const lastNames: Array = ["Nutcrack", "Nutmeg", "Seedsower", "McScuiri", "Rodentia", "Arbora", "Patagi"]; +const COLOR: string = "#E81B47"; +const newPlayerTemplate: player = { + "name": "", + "race": "", + "class": "", + "weapon": { + "weaponName": "", + "attackStat": 0, + "defenseStat": 0, + "secondStat": 0 + }, + "level": 1, + "nuts": 0, + "staminaMax": 0, + "stamina": 0, + "dm": false, + "dm_points": 0 +} +export let channels: any = { + general: "", + encounter: "", + preparing: "" +} +export let processes: any = { + "test": { + title: "Test", + description: "For testing", + args: "", + run: (msg: any, data: player, args: string[], file: any) => encounter() + }, + "help": { + title: "Help", + description: "Show a description of a command", + args: "**command** - the command you'd like to know more about", + run: (msg: any, data: player, args: string[], file: any) => help(msg, args) + }, + "list": { + title: "List", + description: "List all commands", + args: "", + run: (msg: any, data: player, args: string[], file: any) => list(msg) + }, + "read": { + title: "Read", + description: "Read a description of your squirrel", + args: "", + run: (msg: any, data: player, args: string[], file: any) => read(msg, data) + }, + "namechange": { + title: "Namechange", + description: "Change the name of your squirrel, can only be used at level 1", + args: "**name** - the new name for your squirrel", + run: (msg: any, data: player, args: string[], file: any) => nameChange(msg, data, args, file) + }, + "races": { + title: "Races", + description: "List all the races", + args: "", + run: (msg: any, data: player, args: string[], file: any) => printRaces(msg) + }, + "classes": { + title: "Classes", + description: "List all the classes", + args: "", + run: (msg: any, data: player, args: string[], file: any) => printClasses(msg) + }, + "create": { + title: "Create", + description: "Create a squirrel, can only be used once", + args: "**name** - the name of the created squirrel\n**race** - The race of the created squirrel, type !races for race options\n**class** - The class of the created squirrel, type !classes for class options", + run: (msg: any, data: player, args: string[], file: any) => create(msg, args, file) + } +} + +//===COMMAND FUNCTIONS== + +function help(msg: any, args: string[]): void { + let argument: string = args[0].toLowerCase(); + if(argument === "") { + msg.reply(`Please provide a command, like "!help help", or "!help races"\nAlternatively type "!list" for a list of commands`); + } else if(processes.hasOwnProperty(argument)){ + let embed = new Discord.RichEmbed() + .setTitle(processes[argument].title) + .setColor(COLOR) + .setDescription(processes[argument].description); + if(processes[argument].args === "") { + embed.addField("Arguments:", `This command has no arguments`); + } else { + embed.addField("Arguments:", processes[argument].args); + } + msg.channel.send(embed); + } else { + msg.reply(`That command does not exist`); + } +} + +function list(msg: any): void { + let embed = new Discord.RichEmbed() + .setTitle("List of Commands") + .setColor(COLOR); + let description: string = ""; + Object.keys(processes).forEach(process => { + description += `**${processes[process].title}:** ${processes[process].description}.\n`; + }); + embed.setDescription(description); + msg.author.send(embed); +} + +function read(msg: any, data: player): void { + let embed = new Discord.RichEmbed() + .setTitle(msg.author.username) + .setColor(COLOR) + .setThumbnail(msg.author.avatarURL) + .setDescription("Squirrel Info") + .addField("Name", data.name) + .addField("Race", raceText(data.race)) + .addField("Class", capitalize(data.class)) + .addField("Nuts", data.nuts) + .addField("Level", data.level); + if (data.dm === true) + embed.addField("DM Points", data.dm_points); + + msg.channel.send(embed); +} + +function create(msg: any, args: Array, file: any): boolean { + if (args.length === 3) { + let newPlayer: player = newPlayerTemplate; + let incorrect: string = ""; + + incorrect = " race"; + races.some(type => { + if (args[1].toLowerCase() == type) { + incorrect = ""; + return true; + } + }); + + if (incorrect == "") + incorrect = " class"; + else + incorrect += ", and class"; + classes.some(type => { + if (args[2].toLowerCase() == type) { + if (incorrect == " race, and class") + incorrect = " race"; + else + incorrect = ""; + return true; + } + }); + + if (incorrect === "") { + newPlayer.name = args[0] + " " + lastNames[randomInt(0, lastNames.length - 1)]; + newPlayer.race = args[1]; + newPlayer.class = args[2]; + fs.writeFileSync(file, JSON.stringify(newPlayer)); + msg.reply(`Squirrel ${newPlayer.name} has been created`); + return true; + } else { + msg.reply(`Some parameters were entered incorrectly. Remember the format is "create name race class". Your name can be whatever you want, but you have to choose from !race, and !class. You incorrectly entered your:${incorrect}.`); + return false; + } + } else { + msg.reply(`Too many or too few parameters were entered. The format is "create name race class". You only get to choose your first name, don't write a last name.`); + return false; + } +} + +function nameChange(msg: any, data: player, args: string[], file: any): void { + if (data.level == 1) { + if (args.length >= 1) { + data.name = capitalize(args[0]) + " " + data.name.split(' ')[1]; + fs.writeFileSync(file, JSON.stringify(data)); + msg.reply(`Name changed to ${data.name}`); + } else { + msg.reply(`Please provide a name`); + } + } else { + msg.reply(`Sorry, you have to be level 1 to change your name. You're stuck with ${data.name}`); + } +} + +function printRaces(msg: any): void { + let print = "The races are: "; + for (let i = 0; i < races.length; i++) { + if (i === races.length - 1) { + print += `& ${raceText(races[i])}s`; + } else { + print += `${raceText(races[i])}s, `; + } + } + msg.reply(print); +} + +function printClasses(msg: any): void { + let print = "The classes are: "; + for (let i = 0; i < classes.length; i++) { + if (i === classes.length - 1) { + print += `& ${capitalize(classes[i])}s`; + } else { + print += `${capitalize(classes[i])}s, `; + } + } + msg.reply(print); +} \ No newline at end of file diff --git a/enums.ts b/scripts/enums.ts similarity index 99% rename from enums.ts rename to scripts/enums.ts index 87b7964..72fc4af 100644 --- a/enums.ts +++ b/scripts/enums.ts @@ -16,4 +16,4 @@ export interface weapon { attackStat: number; defenseStat: number; secondStat: number; -} +} \ No newline at end of file diff --git a/scripts/functions.ts b/scripts/functions.ts new file mode 100644 index 0000000..8f4db41 --- /dev/null +++ b/scripts/functions.ts @@ -0,0 +1,32 @@ +import { races, channels } from "./commands"; + +export let encounterInProgress: boolean = false; + +export function encounter(): void { + if (encounterInProgress == false) { // randomInt(1,20) === 20 && + console.log("Starting Encounter"); + encounterInProgress = true; + channels.encounter.send("An encounter is beginning!"); + + channels.encounter.send(`\`■■■ ■■■ ■■■ ■■■\`\n\`■■■ ■■■ ■■■ ■■■\`\n\`■■■ ■■■ ■■■ ■■■\``) + console.log("Encounter finished"); + encounterInProgress = false; + } +} + +export function randomInt(low: number, high: number): number { + return Math.floor(Math.random() * (high - low + 1) + low) +} + +export function raceText(race: string): string { + if (race === races[2]) return capitalize(race); + else if (race === races[0] || race === races[1]) return `${capitalize(race)} Squirrel`; + else { + console.log(`Error ${race} is not a valid race`); + return ""; + } +} + +export function capitalize(toCaps: string): string { + return toCaps.charAt(0).toUpperCase() + toCaps.slice(1).toLowerCase(); +} \ No newline at end of file From f83a4231f1ea027c8db484848d175aefd5b68a63 Mon Sep 17 00:00:00 2001 From: Julia Lange Date: Wed, 4 Mar 2020 18:04:49 -0800 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=86=95:Command=20File=20Changed=20?= =?UTF-8?q?=E2=9D=8C:All=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently only Create command works --- scripts/commands.ts => commands/commands.old | 89 +----------- commands/create.ts | 34 +++++ data/playerdata/examplePlayerFile | 17 +++ main.ts | 78 +++------- scripts/enums.ts | 26 ++-- scripts/functions.ts | 64 +++++--- yarn.lock | 145 +++++++++++-------- 7 files changed, 226 insertions(+), 227 deletions(-) rename scripts/commands.ts => commands/commands.old (58%) create mode 100644 commands/create.ts create mode 100644 data/playerdata/examplePlayerFile diff --git a/scripts/commands.ts b/commands/commands.old similarity index 58% rename from scripts/commands.ts rename to commands/commands.old index a48e526..b7c8820 100644 --- a/scripts/commands.ts +++ b/commands/commands.old @@ -1,35 +1,10 @@ -import { Discord, fs} from "../main"; -import { player } from "./enums"; -import { raceText, capitalize, randomInt, encounter } from "./functions"; +import { Discord, fs } from "../main"; +import { player } from "../scripts/enums"; +import { raceText, capitalize, randomInt } from "../scripts/functions"; //===Data stored for use, such as class, race, and last names=== -export const races: Array = ["tree", "ground", "chipmunk"]; -const classes: Array = ["rogue", "berserker", "knight", "ranger", "priest"]; -const lastNames: Array = ["Nutcrack", "Nutmeg", "Seedsower", "McScuiri", "Rodentia", "Arbora", "Patagi"]; -const COLOR: string = "#E81B47"; -const newPlayerTemplate: player = { - "name": "", - "race": "", - "class": "", - "weapon": { - "weaponName": "", - "attackStat": 0, - "defenseStat": 0, - "secondStat": 0 - }, - "level": 1, - "nuts": 0, - "staminaMax": 0, - "stamina": 0, - "dm": false, - "dm_points": 0 -} -export let channels: any = { - general: "", - encounter: "", - preparing: "" -} -export let processes: any = { + +let processes: any = { "test": { title: "Test", description: "For testing", @@ -72,26 +47,20 @@ export let processes: any = { args: "", run: (msg: any, data: player, args: string[], file: any) => printClasses(msg) }, - "create": { - title: "Create", - description: "Create a squirrel, can only be used once", - args: "**name** - the name of the created squirrel\n**race** - The race of the created squirrel, type !races for race options\n**class** - The class of the created squirrel, type !classes for class options", - run: (msg: any, data: player, args: string[], file: any) => create(msg, args, file) - } } //===COMMAND FUNCTIONS== function help(msg: any, args: string[]): void { let argument: string = args[0].toLowerCase(); - if(argument === "") { + if (argument === "") { msg.reply(`Please provide a command, like "!help help", or "!help races"\nAlternatively type "!list" for a list of commands`); - } else if(processes.hasOwnProperty(argument)){ + } else if (processes.hasOwnProperty(argument)) { let embed = new Discord.RichEmbed() .setTitle(processes[argument].title) .setColor(COLOR) .setDescription(processes[argument].description); - if(processes[argument].args === "") { + if (processes[argument].args === "") { embed.addField("Arguments:", `This command has no arguments`); } else { embed.addField("Arguments:", processes[argument].args); @@ -131,49 +100,7 @@ function read(msg: any, data: player): void { msg.channel.send(embed); } -function create(msg: any, args: Array, file: any): boolean { - if (args.length === 3) { - let newPlayer: player = newPlayerTemplate; - let incorrect: string = ""; - incorrect = " race"; - races.some(type => { - if (args[1].toLowerCase() == type) { - incorrect = ""; - return true; - } - }); - - if (incorrect == "") - incorrect = " class"; - else - incorrect += ", and class"; - classes.some(type => { - if (args[2].toLowerCase() == type) { - if (incorrect == " race, and class") - incorrect = " race"; - else - incorrect = ""; - return true; - } - }); - - if (incorrect === "") { - newPlayer.name = args[0] + " " + lastNames[randomInt(0, lastNames.length - 1)]; - newPlayer.race = args[1]; - newPlayer.class = args[2]; - fs.writeFileSync(file, JSON.stringify(newPlayer)); - msg.reply(`Squirrel ${newPlayer.name} has been created`); - return true; - } else { - msg.reply(`Some parameters were entered incorrectly. Remember the format is "create name race class". Your name can be whatever you want, but you have to choose from !race, and !class. You incorrectly entered your:${incorrect}.`); - return false; - } - } else { - msg.reply(`Too many or too few parameters were entered. The format is "create name race class". You only get to choose your first name, don't write a last name.`); - return false; - } -} function nameChange(msg: any, data: player, args: string[], file: any): void { if (data.level == 1) { diff --git a/commands/create.ts b/commands/create.ts new file mode 100644 index 0000000..9112033 --- /dev/null +++ b/commands/create.ts @@ -0,0 +1,34 @@ +import { squirrel } from "../scripts/enums"; +import { newSquirrel, updateSquirrelFile } from "../scripts/functions"; + +module.exports = { + name: 'create', + description: "Create a squirrel, can only be used once", + args: "**name** - the name of the created squirrel\n**race** - The race of the created squirrel, type !races for race options\n**class** - The class of the created squirrel, type !classes for class options", + execute(msg, args) { + if (args.length !== 3) { + msg.reply(`Too many or too few parameters were entered. The format is "create name race class". You only get to choose your first name, don't write a last name.`); + return false; + } + + let newSquirrel: squirrel = squirrel(args[0], args[1], args[2]); + + let incorrect: string = ""; + + if (newSquirrel.race === -1) + incorrect += ` race as ${args[1]}`; + if (newSquirrel.class === -1) + incorrect += ` class as ${args[2]}`; + + if (incorrect === "") { + updateSquirrelFile(msg.author.id, newSquirrel); + msg.reply(`Squirrel ${newSquirrel.name} has been created`); + } else { + msg.reply(`Some parameters were entered incorrectly. Remember the format is "create first_name race class". Your name can be whatever you want, but you have to choose from !race, and !class. You incorrectly entered:${incorrect}.`); + } + } +} + +function squirrel(name: string, race: string, classtype: string): squirrel { + return newSquirrel(name, race, classtype); +} \ No newline at end of file diff --git a/data/playerdata/examplePlayerFile b/data/playerdata/examplePlayerFile new file mode 100644 index 0000000..c20709a --- /dev/null +++ b/data/playerdata/examplePlayerFile @@ -0,0 +1,17 @@ +{ + "name": "Snickers Patagi", + "race": 0, + "class": 2, + "weapon": { + "weaponName": "", + "attackStat": 0, + "defenseStat": 0, + "secondStat": 0 + }, + "level": 1, + "nuts": 0, + "staminaMax": 0, + "stamina": 0, + "dm": false, + "dm_points": 0 +} \ No newline at end of file diff --git a/main.ts b/main.ts index 8841ddd..fbfa74a 100644 --- a/main.ts +++ b/main.ts @@ -1,84 +1,48 @@ // Created by Julia Lange //===Requirements=== -export const Discord = require('discord.js'); -const client = new Discord.Client(); export const fs = require('fs'); +export const Discord = require('discord.js'); + const info = JSON.parse(fs.readFileSync(`./data/info.json`)); +const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); -import { player } from "./scripts/enums"; -import { processes, channels } from "./scripts/commands"; -import { encounterInProgress } from "./scripts/functions"; - - -//===Global editable variables=== +const client = new Discord.Client(); +client.commands = new Discord.Collection(); +for (const file of commandFiles) { + const command = require(`./commands/${file}`); + client.commands.set(command.name, command); +} //===Initalization=== client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); - channels.general = client.channels.find(ch => ch.id === info.channels.general); - channels.encounter = client.channels.find(ch => ch.id === info.channels.encounter); - channels.preparing = client.channels.find(ch => ch.id === info.channels.preparing); - // const preparingCollector = new Discord.MessageCollector(preparingChannel); - // preparingCollector.on('collect', msg => { - // console.log(msg.content); - // }); - // setInterval( function() { encounter(encounterChannel); }, 300000 ); - // encounter(encounterChannel); }); //===When receiving messages client.on('message', msg => { //Reasons to exit - if (!msg.content.split(" ")[0].startsWith(info.prefix)) return; // if the message doesn't start with the prefix - switch(msg.channel) { - case channels.encounter: - if(encounterInProgress) return; - encounterChannelMessage(msg); - break; - default: - defaultChannelMessage(msg); - } - + if (!msg.content.split(" ")[0].startsWith(info.prefix) || msg.author.bot) return; // if the message doesn't start with the prefix + + executeCommand(msg); }); // Log the bot in client.login(info.key); - -// Channel Cases -function defaultChannelMessage(msg: any): void { - let messageContent: Array = msg.content.split(" "); // split message into an array on spaces - let command: string = messageContent[0]; // This is the command they are using - +function executeCommand(msg: any) { + const messageContent: Array = msg.content.slice(1).split(" "); // split message into an array on spaces + const command: string = messageContent[0].toLowerCase(); // This is the command they are using let args: Array = [""]; // arguments of the message if (messageContent.length > 1) args = messageContent.slice(1); - let authorId: number = msg.author.id; // Message Author - let playerFile: string = `./data/playerdata/${authorId}.json`; - if (fs.existsSync(playerFile)) { // If they're file exists, they can use commands, otherwise direct them to the create command - let playerData: player = JSON.parse(fs.readFileSync(playerFile)); + if (!client.commands.has(command)) return; - Object.keys(processes).forEach(process => { // See if the command they typed is a command - if(`${info.prefix}${processes[process].title.toLowerCase()}` === command){ - processes[process].run(msg, playerData, args, playerFile); - } - }); - - } else { - if(command === `${info.prefix}create`){ // if they are using the create command - console.log(`Attempting to make a squirrel for ${authorId}`); - if (processes["create"]["create"].run(msg, null, args, playerFile)) - console.log(`Squirrel made succesfully for ${authorId}`); - else - console.log(`Failed to create a squirrel for ${authorId}`); - } else { - msg.reply(`Please make a squirrel before interacting with the bot. To do so please use the create command. For more information on creation type "!help create"`); - } + try { + client.commands.get(command).execute(msg, args); + } catch (e) { + console.error(e); + msg.reply(`Failed to execute the given command for some reason. Sad.`); } -} - -function encounterChannelMessage(msg: any): void { - } \ No newline at end of file diff --git a/scripts/enums.ts b/scripts/enums.ts index 72fc4af..017e9a2 100644 --- a/scripts/enums.ts +++ b/scripts/enums.ts @@ -1,19 +1,19 @@ -export interface player { - name: string; - race: string; - class: string; - weapon: weapon; - nuts: number; - level: number; +export interface squirrel { + name: string; + race: number; + class: number; + weapon: weapon; + nuts: number; + level: number; staminaMax: number; - stamina: number; - dm: boolean; - dm_points: number; + stamina: number; + dm: boolean; + dm_points: number; } export interface weapon { - weaponName: string; - attackStat: number; + weaponName: string; + attackStat: number; defenseStat: number; - secondStat: number; + secondStat: number; } \ No newline at end of file diff --git a/scripts/functions.ts b/scripts/functions.ts index 8f4db41..d291c43 100644 --- a/scripts/functions.ts +++ b/scripts/functions.ts @@ -1,31 +1,57 @@ -import { races, channels } from "./commands"; +import { squirrel } from "../scripts/enums"; +import { fs } from "../main"; -export let encounterInProgress: boolean = false; +const races: Array = ["tree", "ground", "chipmunk"]; +const classes: Array = ["rogue", "berserker", "knight", "ranger", "priest"]; +const lastNames: Array = ["Nutcrack", "Nutmeg", "Seedsower", "McScuiri", "Rodentia", "Arbora", "Patagi"]; +// const COLOR: string = "#E81B47"; -export function encounter(): void { - if (encounterInProgress == false) { // randomInt(1,20) === 20 && - console.log("Starting Encounter"); - encounterInProgress = true; - channels.encounter.send("An encounter is beginning!"); +export function newSquirrel(name: string, race: string, classtype: string): squirrel { + let raceNum: number = -1; + let classNum: number = -1; - channels.encounter.send(`\`■■■ ■■■ ■■■ ■■■\`\n\`■■■ ■■■ ■■■ ■■■\`\n\`■■■ ■■■ ■■■ ■■■\``) - console.log("Encounter finished"); - encounterInProgress = false; - } + if (races.includes(race.toLowerCase())) + raceNum = races.indexOf(race.toLowerCase()); + + if (classes.includes(classtype.toLowerCase())) + classNum = classes.indexOf(classtype.toLowerCase()); + + return { + "name": `${capitalize(name)} ${lastNames[randomInt(0, lastNames.length - 1)]}`, + "race": raceNum, + "class": classNum, + "weapon": { + "weaponName": "", + "attackStat": 0, + "defenseStat": 0, + "secondStat": 0 + }, + "level": 1, + "nuts": 0, + "staminaMax": 0, + "stamina": 0, + "dm": false, + "dm_points": 0 + }; +} + +export function updateSquirrelFile(playerId: string, squirrel: squirrel): void { + let playerFile: string = `./data/playerdata/${playerId}.json`; + fs.writeFileSync(playerFile, JSON.stringify(squirrel)); } export function randomInt(low: number, high: number): number { return Math.floor(Math.random() * (high - low + 1) + low) } -export function raceText(race: string): string { - if (race === races[2]) return capitalize(race); - else if (race === races[0] || race === races[1]) return `${capitalize(race)} Squirrel`; - else { - console.log(`Error ${race} is not a valid race`); - return ""; - } -} +// export function raceText(race: number): string { +// if (race === 2) return capitalize(races[race]); +// else if (race === 0 || race === 1) return `${capitalize(races[race])} Squirrel`; +// else { +// console.log(`Error ${race} is not a valid race`); +// return ""; +// } +// } export function capitalize(toCaps: string): string { return toCaps.charAt(0).toUpperCase() + toCaps.slice(1).toLowerCase(); diff --git a/yarn.lock b/yarn.lock index d90a4b6..4cb5666 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,75 +2,106 @@ # yarn lockfile v1 -"@types/node@^11.9.3": - version "11.13.20" - resolved "https://registry.yarnpkg.com/@types/node/-/node-11.13.20.tgz#da42fe93d6599f80b35ffeb5006f4c31f40d89ea" - integrity sha512-JE0UpLWZTV1sGcaj0hN+Q0760OEjpgyFJ06DOMVW6qKBducKdJQaIw0TGL6ccj7VXRduIOHLWQi+tHwulZJHVQ== +"@discordjs/collection@^0.1.5": + version "0.1.5" + resolved "https://registry.yarnpkg.com/@discordjs/collection/-/collection-0.1.5.tgz#1781c620b4c88d619bd0373a1548e5a6025e3d3a" + integrity sha512-CU1q0UXQUpFNzNB7gufgoisDHP7n+T3tkqTsp3MNUkVJ5+hS3BCvME8uCXAUFlz+6T2FbTCu75A+yQ7HMKqRKw== -async-limiter@~1.0.0: +"@types/node@^13.7.7": + version "13.7.7" + resolved "https://registry.yarnpkg.com/@types/node/-/node-13.7.7.tgz#1628e6461ba8cc9b53196dfeaeec7b07fa6eea99" + integrity sha512-Uo4chgKbnPNlxQwoFmYIwctkQVkMMmsAoGGU4JKwLuvBefF0pCq4FybNSnfkfRCpC7ZW7kttcC/TrRtAJsvGtg== + +abort-controller@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" + integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== + dependencies: + event-target-shim "^5.0.0" + +asynckit@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" + integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= + +combined-stream@^1.0.8: + version "1.0.8" + resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" + integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== + dependencies: + delayed-stream "~1.0.0" + +delayed-stream@~1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8" - integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg== + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= -discord.js@^11.5.1: - version "11.5.1" - resolved "https://registry.yarnpkg.com/discord.js/-/discord.js-11.5.1.tgz#910fb9f6410328581093e044cafb661783a4d9e8" - integrity sha512-tGhV5xaZXE3Z+4uXJb3hYM6gQ1NmnSxp9PClcsSAYFVRzH6AJH74040mO3afPDMWEAlj8XsoPXXTJHTxesqcGw== +discord.js@^12.0.1: + version "12.0.1" + resolved "https://registry.yarnpkg.com/discord.js/-/discord.js-12.0.1.tgz#58574c0c9acc598095f943d6b14da4725d37b8b9" + integrity sha512-lUlrkAWSb5YTB1WpSZHjeUXxGlHK8VDjrlHLEP4lJj+etFAellURpmRYl29OPJ/7arQWB879pP4rvhhzpdOF7w== dependencies: - long "^4.0.0" - prism-media "^0.0.3" - snekfetch "^3.6.4" - tweetnacl "^1.0.0" - ws "^6.0.0" + "@discordjs/collection" "^0.1.5" + abort-controller "^3.0.0" + form-data "^3.0.0" + node-fetch "^2.6.0" + prism-media "^1.2.0" + setimmediate "^1.0.5" + tweetnacl "^1.0.3" + ws "^7.2.1" -dom-walk@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/dom-walk/-/dom-walk-0.1.1.tgz#672226dc74c8f799ad35307df936aba11acd6018" - integrity sha1-ZyIm3HTI95mtNTB9+TaroRrNYBg= +event-target-shim@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" + integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== -global@^4.3.2: - version "4.4.0" - resolved "https://registry.yarnpkg.com/global/-/global-4.4.0.tgz#3e7b105179006a323ed71aafca3e9c57a5cc6406" - integrity sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w== +form-data@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.0.tgz#31b7e39c85f1355b7139ee0c647cf0de7f83c682" + integrity sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg== dependencies: - min-document "^2.19.0" - process "^0.11.10" + asynckit "^0.4.0" + combined-stream "^1.0.8" + mime-types "^2.1.12" -long@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28" - integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA== +fs@^0.0.1-security: + version "0.0.1-security" + resolved "https://registry.yarnpkg.com/fs/-/fs-0.0.1-security.tgz#8a7bd37186b6dddf3813f23858b57ecaaf5e41d4" + integrity sha1-invTcYa23d84E/I4WLV+yq9eQdQ= -min-document@^2.19.0: - version "2.19.0" - resolved "https://registry.yarnpkg.com/min-document/-/min-document-2.19.0.tgz#7bd282e3f5842ed295bb748cdd9f1ffa2c824685" - integrity sha1-e9KC4/WELtKVu3SM3Z8f+iyCRoU= +mime-db@1.43.0: + version "1.43.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.43.0.tgz#0a12e0502650e473d735535050e7c8f4eb4fae58" + integrity sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ== + +mime-types@^2.1.12: + version "2.1.26" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.26.tgz#9c921fc09b7e149a65dfdc0da4d20997200b0a06" + integrity sha512-01paPWYgLrkqAyrlDorC1uDwl2p3qZT7yl806vW7DvDoxwXi46jsjFbg+WdwotBIk6/MbEhO/dh5aZ5sNj/dWQ== dependencies: - dom-walk "^0.1.0" + mime-db "1.43.0" -prism-media@^0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/prism-media/-/prism-media-0.0.3.tgz#8842d4fae804f099d3b48a9a38e3c2bab6f4855b" - integrity sha512-c9KkNifSMU/iXT8FFTaBwBMr+rdVcN+H/uNv1o+CuFeTThNZNTOrQ+RgXA1yL/DeLk098duAeRPP3QNPNbhxYQ== +node-fetch@^2.6.0: + version "2.6.0" + resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.0.tgz#e633456386d4aa55863f676a7ab0daa8fdecb0fd" + integrity sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA== -process@^0.11.10: - version "0.11.10" - resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" - integrity sha1-czIwDoQBYb2j5podHZGn1LwW8YI= +prism-media@^1.2.0: + version "1.2.1" + resolved "https://registry.yarnpkg.com/prism-media/-/prism-media-1.2.1.tgz#168f323712bcaacb1d70ae613bf9d9dc44cf43d4" + integrity sha512-R3EbKwJiYlTvGwcG1DpUt+06DsxOGS5W4AMEHT7oVOjG93MjpdhGX1whHyjnqknylLMupKAsKMEXcTNRbPe6Vw== -snekfetch@^3.6.4: - version "3.6.4" - resolved "https://registry.yarnpkg.com/snekfetch/-/snekfetch-3.6.4.tgz#d13e80a616d892f3d38daae4289f4d258a645120" - integrity sha512-NjxjITIj04Ffqid5lqr7XdgwM7X61c/Dns073Ly170bPQHLm6jkmelye/eglS++1nfTWktpP6Y2bFXjdPlQqdw== +setimmediate@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" + integrity sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU= -tweetnacl@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-1.0.1.tgz#2594d42da73cd036bd0d2a54683dd35a6b55ca17" - integrity sha512-kcoMoKTPYnoeS50tzoqjPY3Uv9axeuuFAZY9M/9zFnhoVvRfxz9K29IMPD7jGmt2c8SW7i3gT9WqDl2+nV7p4A== +tweetnacl@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-1.0.3.tgz#ac0af71680458d8a6378d0d0d050ab1407d35596" + integrity sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw== -ws@^6.0.0: - version "6.2.1" - resolved "https://registry.yarnpkg.com/ws/-/ws-6.2.1.tgz#442fdf0a47ed64f59b6a5d8ff130f4748ed524fb" - integrity sha512-GIyAXC2cB7LjvpgMt9EKS2ldqr0MTrORaleiOno6TweZ6r3TKtoFQWay/2PceJ3RuBasOHzXNn5Lrw1X0bEjqA== - dependencies: - async-limiter "~1.0.0" +ws@^7.2.1: + version "7.2.1" + resolved "https://registry.yarnpkg.com/ws/-/ws-7.2.1.tgz#03ed52423cd744084b2cf42ed197c8b65a936b8e" + integrity sha512-sucePNSafamSKoOqoNfBd8V0StlkzJKL2ZAhGQinCfNQ+oacw+Pk7lcdAElecBF2VkLNZRiIb5Oi1Q5lVUVt2A== From 16fc473a2a3378952909a29b3976b21d66b7086d Mon Sep 17 00:00:00 2001 From: Julia Lange Date: Thu, 2 Apr 2020 19:14:49 -0700 Subject: [PATCH 3/4] +tsconfig, example info.json file, package.json. -.json & .js files from gitignore. JS files now go to /output --- .gitignore | 5 +++-- data/info.json | 4 ++++ package.json | 7 +++++++ tsconfig.json | 7 +++++++ 4 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 data/info.json create mode 100644 package.json create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore index 2f4b981..2ea6f14 100644 --- a/.gitignore +++ b/.gitignore @@ -74,5 +74,6 @@ typings/ # FuseBox cache .fusebox/ -*.json -*.js + +# Outputed JS files from compiling +output/ diff --git a/data/info.json b/data/info.json new file mode 100644 index 0000000..de0ff7c --- /dev/null +++ b/data/info.json @@ -0,0 +1,4 @@ +{ + "key": "your key here", + "prefix": "!" +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..0889106 --- /dev/null +++ b/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "@types/node": "^13.7.7", + "discord.js": "^12.0.1", + "fs": "^0.0.1-security" + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..86dba06 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "outDir": "output" + } +} \ No newline at end of file From bd6374c1c77e61d0f4e10d6833d68d97a273205d Mon Sep 17 00:00:00 2001 From: Julia Lange Date: Thu, 2 Apr 2020 19:15:26 -0700 Subject: [PATCH 4/4] +Commands{change name, help, read} better error catching. --- commands/change name.ts | 23 +++++++++++++ commands/commands.old | 71 ----------------------------------------- commands/help.ts | 33 +++++++++++++++++++ commands/read.ts | 41 ++++++++++++++++++++++++ main.ts | 20 ++++++++---- scripts/functions.ts | 34 ++++++++++++++------ 6 files changed, 135 insertions(+), 87 deletions(-) create mode 100644 commands/change name.ts create mode 100644 commands/help.ts create mode 100644 commands/read.ts diff --git a/commands/change name.ts b/commands/change name.ts new file mode 100644 index 0000000..50754e2 --- /dev/null +++ b/commands/change name.ts @@ -0,0 +1,23 @@ +import { squirrel } from "../scripts/enums"; +import { capitalize, getPlayerData, updateSquirrelFile } from "../scripts/functions"; + +module.exports = { + name: "namechange", + description: "Change the name of your squirrel, can only be used at level 1", + args: "**name** - the new name for your squirrel", + execute(msg, args) { + let data: squirrel = getPlayerData(msg.author.id); + + if (data.level == 1) { + if (args.length >= 1) { + data.name = capitalize(args[0]) + " " + data.name.split(' ')[1]; + updateSquirrelFile(msg.author.id, data); + msg.reply(`Name changed to ${data.name}`); + } else { + msg.reply(`Please provide a name`); + } + } else { + msg.reply(`Sorry, you have to be level 1 to change your name. You're stuck with ${data.name}`); + } + } +} diff --git a/commands/commands.old b/commands/commands.old index b7c8820..a6955e5 100644 --- a/commands/commands.old +++ b/commands/commands.old @@ -11,30 +11,12 @@ let processes: any = { args: "", run: (msg: any, data: player, args: string[], file: any) => encounter() }, - "help": { - title: "Help", - description: "Show a description of a command", - args: "**command** - the command you'd like to know more about", - run: (msg: any, data: player, args: string[], file: any) => help(msg, args) - }, "list": { title: "List", description: "List all commands", args: "", run: (msg: any, data: player, args: string[], file: any) => list(msg) }, - "read": { - title: "Read", - description: "Read a description of your squirrel", - args: "", - run: (msg: any, data: player, args: string[], file: any) => read(msg, data) - }, - "namechange": { - title: "Namechange", - description: "Change the name of your squirrel, can only be used at level 1", - args: "**name** - the new name for your squirrel", - run: (msg: any, data: player, args: string[], file: any) => nameChange(msg, data, args, file) - }, "races": { title: "Races", description: "List all the races", @@ -51,26 +33,6 @@ let processes: any = { //===COMMAND FUNCTIONS== -function help(msg: any, args: string[]): void { - let argument: string = args[0].toLowerCase(); - if (argument === "") { - msg.reply(`Please provide a command, like "!help help", or "!help races"\nAlternatively type "!list" for a list of commands`); - } else if (processes.hasOwnProperty(argument)) { - let embed = new Discord.RichEmbed() - .setTitle(processes[argument].title) - .setColor(COLOR) - .setDescription(processes[argument].description); - if (processes[argument].args === "") { - embed.addField("Arguments:", `This command has no arguments`); - } else { - embed.addField("Arguments:", processes[argument].args); - } - msg.channel.send(embed); - } else { - msg.reply(`That command does not exist`); - } -} - function list(msg: any): void { let embed = new Discord.RichEmbed() .setTitle("List of Commands") @@ -83,39 +45,6 @@ function list(msg: any): void { msg.author.send(embed); } -function read(msg: any, data: player): void { - let embed = new Discord.RichEmbed() - .setTitle(msg.author.username) - .setColor(COLOR) - .setThumbnail(msg.author.avatarURL) - .setDescription("Squirrel Info") - .addField("Name", data.name) - .addField("Race", raceText(data.race)) - .addField("Class", capitalize(data.class)) - .addField("Nuts", data.nuts) - .addField("Level", data.level); - if (data.dm === true) - embed.addField("DM Points", data.dm_points); - - msg.channel.send(embed); -} - - - -function nameChange(msg: any, data: player, args: string[], file: any): void { - if (data.level == 1) { - if (args.length >= 1) { - data.name = capitalize(args[0]) + " " + data.name.split(' ')[1]; - fs.writeFileSync(file, JSON.stringify(data)); - msg.reply(`Name changed to ${data.name}`); - } else { - msg.reply(`Please provide a name`); - } - } else { - msg.reply(`Sorry, you have to be level 1 to change your name. You're stuck with ${data.name}`); - } -} - function printRaces(msg: any): void { let print = "The races are: "; for (let i = 0; i < races.length; i++) { diff --git a/commands/help.ts b/commands/help.ts new file mode 100644 index 0000000..a85713e --- /dev/null +++ b/commands/help.ts @@ -0,0 +1,33 @@ +import { client } from "../main"; +import { capitalize, COLOR } from "../scripts/functions"; + +module.exports = { + name: 'help', + description: "Show a description of a command", + args: "**command** - the command you'd like to know more about", + execute(msg, args) { + const command = args[0].toLowerCase(); + if (command === "") { + msg.reply(`Please provide a command, like "!help help", or "!help races"\nAlternatively type "!list" for a list of commands`); + return; + } + + if (client.commands.has(command)) { + const commandData: any = client.commands.get(command); + const helpEmbed: object = { + color: COLOR, + title: capitalize(commandData.name), + description: commandData.description, + fields: [ + { + name: 'Arguments', + value: commandData.args + } + ] + } + msg.channel.send("{ embed: helpEmbed }"); + } else { + msg.reply(`That command does not exist`); + } + } +} \ No newline at end of file diff --git a/commands/read.ts b/commands/read.ts new file mode 100644 index 0000000..d9daafa --- /dev/null +++ b/commands/read.ts @@ -0,0 +1,41 @@ +import { squirrel } from "../scripts/enums"; +import { classText, COLOR, getPlayerData, raceText } from "../scripts/functions"; + +module.exports = { + name: "read", + description: "Read a description of your squirrel", + args: "", + execute(msg, args) { + const data: squirrel = getPlayerData(msg.author.id); + const squirrelEmbed: object = { + color: COLOR, + title: msg.author.username, + thumbnail: { + url: msg.author.avatarURL() + }, + fields: [ + { + name: 'Name', + value: data.name + }, + { + name: 'Race', + value: raceText(data.race) + }, + { + name: 'Class', + value: classText(data.class) + }, + { + name: 'Nuts', + value: data.nuts + }, + { + name: 'Level', + value: data.level + } + ] + } + msg.channel.send({ embed: squirrelEmbed }); + } +} diff --git a/main.ts b/main.ts index fbfa74a..75711cf 100644 --- a/main.ts +++ b/main.ts @@ -2,12 +2,12 @@ //===Requirements=== export const fs = require('fs'); -export const Discord = require('discord.js'); +const Discord = require('discord.js'); const info = JSON.parse(fs.readFileSync(`./data/info.json`)); const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); -const client = new Discord.Client(); +export const client = new Discord.Client(); client.commands = new Discord.Collection(); for (const file of commandFiles) { @@ -15,6 +15,8 @@ for (const file of commandFiles) { client.commands.set(command.name, command); } + + //===Initalization=== client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); @@ -37,12 +39,18 @@ function executeCommand(msg: any) { let args: Array = [""]; // arguments of the message if (messageContent.length > 1) args = messageContent.slice(1); - if (!client.commands.has(command)) return; - + if (!client.commands.has(command)) { + msg.reply(`That command: "${command}" doesn't exist. Sad.`); + return; + } try { client.commands.get(command).execute(msg, args); } catch (e) { - console.error(e); - msg.reply(`Failed to execute the given command for some reason. Sad.`); + if (e.code === 'ENOENT') + msg.reply(`Please create a squirrel using "!create" first, before trying that command.`); + else { + console.error(e); + msg.reply(`Failed to execute the given command for some reason. Sad.`); + } } } \ No newline at end of file diff --git a/scripts/functions.ts b/scripts/functions.ts index d291c43..15f0ea0 100644 --- a/scripts/functions.ts +++ b/scripts/functions.ts @@ -1,10 +1,14 @@ -import { squirrel } from "../scripts/enums"; import { fs } from "../main"; +import { squirrel } from "../scripts/enums"; const races: Array = ["tree", "ground", "chipmunk"]; const classes: Array = ["rogue", "berserker", "knight", "ranger", "priest"]; const lastNames: Array = ["Nutcrack", "Nutmeg", "Seedsower", "McScuiri", "Rodentia", "Arbora", "Patagi"]; -// const COLOR: string = "#E81B47"; +export const COLOR: string = "#E81B47"; + +export function getPlayerData(playerId: string): squirrel { + return JSON.parse(fs.readFileSync(`./data/playerdata/${playerId}.json`)) +} export function newSquirrel(name: string, race: string, classtype: string): squirrel { let raceNum: number = -1; @@ -44,14 +48,24 @@ export function randomInt(low: number, high: number): number { return Math.floor(Math.random() * (high - low + 1) + low) } -// export function raceText(race: number): string { -// if (race === 2) return capitalize(races[race]); -// else if (race === 0 || race === 1) return `${capitalize(races[race])} Squirrel`; -// else { -// console.log(`Error ${race} is not a valid race`); -// return ""; -// } -// } +export function raceText(raceIndex: number): string { + if (raceIndex >= races.length) { + console.log(`Error ${raceIndex} is outside of bounds`); + return ""; + } + + if (raceIndex === 2) return capitalize(races[raceIndex]); + else if (raceIndex === 0 || raceIndex === 1) return `${capitalize(races[raceIndex])} Squirrel`; +} + +export function classText(classIndex: number): string { + if (classIndex >= classes.length) { + console.log(`Error ${classIndex} is outside of bounds`); + return ""; + } + + return capitalize(classes[classIndex]); +} export function capitalize(toCaps: string): string { return toCaps.charAt(0).toUpperCase() + toCaps.slice(1).toLowerCase();