【问题标题】:Discord.js: Cannot read property "cache" of undefinedDiscord.js:无法读取未定义的属性“缓存”
【发布时间】:2021-03-15 20:21:03
【问题描述】:

我目前正在使用 discord.js 编写一个不和谐机器人。我正在尝试通过 id 从特定公会获取特定频道,然后将消息写入其中。我在 grepper 上找到了这个解决方案,但是在运行时出现错误“无法读取未定义的属性‘缓存’”但是为什么通道未定义? discord.js 文档将频道列为公会的属性:https://discord.js.org/#/docs/main/stable/class/Guild。有人知道为什么会这样吗?

client.guilds.fetch(guildID).channels.cache.get(channelID)

【问题讨论】:

  • 你运行的是什么版本的 Discord?
  • Discord.js 版本 12.3.1
  • 这段代码什么时候运行? (任何事件或?=)
  • client.on("ready", () => { ... }) 事件内部

标签: javascript node.js discord.js


【解决方案1】:

client.guilds.fetch(guildID) 是一个承诺,你需要的是:

client.guilds.fetch(guildID).then(guild => guild.channels.cache.get(channelID).send('HI!'))

如果你想 100% 安全

client.guilds.fetch(guildID)
    .then(guild => 
        guild.channels.fetch(channelID)
            .then(channel => 
                 channel.send('HI!')
));

【讨论】:

  • 频道与公会一起缓存,因此无需获取频道。
【解决方案2】:

最简单快捷的方法是

const channel = client.channels.cache.get("CHANNEL-ID")
channel.send("Hello")

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2020-07-23
    • 2021-04-19
    • 2022-06-10
    • 2021-06-27
    • 2020-07-20
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多