adding refresh button

This commit is contained in:
Mylloon 2021-07-30 13:57:23 +02:00
parent 69ea7bf5db
commit 6f6bd3ac11
2 changed files with 84 additions and 66 deletions

View file

@ -1,7 +1,7 @@
import discord import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
from discord_slash import cog_ext from discord_slash import cog_ext
from utils.reminder import Reminder from utils.reminder import Reminder, embedListe, listReaction
from utils.core import getURLsInString, getMentionInString, isSlash, mySendHidden, mentionToUser, cleanCodeStringWithMentionAndURLs from utils.core import getURLsInString, getMentionInString, isSlash, mySendHidden, mentionToUser, cleanCodeStringWithMentionAndURLs
from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString
@ -150,9 +150,11 @@ class ReminderDiscord(commands.Cog):
if fromSlash != True: if fromSlash != True:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
embed, pageMAX = Reminder().embedListe(utilisateur, ctx.guild.id, page) embed, pageMAX, refresh = embedListe(utilisateur, ctx.guild.id, page)
message = await ctx.send(embed = embed) message = await ctx.send(embed = embed)
if pageMAX > 1: if refresh:
await message.add_reaction("🔄")
elif pageMAX > 1:
for emoji in ["⬅️", "➡️"]: for emoji in ["⬅️", "➡️"]:
await message.add_reaction(emoji) await message.add_reaction(emoji)
@cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.")
@ -164,13 +166,13 @@ class ReminderDiscord(commands.Cog):
@commands.Cog.listener() @commands.Cog.listener()
async def on_raw_reaction_add(self, payload): async def on_raw_reaction_add(self, payload):
message, embed = await Reminder().listReaction(self.client, payload) message, embed = await listReaction(self.client, payload)
if message: if message:
await message.edit(embed = embed) await message.edit(embed = embed)
@commands.Cog.listener() @commands.Cog.listener()
async def on_raw_reaction_remove(self, payload): async def on_raw_reaction_remove(self, payload):
message, embed = await Reminder().listReaction(self.client, payload) message, embed = await listReaction(self.client, payload)
if message: if message:
await message.edit(embed = embed) await message.edit(embed = embed)

View file

@ -70,69 +70,85 @@ class Reminder(Database):
""" """
return True if self.affichageResultat(self.requete(requete, [id, userID, guildID]))[0][0] == 1 else False return True if self.affichageResultat(self.requete(requete, [id, userID, guildID]))[0][0] == 1 else False
def embedListe(self, utilisateur, guildID, page, color = None): def embedListe(utilisateur, guildID, page, color = None):
"""Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur""" """Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur."""
reminders = self.listeReminder(utilisateur.id, guildID) reminders = Reminder().listeReminder(utilisateur.id, guildID)
pageMAX = -(-len(reminders) // 5) pageMAX = -(-len(reminders) // 5)
if color == None: if pageMAX > 1:
color = Colour.random() refresh = False
embed = Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de {utilisateur.mention}** • Page {page}/{pageMAX}", color = color) else:
embed.set_thumbnail(url = utilisateur.avatar_url_as(size = 64)) refresh = True
limit = 5 * page if color == None:
if len(reminders) > 0 and page <= pageMAX: color = Colour.random()
curseur = limit - 4 embed = Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de {utilisateur.mention}** • Page {page}/{pageMAX}", color = color)
for reminder in reminders[limit - 5:]: embed.set_thumbnail(url = utilisateur.avatar_url_as(size = 64))
if curseur <= limit: limit = 5 * page
texte = reminder[0] if len(reminders) > 0 and page <= pageMAX:
if len(texte) > 1024: curseur = limit - 4
texte = f"{texte[:1021]}..." for reminder in reminders[limit - 5:]:
expiration = reminder[2] - int(nowUTC()) if curseur <= limit:
if expiration > 0: texte = reminder[0]
expiration = f"Expire dans {timedeltaToString(expiration)}" if len(texte) > 1024:
else: texte = f"{texte[:1021]}..."
expiration = f"A déjà expiré." expiration = reminder[2] - int(nowUTC())
embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) if expiration > 0:
curseur += 1 expiration = f"Expire dans {timedeltaToString(expiration)}"
else: else:
embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") expiration = f"A déjà expiré."
embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False)
return (embed, pageMAX) curseur += 1
else:
embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !")
embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.")
return (embed, pageMAX, refresh)
async def listReaction(self, client, payload): async def listReaction(client, payload):
if payload.emoji.name in ["⬅️", "➡️"]: """Gère le changement de page du reminderlist avec les réactions."""
if payload.event_type == "REACTION_ADD": if payload.emoji.name in ["⬅️", "🔄", "➡️"]:
if payload.member.bot == True: if payload.event_type == "REACTION_ADD":
return False, False if payload.member.bot == True:
channel = client.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if message.author.id != client.user.id and len(message.embeds) == 0: # vérification message du bot + au moins 1 embed
return False, False return False, False
embed = message.embeds[0].to_dict() channel = client.get_channel(payload.channel_id)
if "description" in embed: # si c'est un embed avec une description message = await channel.fetch_message(payload.message_id)
if len(findall(r"\*\*Rappels? de <@\!?\d+>\*\* • Page \d+\/\d+", embed["description"])) == 1: # si c'est le bon embed if message.author.id != client.user.id and len(message.embeds) == 0: # vérification message du bot + au moins 1 embed
infoDescription = findall(r"\*\*Rappels? de <@\!?(\d+)>\*\* • Page (\d+)\/(\d+)", embed["description"])[0] return False, False
utilisateur = client.get_user(int(infoDescription[0])) embed = message.embeds[0].to_dict()
page = int(infoDescription[1]) if "description" in embed: # si c'est un embed avec une description
if payload.emoji.name == "⬅️": if len(findall(r"\*\*Rappels? de <@\!?\d+>\*\* • Page \d+\/\d+", embed["description"])) == 1: # si c'est le bon embed
if page > 1: infoDescription = findall(r"\*\*Rappels? de <@\!?(\d+)>\*\* • Page (\d+)\/(\d+)", embed["description"])[0]
page -= 1 utilisateur = client.get_user(int(infoDescription[0]))
else: page = int(infoDescription[1])
if int(infoDescription[2]) > 1: if payload.emoji.name == "⬅️":
page += 1 if page > 1:
else: page -= 1
return False, False else:
if payload.emoji.name == "➡️": if int(infoDescription[2]) > 1:
if page + 1 <= int(infoDescription[2]):
page += 1 page += 1
else: else:
if len(findall(r"L'utilisateur n'a aucun rappel en attente ou page n°\d+ vide !", embed["fields"][0]["value"])) == 1: return False, False
if len(self.listeReminder(utilisateur.id, payload.guild_id)) > 0: if payload.emoji.name == "➡️":
page += 1 if page + 1 <= int(infoDescription[2]):
else: page += 1
return False, False else:
else: return False, False
return False, False if payload.emoji.name == "🔄":
embed, _ = Reminder().embedListe(utilisateur, payload.guild_id, page, embed["color"]) reminders = Reminder().listeReminder(utilisateur.id, payload.guild_id)
return message, embed if len(reminders) > 0:
return False, False page = 1
if -(-len(reminders) // 5) > 1 and message.reactions[0] != "⬅️":
for emoji in ["⬅️", "➡️"]:
await message.add_reaction(emoji)
else:
return False, False
embed, _, refresh = embedListe(utilisateur, payload.guild_id, page, embed["color"])
if refresh:
await message.add_reaction("🔄")
else:
for reaction in message.reactions:
if str(reaction) == "🔄":
users = await reaction.users().flatten()
for user in users:
await message.remove_reaction("🔄", user)
return message, embed
return False, False