简体   繁体   English

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

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

I am trying to add a customizable chat revival command feature that sends a topic to revive the chat after nobody has spoken for X minutes, X can be set by an admin, I have asked a similar question before but the answer I got doesn't apply here.我正在尝试添加一个可自定义的聊天恢复命令功能,该功能发送一个主题以在 X 分钟内没有人发言后恢复聊天,X 可以由管理员设置,我之前问过类似的问题但我得到的答案没有在这里申请。

So how the feature works: An admin enables the feature by executing a command and specifying the number of minutes they want, then the minutes are saved to a database.那么该功能是如何工作的:管理员通过执行命令并指定他们想要的分钟数来启用该功能,然后将分钟数保存到数据库中。

The problem is not with saving the minutes to the database, it works well, the problem is with creating a loop to check if the channel last message date exceeded the limit set by the admins.问题不在于将会议记录保存到数据库,它运行良好,问题在于创建一个循环来检查频道最后一条消息日期是否超过管理员设置的限制。

I have tried several ways, Like using asyncio.sleep and wait_for() , but they affected the other commands, so they aren't the right way to go, and I tried this:我尝试了几种方法,比如使用asyncio.sleepwait_for() ,但它们影响了其他命令,所以它们不是 go 的正确方法,我试过这个:

@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)

I have asked some people in some servers, they told me the way above is not good for memory, so I am also assuming it is not a way to go either.我问过某些服务器的一些人,他们告诉我上面的方法对 memory 不好,所以我也假设它也不是 go 的方法。 One friend has told me to use the discord.py tasks, but I am not sure how to implement them.一位朋友告诉我使用 discord.py 任务,但我不确定如何执行它们。

Any help regarding this case will be appreciated.任何有关此案例的帮助将不胜感激。

You can use tasks .您可以使用tasks It's not a excellent solution but it will work for you.这不是一个很好的解决方案,但它会为你工作。

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

You can do that and also you should add checker.start() end of to the your code.你可以这样做,你也应该添加checker.start()结束到你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM