Skip to content

Instantly share code, notes, and snippets.

@ThomasAunvik
Created May 19, 2020 11:49
Show Gist options
  • Save ThomasAunvik/b89f6776ba950094215ca278ebc9a135 to your computer and use it in GitHub Desktop.
Save ThomasAunvik/b89f6776ba950094215ca278ebc9a135 to your computer and use it in GitHub Desktop.
import { Client, Collection, Message } from 'discord.js';
import * as fs from 'fs';
const config = require('./config.json');
export interface Command {
default: Command;
name: string;
guildOnly: boolean;
args: string[];
usage: string;
aliases: string[];
cooldown: number;
execute(message: Message, args: string[]);
}
const client = new Client();
const cooldowns: Collection<string, Collection<string, number>> = new Collection();
const commands: Collection<string, Command> = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.ts'));
commandFiles.forEach(async (file) => {
if (file.includes('template') || file.includes('category_info')) return;
const command: Command = await import(`./commands/${file}`).then((v: Command) => v.default);
commands.set(command.name, command);
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
const args: Array<string> = message.content.slice(config.prefix.length).split(/ +/);
const commandName: string = args.shift().toLowerCase();
if (!commands.has(commandName)) return;
const command = commands.get(commandName) || commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command in DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${config.prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command`);
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
}
try {
command.execute(message, args);
}
catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command!');
}
});
client.login(config.token);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment