What could be causing this error: RuntimeError('Event loop is closed') in Python

Question:

I am creating a discord bot in pyCharm. This is the following code I have:

# bot.py
import os

import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()


@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break
    print(
        f'{client.user} is connected to the following guild:n'
        f'{guild.name}(id: {guild.id})'
    )


client.run(TOKEN)

When I run it the following errors are produced:

Traceback (most recent call last):
  File "C:Userselrodvenvlibsite-packagesdiscordhttp.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:Userselrodvenvlibsite-packagesdiscordhttp.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:UserselrodOneDriveDesktopAssignmentsCPSCPythonHextchLibraryAppHextechLibrary.py", line 25, in <module>
    client.run(TOKEN)
  File "C:Userselrodvenvlibsite-packagesdiscordclient.py", line 723, in run
    return future.result()
  File "C:Userselrodvenvlibsite-packagesdiscordclient.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:Userselrodvenvlibsite-packagesdiscordclient.py", line 665, in start
    await self.login(*args, bot=bot)
  File "C:Userselrodvenvlibsite-packagesdiscordclient.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:Userselrodvenvlibsite-packagesdiscordhttp.py", line 304, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022950CEF160>
Traceback (most recent call last):
  File "C:UserselrodAppDataLocalProgramsPythonPython39libasyncioproactor_events.py", line 116, in __del__
    self.close()
  File "C:UserselrodAppDataLocalProgramsPythonPython39libasyncioproactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:UserselrodAppDataLocalProgramsPythonPython39libasynciobase_events.py", line 751, in call_soon
    self._check_closed()
  File "C:UserselrodAppDataLocalProgramsPythonPython39libasynciobase_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Process finished with exit code 1

Now, what I find interesting is this:

  • I can assure you that I have a .env file set up as such:
    DISCORD_TOKEN={my-token-here}
    DISCORD_GUILD={my-server-here}
    and it is the correct information
  • I know this because when I take the same token out of the .env file and just paste it directly into client.run() it works without issue, but of course this is private information!
  • So, the issue is that my file isnt being read properly? I would disagree because in testing I find that the string in DISCORD_GUILD is being read in properly without issue
  • I also tried the ole turn it off and back on trick by resetting to a new token but no luck

This is my last resort to understanding this error. Does anyone know what could be causing this error and ho to fix it?

Asked By: Michael Elrod

||

Answers:

Your .env file should look like this:

# .env

DISCORD_TOKEN = ADASIUHFOAka12312jsdfhpAFDA.GnTdIh.dOU0fjmz-WhfDebLN7x8ncuGbLVWyPXNftirGA

Should not contain the {}, if you included them (taking literally as you wrote in your question).

Also, you should set your intents under Discord Developers – Applications and declare them when defining client.

Answered By: Pedro Caribé
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.