el_crazy7806

cree un code a base de celui la mais en modifiant les commandes +xp add et +xp remove +xp set en modifiant la limite non pas de 500 mais part l'infini et en les ajoutant en commande discord

πŸ“Ž 1 file 6,654 chars
πŸ“„
pasted-code-1783107466701.txt
txt 166 lines
β–Ά
STAFF_ROLE_ID = 1522328141886914711  # ID du rΓ΄le autorisΓ© (ex: ModΓ©rateur / Admin)
STAFF_ROLE_ID = 1522624412757655685  # ID du rΓ΄le autorisΓ© (ex: ModΓ©rateur / Admin)

def load_data():
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, "r") as f:
                return json.load(f)
        except:
            return {}
    return {}

def save_data(d):
    with open(DATA_FILE, "w") as f:
        json.dump(d, f, indent=4)

def get_xp_needed(level):
    return level * 100

def draw_card(xp, needed):
    img = Image.open(RANK_BG).convert("RGBA").resize((800, 450))
    draw = ImageDraw.Draw(img)
    draw.rounded_rectangle([50, 380, 750, 405], radius=10, fill=(20, 20, 30, 200))
    w = int(700 * (xp / max(1, needed)))
    if w > 0: 
        draw.rounded_rectangle([50, 380, 50 + min(w, 700), 405], radius=10, fill=(0, 150, 255, 255))
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    buf.seek(0)
    return buf

async def draw_leader(players):
    img = Image.open(LEADER_BG).convert("RGBA").resize((600, 800))
    draw = ImageDraw.Draw(img)
    draw.rounded_rectangle([40, 40, 560, 760], radius=20, fill=(10, 10, 25, 210))
    try:
        f_title = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 32)
        f_txt = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 20)
    except:
        f_title = f_txt = ImageFont.load_default()
    
    draw.text((300, 80), "πŸ† COSMIC LEADERBOARD", fill=(255, 215, 0), font=f_title, anchor="mm")
    y = 160
    for i, (uid, stats) in enumerate(players[:10], start=1):
        m = "πŸ₯‡ " if i==1 else "πŸ₯ˆ " if i==2 else "πŸ₯‰ " if i==3 else f"#{i} "
        try:
            u = await bot.fetch_user(int(uid))
            name = u.name
        except:
            name = f"User ({uid})"
            
        draw.text((70, y), f"{m}{name}", fill=(255, 255, 255), font=f_txt)
        draw.text((530, y), f"Lvl {stats.get('level', 1)} ({stats.get('xp', 0)} XP)", fill=(0, 190, 255), font=f_txt, anchor="ra")
        y += 55
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    buf.seek(0)
    return buf

