【问题标题】:How to Fix Runtime Error: Cannot close a running event loop - Python Discord Bot如何修复运行时错误:无法关闭正在运行的事件循环 - Python Discord Bot
【发布时间】:2019-12-29 13:45:38
【问题描述】:

我正在尝试使用 Python 创建一个 Discord 机器人,但是每当我在这里运行示例代码时:

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 

其他每一行似乎都运行得很好,但没有最后一行,它就无法连接到服务器,这使得它毫无用处。

注意:我已经看到问题here,但是 OP 的解决方案似乎不适用于我的情况。

【问题讨论】:

  • 你用的是什么版本?运行print(discord.__version__)
  • (这里是 Spyder 维护者) 要在我们的控制台中运行异步代码,您首先需要安装 nest_asyncio 包,然后在运行任何代码之前在我们的控制台中调用它.
  • @Carlos Cordoba 非常感谢老兄!您可以将其添加为答案,以便我接受您的问题吗?再次感谢您!
  • 很高兴知道这解决了您的问题!

标签: python discord spyder python-asyncio discord.py


【解决方案1】:

(此处为 Spyder 维护者)要在我们的控制台中运行异步代码,您首先需要安装 nest_asyncio 包,然后在运行自述文件中所述的任何代码之前调用它。

【讨论】:

【解决方案2】:

我在尝试在 Jupyter Notebook 上运行 Discord 示例时遇到了同样的问题。改用普通的 python 脚本为我解决了这个问题。

【讨论】:

  • 事实证明这个问题似乎是 anaconda 独有的,所以这会起作用。我一直在为所有编译器寻找解决方案,因此切换到纯 Python 脚本实际上并不适用。
猜你喜欢
  • 2021-11-17
  • 2022-10-30
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 2017-02-06
  • 2020-06-23
  • 2021-01-25
相关资源
最近更新 更多