【问题标题】:How can I separate Username and ID from command?如何将用户名和 ID 与命令分开?
【发布时间】:2020-01-22 01:49:09
【问题描述】:

我使用 DankMemer Youtube Imgen API 编写了一个代码。当我输入: ,youtube hello ,它显示:

但是当我标记某人时,它会显示文本和 ID:

有没有办法将用户名与文本分开?

let target = message.mentions.users.first() || message.author;
let profilepic = target.avatarURL;
let sentence =  args.join(" ");
let url = ` https://dankmemer.services/api/youtube?avatar1=${profilepic}&username1=${target.username}&text=${sentence}`;

message.channel.startTyping();

snekfetch.get(url, {
  headers: {
    "Authorization": token
  }
}).then(async res => {
  await message.channel.send({
    files: [{
      attachment: res.body,
      name: `${target.tag}-youtube.jpg`
    }]
  }).then(() => message.channel.stopTyping());
}).catch(err => console.error(err));

【问题讨论】:

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


    【解决方案1】:
    let sentence =  args.join(" ");
    

    您在那里加入了我认为还包括提到的用户的参数。您唯一需要做的就是删除提及。如果您只想删除第一次提及,请执行此操作-

    if (!target === message.author) {
        let toremove = `{@${target.id}}`;
        sentence = sentence.replace(toremove, "");
    }
    

    在此行之后添加此代码-

    let sentence =  args.join(" ");
    

    【讨论】:

    • 我有个主意,写了这个:` let sentence = args.join(" ").replace(new RegExp(${message.mentions.users.first()}), "") `它成功了!感谢这个想法
    • 是的,这是我经常搞砸正则表达式的好方法,所以我没有使用它。
    【解决方案2】:

    您可以将邮件内容中的所有提及替换为空白using regex,如下所示:

    let messageContentWithoutMentions = message.content.replace(new RegExp("<@\d+>","gm"),"")
    

    如果您想删除其他内容,只需使用 string.replace 函数即可。

    【讨论】:

    • 也许编辑您的答案以显示预期的输入和输出?在我看来,您只是想从消息中删除提及。
    猜你喜欢
    • 2019-06-16
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2017-12-17
    • 2019-07-15
    • 2011-12-18
    • 2015-10-21
    相关资源
    最近更新 更多