I’m working on a Discord bot in Python that creates and removes channels based on user commands. I want to add a feature that checks all channels and deletes the ones that are no longer needed.
Here’s what I’ve tried:
async def clean_channels():
while True:
await asyncio.sleep(60)
channel_pattern = re.compile(r'\d+_[a-z0-9]+-\d+')
for channel in bot.get_all_channels():
if channel_pattern.match(channel.name):
raid_num = int(channel.name[0])
current_raid = active_raids[raid_num]
now = datetime.datetime.now()
if current_raid.end_time < now:
if current_raid.close():
channel_id = current_raid.channel.id
await update_raid_list(current_raid)
await bot.delete_channel(bot.get_channel(channel_id))
Sometimes it works, but I often get this error:
RuntimeError: dictionary changed size during iteration
I think the problem is that I’m modifying the channel list while looping through it. How can I safely remove these channels without causing errors? Any suggestions would be great!