Skip to content

Commit

Permalink
🎉 Initial commit
Browse files Browse the repository at this point in the history
wip :)
  • Loading branch information
4nt0n10M4 committed Oct 25, 2021
0 parents commit c11dc05
Show file tree
Hide file tree
Showing 21 changed files with 1,402 additions and 0 deletions.
13 changes: 13 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Your bot's token https://discord.com/developers/applications
DISCORD_TOKEN=
# Your id
OWNER_ID=
# The guild you're ussing to test slash commands (only fill if on dev mode)
DISCORD_DEV_GUILD=
# Bot prefix
#PREFIX=jo!


# Debugging config
#LOG_LEVEL=debug
#PRETTY_PRINT=true
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.env
node_modules/
dist/

# For local testing cmds
src/commands/dev_*
6 changes: 6 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"mikestead.dotenv",
"vtrois.gitmoji-vscode"
]
}
21 changes: 21 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\src\\index.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
// "outputCapture": "std"
"console": "integratedTerminal"
}
]
}
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2021 Antonio M A (@4nt0n10M4)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "jo-bot",
"version": "0.0.1",
"main": "dist/index.js",
"license": "MIT",
"scripts": {
"build": "npx tsc",
"start": "node dist/.",
"dev": "yarn build && yarn start"
},
"dependencies": {
"@discordjs/builders": "^0.6.0",
"@discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.23.1",
"discord-cmd-parser": "^2.2.0",
"discord.js": "^13.2.0",
"dotenv": "^10.0.0",
"pino": "^7.0.3",
"pino-pretty": "^7.1.0",
"typescript": "^4.4.3"
}
}
232 changes: 232 additions & 0 deletions src/CommandHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
import Collection from "@discordjs/collection";
import BotClient from "./types/Client";
import Command from "./types/Command";
import { promises as fs } from 'fs';
import path from 'path';
import { CommandInteraction, GuildMember, Message } from "discord.js";
import { SlashCommandBuilder } from "@discordjs/builders";
import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v9';
import CommandCall from "./types/CommandCall";
import Parser, { createParser } from 'discord-cmd-parser';
import { Args, capitalize, CommandNotFoundError, InvalidChannelTypeError } from "./types/misc";
import MentionsParser from "./types/MentionsParser";

class CommandHandler {
constructor(client: BotClient){
this.client = client;
this.commands = new Collection();
this.aliases = new Collection();
this.prefix = process.env.PREFIX || 'jo!';

this.argsParser = createParser();
this.mentionsParser = new MentionsParser(this.client);
}

public commands: Collection<String, Command>
public aliases: Collection<String, String>
public client: BotClient;
public prefix: string;
public argsParser: Parser.Parser;
public mentionsParser: MentionsParser;

getCmd(name: string){
let cmd = this.commands.get(name);
if(!cmd){
let theCommandIsAnAliase = this.aliases.get(name);
if(theCommandIsAnAliase) cmd = this.commands.get(theCommandIsAnAliase);
}
if(!cmd)throw new CommandNotFoundError("Command not found");

return cmd;
}

async handleMessage(msg: Message){
if(msg.author.bot)return;
if(!msg.content.startsWith(this.prefix))return;
if(msg.guild == null)return; // Igmore DMs
if(msg.member == null)return; //ts stop crying

let content = msg.content.substring(this.prefix.length).trim();
let args = content.split(' '); args.shift(); // remove prefix and command name
let argsStr = args.join(' ');
let current_arg; // used to know what argument throwed the exception
try {
let cmd = this.getCmd(content.split(' ')[0]);

let parsedArgs : Args = this.argsParser.parseCommandArgs(this.argsParser.parse(argsStr), cmd.argsForParser()); // parse general args
Object.keys(parsedArgs).forEach(k => { if(parsedArgs[k] == '')delete parsedArgs[k] }) // remove empty args
// handle args
for await (let a of cmd.args){
current_arg = a.name;
if(parsedArgs[a.name] == undefined)continue;
try {
if(a.type == 'content'){ // handle "content" args
parsedArgs[a.name] = argsStr;
} else if(a.type == 'user'){
parsedArgs[a.name] = await this.mentionsParser.userByMentionOrId(parsedArgs[a.name]);
} else if(a.type == 'role'){
if(!msg.guild)throw new Error("This command can't be used on DMs");

parsedArgs[a.name] = await this.mentionsParser.roleByMentionOrId(parsedArgs[a.name], msg.guild);
} else if (a.type == 'channel'){
if(!msg.guild)throw new Error("This command can't be used on DMs");

parsedArgs[a.name] = await this.mentionsParser.channelByMentionOrId(parsedArgs[a.name], msg.guild);
if(a.channelTypes){
if(!a.channelTypes.includes(parsedArgs[a.name].type))throw new InvalidChannelTypeError(`Invalid channel, it must be ${a.channelTypes.join(' or ')}. // You provided ${parsedArgs[a.name].type}`);
}
}
} catch (e){
if(a.required)throw e; // If is required we throw the error but otherwise we just ignore the arg
delete parsedArgs[a.name];
}
}
current_arg = undefined;

let neededArgs = cmd.args.filter(a => a.required) // get required args
.filter(a => parsedArgs[a.name] == undefined); // check if any of those is undefined
// If any of the required args was not specified throw an Error
if(neededArgs.length > 0)return await msg.reply({ content: `**Error**: Not enough arguments passed.\n\`\`\`${this.prefix}${cmd.usage}\`\`\`\`\`\`${cmd.argsExplanation}\`\`\`` }); // ${neededArgs.map(a => a.name).join('", "')}

// All the args SeemsGood so we call the cmd
await this.execCmd(new CommandCall({command: cmd, client: this.client, args: parsedArgs, member: msg.member, _type: 'Message', _source: msg}));
} catch(e){
if(e instanceof CommandNotFoundError)return this.client.logger.debug({file: 'CommandHandler', fnc: 'handleMessage'}, 'Handled error (cmd not found)', e);

msg.reply({ content: `${current_arg ? `Error found while parsing \`${current_arg}\` arg.\n` : ''}\`\`\`js\n${e}\n\`\`\`` });
if(e instanceof InvalidChannelTypeError)return this.client.logger.debug({file: 'CommandHandler', fnc: 'handleMessage'}, 'Handled error (invalid channel)', e);
this.client.logger.error({file: 'CommandHandler', fnc: 'handleMessage', msg, user: {tag: msg.author.tag, id: msg.author.id}, guild: {id: msg.guild?.id, name: msg.guild?.name}}, 'Error handling message', e);
}
}

