踢所有命令

时间:2019-05-16 17:53:14

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

我需要一个kick all命令,以一种有趣的方式终止服务器

@bot.command(pass_context=True)
async def kick_all(ctx):
    while True:
        for server_member in ctx.message.server.members:
            try:
                channel = bot.get_channel('540612578401976330')
                await bot.kick(server_member)
                await bot.send_message(channel, "someone got kicked")
            except discord.Forbidden:
                pass

输出:

Ignoring exception in command kick_all
Traceback (most recent call last):
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "C:/Users/adamk/PycharmProjects/bot/Server_KillSwitch.py", line 18, in kick_all
    for server_member in ctx.message.server.members:
RuntimeError: dictionary changed size during iteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 374, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 54, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: dictionary changed size during iteration

2 个答案:

答案 0 :(得分:1)

问题是您要在ctx.message.server.members 上进行迭代时删除项目,这是不允许的,也没有太大意义:下一个元素要做什么在删除当前元素之前的元素之后?还是下一个?还是当前的?

您可以通过遍历字典的副本来快速解决此问题:

for server_member in ctx.message.server.members.copy():
    ...  # your code here

答案 1 :(得分:0)

您正在更改列表,同时引发错误。使用

@bot.command(pass_context=True)
async def kick_all(ctx):
    members = ctx.message.server.members.copy();
    while True:
        for server_member in members:
            try:
                channel = bot.get_channel('540612578401976330')
                await bot.kick(server_member)
                await bot.send_message(channel, "someone got kicked")
            except discord.Forbidden:
                pass