【问题标题】:Confusion between commands.Bot and discord.Client | Which one should I use?commands.Bot 和 discord.Client 之间的混淆 |我应该使用哪一个?
【发布时间】:2022-11-20 04:18:29
【问题描述】:

每当您从该网站查看 YouTube 教程或代码时,都会发现真正的差异。一些开发人员使用client = discord.Client(intents=intents),而其他开发人员使用bot = commands.Bot(command_prefix="something", intents=intents)。现在我对其中的区别略有了解,但是当我使用它们中的任何一个时,我会从我的代码中的不同地方得到错误,这很令人困惑。特别是因为多年来 discord.py 发生了一些变化,所以很难找到真正的区别。

我试着坚持discord.Client 然后我发现commands.Bot 有更多的功能。然后发现使用commands.Bot时出错。

这方面的一个例子是:

当我尝试使用commands.Bot

client = commands.Bot(command_prefix=">",intents=intents)

async def load():
    for filename in os.listdir("./Cogs"):
      if filename.endswith(".py"):
        client.load_extension(f"Cogs.{filename[:-3]}")

以上没有给出我的 Cogs 的任何回应,还说

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited  
  client.load_extension(f"Cogs.{filename[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback`.

然后当我尝试使用discord.Client

client = discord.Client(command_prefix=">",intents=intents)
async def load():
    for filename in os.listdir("./Cogs"):
      if filename.endswith(".py"):
        client.load_extension(f"Cogs.{filename[:-3]}")

上面也给我一个错误:Exception has occurred: AttributeError 'Client' object has no attribute 'load_extension'

从长远来看,哪个更好?确切的区别是什么?

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    不同之处在于 commands.Bot 提供了更多的功能(如 Commands),而 Client 则没有。 Bot 是一个子类来自Client,所以它可以做 Client 可以做的一切,但反之则不行.

    从长远来看,你应该使用你需要的那个。如果您想使用Bot 功能,请使用Bot。如果您不关心 Bot 功能,那么使用 Client,或者您仍然可以使用 Bot,只是不使用额外的功能。

    您帖子中的第一个错误是coroutine load_extension was never awaited,它确切地告诉您问题出在哪里。 load_extension 是协程(一个async 函数),而你不是 awaiting 它。扩展在 2.0 中是异步的,你应该调整你的代码以适应它。迁移指南解释了该怎么做:https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous

    您帖子中出现的第二个错误是因为您试图在Client 中使用Bot 功能(扩展)。它告诉您 Client 没有 load_extension(),因为它没有。

    考虑到您使用的是过时的代码,我假设您正在关注 YouTube 教程。这是他们面临的主要问题之一。他们教的代码很糟糕,而且很快就过时了。他们还教你做一件特定的事情,然后你将无法创建自己的任何功能。不要遵循 YouTube 教程,只需阅读文档即可。

    【讨论】:

    • 非常感谢。了解你在做什么要好得多,我已经意识到 YouTube 视频永远不允许你这样做。我曾经只使用 YouTube 教程来“编码”discord 机器人,每当我像前几天一样遇到困难时,我都会删除命令。当我最近(过去 2 周)回来时,我尽量不看 YouTube 视频,但我无法仅使用文档进行编码。您的回答非常有道理,非常感谢。我的字符快用完了,所以我将在下一个评论中用示例解释问题 :)
    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 2010-09-07
    • 2011-01-12
    • 2015-04-10
    • 2013-07-16
    • 1970-01-01
    • 2016-09-22
    • 2015-06-01
    相关资源
    最近更新 更多