I'm using discord.py rewrite. I've been 3 days trying to get these two lines of code to work:
await member.remove_roles(tryMember, tryRole)
.
.
.
await member.add_roles(tryMember, tryRole)
here is the surrounding code including my troubleshoting comented out. I have user ID# and role ID# to work with. This is a background process.
memberList = []
for member in guild.members:
...
... decide on one of 3 roles for the user as proposedRole. # role ID number
...
for roleID in (serverSettings["inactive_r"], serverSettings["active_r"], serverSettings["very_active_r"]):
if roleID != proposedRole:
try:
print (roleID)
tryRole = discord.utils.find(lambda r: r.id == roleID, guild.roles)
tryMember = discord.utils.find(lambda m: m.id == member.id, guild.members)
print (tryRole) #only prints a member's name#number
print (tryMember) #only prints the role name
await member.remove_roles(tryMember, tryRole)
print (f'Removed {tryRole} from {tryMember} in {guild.name}')
except Exception as e:
print ('There was an error running this command: ' + str(e))
... And repeat all this but adding the right role instead of removing the inocrrect roles
What gets printed out on the cosole per member is this:
709425978044186725 # the correct role ID
inactive # the correct role name (I was expecting an object)
ArdenFutura#2469 # the correct member name (I was expecting an object)
There was an error running this command: 404 Not Found (error code: 10011): Unknown Role
# the e exception
664856898838855681 #aaaaand repeat...
active
ArdenFutura#2469
There was an error running this command: 404 Not Found (error code: 10011): Unknown Role
726974763649728593
very active
ArdenFutura#2469
There was an error running this command: 404 Not Found (error code: 10011): Unknown Role
Ive been 3 days on these two lines of code. please help.
You may be confused with an older version of the API Reference. remove_roles used to take two parameters:
remove_roles(member, *roles)
However, the new documentation states that only one parameter is required:
remove_roles(*roles, reason=None, atomic=True)
roles takes in a single role. If you wanted to remove multiple roles, a list of roles with an asterisk preceding the list would be passed in (remove_roles(*[roleOne, roleTwo])).
reason and atomic are optional parameters of type str and bool.
In your case, you are trying to remove tryRole from tryMember. The result would be:
await tryMember.remove_roles(tryRole)
Related
I have a text file that has the following format:
group A:
red team: worker 1, worker 2
green team: worker 2, worker 3
Group B:
Team_Blue:worker 4, worker 2
Team_Black: worker 5, worker 6
Team_Grey: worker 6
From this text file, I want to create users and assign them to a group/team which for permission control.
I'm not sure how to go about this within a shell script, The python code snippet below shows the behaviour I'm after in the shell script.
Current attempt:
The file, usersfile.txt, looks like:
Headers - Group : Team : User
usersfile.txt as code block:
Group_A:Team_Red,Team_Green:worker_1,worker_2 worker_2,worker_3
Group_B:Team_Blue,Team_Black,Team_Grey:worker_4,worker_2 worker_5 worker_4,worker_6
Code:
with open("usersfile.txt") as file:
user_dict = {}
for line in file:
line = line.strip()
cols = line.split(':')
#get columns
group = cols[0]
teams = cols[1].split(',')
users = cols[2].split(' ')
#mkdir $group <--- directory created based off group name
#determine which teams a user is part of
for idx, members in enumerate(users):
for member in members.split(','):
#print(idx, group, teams[idx], member)
user_dict.setdefault(member,[]).append(teams[idx])
#Now we have users and their team, we can create a user account and assign them to a team
print(user_dict)
for user in user_dict:
print(f"ADDING USER {user} who is part of groups {user_dict[user]}")
# In shell script I would then create users
#echo " "
#echo "ADDING USER: " $user
#useradd $user -G $teams
output:
{'worker_1': ['Team_Red'], 'worker_2': ['Team_Red', 'Team_Green', 'Team_Blue'], 'worker_3': ['Team_Green'], 'worker_4': ['Team_Blue', 'Team_Grey'], 'worker_5': ['Team_Black'], 'worker_6': ['Team_Grey']}
ADDING USER worker_1 who is part of groups ['Team_Red']
ADDING USER worker_2 who is part of groups ['Team_Red', 'Team_Green', 'Team_Blue']
ADDING USER worker_3 who is part of groups ['Team_Green']
ADDING USER worker_4 who is part of groups ['Team_Blue', 'Team_Grey']
ADDING USER worker_5 who is part of groups ['Team_Black']
ADDING USER worker_6 who is part of groups ['Team_Grey']
If anyone has any suggestions on how to get this exact behavior from a shell script, im all ears.
So I’m making a discord bot that creates a profile for a user based off of their username and userID. The userID is the unique identifier for the profile, and the username is what is responded and searched when looking for said profile.
In order to get the userID and username, I’ve been trying to use discord.User, and getting the userID then transferring that to a username, both return with this error:
error image
I can’t figure out how to fix this, I’ve tried many different ways of getting the username and ID, but they all return a similar error.
Packages:
Discord, discord.ext, replit, os, db(replit extension)
Language:
Python V 3.8.0
Code:
#bot.command()
async def create(ctx, message):
user_id = message.author.id
userName = bot.get_user(user_id)
Just use ctx - you don't need message. Also, if you just want the username and ID of the person who calls the command, you don't even need to use discord.User.
#bot.command()
async def create(ctx):
user_id = ctx.author.id
user_name = ctx.author.name
I'm new to discord.py and I'm a intermediate student, I made a program to give a role to a specific user id, but I encounter some problem that I cannot solve it, anyone can help?
#tasks.loop(seconds=5)
async def change_status():
for number in range(len(data_dict["username"]) - 1):
if data_dict["year_start"][number] == year_now and data_dict["month_start"][number] == month_now and data_dict["date_start"][number] == date_now:
userid = int(data_dict["username"][number])
member = Guild.get_member(userid)
role = Guild.get_role(840609566093606953)
member.add_role(role)
Have you set the guild object correctly,
You need the line:
Guild = client.get_guild(ID)
You can find the guild Id by enabling dev mode in user settings and then right clicking on the server name when your server is open
So I have been trying to create a command where I can run the command "-roster Arizona Cardinals" as an example. And what it will do is return a list of mentions, and name#discriminators of the members within the Arizona Cardinals Role. But the Issue I have been stuck with, is When I am trying to return the Franchise Owner, General Manager, and Head Coach User mentions within the cardinals role, I cannot seem to do it without breaking the for loop for the for member in role.members Here is a snippet of where I am attempting to troubleshoot.
#commands.Command()
async def roster(ctx, role: discord.Role=None):
em = discord.Embed(title=f"{role.name}\'s Current Team Roster:", color=role.color)
em.set_author()
fo=discord.utils.get(ctx.message.guild.roles,id=846618354478481409)
gm=discord.utils.get(ctx.message.guild.roles,id=846618640957833259)
hc=discord.utils.get(ctx.message.guild.roles,id=846618777213730837)
for member in role.members:
embed.add_field(name="\u200b",
value=f"{member.mention}\n"
f"`{member.name}#{member.discriminator}`"
)
Wait, I think if I just add a item loop (e.g member = [member for member in role.members]) and then the franchise owner general manager and head coach user mentions. then finish the loop with:
embed.add_field(name="\u200b", value=f"{member.mention}\n {member.name}#{member.discriminator}")
that should work if I am correct? Am I not? So my finishing snippet would be:
#commands.Command()
async def roster(ctx, role: discord.Role=None):
em = discord.Embed(title=f"{role.name}\'s Current Team Roster:", color=role.color)
em.set_author()
fo=discord.utils.get(ctx.message.guild.roles,id=846618354478481409)
gm=discord.utils.get(ctx.message.guild.roles,id=846618640957833259)
hc=discord.utils.get(ctx.message.guild.roles,id=846618777213730837)
for role in ctx.guild.roles:
member = [member for member in role.members]
if role == fo:
em.add_field(name="**__Franchise Owner__**:", value=f"{member.mention}\n"
f"`{member.name}#{member.discriminator}`"
)
elif role == gm:
. . .
else:
em.add_field(name="\u200b", value=f"{member.mention}\n"
f"`{member.name}#{member.discriminator}`"
)
I understand why the error check is printed, but I don't understand why despite the fact that the user calling does not have the mod label, it runs the function anyway, maybe I don't really understand decorators (user also has a token role but I commented that part out for this test)
# token check
#bot.command(name='wallet', help='display if a token is available for user')
#commands.has_role('mod') # remove later
# #commands.has_any_role('PBToken 3', 'PBToken 6')
async def token_check(ctx):
name = ctx.author.name
response = name + ', You have a token available!'
await ctx.send(response)
# error message if user has no token currently
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.MissingRole):
name = ctx.author.name
# await ctx.send(name + ', you currently do not have a token, keep leveling up!')
await ctx.send('error check')
Here is the output:
Intead of using the mod role, why don't you run it using the check for whether the user has server administrator. To do that, all you do would be to replace:
#commands.has_role('mod')
with:
#commands.has_guild_permissions(administrator=True)
This would make the command only run if the specified user has server admin.
Please feel free to reply if you need any more help! :)