@bot.event
async def on_message(msg):
    if msg.author.bot: return
    data = load_data()
    uid = str(msg.author.id)
    content = msg.content.strip()

    # πŸͺ Commande Texte : +rank
    if content.lower() == "+rank":
        async with msg.channel.typing():
            u = data.get(uid, {"xp": 0, "level": 1})
            need = get_xp_needed(u.get("level", 1))
            file = discord.File(fp=draw_card(u.get("xp", 0), need), filename="rank.png")
            emb = discord.Embed(title="🌌 RANK PROFILE", description=f"Stats for {msg.author.mention}\nπŸ›°οΈ **Level {u.get('level', 1)}**\n✨ **XP:** {u.get('xp', 0)}/{need}", color=0x0A2540)
            emb.set_thumbnail(url=msg.author.display_avatar.url).set_image(url="attachment://rank.png")
            await msg.channel.send(embed=emb, file=file)
            return

    # πŸ† Commande Texte : +top
    if content.lower() == "+top":
        async with msg.channel.typing():
            if not data: 
                return await msg.channel.send("No scores recorded yet.")
            
            top = sorted(data.items(), key=lambda x: (x[1].get("level", 1), x[1].get("xp", 0)), reverse=True)
            leader_buffer = await draw_leader(top)
            file = discord.File(fp=leader_buffer, filename="top.png")
            
            pings_list = [f"{'πŸ₯‡' if i==1 else 'πŸ₯ˆ' if i==2 else 'πŸ₯‰' if i==3 else f'#{i}'} <@{p_id}> β€” Level {s.get('level', 1)}" for i, (p_id, s) in enumerate(top[:10], start=1)]
            emb = discord.Embed(title="πŸ† Cosmic Leaderboard Matrix", description="\n".join(pings_list), color=0x0A2540)
            emb.set_image(url="attachment://top.png")
            await msg.channel.send(embed=emb, file=file)
            return

    # πŸ› οΈ Commandes Administrateur / Staff : +xp
    if content.lower().startswith("+xp "):
        is_staff = msg.author.guild_permissions.administrator or discord.utils.get(msg.author.roles, id=STAFF_ROLE_ID)
        if not is_staff:
            await msg.channel.send("❌ You do not have permission to use staff XP commands.")
            return

        parts = content.split()
        if len(parts) < 4:
            await msg.channel.send("❌ Incorrect structure. Example: `+xp add @user 500`")
            return

        action = parts[1].lower()  # add, remove, or set
        
        if not msg.mentions:
            await msg.channel.send("❌ Please mention the user you want to modify.")
            return
            
        target_user = msg.mentions[0]
        target_id = str(target_user.id)
        amount_str = parts[-1]  # Toujours rΓ©cupΓ©rer le dernier Γ©lΓ©ment (le nombre d'XP)
        
        try:
            amount = int(amount_str)
        except ValueError:
            await msg.channel.send("❌ The XP amount must be a number.")
            return

        t_data = data.setdefault(target_id, {"xp": 0, "level": 1})

        if action == "add":
            t_data["xp"] += amount
            while t_data["xp"] >= get_xp_needed(t_data["level"]):
                t_data["xp"] -= get_xp_needed(t_data["level"])
                t_data["level"] += 1
                gg_channel = bot.get_channel(GG_CHANNEL_ID) or msg.channel
                await gg_channel.send(f"πŸŽ‰ **GG** {target_user.mention}! You leveled up to **Level {t_data['level']}**!")
            await msg.channel.send(f"βœ… Added {amount} XP to {target_user.mention}.")

        elif action == "remove":
            t_data["xp"] = max(0, t_data["xp"] - amount)
            await msg.channel.send(f"βœ… Removed {amount} XP from {target_user.mention}.")

        elif action == "set":
            t_data["xp"] = max(0, amount)
            t_data["level"] = 1
            while t_data["xp"] >= get_xp_needed(t_data["level"]):
                t_data["xp"] -= get_xp_needed(t_data["level"])
                t_data["level"] += 1
            await msg.channel.send(f"βœ… Set {target_user.mention}'s XP balance to {amount}.")

        save_data(data)
        return

    # Gain d'XP passif standard (35 XP par message)
    u = data.setdefault(uid, {"xp": 0, "level": 1})
    u["xp"] += 35
    if u["xp"] >= get_xp_needed(u["level"]):
        u["xp"] -= get_xp_needed(u["level"])
        u["level"] += 1
        gg_channel = bot.get_channel(GG_CHANNEL_ID) or msg.channel
        await gg_channel.send(f"πŸŽ‰ **GG** {msg.author.mention}! Level **{u['level']}**!")
    save_data(data)

@bot.event
async def on_ready():
    print(f"Bot connected: {bot.user.name}")

keep_alive()
# πŸ”΄ METTEZ VOTRE TOKEN VALIDE ICI DANS LES GUILLEMETS
bot.run("")

Kodari AI
KodariJul 3 at 7:39 pm 1

I’ll create a Discord rank/XP bot with slash commands for XP management (add/remove/set) with no amount limit.

CosmicXP
A Discord rank/XP bot with message-based XP gain and slash command XP management. Features automatic XP per message (35 XP), level-up notifications, rank image cards with progress bar, and a global leaderboard. Staff can manage XP via /xp add, /xp remove, and /xp set slash commands with no amount restrictions. Supports +rank and +top text commands for player stats.
Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 225
bot.py
import discord
from discord.ext import commands
from discord import app_commands
import os
import json
import io
from PIL import Image, ImageDraw, ImageFont
from dotenv import load_dotenv

load_dotenv()

# ── Configuration ──────────────────────────────────────────────
DATA_FILE = "data.json"
RANK_BG = "rank_bg.png"
LEADER_BG = "leader_bg.png"
STAFF_ROLE_ID = 1522328141886914711
GG_CHANNEL_ID = None  # None = level-up message in same channel

bot = commands.Bot(command_prefix="+", intents=discord.Intents.all())

# ── Data helpers ───────────────────────────────────────────────
def load_data():
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, "r") as f:
                return json.load(f)
        except:
            return {}
    return {}

def save_data(d):
    with open(DATA_FILE, "w") as f:
        json.dump(d, f, indent=4)

def get_xp_needed(level):
    return level * 100

async def is_staff(member: discord.Member):
    return member.guild_permissions.administrator or discord.utils.get(member.roles, id=STAFF_ROLE_ID)

# ── Image generation ───────────────────────────────────────────
def draw_card(xp, needed):
    img = Image.open(RANK_BG).convert("RGBA").resize((800, 450))
    draw = ImageDraw.Draw(img)
    draw.rounded_rectangle([50, 380, 750, 405], radius=10, fill=(20, 20, 30, 200))
    w = int(700 * (xp / max(1, needed)))
    if w > 0:
        draw.rounded_rectangle([50, 380, 50 + min(w, 700), 405], radius=10, fill=(0, 150, 255, 255))
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    buf.seek(0)
    return buf

async def draw_leader(players):
    img = Image.open(LEADER_BG).convert("RGBA").resize((600, 800))
    draw = ImageDraw.Draw(img)
    draw.rounded_rectangle([40, 40, 560, 760], radius=20, fill=(10, 10, 25, 210))
    try:
        f_title = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 32)
        f_txt = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 20)
    except:
        f_title = f_txt = ImageFont.load_default()

    draw.text((300, 80), "πŸ† COSMIC LEADERBOARD", fill=(255, 215, 0), font=f_title, anchor="mm")
    y = 160
    for i, (uid, stats) in enumerate(players[:10], start=1):
        m = "πŸ₯‡ " if i == 1 else "πŸ₯ˆ " if i == 2 else "πŸ₯‰ " if i == 3 else f"#{i} "
        try:
            u = await bot.fetch_user(int(uid))
            name = u.name
        except:
            name = f"User ({uid})"
        draw.text((70, y), f"{m}{name}", fill=(255, 255, 255), font=f_txt)
        draw.text((530, y), f"Lvl {stats.get('level', 1)} ({stats.get('xp', 0)} XP)", fill=(0, 190, 255), font=f_txt, anchor="ra")
        y += 55
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    buf.seek(0)
    return buf

# ── XP Management β€” Slash Commands ─────────────────────────────
class XPGroup(app_commands.Group):
    """Manage user XP (staff only)"""

    @app_commands.command(name="add", description="Add XP to a user β€” no limit")
    @app_commands.describe(user="The target member", amount="XP amount to add")
    async def xp_add(self, interaction: discord.Interaction, user: discord.Member, amount: int):
        if not await is_staff(interaction.user):
            return await interaction.response.send_message("❌ You do not have permission.", ephemeral=True)
        if amount < 0:
            return await interaction.response.send_message("❌ Amount must be positive.", ephemeral=True)

        data = load_data()
        uid = str(user.id)
        t_data = data.setdefault(uid, {"xp": 0, "level": 1})
        t_data["xp"] += amount

        while t_data["xp"] >= get_xp_needed(t_data["level"]):
            t_data["xp"] -= get_xp_needed(t_data["level"])
            t_data["level"] += 1
            ch = bot.get_channel(GG_CHANNEL_ID) if GG_CHANNEL_ID else interaction.channel
            if ch:
                await ch.send(f"πŸŽ‰ **GG** {user.mention}! You leveled up to **Level {t_data['level']}**!")

        save_data(data)
        await interaction.response.send_message(f"βœ… Added {amount} XP to {user.mention}.", ephemeral=True)

    @app_commands.command(name="remove", description="Remove XP from a user")
    @app_commands.describe(user="The target member", amount="XP amount to remove")
    async def xp_remove(self, interaction: discord.Interaction, user: discord.Member, amount: int):
        if not await is_staff(interaction.user):
            return await interaction.response.send_message("❌ You do not have permission.", ephemeral=True)
        if amount < 0:
            return await interaction.response.send_message("❌ Amount must be positive.", ephemeral=True)

        data = load_data()
        uid = str(user.id)
        t_data = data.setdefault(uid, {"xp": 0, "level": 1})
        t_data["xp"] = max(0, t_data["xp"] - amount)

        save_data(data)
        await interaction.response.send_message(f"βœ… Removed {amount} XP from {user.mention}.", ephemeral=True)

    @app_commands.command(name="set", description="Set a user's XP balance β€” no limit")
    @app_commands.describe(user="The target member", amount="New XP amount")
    async def xp_set(self, interaction: discord.Interaction, user: discord.Member, amount: int):
        if not await is_staff(interaction.user):
            return await interaction.response.send_message("❌ You do not have permission.", ephemeral=True)
        if amount < 0:
            return await interaction.response.send_message("❌ Amount must be positive.", ephemeral=True)

        data = load_data()
        uid = str(user.id)
        t_data = data.setdefault(uid, {"xp": 0, "level": 1})
        t_data["xp"] = amount
        t_data["level"] = 1

        while t_data["xp"] >= get_xp_needed(t_data["level"]):
            t_data["xp"] -= get_xp_needed(t_data["level"])
            t_data["level"] += 1
            ch = bot.get_channel(GG_CHANNEL_ID) if GG_CHANNEL_ID else interaction.channel
            if ch:
                await ch.send(f"πŸŽ‰ **GG** {user.mention}! You leveled up to **Level {t_data['level']}**!")

        save_data(data)
        await interaction.response.send_message(f"βœ… Set {user.mention}'s XP to {amount}.", ephemeral=True)

# ── Events ─────────────────────────────────────────────────────
@bot.event
async def on_ready():
    print(f"βœ… Bot connected: {bot.user.name}")
    bot.tree.add_command(XPGroup(name="xp", description="Manage user XP (staff only)"))
    await bot.tree.sync()
    print("βœ… Slash commands synced!")

@bot.event
async def on_message(msg):
    if msg.author.bot:
        return

    data = load_data()
    uid = str(msg.author.id)
    content = msg.content.strip()

    # ── +rank ──────────────────────────────────────────────────
    if content.lower() == "+rank":
        async with msg.channel.typing():
            u = data.get(uid, {"xp": 0, "level": 1})
            need = get_xp_needed(u.get("level", 1))
            file = discord.File(fp=draw_card(u.get("xp", 0), need), filename="rank.png")
            emb = discord.Embed(
                title="🌌 RANK PROFILE",
                description=(
                    f"Stats for {msg.author.mention}\n"
                    f"πŸ›°οΈ **Level {u.get('level', 1)}**\n"
                    f"✨ **XP:** {u.get('xp', 0)}/{need}"
                ),
                color=0x0A2540,
            )
            emb.set_thumbnail(url=msg.author.display_avatar.url)
            emb.set_image(url="attachment://rank.png")
            await msg.channel.send(embed=emb, file=file)
        return

    # ── +top ───────────────────────────────────────────────────
    if content.lower() == "+top":
        async with msg.channel.typing():
            if not data:
                return await msg.channel.send("No scores recorded yet.")

            top = sorted(data.items(), key=lambda x: (x[1].get("level", 1), x[1].get("xp", 0)), reverse=True)
            leader_buffer = await draw_leader(top)
            file = discord.File(fp=leader_buffer, filename="top.png")

            lines = [
                f"{'πŸ₯‡' if i==1 else 'πŸ₯ˆ' if i==2 else 'πŸ₯‰' if i==3 else f'#{i}'} <@{p_id}> β€” Level {s.get('level', 1)}"
                for i, (p_id, s) in enumerate(top[:10], start=1)
            ]
            emb = discord.Embed(title="πŸ† Cosmic Leaderboard Matrix", description="\n".join(lines), color=0x0A2540)
            emb.set_image(url="attachment://top.png")