【问题标题】:Using MongoDB on Discord.py for scheduled tasks在 Discord.py 上使用 MongoDB 执行计划任务
【发布时间】:2021-06-10 07:37:48
【问题描述】:

目的

我有一些命令,例如 temp-mute、temp-ban 和其他需要在命令执行后执行的命令,我确实需要安排诸如赠品之类的事情,并在订阅结束后立即触发一个功能,从命令。

我想要什么?

我想将我所有的时间和事情存储在 MongoDB 中,然后在需要触发函数的时候触发它。我目前使用await asyncio.sleep(seconds),但是当我重新启动机器人或机器人离线时,它会停止,如果时间过去,我希望该功能在它上线时立即触发,或者我希望它即使在之后也能按时触发机器人重新启动。

【问题讨论】:

  • 您可以从数据库中获取数据并执行一些任务,这些任务将一直休眠到它结束的时间,还值得一提的是,asyncio 可以休眠的最大秒数是 3456000 秒(40 天)。我怀疑有人会回答这个问题,它太模糊了,根本没有细节,似乎你也希望我们为你编写代码,而不做尝试,我投票结束,因为这是一个愿望清单,不是编程问题,看看how to ask

标签: python python-3.x mongodb discord.py scheduled-tasks


【解决方案1】:

您可以使用@tasks.loop()

from pymongo import MongoClient
cluster = MongoClient("mongo_url_here")
collection = cluster["name"]

这可能是您描述该系列的方式。现在,当您临时禁止或临时静音某人时,您需要保存最后一次。你可以这样做,

current_time = datetime.datetime.now()
final_time = current_time + datetime.timedelta(seconds=seconds_here)

然后将final_time 保存在数据库中。

现在你需要创建一个@tasks.loop(seconds=x)

x 表示“每隔 x 秒,@tasks.loop() 中的函数将运行一次

@tasks.loop(seconds=10)
async def checker(self):
    try:
        all = collection.find({}) # return all documents inside the db
        current_time = datetime.datetime.now()
        async for x in all:
            if current >= x["Time"]: # do stuff after this
            else:
                pass
    except Exception:
        pass

x["Time"] -> 这可以是存储final_time的文档中的变量

{"id" : id , "Time" : final_time} -> 像这样

现在, async def checker(self): -> Checker 是一个函数,你需要启动它。这取决于您是否使用齿轮

如果不是 -> checker.start() # 在代码中的任何地方开始

如果是cog -> self.checker.start() # 应该放在`init

里面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2014-10-25
    相关资源
    最近更新 更多