Discord.py 踢掉服务器的所有成员

时间:2021-07-03 04:20:28

标签: discord.py try-except

我的代码:

@client.command(pass_contxt=True)
async def kick_all(ctx):
    members = ctx.guild.members 
    members.remove(ctx.me)
    for member in members:
        try:
            if member.id != id or member.id != id: # the two ids inputed(don't want to share my id)
                await member.kick(reason="deleting server")
            else:
                await ctx.send(f"Failed to kick {member}.")
        except discord.Forbidden: # forbidden error is the error that gets returned when the bot is forbidden to do something(in this case kick itself)
            await ctx.send(f"Failed to kick {member}.")
        continue

假设已经导入了 discord。这段代码没有因为使用 try/except 而给我任何错误,但它只工作一次然后停止,因为它不能踢自己(是的,它首先开始尝试踢自己)。

附言我想学习如何做到这一点,因为简单地删除我自己的服务器既无趣又无助于我学习。

另外,任何帮助将不胜感激,并提前致谢!

2 个答案:

答案 0 :(得分:0)

@client.command()
async def role_kick(ctx, role: discord.Role):
    [await member.kick() for member in ctx.guild.members if role in member.roles]

这将踢出具有特定角色的所有成员,因此如果您为每个人分配一个成员角色并执行 [prefix]role_kick [the role],它将踢出所有具有该角色的人。 例如>role_kick @members

希望这能解决您的问题

答案 1 :(得分:0)

试试看:

your_ids = (1234, 5678) # paste you'r ids hear

@client.command()
# me: this is a command, dpy: OK
async def kick_all(ctx):
    await ctx.send('Wait A Second...') # I am alive
    if ctx.author.is_owner() or ctx.author.id in your_ids:
        # This is a check for user, if user is you or server owner will be 
        await ctx.send('Started') # Start
        continued

        members = ctx.guild.members      # This is list of members
        members.remove(ctx.me)           # a user can't kick you'r self so remove bot

        for member in members:           # creating a loop
            try:                         # a bot is limited and limit is Error
                if member.id in your_ids: # Check member is not you
                    await member.kick(reason="omae wa mou shindeiru")
                    # Kick

                else:
                    await ctx.send(f"Failed to kick {member}.")
                    # This is an log for user.

            except Exception as err: # bot has not permission
                await ctx.send(f"Failed to kick {member}.")
                # This is an log for user.
                continue # Next user
    else:
        await ctx.send('You don\'t have permission to use this command.')

bot 需要 members 意图,所以客户端是这样定义的

from discord.ext.commands import *
import discord

intent = discord.Intents.default()
intent.members = True
# or 
intent = discord.Intents.all()

client = Bot(command_perfix='?', intent=intent, ...)

并检查它enter image description here