类型错误:无法读取未定义的 Discord.js 的属性“id”

时间:2021-02-26 19:53:15

标签: javascript node.js discord discord.js

我正在尝试制作一个票务系统,该系统创建一个频道,然后在该频道中发送嵌入内容。

但我得到了 TypeError Cannot read property 'id' of undefined。这是我的代码片段:

const openedTicket = message.guild.channels.cache.find((r) => r.name === `${message.author.username}s-ticket`);

const openedEmbed = new Discord.MessageEmbed().setDescription("Support will be with you shortly." + "To close this ticket react with :lock:");

setTimeout(function () {
    client.channels
        .get(openedTicket.id)
        .send(openedEmbed)
        .then((msg) => {
            msg.react("?");
        });
}, 1000);

2 个答案:

答案 0 :(得分:0)

这真的很容易做到。您只需要一个 .then() 即可继续。所以在你的情况下,这将是:

message.guild.channels.create(`${message.author.username}s-ticket`, {
    type: 'text',
    permissionOverwrites: [
        {
            allow: 'VIEW_CHANNEL',
            id: message.author.id
        },
        {
            deny: 'VIEW_CHANNEL',
            id: message.guild.id
        }
    ]
}).then(channel => {
    const openedEmbed = new Discord.MessageEmbed().setDescription("Support will be with you shortly." + "To close this ticket react with :lock:");

    setTimeout(function () {
        channel.send(openedEmbed)
            .then((msg) => {
                msg.react("?");
            });
    }, 1000);
})

你的反应已经有了正确的解决方案。

编辑:

您的原始代码显示为空,因为您的名字中很可能有一些大写字母,但是所有不和谐文本频道都是小写的,空格被替换为破折号。因此,当您寻找频道时,您需要将所有这些都纳入您的搜索中。所以你的 openedTicket 常量应该是这样的

const openedTicket = message.guild.channels.cache.find(r => r.name === `${message.author.username}s-ticket`.replace(" ", "-").toLowerCase());

答案 1 :(得分:-1)

要么频道不存在,要么你需要使用这个:

const openedTicket = message.guild.channels.cache.find(r => r.name === `${message.author.username}s-ticket`).id;

末尾的 id 意味着您不必拥有 openedTicket.id 并且更容易捕获错误。

此外,您需要将 cache 添加到您的 client.channels.get(openedTicket)

=> client.channels.cache.get(openedTicket)

您还应该获取所有频道以确保您的机器人搜索所有频道:

await message.guild.channels.fetch(); //using await, to return a promise
client.channels.cache.get(openedTicket);