discord.js 命令处理程序错误
Posted
技术标签:
【中文标题】discord.js 命令处理程序错误【英文标题】:discord.js command handler Bugs 【发布时间】:2021-11-02 06:04:56 【问题描述】:我想尝试一个命令处理程序,但我有一个错误。
如果我运行,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 (main) 中的代码
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`);
【问题讨论】:
【参考方案1】:不是从参数获取命令的好方法,args[0]
在这里没有任何上下文,如果你只是输入 ,
不会被注册为命令,而是你可以试试这个:
const command = client.commands.get(args[0])
if (!command)
return
else
try
command.execute(message);
catch (e)
console.log(e)
升力
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);
【讨论】:
以上是关于discord.js 命令处理程序错误的主要内容,如果未能解决你的问题,请参考以下文章
斜杠命令处理程序中的 Discord.js v13 TypeError
在 discord.js 中制作带有前缀的命令处理程序时出现问题 [重复]