async handleSlashCommand(interaction: CommandInteraction){
if(!(interaction.member instanceof GuildMember)){
if(interaction.member == null)throw new Error("[CommandHandler/handleSlashCommand] Member is null");
let member = await interaction.guild?.members.fetch(interaction.member.user.id);
if(member == undefined)throw new Error("[CommandHandler/handleSlashCommand] Couldn't fetch member");
interaction.member = member;
}
try {
let args: Args = {_orig: interaction};
// handle args
interaction.options.data.forEach(data => {
if(data.type == 'STRING'){ // handle "content" args
args[data.name] = data.value;
} else if(data.type == 'USER'){
return args[data.name] = interaction.options.get(data.name)?.user;
} else if(data.type == 'ROLE'){
return args[data.name] = interaction.options.get(data.name)?.role;
} else if(data.type == 'CHANNEL'){
return args[data.name] = interaction.options.get(data.name)?.channel;
}
});
await this.execCmd(new CommandCall({command: interaction.commandName, client: this.client, args, member: interaction.member, _type: 'SlashCommand', _source: interaction}));
} catch(e){
this.client.logger.error({file: 'CommandHandler', fnc: 'handleSlashCommand', interaction, user: {tag: interaction.user.tag, id: interaction.user.id}, guild: {id: interaction.guild?.id, name: interaction.guild?.name}}, 'Error handling SlashCommand', e);
}
}

async execCmd(call: CommandCall){
let channel = call._source?.channel?.type !== 'DM' ? call._source.channel : undefined;
let permsCheck = call.command.hasPermission(call.member, channel);
if(!permsCheck.check){
if(call.command.noPermsSilent)return;

call.reply({ content: `**Error**: The \`${call.command.name}\` command requires one or more permissions you're lacking: \`${permsCheck.missing.map(p => capitalize(p.split('_').join(' ').toLowerCase())).join('`, `')}\`.` });
return this.client.logger.info({file: 'CommandHandler', fn: 'execCmd', cmd: call.command.name, args: call.args, user: {id: call.member.id, tag: call.member.user.tag}, guild: {id: call._source.guild?.id, name: call._source.guild?.name}, permsCheck}, 'Denied execution of command, lacking permissions');
}

try{
call.command.run(call);
this.client.logger.info({file: 'CommandHandler', fn: 'execCmd', cmd: call.command.name, args: call.args, user: {id: call.member.id, tag: call.member.user.tag}, guild: {id: call._source.guild?.id, name: call._source.guild?.name}}, 'Executed command');
} catch (e){
call.reply({ content: `\`\`\`js\n${e}\n\`\`\`` })
this.client.logger.error({file: 'CommandHandler', fnc: 'execCmd', call}, 'Error executing command', e);
}
}

