Addition of a recap of the ToDo's every Saturday at 9am

This commit is contained in:
Mylloon 2021-09-20 11:07:45 +02:00
parent be47cc43b0
commit 1b7b4d0507
3 changed files with 58 additions and 2 deletions

View file

@ -1,9 +1,9 @@
from discord.ext import commands from discord.ext import commands, tasks
from discord_slash import cog_ext from discord_slash import cog_ext
from utils.todo import ToDo, embedListeToDo from utils.todo import ToDo, embedListeToDo
from utils.core import getMentionInString, isSlash, mySendHidden from utils.core import getMentionInString, isSlash, mySendHidden
from utils.core import addReaction, mentionToUser from utils.core import addReaction, mentionToUser
from utils.time import nowUTC from utils.time import nowUTC, timeBeforeNextSaturdayAtNineHours
def setup(client): def setup(client):
"""Adding Cog to bot""" """Adding Cog to bot"""
@ -13,8 +13,44 @@ class ToDoDiscord(commands.Cog, name="Todo"):
"""Commandes relatives aux To Do.""" """Commandes relatives aux To Do."""
def __init__(self, client): def __init__(self, client):
self.client = client self.client = client
self._todoLoop.start()
ToDo().creationTable() ToDo().creationTable()
@tasks.loop(minutes = 1) # ce temps est ignoré
async def _todoLoop(self):
"""Méthode qui se répète toute les samedis pour envoyer un récapitulatif des Todos."""
if self._todoLoop.current_loop in (0, 2): # ignore des boucles non voulue (#1 se lance au démarrage et #3 au changement de l'intervalle)
return
elif self._todoLoop.current_loop == 1: # premier vrai lancement
print("premier lancement")
self._todoLoop.change_interval(hours = 168) # prochain lancement dans 1 semaine
todos = []
listIDs = []
for todo in ToDo().listAll():
if todo[0] in listIDs:
pass
else:
todos.append(todo)
listIDs.append(todo[0])
for todo in todos:
user = self.client.get_user(todo[0])
if user == None: # si l'utilisateur n'est pas trouvé
return # on ignore l'utilisateur
channel = await user.create_dm() # envoie en DM
embed, pageMAX = await embedListeToDo(user, 1)
message = await channel.send("Récapitulatif hebdomadaire de vos To Do's", embed = embed)
if pageMAX > 1:
for emoji in ["⬅️", "➡️"]:
await message.add_reaction(emoji)
else:
await message.add_reaction("🔄")
@_todoLoop.before_loop
async def __avant_todoLoop(self):
"""Wait to start the loop until the whole bot is ready"""
await self.client.wait_until_ready()
self._todoLoop.change_interval(seconds = timeBeforeNextSaturdayAtNineHours())
@commands.command(name='todo') @commands.command(name='todo')
async def _todo(self, ctx, *todo): async def _todo(self, ctx, *todo):
"""Met en place un To Do.\n ➡ Syntaxe: {PREFIX}todo <message>""" """Met en place un To Do.\n ➡ Syntaxe: {PREFIX}todo <message>"""

View file

@ -129,3 +129,16 @@ def ageLayout(tuple):
for i in affichage: for i in affichage:
message = message + f", {tuple[i]} {time[i]}" message = message + f", {tuple[i]} {time[i]}"
return message[2:] return message[2:]
def timeBeforeNextSaturdayAtNineHours() -> int:
"""Envoie le nombre de secondes qu'il y a avant le prochain Samedi à 9h"""
date = datetime.today()
now = date
# prochain 9h
while date.hour != 9:
date = date + timedelta(hours = 1)
# prochain samedi
while date.strftime("%A") != "Saturday":
date = date + timedelta(days = 1)
delta = date - now
return int(delta.total_seconds())

View file

@ -47,6 +47,13 @@ class ToDo(Database):
""" """
return self.affichageResultat(self.requete(requete, userID)) return self.affichageResultat(self.requete(requete, userID))
def listAll(self):
"""Retourne la liste de tout les To Do."""
requete = """
SELECT user_id, id, todo_str, creation_int FROM todo
"""
return self.affichageResultat(self.requete(requete))
def appartenance(self, userID: int, id: int): def appartenance(self, userID: int, id: int):
"""Vérifie qu'un To Do appartiens à un utilisateur. Renvois False si le To Do n'existe pas.""" """Vérifie qu'un To Do appartiens à un utilisateur. Renvois False si le To Do n'existe pas."""
requete = """ requete = """