如果频道最后一条消息是在 X 分钟前发送的,如何创建一个循环来发送消息? [discord.py]

How to create a loop to send a message if the channel last message was sent X minutes ago? [discord.py]

我正在尝试添加一个可自定义的聊天恢复命令功能,在 X 分钟内没有人说话后发送一个主题以恢复聊天,X 可以由管理员设置,我之前问过类似的问题但答案我得到的不适用于此处。

那么该功能是如何工作的:管理员通过执行命令并指定他们想要的分钟数来启用该功能,然后将分钟数保存到数据库中。

问题不在于将会议记录保存到数据库,它运行良好,问题在于创建一个循环来检查频道最后一条消息日期是否超过管理员设置的限制。

我尝试了几种方法,比如使用 asyncio.sleepwait_for(),但是它们影响了其他命令,所以它们不是正确的方法,我试过这个:

@bot.event
async def on_message(message):
    if str(message.channel.id) in data: # Check if the admins has set a number of mintues
        keepLooping = True
        timer = datetime.utcnow() + timedelta(seconds=delay) # delay is the time set by admins, pulled from the database.
        while keepLooping:
            if timer < message.channel.last_message.created_at and message.channel.last_message.author != bot.user:
                await message.channel.send("Random Topic Here")
                return
   
    await bot.process_commands(message)

我问过某些服务器的人,他们告诉我上面的方法对内存不好,所以我也假设这也不是一种方法。一位朋友告诉我使用 discord.py 任务,但我不确定如何执行它们。

任何有关此案例的帮助将不胜感激。

您可以使用 tasks。这不是一个很好的解决方案,但它会为你工作。

from discord.ext import tasks
import datetime
@tasks.loop(seconds=10.0)
async def checker():
    channel = # you should define the channel here
    last_mes = channel.last_message.created_at
    counter = # you should define the 'X' minutes here
    now = datetime.datetime.now()
    if now-last_mes >= datetime.timedelta(minutes=counter):
        await message.channel.send("Random Topic Here")
        return

你可以这样做,而且你应该在你的代码中添加 checker.start() 结尾。