python - 更新 discord.py 后 "RuntimeWarning: coroutine ' BotBase.load_extension ' was never awaited"

标签 python heroku discord discord.py

我一年前制作并部署到 Heroku 的 discord 机器人一直运行到现在。然而,在更改了一些齿轮并将 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行 block 是:

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 上运行我的机器人时,它工作正常,所以我怀疑它可能是版本问题。

我该如何解决?

最佳答案

解释

从 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]}")

您还应该将您的登录包装在一个异步“主”函数中,您将在其中调用该函数。请注意,下面的代码没有设置日志记录,you need to do so yourself :

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 在您的评论中提到这一点)

关于python - 更新 discord.py 后 "RuntimeWarning: coroutine ' BotBase.load_extension ' was never awaited",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71504627/

相关文章:

discord - 如何使用 aiohttp 制作 reddit discord 机器人

python - 我应该在哪里以及如何在 GitHub 上存储带有 key 和 token 的文件?

python - django/nginx 中无法解释的无效 HTTP_HOST 错误

python - 从停用词列表中重新替换多个字符串模式

node.js - 如何使用nodejs请求模块复制curl命令?

javascript - Djs 交互与嵌入分开发送附件

python - 使用 if/else 和 for 循环将项目附加到列表理解中的列表

ruby-on-rails - 在 Heroku 上安装 GEOS

php - 在 Heroku Laravel 实例上设置 HTTPS 重定向

c# - 消息不会被删除?