How to add and remove role from users using ID - discord.py

I'm trying to create a command which allows users with the role Recruiter to promote tryout to soldier, I'm using arg1 as the mentioned user and then striping that down to get just the ID, but i cant add the roles since it keeps saying `str` object has no attriubute `add_roles`
#bot.command(name="promote", aliases = ["p"])
#commands.has_role('Recruiter')
async def _promote(self , ctx: commands.Context , arg1):
"""Promotes a tryout to recruit"""
guild = ctx.guild
tryout = ctx.guild.get_role(976813881232085052)
soldier = ctx.guild.get_role(973765272106332211)
userid = arg1.strip("<>#!")
await userid.add_roles(soldier)
await userid.remove_roles(tryout)
await ctx.send("Successfull")

You really need to read about this library converters and make your life easier;
But in a nutshell typehinting member: discord.Member will actually try to convert string you say in discord to discord.Member object so for example
!promote #Alex, !promote Alex, !promote 1234567 (alex id) will put Alex into member argument as discord.Member (which can be used for add/remove_roles) and raise commands.MemberNotFound if none member could be found.
#bot.command(name="promote", aliases=["p"])
#commands.has_role('Recruiter')
async def _promote(self, ctx: commands.Context, member: discord.Member):
"""Promotes a tryout to recruit"""
tryout = ctx.guild.get_role(976813881232085052)
soldier = ctx.guild.get_role(973765272106332211)
await member.add_roles(soldier)
await member.remove_roles(tryout)
await ctx.send("Successfull")

Related

Add specific user's to be able to view text channel with discord.py

I am trying to make it so that a new channel can be created with a command in a category called alliances, where specific users can be added to the channel. Can't work out how to add the users to the channel by name.
Can anyone help? My code so far:
#client.command()
#commands.has_permissions(manage_channels=True)
async def channelCreate(ctx, channel_name, member: discord.Member):
guild = ctx.message.guild
category = discord.utils.get(ctx.guild.channels, name="Alliances")
await guild.create_text_channel(channel_name, category=category)
Check docs you can use overwrites parameter to create a secret channel. You have to use dictionary with target member or role and PermissionOverwrite as a value.
#client.command()
#commands.has_permissions(manage_channels=True)
async def channelCreate(ctx, channel_name, member : discord.Member):
guild = ctx.message.guild
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True)
}
category = discord.utils.get(ctx.guild.channels, name="Alliances")
await guild.create_text_channel(channel_name, category=category, overwrites=overwrites)

How do I define a member inside a on_raw_reaction_remove()?

I tried to write a code that will remove a role from a member when a certain reaction is added. My code works fine until the end, where the role is removed from the member, where an "Attribute error" pops up; "AttributeError: 'NoneType' object has no attribute 'remove_roles'"
Here's my code:
#client.event
async def on_raw_reaction_remove(payload):
await client.wait_until_ready()
guild = await client.fetch_guild(payload.guild_id)
member = get(guild.members, id=payload.user_id)
if payload.message_id == id:
if payload.emoji.name == "a":
role = discord.utils.get(guild.roles, name = "a")
elif payload.emoji.name == "b":
role = discord.utils.get(guild.roles, name = "b")
await member.remove_roles(role)
My guess is that i'm defining member the wrong way, but I have no idea how to fix it
In this situation client.get_user() works better.
Here is the fixed code
#client.event
async def on_raw_reaction_remove(payload):
await client.wait_until_ready()
guild = await client.fetch_guild(payload.guild_id)
member = client.get_user(id=payload.user_id)
if payload.message_id == id:
if payload.emoji.name == "a":
role = discord.utils.get(guild.roles, name = "a")
elif payload.emoji.name == "b":
role = discord.utils.get(guild.roles, name = "b")
await member.remove_roles(role)
Hope this helped!
The main reason behind this is payload.member is None when using on_raw_reaction_remove.
This is actually because discord does not send this data, so discord.py has it as None.
Source-https://github.com/Rapptz/discord.py/issues/5871
To work around this, you get the guild object in question, then grab the member object from the guild.
The payload does not have the guild object either, so we have to get that as well.
What I did is I actually created the member object and tacked it onto the payload manually in the case of on_raw_reaction_remove.
This way both on_raw_reaction_add and on_raw_reaction_remove have the same payload for my final processing.
async def on_raw_reaction_remove(self, payload):
guild = self.get_guild(payload.guild_id) #Self here is Client/Bot
member = guild.get_member(payload.user_id)
payload.member = member
await reaction_role(payload, remove=True)
Furthermore, this requires the privileged members intent. To enable it, log back into the developer portal and look for the privileged intents > member intent, then tick the slider to on.
intent = discord.Intents.default()
intent.members = True
The intent needs to be passed to the client, or bot wrapper if using the bot extension.
commands.Bot.__init__(self, <...>, intents=intent)

Role delete and Role remove commands are not working | Discord.py

I made a role remove and role delete command that, idk what happened to it. It was working fine but the bot doesn't respond neither does it remove/delete the role. I might have messed it up while working on other commands, since everything else works fine but when I searched up online solutions. All the results were the same as my code. Not sure what's happening.
Role delete command:
#commands.command()
async def roledelete(self, ctx, *, role: discord.Role):
await role.delete()
await ctx.send(f'"{role}" got yeeted')
Role remove command:
#commands.command()
async def roleremove(self, ctx, roles, member: discord.Member=None):
if member == None:
member = ctx.message.author
guild = ctx.guild
role = discord.utils.get(guild.roles, name=f"{roles}")
await member.remove_roles(role)
await ctx.send(f"{roles} role has been removed")
For roleremove, you are running the code to remove a role from a member if member == None. If a member is specified there is no code to remove the role from the user. This should fix that
#commands.command()
async def roleremove(self, ctx, roles, member: discord.Member=None):
if member == None:
pass
else:
member = ctx.message.author
guild = ctx.guild
role = discord.utils.get(guild.roles, name=f"{roles}")
await member.remove_roles(role)
await ctx.send(f"{roles} role has been removed")
There is no problem in roledelete so the issue must be elsewhere in your code.
the question was only meant for remove not delete command lol. Anyways, so I removed a variable and replaced some of the code on my remove command and it worked. I spent a whole day trynna figure out how to do this and the solution was as simple as this lol. Here's the code if anyone needs it:
#commands.command()
async def roleremove(self, ctx, roles, member: discord.Member=None):
role = discord.utils.get(ctx.guild.roles, name=f"{roles}")
await member.remove_roles(role)
await ctx.send(f"{roles} role has been removed")
if member == None:
await ctx.send("Ok I'll remove roles but from who tho??"

How to make a discord.py reaction role code

I'm new to discord bot making, and I'd like to have the bot add a reaction to my message that, once pressed, allows the user reacting to pick up a role. What would be the code to allow me to do this? Thank you.
This is a very well written and formatted question! In order for the bot to detect that the reaction is on a specific message, you can do many ways. The easiest way would be to be by ID, so I'm just going to do this with a simple command.
messageIDs = []
#client.event
async def on_raw_reaction_add(payload):
global messageIDs
for messageID in messageIDs:
if messageID == payload.message_id:
user = payload.member
role = "roleName"
await user.add_roles(discord.utils.get(user.guild.roles, name = role))
#client.command()
async def addMessage(ctx, messageID):
global messageIDs
emoji = "👍"
channel = ctx.message.channel
try:
msg = await channel.fetch_message(messageID)
except:
await ctx.send("Invalid Message ID!")
return
await msg.add_reaction(emoji)
messageIDs.append(messageID)

How to make it so that the bot creates a text channel, with the command user and a certain role with access to the channel? (Rewrite)

I'm making a server and I want private tickets. How do you make it so that the role "Support" and the command user are the only ones to access the channel?(Bots can too).
Current code:
#client.command()
async def ticket(ctx):
global ticketNumber
ticketNumber = str(ticketNumber)
name = 'Tickets'
category = discord.utils.get(ctx.guild.categories, name=name)
guild = ctx.message.guild
await guild.create_text_channel(f'Ticket-{ticketNumber}', category=category)
ticketNumber = int(ticketNumber) + 1
To create a Text Channel with Permissions you can add the parameter overwrites={}.
It takes a Dictonary of the targets so you have to get the "Support" role with the utils.get() function:
support_role = discord.utils.get(ctx.guild.roles, name="Support")
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
ctx.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True),
support_role: discord.PermissionOverwrite(read_messages=True, send_messages=True),
ctx.author: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
await ctx.guild.create_text_channel(f'Ticket-{ticketNumber}', category=category, overwrites=overwrites)
The dictonary overwrites takes a Member or Role. In this example:
ctx.guild.default_role for #everyone
ctx.guild.me for the bot itself
support_role for the support role
ctx.author for the command user

Resources