如何使用discord bot自动删除频道

时间:2018-03-08 00:19:21

标签: python python-3.x dictionary runtime-error discord.py

我正在做一个不和谐的python机器人。它根据播放器指令创建删除频道。 我想创建一个垃圾收集器来测试所有的server.channels并删除过时的。

我做:

async def waitTimer():
    while True:
        await asyncio.sleep(10)

        regex = re.compile(r"[0-9]*_[a-z0-9]*-[0-9]*") #nom des channels de raid

        for cCurrent in client.get_all_channels():
            if regex.match(cCurrent.name):
                numRaid = int(cCurrent.name[0])
                cRaidCurrent = cRaids[numRaid]
                date = datetime.datetime.now()
                print (cRaidCurrent.raid.fin.timestamp())
                print (date.timestamp())
                if cRaidCurrent.raid.fin < date:
                    if cRaidCurrent.retirerRaid():
                        cId = cRaidCurrent.com.id
                        await removeFromListe(cRaidCurrent)
                        await client.delete_channel(client.get_channel(cId))
                        cCurrent = 0

有时会通过,有时我会收到此错误:

    for cCurrent in client.get_all_channels():
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 581,
 in get_all_channels
    for channel in server.channels:
RuntimeError: dictionary changed size during iteration

如果我清楚地理解client.get_all_channels是一本字典而我在迭代期间无法删除频道......所以问题是我还有什么其他可能性来移除这些频道?

1 个答案:

答案 0 :(得分:0)

感谢Patrick Haugh获得完美合作的答案。

最后,删除操作需要进行2次。如果有人需要,这是代码:

for cCurrent in client.get_all_channels():
    if regex.match(cCurrent.name):
        numRaid = getNumChannel(cCurrent.name)
        cRaidCurrent = cRaids[numRaid]
        now = datetime.datetime.now()
        if cRaidCurrent.raid.fin < now:
            toDelete.append(cRaidCurrent)

for cRaidCurrent in toDelete:
    cId = cRaidCurrent.id
    cRaidCurrent.retirerRaid()
    await removeCRaid(cRaidCurrent)
    del cRaids[cId]