1

I keep getting this error "RuntimeError: Cannot close a running event loop" whenever I run the code below, tried many solutions but none of them worked.

I am using jupyter notebook, print(discord.__version__) --> 1.7.3

Thanks in advance.

import nest_asyncio
nest_asyncio.apply()

import discord
import os
from dotenv import load_dotenv

# https://stackoverflow.com/questions/63530888/how-would-i-go-about-creating-an-env-file-for-my-discord-bot-token


client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))
    
    
@client.event
async def on_message(message):
    if message.author == message.user:
        return
    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')
        
        
TOKEN = os.getenv("token")

client.run('TOKEN')

code output:

Task exception was never retrieved future: <Task finished name='Task-21' coro=<Client.run..runner() done, defined at C:\Users\username\anaconda3\lib\site-packages\discord\client.py:700> exception=LoginFailure('Improper token has been passed.')> Traceback (most recent call last): File "C:\Users\username\anaconda3\lib\site-packages\discord\http.py", line 300, in static_login data = await self.request(Route('GET', '/users/@me')) File "C:\Users\username\anaconda3\lib\site-packages\discord\http.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:\Users\username\anaconda3\lib\asyncio\tasks.py", line 280, in __step result = coro.send(None) File "C:\Users\username\anaconda3\lib\site-packages\discord\client.py", line 702, in runner await self.start(*args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\discord\client.py", line 665, in start await self.login(*args, bot=bot) File "C:\Users\username\anaconda3\lib\site-packages\discord\client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) File "C:\Users\username\anaconda3\lib\site-packages\discord\http.py", line 304, in static_login raise LoginFailure('Improper token has been passed.') from exc discord.errors.LoginFailure: Improper token has been passed.

RuntimeError                              Traceback (most recent call last)
<ipython-input-10-ccfa19a2810e> in <module>
     26 TOKEN = os.getenv("token")
     27 
---> 28 client.run('TOKEN')
     29 
     30 

~\anaconda3\lib\site-packages\discord\client.py in run(self, *args, **kwargs)
    717             future.remove_done_callback(stop_loop_on_completion)
    718             log.info('Cleaning up tasks.')
--> 719             _cleanup_loop(loop)
    720 
    721         if not future.cancelled():

~\anaconda3\lib\site-packages\discord\client.py in _cleanup_loop(loop)
     93     finally:
     94         log.info('Closing the event loop.')
---> 95         loop.close()
     96 
     97 class _ClientEventTask(asyncio.Task):

~\anaconda3\lib\asyncio\selector_events.py in close(self)
     87     def close(self):
     88         if self.is_running():
---> 89             raise RuntimeError("Cannot close a running event loop")
     90         if self.is_closed():
     91             return

RuntimeError: Cannot close a running event loop
1
  • Please post the whole traceback. Commented Sep 23, 2021 at 17:05

1 Answer 1

0

Change the last line from client.run('TOKEN') to client.run(TOKEN). You are using the string "TOKEN" not the variable TOKEN.

Sign up to request clarification or add additional context in comments.

6 Comments

Changed it and still getting the error.
I tried running your code and got a different error - "NoneType object can't be stripped", but it was caused by the fact you never run load_dotenv() which should be run before trying to access values in the .env file. If you run this at the start of the file it might work.
Unfortunately, it didn't work, and I still get the same error.
That's odd - it runs fine for me. The only other thing I can suggest is to make sure the token in the .env file is correct.
The code works fine on an online ide, on jupyter notebook I get the "RunTimeError". I am missing something and I can't figure what is it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.