提问者:小点点

在 Discord JS 上收到错误“无法读取未定义的'内容'的属性”


代码如下 我有一个简单的不和谐机器人,并在事件下添加了一条消息文件--公会

    module.exports = (Discord, client, message) => {
    const prefix = '!';
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const cmd = args.shift().toLowerCase();

    const command = client.commands.get(cmd);

    if(command) commmand.execute(client, message, args, Discord);
 }

```
Just Incase You need it here is my main file
```
const Discord = require('discord.js');
const client = new Discord.Client();
client.commands = new Discord.Collection();
client.events = new Discord.Collection();


['command_handler', 'event_handler'].forEach(handler =>{;
    require(`./handlers/${handler}`)(client, Discord)
})

 

 
client.login('My Token');
full error below
TypeError: Cannot read property 'content' of undefined
    at Object.module.exports (E:\Software\Discord Bots\BombBot\events\guild\message.js:3:17)
    at Client.emit (events.js:315:20)
    at MessageCreateAction.handle (E:\Software\Discord Bots\BombBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (E:\Software\Discord Bots\BombBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (E:\Software\Discord Bots\BombBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (E:\Software\Discord Bots\BombBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (E:\Software\Discord Bots\BombBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (E:\Software\Discord Bots\BombBot\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (events.js:315:20)

关于:这个不和谐机器人是一个简单的机器人,我正在尝试使用命令和事件处理程序来做,因为我是 discord js 而不是 javascript 的新手,我试图看看是否有一些问题,但找不到任何问题。调试窗口也无济于事,因为它是一个值/变量,显示为未定义,但在上面定义。因为我有点新,所以我使用了教程:https://www.youtube.com/watch?v=Sihf7B8D4Y8 并多次重写了代码。如果您有想法,请在我再次重写之前告诉我。

The Debugger is below
 E:\Software\node JS\node.exe .\index.js
BOT Is ONLINE
                                                          events/client/ready.js:4
Uncaught TypeError: Cannot read property 'content' of undefined
No debugger available, can not send 'variables'
Process exited with code 1

共1个答案

匿名用户

很难根据您提供的信息确定错误的来源。

不保证消息内容。来自嵌入的其他机器人的消息没有内容,因此未定义。要解决此问题,请在您的条件中添加可选链接:

if(!message.content?.startsWith(prefix) || message.author.bot) return;

如果这不起作用,这可能意味着您的消息对象根本不是 Discord 消息。确保将参数正确传递给函数。