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

2024-09-29 23:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试添加一个可定制的聊天恢复命令功能,在没有人发言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任务,但我不知道如何实现它们

任何有关本案的帮助都将不胜感激


Tags: the方法命令功能数据库messageif管理员
1条回答
网友
1楼 · 发布于 2024-09-29 23:20:27

您可以使用^{}。这不是一个很好的解决方案,但它会对你有用

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()结尾添加到代码中

相关问题 更多 >

    热门问题