提问者:小点点

当user不是字符串时如何修复{user.UserName}?


我实际上正在编写一个Js Discord机器人,我正在创建一个XP系统。

当输入&level时,我想让我的机器人给出作者的级别,并且它可以工作。

但是如果我做了&level@discorduser,我可以获得这个Discord用户的用户id,除非我在嵌入式中使用它,如下所示:

const embed = {
                  "title": "Fiche Niveau d'Exagide",
                  "description": 'Utilisateur : **' + `${userid.username}` + "**",
                  "color": 10384204
               }

在本例中,它返回:utilisateur:undefined

userid是从将提及转换为ID函数获取的常量

例如,它将<@549317568339640336>转换为549317568339640336

function getUserFromMention(mention) {
              if (!mention) return;

              if (mention.startsWith('<@') && mention.endsWith('>')) {
                mention = mention.slice(2, -1);

                if (mention.startsWith('!')) {
                  mention = mention.slice(1);
                }
                return mention;
              }}

如果提到@Discord user,我只希望嵌入返回utilisateur:Discord user


共2个答案

匿名用户

只需简单地使用以下方法获取所述用户的user对象:

message.mentions.users.first()

或所述用户的成员对象:

message.mentions.members.first()

匿名用户

您可以使用以下代码

 function mentionsRegex (dot) {
if (dot) {
// e.g. @google.com will match `google.com`
return /(?:^|[^a-zA-Z0-9_@!@#$%&*])(?:(?:@|@)(?!\/))([a-zA-Z0-9/_.]{1,15}) 
 (?:\b(?!@|@)|$)/
}
 // e.g. @google.com will match `google`
return /(?:^|[^a-zA-Z0-9_@!@#$%&*])(?:(?:@|@)(?!\/))([a-zA-Z0-9/_]{1,15})(?:\b(?!@| 
@)|$)/
}

从mentions-regex中也可以看到字符串中的提及,比如javascript中的twitter