【问题标题】:"typeError: Cannot read property 'username' of undefined."“typeError:无法读取未定义的属性‘用户名’。”
【发布时间】:2019-07-27 12:10:02
【问题描述】:

这是我的不和谐机器人的>top10 命令代码:

const Discord = require("discord.js");

module.exports.run = async(bot, message, args, con) => {

  const top10query = `SELECT user, points, lstmsg FROM scores WHERE guild = '${message.guild.id}' ORDER BY cast(points as SIGNED) ASC LIMIT 10`
  //const top10 = con.query(top10query)

  const query = querytxt => {
    return new Promise((resolve, reject) => {
      con.query(querytxt, (err, results, fields) => {
        if (err) reject(err);
        resolve([results, fields]);
      });
    });
  };
  const [results, fields] = await query(top10query);

  const map1 = results.map(results => `User: ${(bot.fetchUser(results.user)).username} Messages: ${results.points} Last message: ${results.lstmsg}`);
  message.channel.send(map1)
}
module.exports.help = {
  name: "top10",
  usage: "``prefix`` top10",
  description: "top 10 points",
}

“用户”的数据存储为用户 ID。当我使用 >top10 命令时,我得到“未定义”。

有什么想法吗?


编辑:
我试过替换

const map1 = results.map(results => `User: ${(bot.fetchUser(results.user)).username} Messages: ${results.points} Last message: ${results.lstmsg}`);
      message.channel.send(map1)

const map1 = results.map(results => `User: ${(bot.users.get(results.user.id)).username} Messages: ${results.points} Last message: ${results.lstmsg}`);

但我收到此错误:

(node:21128) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined

【问题讨论】:

  • 我假设bot.fetchUser(results.user)).username 这是引发错误的行。您是否在上面进行过任何日志记录,例如退出 results.user,然后退出 bot.fetchUser(results.user) 以确保您得到预期的结果?
  • UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined 当我登录时console.log(bot.fetchUser(results.user))
  • bot.fetchUser(results.user) 是异步的
  • 首先,您可以将 .fetchUser 与机器人帐户一起使用(写在 djs 文档中)。如果您甚至使用 bot.users.get(...) 获得用户,请尝试登录

标签: javascript mysql promise discord.js userid


【解决方案1】:

替换

User: ${(bot.fetchUser(results.user)).username

与:

User: ${bot.users.get(results.user).username

【讨论】:

  • 我认为最好保留 fetchUser() 作为排行榜,用户可能不在 bot.users 中
  • 它不是一个函数,它是一个类/对象
【解决方案2】:

你想做的

const map1 = await results.map(async result => {
        const user = await client.fetchUser(result);
        return `User: ${user.username} Messages: ${result.points} Last message: ${result.lstmsg}`; 
});

【讨论】:

    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 2021-08-03
    • 2022-01-01
    • 1970-01-01
    • 2020-02-11
    • 2021-03-12
    • 2018-12-18
    相关资源
    最近更新 更多