Unable to Assign Role with member.roles.add (id) - discord.js

I'm trying to make an assignrole command which takes userID and roleID as arguments.
content = message.content.slice(message.content.indexOf(' ')+1)
args = content.split(', ');
const userID = args[0]
const roleID = args[1]
const desiredUser = message.guild.members.cache.get(userID)
const desiredRole = message.guild.roles.cache.get(roleID)
if (desiredUser != undefined){
if (desiredRole != undefined){
usern = desiredUser.user.username
desiredUser.roles.add(roleID).catch(console.error);
message.channel.send(usern + " has been assigned the "+ desiredRole.name +" role")
console.log("added role")
} else {
message.channel.send("role with ID " + roleID + " does not exist")
}
} else {
message.channel.send("user with ID " + userID + " does not exist")
}
The function succeeds at "getting" the correct user and role, and successfully sends the "USER has been assigned the ROLENAME role" message. However, the role itself isn't actually added to the user!
My console throws a DiscordAPIError: Missing Permissions error, but I don't know how to interpret it. The error does not quit the bot, however.
How do I add the role to the user?

It is likely that you are missing the MANAGE_ROLES permission as it is, like the name would suggest, required to manage rules.
https://discord.com/developers/docs/topics/permissions
Here are other possibilities that may be causing the error:
I found these here
It is trying to execute an action on a guild member with a role higher than or equal to your bots highest role.
It is trying to modify or assign a role that is higher than or equal to its highest role.
It is trying to execute a forbidden action on the server owner.

Related

How do I get a list of all members in a discord server, preferably those who aren't bot

I'm attempting checks if a username is in a valid username in the server. The check is done by the following code
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!logan',
intents=intents,
helpCommand=helpCommand)
Users = [# Need help getting users]
async def Fight(ctx, User):
if ctx.author.name != User:
if User in Users:
open_file = open(str(ctx.author.name), "w")
open_file.write(User + "\n300\nTurn")
open_file.close()
open_file = open(User, "w")
open_file.write(str(ctx.author.name) + "\n300\nNot")
open_file.close()
await ctx.author.send("You are now fighting " + User)
#await ctx.User.send("You are now fighting " + ctx.author.name)
else:
await ctx.send("User is not in this server")
else:
await ctx.send("You Cannot Fight Yourself")
I've tried googling, but I haven't found a valid answer
There are other ways to get your guild name, but here's a possible method to get it and get the member list from it.
In member (and user so), there is the ".bot" that is a boolean, 0 if not a bot.
listMembers = []
#bot.command(name="init")
async def FuncInit (ctx) :
global listMembers
guilde = ctx.message.guild
for member in guilde.members :
if not member.bot :
listMembers.append(member.name)

GraphClientService throws exception when calling 'Any'

Given a GUID, I need to know if a user exists in azure active directory.
If I pass the Id of an exisitng user everything is Ok.
If I pass the id for which no user account exists, I get the following exeption:
ServiceException: Code: Request_ResourceNotFound Message: Resource
'02803255-b96e-438a-9123-123' does not exist or one of its queried
reference-property objects are not present.
I know this record doen not exist, as this is what I'm testing, I want false to be returned somehow.
Surely I do not have to catch the exception?
//Simple code:
public bool CheckUserExists(string userId) {
bool exists = false;
//purposefully set this to a string that does not match any user.
userId = "02803255-b96e-438a-9123-123";
var user = _graphServiceClient
.Users
.Request()
.Filter("Id eq '" + userId + "'")
.GetAsync();
//exception thrown on next line.
if (user.Result.Count == 1) {
exists = true;
}
Please try checking if user count is less than or equals 0 condition , instead if count equals 1.
var users = await graphClient.Users.Request().GetAsync();
var exists=true;
try {
var user = _graphServiceClient
.Users
.Request()
.Filter("Id eq '" + userId + "'")
.GetAsync();
if (user.Count <= 0) {
exists = false;
break;
}
}
catch (ServiceException ex) {
exists = false;
}
return exists;
or try with
if (user.Count !=null && user.Count>=0)
Reference:
verify if user account exists in azure active directory -SO
reference
Microsoft.Azure.ActiveDirectory.GraphClient/User

discord.js v12 info command always showing offline status

So I'm trying to make a command that show info about a specific user, the command works fine but the status of the user always shows as offline
This is the main part of the info code that shows the status of the user
if (user.presence.status === 'online') status = `${client.config.emojis.ONLINE}Online` ;
if (user.presence.status === 'idle') status = `${client.config.emojis.IDLE}Idle`;
if (user.presence.status === 'dnd') status = `${client.config.emojis.DND}Dnd`;
if (user.presence.status === 'offline') status = `${client.config.emojis.OFFLINE}Offline`;
if (user.presence.clientStatus != null && user.presence.clientStatus.desktop === 'online') plateforme = '🖥️ desktop'
if (user.presence.clientStatus != null && user.presence.clientStatus.mobile === 'online') plateforme = '📱 Mobile'
let permissions_arr = userInfo.permissions.toArray().join(', ');
let permissions = permissions_arr.toString()
permissions = permissions.replace(/\_/g, ' ');
const embedMember = new MessageEmbed()
embedMember.setFooter(`ID: ${userInfo.user.id}`,``,true)
embedMember.setThumbnail(userInfo.user.displayAvatarURL({ dynamic: true }))
embedMember.setColor(`${client.config.color.EMBEDCOLOR}`)
embedMember.setTitle(`${userInfo.user.tag}`)
embedMember.addField('Joined:', `${moment.utc(userInfo.joinedAt).format('MMMM Do YYYY \n -HH:mm')}`, true)
embedMember.addField('Account created:', `${moment.utc(userInfo.user.createdAt).format('MMMM Do YYYY \n -HH:mm')}`, true)//
embedMember.addField('Status:', `${status}`, true)
embedMember.addField('Roles:', `${userInfo.roles.cache.map(r => r.toString()).join(' ')}`)
message.channel.send(embedMember);
User status is part of the user's presence. In order to access the presence of guild members, you must subscribe to the GUILD_PRESENCES intent. This is what the construction of your Client object will need to look like:
const bot_intents = ["GUILD_PRESENCES"];
const client = new Discord.Client({intents: bot_intents, ws:{intents: bot_intents}});
Because presences are a privileged intent, you will also need to go to your bot's application page in the Discord Developer Portal and enable this setting:
You can, of course, add any other intents you may need/want to the bot_intents variable. This answer assumes you are not already using the GUILD_PRESENCES intent, as you did not mention it in your question.

How to get role members count in discord.js

I want to get member count who have specific role. role.member is collection. how can i get member count?
ps i'll use role id.
You can use role.members.size:
client.on('message', (message) => {
let guild = await message.guild.fetchMembers();
let roleID = '3933783737379';
let memberCount = guild.roles.get(roleID).members.size;
message.channel.send(memberCount + " members have this role!");
});
Note this only counts cached members so maybe you will have to use guild.fetchMembers() before.

google app engine: checking if user exists during signup

I have a little signup page that I'm trying to get working. Basically you give your username, password, and email, and then if the username that you entered doesn't already exist then it redirects you to a welcome page that says, "welcome (username here)!". If the user DOES exist, then it re-renders the signup page. The problem is, even if the user doesn't exist, it keeps re-rendering the signup page. I get no errors. The function "getByName" that checks if the user exists keeps returning true. Can anybody see the issue?
here's the code that calls the "getByName" function.
if(username and password and verify and email):
if UserInfo.getByName(username) == True:
self.renderSignup()
else:
UserInfo.register(username, password, email)
cookieVal = str(encrypt.makeCookieHash(username))
self.response.headers.add_header("Set-Cookie", "username=%s; Path=/" % (cookieVal))
self.redirect("/welcome")
else:
self.renderSignup(username, email, usernameError, passwordError, verifyError, emailError)
Here's the "UserInfo" data model that contains the "getByName" function, along with others.
class UserInfo(db.Model):
passwordHash = db.StringProperty(required = True)
email = db.StringProperty(required = True)
username = db.StringProperty(required = True)
#classmethod
def register(cls, name, password, email):
encrypt = Encrypt()
pwHash = encrypt.hashUserInfo(name, password)
UserInfo(passwordHash = pwHash, email = email, username = name).put()
#classmethod
def getByName(cls,name):
usersWithName = UserInfo.gql("where username = :1", name)
if usersWithName != None:
return True
return False
The lines
usersWithName = UserInfo.gql("where username = :1", name)
if usersWithName != None:
where you do the comparison is where you are going wrong. userWithName is a query object and your comparison will alwys be true. You need to execute the query with a get, fetch etc.... and then see if the result set has contents.
You should be doing something like
usersWithName = UserInfo.gql("where username = :1", name).get()
if usersWithName != None:
Or you could do a fetch(10), and check for a non empty list. Of course if you found more than 1 item matching, then that would indicate a broader error in your system.

Resources