【问题标题】:Issue with ban command discord.py (rewrite branch)禁止命令 discord.py 的问题(重写分支)
【发布时间】:2025-12-08 06:35:02
【问题描述】:

我一直在用 discord.py(重写分支)编写一个机器人,我想添加一个禁止命令。该机器人仍然没有禁止该成员,它只是显示一个错误:

@client.command(aliases=['Ban'])
async def ban(ctx,member: discord.Member, days: int = 1):
    if "548841535223889923" in (ctx.author.roles):
        await client.ban(member, days)
        await ctx.send("Banned".format(ctx.author))
    else:
        await ctx.send("You don't have permission to use this command.".format(ctx.author))
        await ctx.send(ctx.author.roles)      

它将禁止被ping的用户并确认它确实禁止

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    Member.rolesRole 对象的列表,而不是字符串。您可以使用 discord.utils.get 使用 id(作为 int)搜索该列表。

    from discord.utils import get
    
    @client.command(aliases=['Ban'])
    async def ban(ctx, member: discord.Member, days: int = 1):
        if get(ctx.author.roles, id=548841535223889923):
            await member.ban(delete_message_days=days)
            await ctx.send("Banned {}".format(ctx.author))
        else:
            await ctx.send("{}, you don't have permission to use this command.".format(ctx.author))
            await ctx.send(ctx.author.roles)
    

    也不再有 Client.ban 协程,Member.ban 的附加参数必须作为关键字参数传递。

    【讨论】:

    • 谢谢!那么,如果我的机器人加入另一台服务器怎么办..?我应该用什么替换角色 ID,这样才能通用?
    • 这取决于您要查找的内容。具有特定名称的角色,通过不和谐本身禁止成员的权限等。
    • K,我得到了命令,它是commands.has _permission(ban_members = True),谢谢你的帮助!
    【解决方案2】:
    async def ban(ctx, member: discord.Member=None, *, reason=None):
      if reason:
        await member.send(f'You got banned from {ctx.guild.name} by {ctx.author}, reason: ```{reason}```')
        
        await member.ban()
        
        await ctx.send(f'{member.mention} got banned by {ctx.author.mention} with reason: ```{reason}```')
      if reason is None: 
        await ctx.send("please specify a reason")
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票