I want to remove the the role from the users in the server who have the corresponding role by using the role mention.
For example, '%remove_role#TEAM_A' removes 'TEAM_A' from the roles of people who have the role 'TEAM_A'.
I searched hard on Google, but I couldn't find an answer or a way to do it, so I made it myself, but I failed to complete it, so I wrote a question here.
1st. %rmrole team name
2nd. Check if the team name you entered is in 'role_list'.
3rd. Remove the role of the team name entered from users on the server.
this is my code.
#bot.command()
async def rmrole(ctx, team_name):
key = 0
role = get(ctx.guild.roles, name=team_name)
team_list = []
print(role)
# typo check
role_list = ["TEAM_A", "TEAM_B", "TEAM_C", "TEAM_D"]
if role in role_list:
type_error = 1
else:
type_error = 0
# remove_role
empty = True
if type_error == 1:
for member in ctx.guild.members:
if role in member.roles:
await member.remove_roles(role)
empty = False
if empty:
await ctx.send("anyone has this role.")
else:
await ctx.send("check the typos."
async def remove_role(ctx, role: discord.Role)
I was worried that if I write like this, users would get a lot of alarms.
Thus, in the body, I enter the name of the role in text, and I write it in a way that scans the role in the code.
The '#remove_role' part was searched and found.
The code was executed, but the role was not removed.
I wonder where the wrong part is, and I need help to make what I want.
Your mistake is simple:
role_list = ["TEAM_A", "TEAM_B", "TEAM_C", "TEAM_D"]
if role in role_list:
type_error = 1
else:
type_error = 0
This code will always fail and lead to type_error = 0, as role is a discord.role.Role class and not a string. This means comparing the role you got via get and a string representing its name will always fail : and so, that the second part of your code that removes the role is never accessed. It works otherwise.
Instead, you want:
if role.name in role_list:
type_error = 1
else:
type_error = 0
Or better yet, this instead:
if role is None:
return await ctx.send("Role doesn't exist")
...since I don't quite see the point of your code personally: if role = get(ctx.guild.roles, name=team_name) fails (i.e the role doesn't exist), role will be None, and you can easily check for it instead of comparing it against a hardcoded list.
Related
While reading the cloud firestore role based access example https://firebase.google.com/docs/firestore/solutions/role-based-access#rules, step 4, I find it not clear whether the user can create a comment or not.
According to the above link, the comment is owned by a user, here is the data model:
/stories/{storyid}/comments/{commentid}
{
user: "alice",
content: "I think this is a great story!"
}
And the rules:
match /comments/{comment} {
allow read: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
['owner', 'writer', 'commenter', 'reader']);
// Owners, writers, and commenters can create comments. The
// user id in the comment document must match the requesting
// user's id.
//
// Note: we have to use get() here to retrieve the story
// document so that we can check the user's role.
allow create: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
['owner', 'writer', 'commenter'])
&& request.resource.data.user == request.auth.uid;
}
Note the last line of the rules, to create the comment, the authenticated user (request.auth.uid) has to be the user who is the owner of the comment. However, before even create this comment, how can this user property exist? Maybe, when create the comment, do not require the last segment of the rule "&& request.resource.data.user == request.auth.uid". But when update the comment, can add this rule.
Did I miss anything? Btw, do they actually test examples before using them for online reference? It is also a pity that there is no timestamp when these online documents are created. I was told nowadays things two years old can be obsolete.
The request.resource variable contains the document as it will exist after this operation is completed (assuming it is allowed). So request.resource.data.user is the value of the user field that the operation is trying to write, not the value as it currently exists (that'd be resource.data.user, without request.).
So I'm trying to create a bot that is more universal and can be added to more than one server. I've managed to reformat commands like announce or join messages etc. by using .find("name", "announcements").
My problem is that the same does not work for roles.
I've tried what little I could find on the internet, such as member.guild.roles.find("name", "Member") or member.guild.roles.find(role => role.name === "Member") but none of these work. A variety of different ways return different errors, but they usually say something along the lines of it not being an integer (I think) or snowflake.
This is the function that I am currently wrestling with:
client.on('guildMemberAdd', (member) => {
var joinResponse = ("Hello **" + member.displayName + "**, welcome to **" + member.guild.name + "**!")
let role = member.guild.roles.find("name", "Member");
member.addRole(role).catch(console.error);
member.guild.channels.find('name', 'general').send(joinResponse);
In short summary, what I'm looking for is the ability to get a role by name and add a user to it.
(I'm nearly certain it's possible, since popular bots like Dyno are capable of using commands to add roles to users.)
client.on('guildMemberAdd', (member) => {
const joinResponse = `Hello **${member.user.username}**, welcome to: **${member.guild.name}**!`
let role = member.guild.roles.get('Member');
if(!role) return console.log("Role doesen't exist.");
member.addRole(role);
const ch = member.guild.channels.get('general');
if(!ch) return console.log("Channel doesen't exist.");
ch.send(joinResponse);
});//You didn't have closing brackets (Could've been a problem)
First of all your string joinResponse was a function and you completely messed up merging it, I recommend using Template literal.
I used get function since it's a lot easier to use and cleaner, you only pass ID or name as a string.
To check if channel exists I used if statements and exclamation mark which means doesen't exist/false.
If I helped you please mark this as answer, thanks <3. If you need anything add comment to answer or message me on Discord (You can find my discriminator on my stack overflow profile).
For further explanation click on Blue words.
I reviewed how to delete from webapp2_extras.appengine.auth.models.Unique
This solution worked with:
Unique.delete_multi( map(lambda s: 'User.auth_id:' + s,user.auth_ids))
Problem is that there is a second record. The following statement has no effect:
Unique.delete_multi( map(lambda s: 'User.email:' + s,user.email))
No error in the log. Nothing happens.
The record I'm trying to delete has the value in field "Key Name" in Unique is "User.email:test#example.com"
When the user is created, the unique_properties is as follows:
unique_properties = ['email']
Thinking it was some kind of lock, I tried logging user out first, then deleting user (saved user.email to a temp var). No dice.
solution was found in using delete_multi differently for auth_ids and email:
for user.email (note in OP the way email was created):
unique_email = ['User.email:%s' % user.email]
Unique.delete_multi(unique_email)
for user.auth_ids:
Unique.delete_multi( map(lambda s: 'User.auth_id:' + s,user.auth_ids))
First off, I'm relatively new to Google App Engine, so I'm probably doing something silly.
I want the username to be set as key in model User
class User(db.Model):
#username is key
password = db.StringProperty(required = True)
type = db.StringProperty(required = True)
approved = db.BooleanProperty(required = True)
To insert i do this
user = User(key_name = self.request.get('username'), password = password, type = type, approved = False)
user.put()
I believe that when you set key_name manually it should be exactly what you set it to be but when i query user modle
users = db.GqlQuery("SELECT * FROM User")
for(user in users):
self.response.write(user.key())
I got the output as agxkZXZ-dmhvc3RlbDNyEQsSBFVzZXIiB2JodXNoYW4M
Please someone help!!
To start with you should read the docs on the Key class https://developers.google.com/appengine/docs/python/datastore/keyclass and how keys a structured - https://developers.google.com/appengine/docs/python/datastore/#Python_Kinds_keys_and_identifiers
Any way to your problem, note that the output of self.response.write(user.key()) is giving you the string agxkZXZ-dmhvc3RlbDNyEQsSBFVzZXIiB2JodXNoYW4M which is correct behaviour.
This is a URL safe form of the key which encodes all artifacts that make up the key.
This means you can round trip
user.key() = db.Key(encoded=str(user.key())
This allows you to use keys as part of URL. Whether that's wise or not is another discussion.
If you want to just show the name you used as the key_name then the docs for the Key class show you that the method name() will return the name.
As in user.key().name() or you could use id_or_name method which does what the name implies.
Perhaps self.request.get('username') is returning Null or None, and that results in the Datastore generating a default entry. According to the Users Service documentation it might need users.get_current_user().nickname() instead. Check by logging the values.
As Tim says you retrieve the name from the key using user.key().name().
I have a Permissions class for which I need to create a static method to get the corresponding element based on the POST method in my views.py. The choices are done via checkboxes, in which you can select either of those, a pair or all of them, based on your preferences. That creates a list of strings (u'OWNER'), which should be processed in the static method and return the corresponding Permissions.OWNER, Permissions.HR, Permissions.USER_ADMIN
My views.py's POST method looks like this:
permissions = self.request.get_all('permissions')
user.new_permission = Permissions.get_permission(permissions)
Model looks like this:
class Permissions(object):
OWNER = 'OWNER'
HR = 'HR'
USER_ADMIN = 'USER_ADMIN'
descriptions = {
OWNER: """Company owner (full admin)""",
HR: """Human Resources administrator (access to special fields within job and submissions)""",
USER_ADMIN: """Add/Delete users, change user permissions""",
}
What I have so far on the static method:
#staticmethod
def get_permissions(permissions):
new_perms = []
for permission in permissions:
name = permission
if permission ==
new_perms.append(permission)
return new_perms
I really do not know how can I compare a string to the value in the model... Nor I am sure if I have titled the question correctly.
Thank you in advance,
Borislav
There are a whole bunch of things wrong with your code, and it seems to be overcomplicated.
I suggest you do some python tutorials. I m not sure how the class definition was ever going to work. Any way here is one way you could do it.
class Permissions(object):
_perms = {
'OWNER': """Company owner (full admin)""",
'HR': """Human Resources administrator (access to special fields within job and submissions)""",
'USER_ADMIN': """Add/Delete users, change user permissions""",
}
#classmethod
def get_permissions(cls,permissions):
new_perms = []
for choice in permissions:
if choice in cls._perms:
new_perms.append(choice)
return new_perms
#classmethod
def get_description(cls,permission)
return cls._perm.get(permission)
Actually on re-reading your question I am not sure what you are really trying to do. You mention a model, but the permissions class you provide doesn't reflect that, and I assume you need to query for the object. In fact if you where using a model to define permissions you would have a Permission object for each possible Permission - maybe.
alternate strategy, but there are many and without looking in more detail at how you really plan to use permissions. (I use repose.who/what for a fairly well developed permission model). At its most basic you can use getattr with your existing class. However I not keen on it, as there are no checks in place.
class Permissions(object):
OWNER = 'OWNER'
HR = 'HR'
USER_ADMIN = 'USER_ADMIN'
#classmethod
def get_permission(cls,permission):
if hasattr(cls,permission):
return getattr(cls,permission)
else:
raise KeyError("No permission %s" % permission) # Some better exception should be used.