简体   繁体   中英

(Python) Discord bot code returns "RuntimeError: Cannot close a running event loop"

I was trying to create code in Spyder to start my discord bot, but I encountered the following error:

Traceback (most recent call last):

File "", line 1, in runfile('C:/Users/Nathan/Desktop/HW/Python stuff/my_discord_bot.py', wdir='C:/Users/Nathan/Desktop/HW/Python stuff')

File "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder_kernels\\customize\\spydercustomize.py", line 827, in runfile execfile(filename, namespace)

File "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder_kernels\\customize\\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Nathan/Desktop/HW/Python stuff/my_discord_bot.py", line 17, in client.run('my application token')

File "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\discord\\client.py", line 705, in run _cleanup_loop(loop)

File "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\discord\\client.py", line 98, in _cleanup_loop loop.close()

File "C:\\ProgramData\\Anaconda3\\lib\\asyncio\\selector_events.py", line 83, in close raise RuntimeError("Cannot close a running event loop")

RuntimeError: Cannot close a running event loop

I've searched online and someone told me to use a package called "nest_asyncio". I pip installed the package, imported it, and ran nest_asyncio.apply() in the console, but the code still gave the same error after running it again.

This was my code:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    print ('Bot is ready.')
    
client.run('my application token')

By the way, I replaced my actual token with "my application token" because I don't want to share it with anyone.

Please help. How do I get rid of this error and get it to run like normal?

( Spyder maintainer here ) In order to run async code in Spyder, you need to install a package called nest-asyncio and add these two lines to be the first ones in your code:

import nest_asyncio
nest_asyncio.apply()

I found the solution. Instead of using Spyder's built-in console I used the command prompt to run my code, and this bypassed the RuntimeError.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM