首页 > 解决方案 > Discord.JS - 如何从用户名中获取用户 ID?

问题描述

有人可以帮我从用户 ID 中检索用户名并使用该 ID 向聊天室发送消息吗?

    if (message.content.startsWith(prefix)) {
        const [CMD_NAME, ...args] = message.content
          .trim()
          .substring(prefix.length)
          .split(/\s+/);

      if (CMD_NAME === "getid") {
        const getid1 = new MessageEmbed()
          .setDescription("❗️ | Please tag the member to retrieve the ID!")
          .setColor(10181046);
      if (args.length === 0) return message.reply(getid1);

        const username = client.guilds.cache.get('<GUILD ID>');
        const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id
        message.channel.send(`${username} id is ${userid}`);

      }
    }

});

当我输入命令“d!getid @Username”时,它显示了这个错误:

C:\Users\USER\Desktop\DiscordBotas\index.js:152 const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id TypeError: Cannot read property '在客户端未定义的 id'。(C:\Users\USER\Desktop\DiscordBotas\index.js:152:90)

标签: discord.js

解决方案


您正在创建一个刚刚在实际 lambda 之上定义的变量的 lambda,这可能会弄乱您的代码。

const username = client.guilds.cache.get('<GUILD ID>');是错的。

如果您修复它上面的行,那么获取 userId 应该可以工作。


推荐阅读