简体   繁体   English

为用户 [Discord.js] 使用提及和 ID 命令

[英]Using mentions and ID commands for user [Discord.js]

Can someone help?有人可以帮忙吗? I wanted my commands to be able to be used with @olios or 49556804 *** 0471817. I don't know what I'm doing wrong but my code isn't working.我希望我的命令能够与@olios 或 49556804 *** 0471817 一起使用。我不知道我做错了什么,但我的代码不起作用。

 let userLevel = mentions.users.first () || msg.guild.members.cache.get (args [0]) || msg.author
 const userLevelID = userLevel.id
 const userLevelName = userLevel.user.username

And I get something like this from the console:我从控制台得到这样的东西:

TypeError: Cannot read property 'username' of undefined

Can it be done at all, or it worked on mentions and ID?它可以完成吗,或者它适用于提及和ID?

While both msg.mentions.users.first() and msg.author return a User , msg.guild.members.cache.get(args[0]) returns a GuildMember .虽然msg.mentions.users.first()msg.author返回一个Usermsg.guild.members.cache.get(args[0])返回一个GuildMember Both User and GuildMember have an id property, but only GuildMember has a user . User 和 GuildMember 都有一个id属性,但只有GuildMember有一个user

If you try to get the user from a GuildMember , you will be fine, but you will always receive a TypeError if you try to get it from a User .如果您尝试从GuildMember获取user ,您会很好,但如果您尝试从User获取它,您将始终收到 TypeError。

You can update your code to get the user from message.guild.members.cache.get(args[0]) only.您可以更新代码以仅从message.guild.members.cache.get(args[0])获取user I used optional chaining ( ? ) to ignore it if there is no args[0] and fall back to msg.author .如果没有args[0]并回msg.author ,我使用可选链接 ( ? )忽略它。

The following will work with all three cases:以下将适用于所有三种情况:

let userLevel =
  msg.mentions.users.first() ||
  msg.guild.members.cache.get(args[0])?.user ||
  msg.author;
const userLevelID = userLevel.id;
const userLevelName = userLevel.username;

console.log({ userLevelID, userLevelName });

Optional chaining requires Node.js v14+.可选链接需要 Node.js v14+。 If you have an older version you can use a simple AND operator:如果您有旧版本,则可以使用简单的 AND 运算符:

let userLevel =
  message.mentions.users.first() ||
  (message.guild.members.cache.get(args[0]) &&
    message.guild.members.cache.get(args[0]).user) ||
  message.author;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM