Skip to content

Commit

Permalink
Add tombola command for raffle events and enhance text formatting wit…
Browse files Browse the repository at this point in the history
…h custom emoji support.
  • Loading branch information
SonOfLope committed Nov 22, 2024
1 parent 3236433 commit d8d0d3f
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 9 deletions.
7 changes: 7 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
DISCORD_TOKEN=
GITHUB_TOKEN=
API_ADDRESS=
API_PORT=
MONGO_USER=
MONGO_PASSWORD=
MONGO_HOST=
99 changes: 99 additions & 0 deletions cogs/admin/management.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

from discord import Embed, Color, utils, File
import discord
from cogs.prompts import\
prompt_user,\
prompt_user_with_confirmation,\
Expand All @@ -12,6 +13,7 @@
send_delayed_dm
from cogs.admin import is_authorized
import asyncio
import random

def _create_server_management_cmds(trema_bot, trema_db):

Expand Down Expand Up @@ -125,3 +127,100 @@ async def annonce(ctx):
await ctx.author.send('Annonce programmée.')
else:
await ctx.author.send('Annonce annulée.')

@trema_bot.command(name="tombola", description="Organiser un tirage au sort")
async def tombola(ctx):
await ctx.respond("Veuillez vérifier vos messages privés pour des instructions supplémentaires.", ephemeral=True)

mention_dict = generate_mention_dict(ctx.guild)

time_and_date, delay = await prompt_user_with_date(ctx, "Quelle est la date et l'heure du tirage au sort ? (AAAA-MM-JJ HH:MM:SS)", 'Date et heure du tirage')
if not time_and_date:
return

message_content = await prompt_user(ctx, "Entrez le message à inclure dans l'annonce du tirage au sort:"
"\nPour personnaliser ce message, vous pouvez utiliser les mentions suivantes:\n"
"- `{username}` pour mentionner un username\n"
"- `{server}` pour le nom du serveur\n"
"- `{&role}` pour mentionner un rôle par son nom\n"
"- `{#channel}` pour un lien vers un canal\n"
"- `{!emojiname}` pour un emoji personnalisé\n"
"- `{everyone}` pour `@everyone`\n"
"- `{here}` pour `@here`\n\n", 'Message du tirage au sort')
if not message_content:
return

emoji_input = await prompt_user(ctx, "Veuillez entrer l'emoji personnalisé à utiliser pour le tirage au sort. Vous pouvez envoyer l'emoji directement ou taper son nom (par exemple :cedille:).", 'Emoji personnalisé')
if not emoji_input:
return

try:
# Try to find the emoji in the guild if it's a custom emoji name
emoji = None
if emoji_input.startswith(":") and emoji_input.endswith(":"):
emoji_name = emoji_input.strip(':')
emoji = discord.utils.get(ctx.guild.emojis, name=emoji_name)
if not emoji:
raise ValueError(f"L'emoji nommé `{emoji_name}` n'a pas été trouvé dans le serveur.")
else:
emoji = emoji_input

if isinstance(emoji, discord.Emoji):
emoji_display = f"<:{emoji.name}:{emoji.id}>"
else:
emoji_display = emoji
except Exception as e:
await ctx.author.send(f"Emoji invalide ou non trouvé dans le serveur. Veuillez réessayer. Erreur : {e}")
return

body_with_mentions = make_mention(message_content, mention_dict, ctx.guild)
formatted_time = time_and_date.strftime('%Y-%m-%d %H:%M:%S')
announcement_message = f"{body_with_mentions}\n\nLe tirage au sort aura lieu le {formatted_time}.\nRéagissez avec {emoji_display} pour participer."

confirmation_embed = Embed(title="Détails du tirage au sort", description=f"Date du tirage : {formatted_time}\nEmoji du tirage : {emoji_display}\n\nAperçu du message d'annonce :", color=Color.blurple())
await ctx.author.send(embed=confirmation_embed)
await ctx.author.send(announcement_message)

final_confirmation = await prompt_user_with_confirmation(ctx, "Confirmez-vous ces détails ?")
if not final_confirmation:
await ctx.author.send('Opération annulée.')
return

try:
message = await ctx.channel.send(announcement_message)
except Exception as e:
await ctx.author.send(f"Erreur lors de l'envoi de l'annonce : {e}")
return

try:
if isinstance(emoji, discord.Emoji):
await message.add_reaction(emoji)
else:
await message.add_reaction(emoji_display)
except Exception as e:
await ctx.author.send(f"Erreur lors de l'ajout de la réaction : {e}")
return

async def pick_winner():
await asyncio.sleep(delay)
try:
cached_message = await ctx.channel.fetch_message(message.id)
for reaction in cached_message.reactions:
if str(reaction.emoji) == str(emoji) or str(reaction.emoji) == emoji_display:
users = await reaction.users().flatten()
# Remove the bot itself from the list
users = [user for user in users if user.id != ctx.bot.user.id]
break
else:
users = []

if users:
winner = random.choice(users)
await ctx.channel.send(f"🎉 Le gagnant du tirage au sort est : {winner.mention} ! Félicitations !")
else:
await ctx.channel.send("Personne n'a participé au tirage au sort.")
except Exception as e:
await ctx.channel.send(f"Erreur lors du tirage au sort : {e}")

asyncio.create_task(pick_winner())
await ctx.author.send('Tirage au sort organisé avec succès.')
28 changes: 19 additions & 9 deletions cogs/utils/text_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,35 @@
_REQUEST_VALUE = "$"
_SPACE = " "

def make_mention(text, mention_dict):
def make_mention(text, mention_dict, guild=None):
"""
Searches a text for occurrences of placeholders and replaces them with
the mention of corresponding objects.
the mention of corresponding objects, including custom emojis.
Args:
text (str): any text
mention_dict (dict): a dictionary where the key is the placeholder and
the value is the object to mention.
text (str): The input text containing placeholders.
mention_dict (dict): A dictionary where the key is the placeholder and
the value is the object to mention.
guild (discord.Guild, optional): The guild to search for custom emojis. Required for emoji replacement.
Returns:
str: the given text with mentions replaced.
str: The given text with mentions and custom emojis replaced.
"""
for placeholder in list(mention_dict.keys()):
if placeholder in text:
text = text.replace(placeholder, mention_dict.get(placeholder, "{mention non trouvé}"))
if guild:
emoji_dict = {f"{{!{emoji.name}}}": f"<:{emoji.name}:{emoji.id}>" for emoji in guild.emojis}
else:
emoji_dict = {}

for placeholder, replacement in mention_dict.items():
text = text.replace(placeholder, replacement)

for emoji_placeholder, emoji_value in emoji_dict.items():
text = text.replace(emoji_placeholder, emoji_value)

return text



def generate_mention_dict(guild, newMember = None):
mention_dict = {
'{server}': guild.name,
Expand Down

0 comments on commit d8d0d3f

Please sign in to comment.