async loadCommands(){
let files = (await fs.readdir(path.join(__dirname, './commands'))).filter(file => file.endsWith('.js'));
this.commands.clear();

files.forEach(command => {
let cmd = require(`./commands/${command}`).default;
cmd = new cmd({commandHandler: this});
cmd.aliases.forEach((name: string, i: number) => {
if(i == 0){
this.commands.set(name, cmd);
} else {
this.aliases.set(name, cmd.name);
}
});
});
}

async refreshSlashCommands(){
let commands = this.commands
.filter(cmd => !cmd.hidden && !cmd.ownerOnly)
.map(cmd => {
let description = cmd.description ? cmd.description : `aka ${cmd.aliases.join(', ')}`;
if(description.length >= 100){
this.client.logger.warn({cmd: cmd.name, fn: 'refreshSlashCommands', file: 'CommandHandler', description}, `'${cmd.name}' description is too long (${description.length}>=100)`);
description = description.substring(0, 97)+'...';
}

let sc = new SlashCommandBuilder().setName(cmd.name)
.setDescription(description);

cmd.args.forEach(arg => {
if(arg.type == 'string' || arg.type == 'content'){
return sc.addStringOption(option => option
.setName(arg.name)
.setDescription(arg.description)
.setRequired(arg.required)
);
} else if (arg.type == 'user') {
return sc.addUserOption(option => option
.setName(arg.name)
.setDescription(arg.description)
.setRequired(arg.required)
);
} else if (arg.type == 'role'){
return sc.addRoleOption
(option => option
.setName(arg.name)
.setDescription(arg.description)
.setRequired(arg.required)
);
} else if (arg.type == 'channel'){
return sc.addChannelOption
(option => {
option
.setName(arg.name)
.setDescription(arg.description)
.setRequired(arg.required)

// TODO: `channel_type` is not yet supported in djs slash cmds builder, it should be on the next release https://github.com/discordjs/builders/pull/41
// if(arg.channelTypes)option.channel_types = arg.channelTypes;

return option;
});
}
});

return sc.toJSON();
});

const rest = new REST({ version: '9' }).setToken(this.client.token+'');

try{
await rest.put(process.env.DISCORD_DEV_GUILD ? Routes.applicationGuildCommands(this.client.application!.id, process.env.DISCORD_DEV_GUILD) : Routes.applicationCommands(this.client.application!.id), { body: commands })
this.client.logger.info('✅ Slash commands refreshed');
} catch(e){
this.client.logger.error('Error updating slash commands', e);
return e;
}

return true;
}
}

export default CommandHandler;
19 changes: 19 additions & 0 deletions src/commands/echo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Command from '../types/Command';
import CommandArg from '../types/CommandArg';
import CommandCall from "../types/CommandCall";

class EchoCommand extends Command {
constructor(){
super({
aliases: ['echo'],
description: 'Make the bot say anything you want',
args: [new CommandArg({name: 'text', description: 'The text to say', required: true, type: "content"})]
});
}

run(call: CommandCall){
return call.reply({ content: call.args.text, allowedMentions: {parse: []} });
}
};

export default EchoCommand;
31 changes: 31 additions & 0 deletions src/commands/eval.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Command from '../types/Command';
import CommandArg from '../types/CommandArg';
import CommandCall from "../types/CommandCall";

class EvalCommand extends Command {
constructor(){
super({
aliases: ['eval'],
ownerOnly: true,
noPermsSilent: true,
hidden: true,
args: [new CommandArg({name: 'code', description: 'The code to eval', required: true, type: 'content'})]
});
}

run(call: CommandCall){
let response;
try{
response = eval(call.args.code);
} catch(e){
response = e;
}
if(typeof response !== 'string')response = JSON.stringify(response, null, 2);

response = response.replace(process.env.DISCORD_TOKEN+"", '');

return call.reply({ content: `\`\`\`js\n${response.replace('\`', '\\\`')}\n\`\`\`` });
}
};

export default EvalCommand;
Loading

0 comments on commit c11dc05

Please sign in to comment.