Python Discord Bot:无法从正在运行的事件循环中调用 asyncio.run()

问题描述 投票:0回答:1

我一直在尝试使用 Python 构建一个不和谐的机器人。不幸的是,我在代码中遇到了这个错误,当我运行代码时,它似乎总是出现。

这是我的错误信息:

runfile('D:/Isaac Khong/Personal and School/Personal/programming/python/Discord Bots/iK10 Official/ik10-discordbot.py', wdir='D:/Isaac Khong/Personal and School/Personal/programming/python/Discord Bots/iK10 Official')
Traceback (most recent call last):

  File "D:\Isaac Khong\Personal and School\Personal\programming\python\Discord Bots\iK10 Official\ik10-discordbot.py", line 56, in <module>
    client.run('4e17e1549ce6dc2eff051db897ffb86d90514ac6dbbb68e20d9074af4aea9559')

  File "C:\Users\isaac\Anacoonda_New\lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())

  File "C:\Users\isaac\Anacoonda_New\lib\asyncio\runners.py", line 33, in run
    raise RuntimeError(

RuntimeError: asyncio.run() cannot be called from a running event loop

这是代码,使用 https://discordpy.readthedocs.io/en/stable/quickstart.html:

中的示例
import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('My Client ID Here (in a string)')

我也在这里尝试了我自己的代码,它出现了指向“client.run(“Client ID Here”)”行的相同错误:

import discord



TOKEN = '1081845655909187594'
GUILD = "iK10 Community"
intents = discord.Intents.default()
client = discord.Client(intents = intents)

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

我正在使用 Spyder Anaconda。这是我的 discord.py 版本:

(base) C:\Users\isaac>pip show discord.py
Name: discord.py
Version: 2.2.2
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: MIT
Location: c:\users\isaac\anacoonda_new\lib\site-packages
Requires: aiohttp
Required-by:

任何帮助将不胜感激。谢谢!

python discord.py spyder
1个回答
0
投票

Asyncio 在一次运行多个循环时遇到了一些麻烦,就像在这篇文章中

Spyder 似乎有问题。幸运的是,其他帖子通过使用

nest_asyncio

解决了这个问题
© www.soinside.com 2019 - 2024. All rights reserved.