Kuby/commandes/goodbye.py
2026-01-01 18:48:25 +01:00

109 lines
No EOL
5 KiB
Python

import discord
from discord.ext import commands
from discord import app_commands
import sqlite3
import aiohttp
import io
import os
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime, timezone
class Goodbye(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db_path = os.path.join(os.path.dirname(__file__), "..", "config.db")
def humanize_time_delta(self, date):
if date is None: return "date inconnue"
if date.tzinfo is None: date = date.replace(tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
delta = now - date
total_days = delta.total_seconds() / (3600 * 24)
rounded_days = round(total_days)
years = rounded_days // 365
months = rounded_days // 30
weeks = rounded_days // 7
days = rounded_days
if years > 0: return f"il y a {years} {'an' if years == 1 else 'ans'}"
elif months > 0: return f"il y a {months} mois"
elif weeks > 0: return f"il y a {weeks} {'semaine' if weeks == 1 else 'semaines'}"
elif days > 0: return f"il y a {days} {'jour' if days == 1 else 'jours'}"
elif delta.seconds // 3600 > 0:
hours = delta.seconds // 3600
return f"il y a {hours} {'heure' if hours == 1 else 'heures'}"
elif (delta.seconds % 3600) // 60 > 0:
minutes = (delta.seconds % 3600) // 60
return f"il y a {minutes} {'minute' if minutes == 1 else 'minutes'}"
else:
seconds = delta.seconds % 60
return f"il y a {seconds} {'seconde' if seconds <= 1 else 'secondes'}"
async def create_goodbye_image(self, username, avatar_url):
current_dir = os.path.dirname(__file__)
base_dir = os.path.abspath(os.path.join(current_dir, ".."))
async with aiohttp.ClientSession() as session:
async with session.get(avatar_url) as resp:
avatar_bytes = await resp.read()
background = Image.open(os.path.join(base_dir, 'background_template_goodbye.png'))
draw = ImageDraw.Draw(background)
font_large = ImageFont.truetype(os.path.join(base_dir, 'custom_font_large.otf'), 70)
font_small = ImageFont.truetype(os.path.join(base_dir, 'custom_font_small.otf'), 50)
font_large_omega = ImageFont.truetype(os.path.join(base_dir, 'custom_font_large.otf'), 55)
draw.text((325, 70), "A Bientot", font=font_large, fill=(255,255,255))
draw.text((325, 135), f"{username} chez", font=font_small, fill=(255,255,255))
draw.text((325, 195), "OMEGA KUBE", font=font_large_omega, fill=(255,255,255))
avatar = Image.open(io.BytesIO(avatar_bytes)).convert("RGBA").resize((224, 224), Image.LANCZOS)
mask = Image.new('L', avatar.size, 0)
mask_draw = ImageDraw.Draw(mask)
mask_draw.ellipse((12, 12, 212, 212), fill=255)
background.paste(avatar, (40, 40), mask)
img_byte_arr = io.BytesIO()
background.save(img_byte_arr, format='PNG')
img_byte_arr.seek(0)
return img_byte_arr
@commands.Cog.listener()
async def on_member_remove(self, member):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT goodbye_channel FROM server_configs WHERE server_id = ?', (member.guild.id,))
result = cursor.fetchone()
conn.close()
if result and result[0]:
channel = member.guild.get_channel(result[0])
if channel:
img = await self.create_goodbye_image(member.name, member.avatar.url if member.avatar else member.default_avatar.url)
joined_message = self.humanize_time_delta(member.joined_at)
embed = discord.Embed(title=f"{member} viens de nous quitter.",
description="Nous espérons vous revoir bientôt <a:rain:1317973615714504806>",
color=discord.Color.dark_magenta())
embed.set_footer(text=f"Avait rejoint {joined_message}")
embed.set_image(url="attachment://goodbye.png")
await channel.send(embed=embed, file=discord.File(img, filename="goodbye.png"))
@app_commands.command(name="setgoodbye", description="Définit le salon d'aurevoir")
@app_commands.checks.has_permissions(administrator=True)
async def set_goodbye(self, interaction: discord.Interaction, channel: discord.TextChannel):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''INSERT INTO server_configs (server_id, goodbye_channel)
VALUES (?, ?) ON CONFLICT(server_id)
DO UPDATE SET goodbye_channel=excluded.goodbye_channel''',
(interaction.guild_id, channel.id))
conn.commit()
conn.close()
await interaction.response.send_message(f"Salon d'aurevoir défini sur {channel.mention}", ephemeral=True)
async def setup(bot):
await bot.add_cog(Goodbye(bot))