【问题标题】:How to use schedule library in cogs in discord.py?如何在 discord.py 的 cogs 中使用调度库?
【发布时间】:2020-09-13 03:51:44
【问题描述】:

我希望机器人每天在特定时间完成一项工作,我知道我可以按计划完成,这也很简单。我试过了,效果很好,但现在我试图把它安排成齿轮并反复出错。

齿轮:

import discord
from discord.ext import commands, tasks
import discord.utils
from discord.utils import get
import schedule
import asyncio
import time

class SmanageCog(commands.Cog, name='Manager') :

    def __init__(self,bot):
        self.bot = bot

    def job(self):
        print("HEY IT'S TIME!")

    schedule.every().day.at("10:00").do(job)

    while True:
        schedule.run_pending()
        time.sleep(1)


def setup(bot):
    bot.add_cog(SmanageCog(bot))
    print("Manager is loaded!")

根据上面的代码,bot 会在每天上午 10 点打印 hey 它的时间。但这不起作用。它在上午 10 点向我抛出错误。 错误是这样的:

File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 653, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 599, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.smanage' raised an error: TypeError: job() missing 1 required positional arguments: 'self'

我不知道我应该从 def job 传递什么参数,我不能在 cog 中留空,而且 self 也会出错,所以我真的不知道要传递什么。

【问题讨论】:

    标签: python discord discord.py schedule


    【解决方案1】:

    你的问题出在这一行:

    schedule.every().day.at("10:00").do(job)
    

    您正在将函数/方法job 传递到调度程序中,并且没有绑定任何对象。因此,当作业运行时,调度程序将该函数作为“裸方法”调用,因此它不会为该方法提供self 参数。

    我不确定你的 SmanageCog 定义的类级别的代码是怎么回事,但如果你的代码在类定义之外,你可以这样做:

    schedule.every().day.at("10:00").do(SmanageCog(bot).job)
    

    然后您将为调度程序提供一个绑定方法,它会有一个对象作为self 传递给该方法。

    您可能想要在您的构造函数中进行调度调用吗?所以:

    def __init__(self,bot):
        self.bot = bot
        schedule.every().day.at("10:00").do(self.job)
    

    我赌主循环:

    while True:
        schedule.run_pending()
        time.sleep(1)
    

    也不属于类定义。

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2021-04-19
      • 2020-12-12
      • 2020-11-13
      • 2019-09-21
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多