I'm trying to make a discord bot using the discord.py library, but whenever I try bot.close() I get a RuntimeError: Event loop is closed
I've reduced the code to the minimun but still get the error
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import asyncio
TOKEN = os.getenv('TOKEN')
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}!')
await asyncio.sleep(5)
print("shuting down")
await bot.close()
bot.run(TOKEN)
The traceback is the following
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x037726E8>
Traceback (most recent call last):
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 711, in call_soon
self._check_closed()
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 504, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x037726E8>
Traceback (most recent call last):
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 116, in __del__
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 108, in close
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 711, in call_soon
File "...\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 504, in _check_closed
RuntimeError: Event loop is closed
I know most people just ignore these errors since they don't really effect the code in an meaningfull way, but I'd like to have a clean program that doesn't produce any errors.
Version I'm using:
This is a known problem when running an asyncio
application on Windows. Don't worry, it's nothing important (it just looks ugly). If you want to fix it, put the following after you import asyncio:
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# ... continue with your code
This sets your asyncio loop policy to a WindowsSelector one, instead of a WindowsProactor, which works a tad differently. You only need to do this once somewhere in your code (as long as it gets executed).