Python Discord bot freezes when using client.close() method

I’m working on a Discord bot using Python and the discord.py library. I created a cleanup function that’s supposed to close the bot connection properly, but I’m running into a weird issue.

async def cleanup_bot(should_exit=True):
    stop_chat_system()
    print("chat system stopped")
    await bot.close()
    print("bot connection closed")
    
    if should_exit:
        print("shutting down...")
        exit()

When I run this function, everything works fine until it hits the bot.close() line. The first print statement shows up, but then the program just hangs there. It never prints the “bot connection closed” message and doesn’t continue to the exit part. The terminal just sits there doing nothing.

I’ve tried putting bot.close() in different spots in my code, even right at the start or inside the on_ready event, but it always does the same thing. Has anyone else run into this problem? What could be causing the bot to freeze like this?

I encountered this exact same issue last year when building my first bot. The problem isn’t necessarily with pending tasks - it’s often related to how the event loop handles the close operation from within itself. What worked for me was separating the close call from the cleanup logic. Instead of calling bot.close() directly in your cleanup function, try scheduling it with asyncio.create_task() or using loop.call_soon_threadsafe(). Also check if you’re running this cleanup from inside an event handler or command - that creates a circular dependency where the bot tries to close itself while still processing the event that triggered the close. Moving the actual close operation outside the immediate execution context usually resolves the hanging issue.

had this same issue couple months ago, super frustrating. try wrapping the whole thing in a try/except block - sometimes theres hidden exceptions that get swallowed. also make sure you’re not calling cleanup_bot from inside a discord event callback, that causes weird blocking behavior. i ended up using asyncio.get_event_loop().stop() after bot.close() which helped force it to actually terminate.

This hanging behavior usually happens when there are still active tasks or connections that prevent the bot from closing cleanly. The discord.py library waits for all pending operations to complete before actually closing, which can cause the freeze you’re experiencing. Try adding a timeout to force the closure if it takes too long. You can also check if you have any background tasks running that might be keeping the event loop busy. Another approach is to use asyncio.wait_for() around the close call with a reasonable timeout like 5-10 seconds. If you’re calling this from a command or event handler, make sure you’re not accidentally creating a deadlock by trying to close the bot from within its own event loop context.