I’m working on a Discord bot in Python that creates and removes channels based on user commands. I need to build a cleanup function that checks all server channels and removes the ones that are no longer needed.
Here’s my current approach:
async def cleanupChannels():
while True:
await asyncio.sleep(15)
pattern = re.compile(r"[0-9]*_[a-z0-9]*-[0-9]*")
for currentChannel in bot.get_all_channels():
if pattern.match(currentChannel.name):
raidNumber = int(currentChannel.name[0])
activeRaid = raidList[raidNumber]
currentTime = datetime.datetime.now()
if activeRaid.endTime < currentTime:
if activeRaid.removeRaid():
channelId = activeRaid.channel.id
await updateRaidList(activeRaid)
await bot.delete_channel(bot.get_channel(channelId))
Sometimes this works fine, but other times I get a RuntimeError saying ‘dictionary changed size during iteration’. I think this happens because get_all_channels()
returns a dictionary and I’m modifying it while iterating. What’s the best way to handle channel deletion without this error?