簡體   English   中英

如何修復運行時錯誤:無法關閉正在運行的事件循環 - Python Discord Bot

[英]How to Fix Runtime Error: Cannot close a running event loop - Python Discord Bot

我正在嘗試使用 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 

其他每一行似乎都運行得很好,但如果沒有最后一行,它就無法連接到服務器,這使得它毫無用處。

注意:我在這里看到了這個問題,但是 OP 的解決方案似乎不適用於我的情況。

(這里是 Spyder 維護者)要在我們的控制台中運行異步代碼,您首先需要安裝nest_asyncio包,然后在運行任何代碼之前調用它,如自述文件中所述。

我在嘗試在Jupyter Notebook上運行 Discord 示例時遇到了同樣的問題。 轉向普通的python腳本為我解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM