首页 > 解决方案 > 在任何参数行中侦听用户的 ID 和提及

问题描述

所以我有这个“touser”变量,当消息作者在 args[0] 中键入它时定义目标的用户 ID,但我希望能够根据它的位置在第一个和最后一个 arg 中抓取它。

我的 CMD 语法是:

#give [用户名/提及] [项目] [项目] [项目]

希望它像这样工作:

#give [项目] [项目] [项目] [用户名/提及]

我现在的代码:

let touser = message.mentions.members.first() || message.guild.members.cache.get(args[0]);

标签: javascriptdiscorddiscord.js

解决方案


您可以像这样从数组中删除特定对象:

const array = [1, 2, 3];

console.log(array);

//takes away 2 from the array
const index = array.indexOf(2);
if (index > -1) {
  array.splice(index, 1);
}

// array = [1, 3]
console.log(array); 


从那里,您只需要稍微修改它,以便它只搜索用户提及,这只会添加一些额外的层来添加。为了解决这个问题,我简单地抓取了用户 ID mentionedID,然后将其格式化为用户提及userString,然后签入args


代码:

client.on('message', (message) => {
    if (message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'give') {
        //user object is first retrieved, never used, but probably will be helpful in your code
        let touser = message.mentions.members.first();
        //grabs the ID in order to match the args
        let mentionedID = message.mentions.users.first().id;
        //formats it so that it matches how a user is mentioned
        let userString = `<@!${mentionedID}>`
        //finds the mention in the array and then removes it
        const index = args.indexOf(userString);
        if (index > -1) {
            args.splice(index,1);
        }
        //displays the newly modified array
        console.log(args);
    }
});

资源:

  1. 如何从数组中删除特定项目?
  2. Discord.js 文档

推荐阅读