无法读取未定义的属性“发送”:Discord 机器人创建频道并向其发送消息然后对其做出反应

我正在尝试制作一个机器人,它将嵌入的消息发送到一个频道,然后对其做出反应。它发送到的频道是由 discord 机器人创建的,所以我没有频道的 ID,只有简单的名称island-info-\<user ID>。该频道在您运行命令时创建,/channel但很快会在您加入服务器时更改为并在您离开时删除。当我运行这段代码时:


else if (cmd === `${prefix}channel`){

    const name = "island-info-" + message.author.username.toLowerCase();

    message.guild.channels.create(name, {

        type: 'text',

        permissionOverwrites: [

        {

            id: message.guild.id, 

            deny: ["VIEW_CHANNEL", "SEND_MESSAGES"]

        },

        {

            id: message.author.id,

            allow: ["VIEW_CHANNEL", "ADD_REACTIONS"]

        },

        ],

        parent: "734170209107051074"

    })

    .catch(console.error);

    const Embed = new Discord.MessageEmbed()

    .setTitle('ISLAND INFO')

    message.guild.channels.cache.find(r => r.name === name).send(Embed)

    message.guild.channels.cache.find(r => r.name === name).messages.fetch({ limit: 1 }).then(messages => {

        messages.first().react("👍")

    }).catch(err => {

        console.error(err)

    })

    }

它抛出错误:Cannot read property 'send' of undefined这是因为 line message.guild.channels.cache.find(r => r.name === name).send(Embed)。有没有更好的方法来做到这一点,因为当我取出cache零件时,它说find这不是命令。谢谢!


(编辑)我相信这是因为它在创建频道的同时或之前将消息发送到频道,出于我不知道的原因,有没有人知道解决这个问题的方法,因为当我在之后访问频道时最后}一切正常


慕桂英3389331
浏览 62回答 2
2回答

慕码人2483693

在您尝试向其发送消息时,该频道不存在。您正在使用.then(),.catch()因此您必须对承诺有一定的了解。请记住,promise 表示的操作不会在任何地方完成,除了在 promise 回调内部(或在您使用 之后await)。基本上你是这样写的://send a request to Discord to make a channelmessage.guild.channels.create(name, {...}).catch(console.error);...//immediately, without waiting for Discord to make the channel, send a message to itmessage.guild.channels.cache.find(r => r.name === name).send(Embed);您发送消息的代码取决于已经创建的频道。因此,它需要在承诺的.then()回调中。channels.create(...)这还有一个额外的好处,即 promise 将实际解析通道对象,因此您可以调用.send()它而不需要搜索缓存。message.guild.channels.create(name, {...}).then(chan => {&nbsp; //make embed&nbsp; chan.send(Embed);}).catch(console.error);您将需要类似地附加 a.then()到.send()呼叫以对刚刚发送的消息做出反应。因为您需要等待 Discord 真正发出消息,然后才能对其做出反应。

慕森卡

如果未定义,则意味着您需要的具有该名称的频道不存在。我不知道在你的情况下你会如何处理这个,但这是一个选择:const Embed = new Discord.MessageEmbed()&nbsp; .setTitle('ISLAND INFO');const channel = message.guild.channels.cache.find(r => r.name === name);if (!channel) message.channel.send("Your channel does not exist!");else {&nbsp; channel.send(embed)}按用户名存储数据时要注意的另一件事是用户名可以更改。我建议你用用户 ID 命名你的频道,因为这些永远不会改变
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript