Proper command handling

This commit is contained in:
entar 2025-05-18 11:21:59 +07:00
parent a867e1979a
commit f429656c0b
3 changed files with 80 additions and 5 deletions

11
commands/base.js Normal file
View File

@ -0,0 +1,11 @@
const client = require("../index")
module.exports = [
{
name: "ping",
run: (ctx, args) => {
console.log(ctx, args)
ctx.reply(`Pong! ${args}`)
}
}
]

View File

@ -1,4 +1,4 @@
const client = require("../index")
const {client} = require("../index")
client.on("ready", () => {
console.log(`Bot ready as ${client.user.username}`)

View File

@ -1,5 +1,5 @@
// Base requires
const { Client, GatewayIntentBits } = require("discord.js")
const { Client, GatewayIntentBits, Events } = require("discord.js")
const fs = require("fs")
// TOKEN is stored in the .env file (node --env-file=.env index.js)
@ -9,18 +9,21 @@ const token = process.env.TOKEN
const client = new Client({
intents: [
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages]
GatewayIntentBits.DirectMessages,
GatewayIntentBits.Guilds
]
}
)
module.exports = client
// Exporting the client for event and command files to use it
module.exports = {client: client, dir: __dirname}
// Requiring all the event files.
fs.readdir(`${__dirname}/events/`, (err, files) => {
files.forEach(file => {
if (!file.endsWith(".js")) {
return
}
@ -28,6 +31,67 @@ fs.readdir(`${__dirname}/events/`, (err, files) => {
})
})
// Command list
const commands = []
// Requiring the command files
fs.readdir(`${__dirname}/commands`, (err, files) => {
files.forEach(file => {
if (!file.endsWith("js")) {
return
}
const commandList = require(`${__dirname}/commands/${file}`)
commands.push(commandList)
})
})
// Function to get the command with that name
function getCommand(commandName) {
var command;
commands.forEach(commandList => {
commandList.forEach(commandArray => {
if (commandArray.name == commandName) {
command = commandArray
}
})
})
return command;
}
// Parsing commands on message create
client.on("messageCreate", async (message) => {
var content = message.content
// Continue only if starts with the prefix
if (!content.startsWith('!')) {
return
}
// Need to remove the prefix after the check
content = content.slice(1, content.length)
// Splitting the message into command and args
const parsed = content.split(" ")
// Getting command name
const command = parsed[0]
// Removing command from the args
const args = parsed.filter(value => {return value != command})
// Actual command
const realCommand = getCommand(command)
// Only continue if command exists
if (!realCommand) {
return
}
// Run command
realCommand.run(message, args)
})
// Time to login
client.login(token)