【问题标题】:"RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited" after updating discord.py\"RuntimeWarning: coroutine \'BotBase.load_extension\' was never awaited\" 更新 discord.py 后
【发布时间】:2022-08-24 20:19:42
【问题描述】:

我一年前制作并部署到 Heroku 的不和谐机器人一直工作到现在。但是,在更改了一些 cogs 并将 python 更新到版本 3.9.10 之后,我在 Heroku 日志中收到以下警告:

app[worker.1]: /app/m_bot.py:120: RuntimeWarning: coroutine \'BotBase.load_extension\' was never awaited
app[worker.1]: client.load_extension(f\"cogs.{filename[:-3]}\")
app[worker.1]: RuntimeWarning: Enable tracemalloc to get the object allocation traceback
app[worker.1]: Bot is ready.
app[api]: Build succeeded> 

120行块是:

for filename in os.listdir(\"./cogs\"):
    if filename.endswith(\".py\"):
        # cut of the .py from the file name
        client.load_extension(f\"cogs.{filename[:-3]}\")

机器人上线但不响应任何命令。除了上面列出的内容之外,我没有进行任何其他更改。

当我在我的 PC 上运行我的机器人时它可以工作,所以我怀疑这可能是版本问题。

我该如何解决这个问题?

    标签: python heroku discord discord.py


    【解决方案1】:

    解释

    从 discord.py 2.0 版开始,Bot.load_extension 现在是协程,必须等待。这是为了允许Cog 子类使用协程覆盖cog_unload

    代码

    await必须在client.load_extension前面使用,如图:

    await client.load_extension("your_extension")
    

    在您的每个齿轮中:

    将标准 setup 函数替换为异步函数:

    async def setup(bot):
        await bot.add_cog(YourCog(bot))
    

    如果要使用常规约定来添加扩展,则需要使用以下代码:

    在您的客户文件中:

    async def load_extensions():
        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                # cut off the .py from the file name
                await client.load_extension(f"cogs.{filename[:-3]}")
    

    您还应该将登录信息包装在异步“主”函数中,您可以在其中调用此函数:

    async def main():
        async with client:
            await load_extensions()
            await client.start('your_token')
    
    asyncio.run(main())
    

    这两个函数取代了旧的方式:

    client.run("your_token")
    

    以及您在问题中发布的代码。

    参考

    discord.py 2.0 async changes(感谢 ChrisDewa 在您的评论中提到这一点)

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-22
      • 1970-01-01
      • 2016-11-28
      • 2022-01-25
      • 2021-07-30
      相关资源
      最近更新 更多