identifying admins from mentions discordjs - discord.js

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.

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.

Related

Discord JS - If the user reacting to message has a specific role I want to add a role

I'm attempting to create a more complex reaction role function.
Basically I want to achieve that if a user has 2 roles, it should have access to some channels.
So the way I'm trying to do this is by checking if the user has one of the roles when clicking on a reaction that grants the member the second role. If the user has the other role, he should get a third role that unlocks these channels.
But, I haven't been able to figure out how to look at the roles of the person reacting to the message.
client.on('messageReactionAdd', async (reaction, user) => {
const message = await reaction.message.fetch(true);
const channelAccess = '918617193988649002';
const foodSweden = message.guild.roles.cache.find(role => role.name === 'πŸ²πŸ‡ΈπŸ‡ͺ');
const foodCategoryReaction = '🍲';
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id === channelAccess) {
if (reaction.emoji.name === foodCategoryReaction && message.member.roles.has('πŸ‡ΈπŸ‡ͺ')) {
await reaction.message.guild.members.cache.get(user.id).roles.add(foodSweden);
} else {
return;
}
}
});
So this is the code. I'm uncertain how message.member.roles.has('πŸ‡ΈπŸ‡ͺ') should be coded.
I've tried reaction.message.member.roles.has('πŸ‡ΈπŸ‡ͺ'), reaction.member.roles.has('πŸ‡ΈπŸ‡ͺ'), user.roles.has('πŸ‡ΈπŸ‡ͺ') and shifted out member for user.
I'm uncertain how message.member.roles.has('πŸ‡ΈπŸ‡ͺ') should be coded. I've tried reaction.message.member.roles.has('πŸ‡ΈπŸ‡ͺ'), reaction.member.roles.has('πŸ‡ΈπŸ‡ͺ'), user.roles.has('πŸ‡ΈπŸ‡ͺ') and shifted out member for user.
None of those are existing methods. member.roles does not have a .has() method. And users represent general discord users outside of guilds; users do not have roles, only guild members have roles. The .has() method of any manager in discord.js also usually utilizes IDs (which is what they are mapped to in the underlying Collection cache), not names or other properties. See the docs.
Here is how you check if the member who reacted has a specific role:
const hasRole = reaction.message.member.roles.cache.some(role => role.name == "πŸ‡ΈπŸ‡ͺ");
The role cache for guild members is almost always up-to-date, so you don't really need to do any fetching. You can rely on the role cache here.

Getting nicknames of users of my Discord bot

I can see the names, ids and user numbers of the servers where my bot is located, but how can I get the list of users (nicknames)?
You can make use of guild.members.fetch() in order to get all members and then use the nickname property to receive their nicknames. Finally I removed all bots with a simple filter.
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
Working example as a command:
client.on("message", async (message) => {
if (message.author.bot) return;
if (message.content === "!list") {
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
}
});
client.login("your-token");
Thanks to #MrMythical who suggested using displayName only. That property automatically returns the normal username when no nickname has been set for a user.
Users do not have nicknames, only guild members, if you are trying to fetch a list of server member nicknames.
You can use the code snippet from below:
const map = message.guild.members.cache.filter(c=> !c.member.user.bot).map(c=>c.displayName).join('\n');
console.log(map)
The
message.guild.members.cache.filter(c=> !c.member.user.bot)
Filters bots from the list, the
.map(c=>c.displayName).join('\n');
maps the data and only the user nicknames and joins them by paragraph breaks.
If there are any issues, please comment!

Is there some way to distinguish between users of different organization in a Microsoft Teams bot?

I want to know the organization of user in teams-bot. I have registered my application on azure portal as a multi-tenant application.
The only way to distinguish between members of different organization using the bot framework is to compare tenant ids. You can access the tenantID by using the team member info mapped to the TeamsChannelAccount object seen here
You can access this object using teamsInfo.getMembers
In the bot code, it would look something like this:
async messageAllMembersAsync(context) {
const members = await TeamsInfo.getMembers(context);
members.forEach(async (teamMember) => {
const test = teamMember;
const message = MessageFactory.text(`Hello ${ teamMember.givenName } ${ teamMember.surname }. I'm a Teams conversation bot.`);
var ref = TurnContext.getConversationReference(context.activity);
ref.user = teamMember;
await context.adapter.createConversation(ref,
async (t1) => {
const ref2 = TurnContext.getConversationReference(t1.activity);
await t1.adapter.continueConversation(ref2, async (t2) => {
await t2.sendActivity(message);
});
});
});
This is the information it returns:
If you want to say, compare company names, you can access the teamMember.userPrincipalName or teamMember.email properties and compare the #companyname.com portion of the emails as well.

Add a role to people that react with a certain emoji in a certain channel

I'm trying to make a discord.js bot for my server I made for people in my school. I'm trying to make a #classes channel and if you react to certain messages it gives you a role (which gives you access to the text channel for that class).
client.on('messageReactionAdd', (reaction, user) => {
console.log("client.on completed.")
if (message.channel.name === 'classes') {
console.log("if(message) completed.")
if (reaction.emoji.name === "reminder_ribbon") {
console.log("emoji test completed.")
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.find(role => role.name === "FACS");
guildMember.addRole(role);
}
}
});
This is what I have tried so far, however, it does not give me/the other people reacted to it the role nor does it return an error message.
P.S. Also, how would I be able to make it so when they unreact it removes the role?
Edit: It seems it only gets reactions from cached messages/messages sent after bot startup. Also, message is not defined on the first if(message.channel.id) message.
Try to use the following code:
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === '552708152232116224') {
if (reaction.emoji.name === "reminder_ribbon") {
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.get('552709290427940875');
guildMember.addRole(role);
}
}
});
First of all, reaction.users is an Object with all the users that reacted on the message, so you first have to define to which user you want to assign the role. I fixed this fetching the guildMember with user.id.
The second mistake was that you tried to assign a role ID to a guildMember although you first have to fetch the role and then assign the role Object to the guildMember.

Saving roles from mentioned user

I am trying to make a tempmute command, I followed a tutorial online which worked... But my own server has users with multiple roles, and these roles allow them to talk even when they receive the "muted" role.
Is there any way to save all the roles from a mentioned user and then to remove and add those roles?
I already tried to make a new let variable
let roleHistory = tomute.member.roles;
and then adding and removing them with:
await(tomute.removerole(roleHistory));
tomute.addRole(roleHistory);
But that didn't work
module.exports.run = async (bot, message, args) => {
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!tomute) return message.reply("Couldn't find user.");
if(tomute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them!");
let muterole = message.guild.roles.find(`name`, "muted");
if(!muterole){
try{
muterole = await message.guild.createRole({
name: "muted",
color: "#000000",
permissions:[]
})
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
}catch(e){
console.log(e.stack);
}
}
let mutetime = args[1];
if(!mutetime) return message.reply("You didn't specify a time!");
await(tomute.addRole(muterole.id));
message.reply(`<#${tomute.id}> has been muted for ${ms(ms(mutetime))}`);
setTimeout(function(){
tomute.removeRole(muterole.id);
message.channel.send(`<#${tomute.id}> has been unmuted!`);
}, ms(mutetime));
}
I want the bot to take the roles away, tempmute the user and giving the roles back after the Timeout.
Your attempt is on the right track, but you missed a small detail. A Guild Member has a method addRole and removeRole which you used. However, these methods are meant for adding/removing a single role.
When you first fetch the user roles with let roleHistory = tomute.member.roles;, it returns a Collection of roles. If you then attempt to use removeRole(roleHistory) it attempts to remove a single role equal to the complete collection (which doesn't exist obviously).
To make it work, you need the methods addRoles and removeRoles which adds/removes an entire collection. So your code would be:
let roleHistory = tomute.roles;
// Removing all the roles
await(tomute.removeRoles(roleHistory));
// Adding all the roles
tomute.addRoles(roleHistory);
P.s. Since your tomute variable is already a user you need to change your code to fetch the roles from let roleHistory = tomute.member.roles; to let roleHistory = tomute.roles;

Resources