Search code examples
pythonpython-3.xdiscord

How can I close a discord client connection without exception


Let's say I have a simple discord.Client code:

import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()

TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    guild = None
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to guild {guild.name} (id: {guild.id})'
    )

client.run(TOKEN)

So, when I stop the code, I get this exception:

Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
    self._check_closed()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Process finished with exit code 0

It does not affect the code and functionality in any way, but it is very annoying to see. How would I disconnect/close connection properly then?


Solution

  • So, after a bit of searching, I found that the

    @client.event
    async def close():
        print(f"{client.user} disconnected")
    

    works just fine.