【问题标题】:I have the TypeError: Cannot read property 'toString' of undefined我有 TypeError: Cannot read property 'toString' of undefined
【发布时间】:2021-09-25 02:12:42
【问题描述】:

我正在制作一个不和谐的欢迎机器人,但存在一个问题,当有人加入服务器时它会发送此错误:

TypeError:无法读取未定义的属性“toString”

这里是源代码:

module.exports = (client) => {
    const channelid = "865471665168580628";
    client.on("guildMemberAdd", (member) => {
        const serverid = member.guild.id
        const guild = client.guilds.cache.get(serverid);

        console.log("member");
        const ruleschannel = guild.channels.cache.find(channel => channel.name === "rules");

        const message = `welcome <@${member.id}> to music and chill! please read the ${member.guild.channels.cache.get(ruleschannel).toString()} before you start chatting.`;

        const channel = member.guild.channels.cache.get(channelid);
        channel.send(message);
    })
}

有人可以帮帮我吗?

【问题讨论】:

  • 可能这个是未定义的:member.guild.channels.cache.get(ruleschannel)

标签: javascript node.js discord discord.js typeerror


【解决方案1】:

这意味着member.guild.channels.cache.get(ruleschannel)undefined。由于ruleschannel是一个通道对象,而Collection#get()方法需要一个雪花,你需要使用它的id属性。

所以member.guild.channels.cache.get(ruleschannel.id) 应该可以工作。

更好的方法是检查ruleschannel 是否存在。此外,您只需在反引号内添加 rulesChannel 即可将其转换为频道链接。查看下面的代码:

client.on('guildMemberAdd', (member) => {
  // not sure why not just: const { guild } = member
  const guild = client.guilds.cache.get(member.guild.id);
  const rulesChannel = guild.channels.cache.find((channel) => channel.name === 'rules');

  if (!rulesChannel)
    return console.log(`Can't find a channel named "rules"`);

  const channel = guild.channels.cache.get(channelid);
  const message = `Welcome <@${member.id}> to music and chill! Please, read the ${rulesChannel}.`;

  channel.send(message);
});

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 2014-07-26
    • 2017-04-24
    • 2023-03-15
    • 2023-02-22
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多