【问题标题】:Discord Bot Raising Type Error With ClassDiscord Bot 类引发类型错误
【发布时间】:2022-01-14 18:37:42
【问题描述】:

我创建了一个 Python Discord Bot,我将所有函数放入一个类中,但是当我这样做时,我开始收到类型错误,唯一的问题是错误告诉我完全按照我的做法去做。 这是受影响的代码和错误。

client = commands.Bot(command_prefix='--', case_insensitive=True)



class Settings:

    def __init__(self):
        self.spitfirerole = 917086768736649258
        with open("data.json") as f:
            data = json.load(f)
        f.close()

        self.prev = data["serial"]

    @client.event
    async def on_ready(self):
        print('ThatOneGuy is online.')
        await client.change_presence(activity=discord.Game(name="chess with Mr.Z"))
        channel = client.get_channel(918300328267497502)
        em = discord.Embed(title=f"Status", color=0x22ff12)
        em.add_field(name="Active", value=f"I am now searching for a Spitfire.")
        await channel.send(f"<@&{self.spitfirerole}>", embed=em)

错误;

Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Libra\PycharmProjects\ThatOneGuy\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
TypeError: on_ready() missing 1 required positional argument: 'self'

【问题讨论】:

  • 看例子。 on_ready() 方法不需要参数discordpy.readthedocs.io/en/stable/quickstart.html
  • 我应该澄清一下,还有更多代码使用self 参数。所以如果我删除它,我会得到更多的错误。
  • 我认为您需要以 pydiscord 事件方法尊重文档中定义的参数的方式单独编写代码

标签: python class discord.py typeerror


【解决方案1】:

on_ready 处理程序注册到@client.event 时,它应该是一个不带参数的函数。如果您希望 on_ready 成为类中的方法,则需要将其设为静态方法:

    @client.event
    @staticmethod
    async def on_ready():
        print('ThatOneGuy is online.')
        await client.change_presence(activity=discord.Game(name="chess with Mr.Z"))

如果它需要是一个实例方法,你可能想继承discord.Client(或commands.Bot)而不是使用@client.event

class Settings(commands.Bot):
    async def on_ready(self):
        print('ThatOneGuy is online.')
        await self.change_presence(activity=discord.Game(name="chess with Mr.Z"))

client = Settings(command_prefix='--', case_insensitive=True)

另一种可能性是拥有一个全局 on_ready,它不接受任何参数并委托给您的 Settings 实例:

client = commands.Bot(command_prefix='--', case_insensitive=True)
settings = Settings()

@client.event
def on_ready():
    settings.on_ready()

【讨论】:

  • 静态方法中没有self——当你用@client.event注册一个处理程序时,你是在函数上注册它,而不是在特定实例的方法上(因此除非调用者提供了self,否则没有self——它没有,因此你的TypeError)。
  • 另一种可能是client.event(settings.on_ready),其中settings 是您的Settings 实例。不确定这是否真的是受支持的模式。
  • 撤消您所做的导致机器人无法启动的更改,然后尝试其他操作?
  • 更仔细地查看你的代码和文档,我可以看到如果你想做子类化的事情,你可能需要子类commands.Bot(它本身就是discord.Client的子类)。不确定您之前遇到了什么错误,但这可能会解决它。更新了我的答案。
  • 你的类是discord.Client 和/或commands.Bot 的子类吗?似乎如果您将方法设为事件处理程序,其想法是让它位于 Client 的子类上。
猜你喜欢
  • 2018-05-02
  • 2021-04-12
  • 1970-01-01
  • 2017-11-05
  • 2019-11-10
  • 2021-07-15
  • 2019-02-03
  • 2018-03-12
  • 2018-03-04
相关资源
最近更新 更多