从未等待机器人 base.load_extentstion 错误消息 discord.py

Bot base.load_extentstion was never awaited error message discord.py

因此,当我尝试 运行 我的 discord 机器人时,我收到此错误消息:

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
2022-04-30T22:38:44.714019+00:00 app[worker.1]: client.load_extension(f"cogs.{file[:-3]}")

这是我的代码:

if __name__ == '__main__':
# When running this file, if it is the 'main' file
# I.E its not being imported from anther python file run this
for file in os.listdir("./cogs"):
    if file.endswith(".py") and not file.startswith("_"):
         client.load_extension(f"cogs.{file[:-3]}")
client.run("random token here")

我试图阅读其他 Whosebug 但是当我尝试按照它说的去做时,它告诉我我不能在函数外使用 await。但是当我使用

修复它时
async def main():
    # do other async things
    await my_async_function()

    # start the client
    async with client:
        await client.start(TOKEN)

并执行 asycnio.run(main()) 它不起作用并告诉我

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

有办法解决这个问题吗?谢谢。

如评论中所述,在 2.0 中加载扩展是异步的。您需要将 client.start()asyncio.

一起使用

正如错误所说,你不能有一个已经 运行ning 的事件循环。 Discord 有自己的事件循环来管理事物,因此您必须使用 get_event_loop 来获取它。然后,run_until_complete 在这里就足够了,因为没有其他需要 运行.

import asyncio

async def main():
    # if you need to, initialize other things, such as aiohttp
    await client.load_extension('my_extension')  # change to whatever you need
    await client.start('token')

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())