identifying admins from mentions discordjs

北慕城南 提交于 2020-04-30 14:08:19

问题


I want to find out if there are mentions in a message which I am doing using if(message.mentions.users.first()) but now among all the mentions I also want to filter out mentions of the admin team and not those of the community members. How to achieve that?

I tried filtering users based on roles like this

   let r = [];
   message.mentions.users.forEach( user => {
        console.log('user' + user)
        user.roles.forEach(role => {
            console.log('role' + role)
            r.push(role);
        }) 
        console.log('roles' + r);
        var member = false;
        for (i in r) {
            if (i == 'admin') {
                member = true;
            }
        }
    })

This doesn't seem to work.


回答1:


const adminName = ['<role name>'];
const adminId = ['<role ID>'];

client.on('message', (msg) => {
  let admins = msg.mentions.members.filter( (user) => {
    return adminId.some(id => user.roles.has(id)) || user.roles.some(r => adminName.includes(r.name));
  });
  console.log(admins.map(d => d.user.username));
});

There, I created 2 arrays, one with the role ID and another with the role name. You can use both, or only one (I prefer to use the id, because you can change a role name, but you can't change an id, except if you delete the role).

Then, I iterate through the members in the mentions of the messages. Why the members and not the users? Because the GuildMember is a type linked to a guild, which is an instance of an user in a guild, and so it has the role of the user.

Then I check if one of the id of my admins roles is in the roles of the user or if one of the roles name is inside my adminName.

The variable admins is a collection of GuildMember.

You can change the function inside the some to match whatever condition make someone an admin for you.



来源:https://stackoverflow.com/questions/57020854/identifying-admins-from-mentions-discordjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!