Discord.JS UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“startsWith”

时间:2021-07-21 07:57:58

标签: javascript discord typeerror

我目前正在尝试在 Discord 机器人中实现语音识别,但我一直遇到错误。我也是 Discord.JS 和整个编程的新手。

我从解释普通消息而不是语音的事件文件中复制了以下一些代码,并且在那里运行良好。

以下行抛出“UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined”:if (!msg.content.startsWith(prefix) || msg.author.bot) return;

我的整个文件:

const fs = require('fs');

module.exports = {
    name: "join",
    description: "Joins the VC that user is in",
    async execute(client, message, args, Discord) {
        const voiceChannel = message.member.voice.channel;
        const connection = await voiceChannel.join();

        if (!voiceChannel) return message.channel.send('Join a VC retard');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT')) return message.channel.send("You don't have the correct permissions");
        if (!permissions.has('SPEAK')) return message.channel.send("You don't have the correct permissions");

        connection.client.on('speech', msg => {
            console.log(msg.content);
            const prefix = 'yo bot ' || 'Aries ' || 'Ares ' || 'yobot ';
            if (!msg.content.startsWith(prefix) || msg.author.bot) return;

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

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

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

2 个答案:

答案 0 :(得分:0)

如果消息内容不是字符串,则不能使用该函数。

您需要先检查消息内容是否存在:

if (!msg.content 
    || !msg.content.startsWith(prefix)
    || msg.author.bot
   ) {...}

答案 1 :(得分:0)

在阅读它的 startsWith 属性之前,您需要确保定义了消息内容。您可以使用 optional chaining 执行此操作。

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

msg?.content?.startWith(prefix) 将返回 undefined ,如果:

  • msg 没有 content 属性
  • content 没有 startWith 属性