如何修复运行时错误:无法关闭正在运行的事件循环-Python Discord Bot [英] How to Fix Runtime Error: Cannot close a running event loop - Python Discord Bot
问题描述
我试图使用Python创建Discord机器人,但是每当我在此处运行示例代码时:
I am trying to create a Discord bot with Python, however whenever I run the sample code here:
import discord
client = discord.Client()
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('!hello'):
msg = 'Hello {0.author.mention}'.format(message)
await client.send_message(message.channel, msg)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run('tokenhere')
返回错误:
Traceback (most recent call last):
File "<ipython-input-6-ea5a13e5703d>", line 1, in <module>
runfile('C:/Users/User/Pictures/rito_bot.py', wdir='C:/Users/User/Pictures')
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 703, in runfile
execfile(filename, namespace)
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/User/Pictures/rito_bot.py", line 22, in <module>
client.run('token')
File "C:\Users\User\Anaconda3\lib\site-packages\discord\client.py", line 595, in run
_cleanup_loop(loop)
File "C:\Users\User\Anaconda3\lib\site-packages\discord\client.py", line 97, in _cleanup_loop
loop.close()
File "C:\Users\User\Anaconda3\lib\asyncio\selector_events.py", line 94, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
其他所有行似乎都可以正常运行,但是如果没有最后一行,它就不会连接到服务器,这使它无用。
Every other line seems to run just fine, but without the last line it doesn't connect to the server, which makes it useless.
注意:我已经看到了此处,但是OP的解决方案似乎不适用于我的情况。
Note: I have seen the question here, however OP's solution doesn't seem applicable to my situation.
推荐答案
(此处为Spyder维护者),要在我们的控制台中运行异步代码,您首先需要安装 nest_asyncio 程序包,然后在运行自述文件中描述的任何代码之前先调用它。
(Spyder maintainer here) To run async code in our consoles you first need to install the nest_asyncio package and then call it before running any of your code as described on its Readme.
这篇关于如何修复运行时错误:无法关闭正在运行的事件循环-Python Discord Bot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!