Reputation: 90
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.
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:
@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. One friend has told me to use the discord.py tasks, but I am not sure how to implement them.
Any help regarding this case will be appreciated.
Upvotes: 0
Views: 224
Reputation: 4743
You can use 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.
Upvotes: 1