I need to ensure that by pressing a button one role is removed and another is added. This is my code:
class SimpleView(discord.ui.View):
def __init__(self):
self.start_time = None
self.stop_time = None
super().__init__(timeout=None)
@discord.ui.button(label="⬆️", style=discord.ButtonStyle.green, custom_id="1")
async def entrata(self, interaction: discord.Interaction, button: discord.ui.Button):
orario_it = datetime.now(pytz.timezone('Europe/Rome'))
orario = orario_it.strftime('%H:%M')
allowed_role_id = 1215328270443094128
added_role_id = 1215318583702454352
removed_role_id = 1215328270443094128
allowed_role = discord.utils.get(interaction.guild.roles, id=allowed_role_id)
user = interaction.user
if allowed_role is None or allowed_role not in interaction.user.roles:
await interaction.response.send_message(f"***Per poter entrare in servizio dei essere in: {allowed_role.mention}!***", ephemeral=True)
if allowed_role in interaction.user.roles:
SimpleView.start_time = time.time()
channel = bot.get_channel(1214495527924928522)
embed=discord.Embed(color=0x23a559)
embed.set_thumbnail(url="https://shft.cl/img/c/cdn.discordapp.com-101395680655364460.webp")
embed.add_field(name="⬆️⬆️", value="", inline=False) #BOTTONE ENTRATA
embed.add_field(name="NOME:", value=f"{interaction.user.mention}", inline=True)
embed.add_field(name="", value="", inline=True)
embed.add_field(name="", value="", inline=False)
embed.add_field(name="", value="", inline=False)
embed.add_field(name="DATA:", value=f"{data}", inline=True)
embed.add_field(name="ORARIO:", value=f"{orario}", inline=True)
embed.set_footer(text="ARMERIA200")
await user.remove_roles(removed_role_id)
await user.add_roles(added_role_id)
await channel.send(embed=embed)
await interaction.response.send_message(f"***SEI ENTRATO IN SERVIZIO ALLE: {orario}.***", ephemeral=True)
My code doesn't work, what can I do? It should add and remove a role but it doesn't work, please help me
In the above code, you have to pass
discord.Rolein the parameter of theuser.add_roles()(also inuser.remove_roles), but in the code you are giving role id in the parameter. You will have to get the role bydiscord.guild.get_role().You can fix the above problem by using the following code:
Also you can use this method instead of
discord.utils.get.Remember: The bot should have
Manage_rolespermission in the server.References: