discord.py 中有特定角色的每个人有没有办法踢?

Is there a way of kicking everyone with a certain role in discord.py?

我正在尝试执行一个命令来踢出具有特定角色的所有成员。进展不太顺利 - 这是我当前的代码:

import discord 
from discord.ext import commands
from discord.ext.commands import has_permissions

client = commands.Bot(command_prefix = "k!")

@client.command(pass_context=True)
@has_permissions(administrator=True)
async def kickall(ctx):
    role_id = 754061046704242799
    for role_id in roles: #roles undefined lol
        try:
            await member.kick()
        except:
            continue

您可以遍历所有成员,并检查他们是否具有指定的角色。如果他们这样做,你可以踢他们。

@client.command(pass_context=True)
@has_permissions(administrator=True)
async def kick(ctx, role: discord.Role, reason: str=None):
    for member in ctx.guild.members:
        if role in member.roles: # does member have the specified role?
            await ctx.guild.kick(member, reason=reason)

用法为k! kick <role> <reason(optional)>

我建议查看 documentation 了解更多详情。

参数(ctx, role: discord.Role, reason: str=None)如下:

  • ctx - 默认传入。这包含所有上下文信息,例如消息作者、消息发送的服务器等
  • role: discord.Role - 用户必须在调用命令时指定要踢出的角色。冒号告诉 python 和 discord.py 尝试将参数转换为的类型,这意味着它会将角色名称(即字符串)转换为 discord.Role 对象,因此您可以对其进行操作,例如比较角色。
  • reason: str=None - 可选参数(默认为 None)。如果提供,被踢的用户将看到此字符串作为被踢的原因消息。