Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python - How to add a role with a Discord Bot

I start creating a Discord bot with the Python API of Discord. So, I tried to make a command that give roles on a discord server. Here is my code :

client = commands.Bot(command_prefix = '/')

@client.command()
async def addrole(ctx, role: discord.Role, user: discord.Member):
    if ctx.author.guild_permissions.administrator:
        await user.add_roles(role)
        await ctx.send(f"Successfully given {role.mention} to {user.mention}.")

When I try to use the command, any error happear. I try to make like the websearch I've done but still don't work. Can someone help me ?

question from:https://stackoverflow.com/questions/65883325/how-to-add-a-role-with-a-discord-bot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't believe basic things like these would require Discords intents, especially the "member intent". What I have done is I've cleaned up your code and required a member to be passed before a multiple string role, if needed.

@client.command()
@commands.has_permissions(manage_roles=True)
async def addrole(ctx, member: discord.Member = None, *, role: discord.Role = None):
        if role == None:
                await ctx.send(f'Provide a role to add')
                return

        if member == None:
                await ctx.send(f'Provide a member to add a role')
                return

        await member.add_roles(role)
        await ctx.send(f"Successfully added role, {role} to {member.name}")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...