discord.js 命令处理程序错误

discord.js command handler Bugs

我想尝试命令处理程序,但出现错误。 如果我 运行 ,ping 机器人是响应,但是如果我 运行 , 我得到一个错误,这是日志:

TypeError: Cannot read property 'execute' of undefined
at Client.<anonymous> (C:\Users\User\disbot\app.js:35:33)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users\User\disbot\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\User\disbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\User\disbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (C:\Users\User\disbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (C:\Users\User\disbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (C:\Users\User\disbot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:394:28)
at Receiver.receiverOnMessage (C:\Users\User\disbot\node_modules\ws\lib\websocket.js:978:20)

这是 app.js 中的代码(主要)

const Discord = require('discord.js')
const { Collection } = require('discord.js')
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
const fs = require("fs")

const PREFIX = ','

client.commands = new Collection()

const files = fs
    .readdirSync("./src/commands")
    .filter((file) => file.endsWith(".js"))

for(const file of files) {
    const command = require (`./src/commands/${file}`)
    client.commands.set(command.name, command);
}

if(process.env.NODE_ENV !==  `production`) {
    require('dotenv').config()
}

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    client.user.setActivity(process.env.STATUS_NAME, { type: process.env.STATUS_TYPE })
    client.user.setStatus(`${process.env.PROFILE_TYPE}`)
});

client.on('messageCreate', message => {
    if(message.author.bot) return;
    if(!message.content.startsWith(PREFIX)) return;
    let args = message.content.substring(PREFIX.length).split(" ");
    client.commands.get(args[0]).execute(message);
});

client.login(process.env.TOKEN)

这个在ping.js

module.exports = {
     name: 'ping',
     description: 'Ping commands adalah mengetes koneksi bot.',
     execute(message) {
         message.channel.send(`pong`);
     }
 }

不是从参数获取命令的好方法,args[0] 这里没有任何上下文,就像你的情况一样,如果你只是输入 , 将不会被注册为命令,相反你可以尝试这个:


    const command = client.commands.get(args[0])
    if (!command) {
        return
    } else {
        try {
            command.execute(message);
        } catch (e) {
            console.log(e)
        }
    }

aliter


    const commandName = args.shift().toLowerCase();
    
    if (!client.commands.has(commandName)) return;
    const command = client.commands.get(commandName)
     try {
        command.execute(message);
    } catch (error) {
        console.log(error);
    }