hesammasters

این کد وقتی ران میشه ارور ها و مشکلاتی داره. دقیق برسی ارور هارو فیکس کن. بدون اینکه ساپورتش از دیتابس فعلی قط بشه

📎 1 file 21,906 chars
📄
pasted-code-1767254070969.txt
txt 548 lines
▶
import discord
from discord import app_commands
import sqlite3
from datetime import datetime

TOKEN = ""

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

# ======================
# DATABASE
# ======================
db = sqlite3.connect("panels.db")
cursor = db.cursor()

# ======================
# PANELS
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS panels (
    id TEXT PRIMARY KEY,
    title TEXT,
    description TEXT,
    type TEXT,
    color INTEGER,
    image TEXT
)
""")

# ======================
# OPTIONS (دکمه / منو)
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS options (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    panel_id TEXT,
    label TEXT,
    response TEXT,
    emoji TEXT,
    icon TEXT
)
""")

# ======================
# PANEL MESSAGES (برای جایگزینی پیام)
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS panel_messages (
    panel_id TEXT PRIMARY KEY,
    channel_id INTEGER,
    message_id INTEGER
)
""")

# ======================
# SETTINGS
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
    key TEXT PRIMARY KEY,
    value TEXT
)
""")

db.commit()


# ======================
# UTILS
# ======================
def is_admin(i: discord.Interaction):
    return i.user.guild_permissions.administrator

def setting(key):
    cursor.execute("SELECT value FROM settings WHERE key=?", (key,))
    r = cursor.fetchone()
    return r[0] if r else None

def set_setting(key, value):
    cursor.execute("INSERT OR REPLACE INTO settings VALUES (?, ?)", (key, value))
    db.commit()

async def log_click(user, panel_id, option_label):
    if setting("log_enabled") != "1":
        return
    ch_id = setting("log_channel")
    if not ch_id:
        return
    try:
        ch = client.get_channel(int(ch_id))
    except (TypeError, ValueError):
       return

    if not ch:
        return
    embed = discord.Embed(title="📊 Panel Click", color=0x57F287, timestamp=datetime.utcnow())
    embed.add_field(name="User", value=user.mention, inline=False)
    embed.add_field(name="Panel", value=panel_id, inline=True)
    embed.add_field(name="Option", value=option_label, inline=True)
    await ch.send(embed=embed)

# ======================
# VIEWS
# ======================
def build_response_embed(panel_id, option_label, response_text, icon=None):
    cursor.execute("SELECT color FROM panels WHERE id=?", (panel_id,))
    panel = cursor.fetchone()
    color = panel[0] if panel else 0x5865F2

    embed = discord.Embed(
        title=option_label,
        description=response_text,
        color=color
    )

    if icon:
        embed.set_thumbnail(url=icon)

    embed.set_footer(text="📌VORIXSHOP")
    return embed


class PanelSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute(
            "SELECT id, label, emoji FROM options WHERE panel_id=?",
            (panel_id,)
        )

        options = []
        for option_id, label, emoji in cursor.fetchall():
            options.append(
                discord.SelectOption(
                    label=label,
                    value=str(option_id),
                    emoji=emoji
                )
            )

        super().__init__(
            placeholder="یک گزینه انتخاب کن",
            options=options,
            custom_id=f"select_{panel_id}"  # این خط اضافه شد
        )

        self.panel_id = panel_id



    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT response, label, icon FROM options WHERE id=?", (option_id,))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ پاسخ یافت نشد", ephemeral=True)
        response_text, label, icon = row
        embed = build_response_embed(self.panel_id, label, response_text, icon)
        await interaction.response.send_message(embed=embed, ephemeral=True)

        await log_click(interaction.user, self.panel_id, label)

class InfoButton(discord.ui.Button):
    def __init__(self, panel_id, label, response, emoji=None, icon=None):
        super().__init__(
            label=label, 
            style=discord.ButtonStyle.primary, 
            emoji=emoji,
            custom_id=f"info_{panel_id}_{label}"  # این خط اضافه شد
        )
        self.panel_id = panel_id
        self.response = response
        self.icon = icon




    async def callback(self, interaction: discord.Interaction):
        embed = build_response_embed(self.panel_id, self.label, self.response, self.icon)
        await interaction.response.send_message(embed=embed, ephemeral=True)

        await log_click(interaction.user, self.panel_id, self.label)

class SelectView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(PanelSelect(panel_id))

class ButtonView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        cursor.execute("SELECT label, response, emoji, icon FROM options WHERE panel_id=?", (panel_id,))
        for label, response, emoji, icon in cursor.fetchall():
          self.add_item(InfoButton(panel_id, label, response, emoji, icon))


# ======================
# SEND PANEL
# ======================
async def send_panel_message(panel_id: str, channel: discord.TextChannel):
    cursor.execute("SELECT title, description, type, color, image FROM panels WHERE id=?",(panel_id,))
    panel = cursor.fetchone()
    
    if not panel:
        return
    title, desc, p_type, color, image = panel

    embed = discord.Embed(title=title,description=desc,color=color)

    if image:
      embed.set_image(url=image)

    view = SelectView(panel_id) if p_type == "select" else ButtonView(panel_id)

    # حذف پیام قبلی
    cursor.execute("SELECT channel_id, message_id FROM panel_messages WHERE panel_id=?", (panel_id,))
    old = cursor.fetchone()
    if old:
      try:
          old_channel = client.get_channel(old[0])
          if old_channel:
              old_msg = await old_channel.fetch_message(old[1])
              await old_msg.delete()
      except:
        pass

    msg = await channel.send(embed=embed, view=view)

    cursor.execute(
       "INSERT OR REPLACE INTO panel_messages VALUES (?, ?, ?)",
       (panel_id, channel.id, msg.id)
    )
db.commit()

    

# ======================
# MODALS
# ======================
class PanelCreateModal(discord.ui.Modal, title="🧩 ساخت پنل"):
    panel_id = discord.ui.TextInput(label="Panel ID")
    title_i = discord.ui.TextInput(label="عنوان پنل")
    desc_i = discord.ui.TextInput(label="توضیح پنل", style=discord.TextStyle.paragraph)
    color_i = discord.ui.TextInput(label="رنگ HEX", placeholder="#5865F2", required=False)
    image_i = discord.ui.TextInput(label="لینک عکس پنل (اختیاری)",
    placeholder="https://example.com/image.png",required=False)


    def __init__(self, panel_type):
        super().__init__()
        self.panel_type = panel_type

    async def on_submit(self, interaction: discord.Interaction):
        if not is_admin(interaction):
            return await interaction.response.send_message("❌ دسترسی نداری", ephemeral=True)
        cursor.execute("SELECT id FROM panels WHERE id=?", (self.panel_id.value,))
        if cursor.fetchone():
            return await interaction.response.send_message("❌ پنل با این ID موجود است", ephemeral=True)
        try:
            color = int((self.color_i.value or "#5865F2").replace("#", ""), 16)
        except ValueError:
            return await interaction.response.send_message("❌ رنگ نامعتبر", ephemeral=True)
        cursor.execute("INSERT INTO panels VALUES (?, ?, ?, ?, ?, ?)",
                       (self.panel_id.value, self.title_i.value, self.desc_i.value, self.panel_type, color, self.image_i.value))
        db.commit()
        await interaction.response.send_message(
            f"✅ پنل ساخته شد. حالا با `/panel_option_add {self.panel_id.value}` گزینه اضافه کن",
            ephemeral=True
        )

class OptionAddModal(discord.ui.Modal, title="➕ افزودن گزینه"):
    label = discord.ui.TextInput(label="متن گزینه")
    response = discord.ui.TextInput(label="پاسخ", style=discord.TextStyle.paragraph)
    emoji = discord.ui.TextInput(label="ایموجی (اختیاری)", required=False)
    icon = discord.ui.TextInput(label="آیکون (URL اختیاری)",placeholder="https://example.com/icon.png",required=False)

    def __init__(self, panel_id):
        super().__init__()
        self.panel_id = panel_id

    async def on_submit(self, interaction: discord.Interaction):
        cursor.execute("SELECT COUNT(*) FROM options WHERE panel_id=?", (self.panel_id,))
        count = cursor.fetchone()[0]
        if count >= 25:
          return await interaction.response.send_message("❌ حداکثر 25 گزینه مجاز است", ephemeral=True)

        cursor.execute("INSERT INTO options (panel_id, label, response, emoji, icon) VALUES (?, ?, ?, ?, ?)",(self.panel_id, self.label.value, self.response.value, self.emoji.value or None, self.icon.value or None))

        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message("✅ گزینه اضافه شد و پنل بروزرسانی شد", ephemeral=True)


# ======================
# DELETE / EDIT VIEWS
# ======================
class OptionDeleteSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute("SELECT id, label FROM options WHERE panel_id=?", (panel_id,))
        options = [discord.SelectOption(label=r[1], value=str(r[0])) for r in cursor.fetchall()]
        super().__init__(placeholder="گزینه برای حذف انتخاب کن", options=options)
        self.panel_id = panel_id

    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT label FROM options WHERE id=? AND panel_id=?", (option_id, self.panel_id))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ گزینه پیدا نشد", ephemeral=True)
        cursor.execute("DELETE FROM options WHERE id=?", (option_id,))
        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message(f"✅ گزینه `{row[0]}` حذف شد", ephemeral=True)

class OptionDeleteView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(OptionDeleteSelect(panel_id))

class OptionEditSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute("SELECT id, label FROM options WHERE panel_id=?", (panel_id,))
        options = [discord.SelectOption(label=r[1], value=str(r[0])) for r in cursor.fetchall()]
        super().__init__(placeholder="گزینه برای ویرایش انتخاب کن", options=options)
        self.panel_id = panel_id

    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT label, response, emoji, icon FROM options WHERE id=? AND panel_id=?", (option_id, self.panel_id))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ گزینه پیدا نشد", ephemeral=True)
        label, response, emoji, icon = row
        await interaction.response.send_modal(EditOptionModal(self.panel_id, option_id, label, response, emoji, icon))


class EditOptionModal(discord.ui.Modal, title="✏️ ویرایش گزینه"):
    def __init__(self, panel_id, option_id, label, response, emoji, icon):
        super().__init__()
        self.panel_id = panel_id
        self.option_id = option_id

        self.label_i = discord.ui.TextInput(label="متن گزینه", default=label)
        self.response_i = discord.ui.TextInput(label="پاسخ", style=discord.TextStyle.paragraph, default=response)
        self.emoji_i = discord.ui.TextInput(label="ایموجی (اختیاری)", required=False, default=emoji or "")
        self.icon_i = discord.ui.TextInput(label="آیکون (URL اختیاری)", required=False, default=icon or "")

        self.add_item(self.label_i)
        self.add_item(self.response_i)
        self.add_item(self.emoji_i)
        self.add_item(self.icon_i)

    async def on_submit(self, interaction: discord.Interaction):
        cursor.execute(
            "UPDATE options SET label=?, response=?, emoji=?, icon=? WHERE id=?",
            (self.label_i.value, self.response_i.value, self.emoji_i.value or None, self.icon_i.value or None, self.option_id)
        )
        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message("✅ گزینه ویرایش شد", ephemeral=True)


class OptionEditView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(OptionEditSelect(panel_id))

# ======================
# SLASH COMMANDS
# ======================
@tree.command(name="panel_change_type", description="تغییر نوع پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_change_type(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT type FROM panels WHERE id=?", (panel_id,))
    row = cursor.fetchone()
    if not row:
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    current_type = row[0]

    class TypeSelect(discord.ui.Select):
        def __init__(self):
            options = [
                discord.SelectOption(label="Select Menu", value="select", emoji="🧩"),
                discord.SelectOption(label="Button Panel", value="button", emoji="🔘")
            ]
            super().__init__(
                placeholder=f"نوع فعلی: {current_type}",
                options=options
            )

        async def callback(self, i: discord.Interaction):
            new_type = self.values[0]
            cursor.execute("UPDATE panels SET type=? WHERE id=?", (new_type, panel_id))
            db.commit()

            cursor.execute("SELECT channel_id FROM panel_messages WHERE panel_id=?", (panel_id,))
            old = cursor.fetchone()
            if old:
                channel = client.get_channel(old[0])
                if channel:
                    await send_panel_message(panel_id, channel)

            await i.response.send_message(f"✅ نوع پنل به `{new_type}` تغییر کرد", ephemeral=True)

    view = discord.ui.View()
    view.add_item(TypeSelect())
    await interaction.response.send_message("نوع جدید پنل را انتخاب کن:", view=view, ephemeral=True)

@tree.command(name="panel_list", description="لیست همه پنل‌ها")
async def panel_list(interaction: discord.Interaction):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT id, type FROM panels")
    rows = cursor.fetchall()

    if not rows:
        return await interaction.response.send_message("❌ پنلی وجود ندارد", ephemeral=True)

    text = "\n".join([f"• `{r[0]}` | {r[1]}" for r in rows])
    embed = discord.Embed(title="📋 لیست پنل‌ها", description=text, color=0x5865F2)
    await interaction.response.send_message(embed=embed, ephemeral=True)
@tree.command(name="panel_send", description="ارسال پنل در کانال")
@app_commands.describe(panel_id="ID پنل")
async def panel_send(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT id FROM panels WHERE id=?", (panel_id,))
    if not cursor.fetchone():
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    await send_panel_message(panel_id, interaction.channel)
    await interaction.response.send_message("✅ پنل ارسال شد", ephemeral=True)

@tree.command(name="panel_create", description="ساخت پنل")
async def panel_create(interaction: discord.Interaction):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    class PanelTypeView(discord.ui.View):
        @discord.ui.select(
            placeholder="نوع پنل را انتخاب کن",
            options=[
                discord.SelectOption(label="Select Menu", value="select", emoji="🧩"),
                discord.SelectOption(label="Button Panel", value="button", emoji="🔘")
            ]
        )
        async def select_type(self, interaction: discord.Interaction, select: discord.ui.Select):
            await interaction.response.send_modal(PanelCreateModal(select.values[0]))
    await interaction.response.send_message("نوع پنل را انتخاب کن:", view=PanelTypeView(), ephemeral=True)

@tree.command(name="panel_option_add", description="افزودن گزینه به پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_add(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM panels WHERE id=?", (panel_id,))
    if not cursor.fetchone():
        return await interaction.response.send_message("❌ پنل وجود ندارد", ephemeral=True)
    await interaction.response.send_modal(OptionAddModal(panel_id))

@tree.command(name="panel_option_delete_select", description="حذف گزینه با انتخاب")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_delete_select(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM options WHERE panel_id=?", (panel_id,))
    if not cursor.fetchall():
        return await interaction.response.send_message("❌ هیچ گزینه‌ای وجود ندارد", ephemeral=True)
    await interaction.response.send_message("گزینه‌ای برای حذف انتخاب کن:", view=OptionDeleteView(panel_id), ephemeral=True)

@tree.command(name="panel_option_edit_select", description="ویرایش گزینه با انتخاب")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_edit_select(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM options WHERE panel_id=?", (panel_id,))
    if not cursor.fetchall():
        return await interaction.response.send_message("❌ هیچ گزینه‌ای وجود ندارد", ephemeral=True)
    await interaction.response.send_message("گزینه‌ای برای ویرایش انتخاب کن:", view=OptionEditView(panel_id), ephemeral=True)

# ======================
# EDIT PANEL COMMAND
# ======================
@tree.command(name="panel_edit", description="ویرایش پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_edit(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT title, description, type, color, image FROM panels WHERE id=?", (panel_id,))
    panel = cursor.fetchone()
    if not panel:
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    class EditPanelModal(discord.ui.Modal, title=f"✏️ ویرایش پنل {panel_id}"):
        title_i = discord.ui.TextInput(label="عنوان پنل", default=panel[0])
        desc_i = discord.ui.TextInput(label="توضیح پنل", style=discord.TextStyle.paragraph, default=panel[1])
        color_i = discord.ui.TextInput(label="رنگ HEX", default=f"#{panel[3]:06x}", required=False)
        image_i = discord.ui.TextInput(label="لینک عکس (اختیاری)", default=panel[4] or "", required=False)

        async def on_submit(self, modal_interaction: discord.Interaction):
            try:
                color = int((self.color_i.value or "#5865F2").replace("#", ""), 16)
            except:
                return await modal_interaction.response.send_message("❌ رنگ نامعتبر", ephemeral=True)

            cursor.execute(
                "UPDATE panels SET title=?, description=?, color=?, image=? WHERE id=?",
                (self.title_i.value, self.desc_i.value, color, self.image_i.value or None, panel_id)
            )
            db.commit()

            cursor.execute("SELECT channel_id FROM panel_messages WHERE panel_id=?", (panel_id,))
            old = cursor.fetchone()
            if old:
                channel = client.get_channel(old[0])
                if channel:
                    await send_panel_message(panel_id, channel)

            await modal_interaction.response.send_message("✅ پنل ویرایش شد", ephemeral=True)

    await interaction.response.send_modal(EditPanelModal())

# ======================
# READY
# ======================
@client.event
async def on_ready():
    await tree.sync()

    cursor.execute("SELECT id, type FROM panels")
    for panel_id, p_type in cursor.fetchall():
        if p_type == "select":
            client.add_view(SelectView(panel_id))
        else:
            client.add_view(ButtonView(panel_id))

    print(f"✅ Bot Ready | Logged in as {client.user}")

client.run(TOKEN)
hesammasters

این کد وقتی ران میشه ارور ها و مشکلاتی داره. دقیق برسی ارور هارو فیکس کن. بدون اینکه ساپورتش از دیتابس فعلی قط بشه

📎 1 file 21,906 chars
📄
pasted-code-1767255409304.txt
txt 548 lines
▶
import discord
from discord import app_commands
import sqlite3
from datetime import datetime

TOKEN = ""

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

# ======================
# DATABASE
# ======================
db = sqlite3.connect("panels.db")
cursor = db.cursor()

# ======================
# PANELS
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS panels (
    id TEXT PRIMARY KEY,
    title TEXT,
    description TEXT,
    type TEXT,
    color INTEGER,
    image TEXT
)
""")

# ======================
# OPTIONS (دکمه / منو)
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS options (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    panel_id TEXT,
    label TEXT,
    response TEXT,
    emoji TEXT,
    icon TEXT
)
""")

# ======================
# PANEL MESSAGES (برای جایگزینی پیام)
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS panel_messages (
    panel_id TEXT PRIMARY KEY,
    channel_id INTEGER,
    message_id INTEGER
)
""")

# ======================
# SETTINGS
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
    key TEXT PRIMARY KEY,
    value TEXT
)
""")

db.commit()


# ======================
# UTILS
# ======================
def is_admin(i: discord.Interaction):
    return i.user.guild_permissions.administrator

def setting(key):
    cursor.execute("SELECT value FROM settings WHERE key=?", (key,))
    r = cursor.fetchone()
    return r[0] if r else None

def set_setting(key, value):
    cursor.execute("INSERT OR REPLACE INTO settings VALUES (?, ?)", (key, value))
    db.commit()

async def log_click(user, panel_id, option_label):
    if setting("log_enabled") != "1":
        return
    ch_id = setting("log_channel")
    if not ch_id:
        return
    try:
        ch = client.get_channel(int(ch_id))
    except (TypeError, ValueError):
       return

    if not ch:
        return
    embed = discord.Embed(title="📊 Panel Click", color=0x57F287, timestamp=datetime.utcnow())
    embed.add_field(name="User", value=user.mention, inline=False)
    embed.add_field(name="Panel", value=panel_id, inline=True)
    embed.add_field(name="Option", value=option_label, inline=True)
    await ch.send(embed=embed)

# ======================
# VIEWS
# ======================
def build_response_embed(panel_id, option_label, response_text, icon=None):
    cursor.execute("SELECT color FROM panels WHERE id=?", (panel_id,))
    panel = cursor.fetchone()
    color = panel[0] if panel else 0x5865F2

    embed = discord.Embed(
        title=option_label,
        description=response_text,
        color=color
    )

    if icon:
        embed.set_thumbnail(url=icon)

    embed.set_footer(text="📌VORIXSHOP")
    return embed


class PanelSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute(
            "SELECT id, label, emoji FROM options WHERE panel_id=?",
            (panel_id,)
        )

        options = []
        for option_id, label, emoji in cursor.fetchall():
            options.append(
                discord.SelectOption(
                    label=label,
                    value=str(option_id),
                    emoji=emoji
                )
            )

        super().__init__(
            placeholder="یک گزینه انتخاب کن",
            options=options,
            custom_id=f"select_{panel_id}"  # این خط اضافه شد
        )

        self.panel_id = panel_id



    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT response, label, icon FROM options WHERE id=?", (option_id,))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ پاسخ یافت نشد", ephemeral=True)
        response_text, label, icon = row
        embed = build_response_embed(self.panel_id, label, response_text, icon)
        await interaction.response.send_message(embed=embed, ephemeral=True)

        await log_click(interaction.user, self.panel_id, label)

class InfoButton(discord.ui.Button):
    def __init__(self, panel_id, label, response, emoji=None, icon=None):
        super().__init__(
            label=label, 
            style=discord.ButtonStyle.primary, 
            emoji=emoji,
            custom_id=f"info_{panel_id}_{label}"  # این خط اضافه شد
        )
        self.panel_id = panel_id
        self.response = response
        self.icon = icon




    async def callback(self, interaction: discord.Interaction):
        embed = build_response_embed(self.panel_id, self.label, self.response, self.icon)
        await interaction.response.send_message(embed=embed, ephemeral=True)

        await log_click(interaction.user, self.panel_id, self.label)

class SelectView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(PanelSelect(panel_id))

class ButtonView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        cursor.execute("SELECT label, response, emoji, icon FROM options WHERE panel_id=?", (panel_id,))
        for label, response, emoji, icon in cursor.fetchall():
          self.add_item(InfoButton(panel_id, label, response, emoji, icon))


# ======================
# SEND PANEL
# ======================
async def send_panel_message(panel_id: str, channel: discord.TextChannel):
    cursor.execute("SELECT title, description, type, color, image FROM panels WHERE id=?",(panel_id,))
    panel = cursor.fetchone()
    
    if not panel:
        return
    title, desc, p_type, color, image = panel

    embed = discord.Embed(title=title,description=desc,color=color)

    if image:
      embed.set_image(url=image)

    view = SelectView(panel_id) if p_type == "select" else ButtonView(panel_id)

    # حذف پیام قبلی
    cursor.execute("SELECT channel_id, message_id FROM panel_messages WHERE panel_id=?", (panel_id,))
    old = cursor.fetchone()
    if old:
      try:
          old_channel = client.get_channel(old[0])
          if old_channel:
              old_msg = await old_channel.fetch_message(old[1])
              await old_msg.delete()
      except:
        pass

    msg = await channel.send(embed=embed, view=view)

    cursor.execute(
       "INSERT OR REPLACE INTO panel_messages VALUES (?, ?, ?)",
       (panel_id, channel.id, msg.id)
    )
db.commit()

    

# ======================
# MODALS
# ======================
class PanelCreateModal(discord.ui.Modal, title="🧩 ساخت پنل"):
    panel_id = discord.ui.TextInput(label="Panel ID")
    title_i = discord.ui.TextInput(label="عنوان پنل")
    desc_i = discord.ui.TextInput(label="توضیح پنل", style=discord.TextStyle.paragraph)
    color_i = discord.ui.TextInput(label="رنگ HEX", placeholder="#5865F2", required=False)
    image_i = discord.ui.TextInput(label="لینک عکس پنل (اختیاری)",
    placeholder="https://example.com/image.png",required=False)


    def __init__(self, panel_type):
        super().__init__()
        self.panel_type = panel_type

    async def on_submit(self, interaction: discord.Interaction):
        if not is_admin(interaction):
            return await interaction.response.send_message("❌ دسترسی نداری", ephemeral=True)
        cursor.execute("SELECT id FROM panels WHERE id=?", (self.panel_id.value,))
        if cursor.fetchone():
            return await interaction.response.send_message("❌ پنل با این ID موجود است", ephemeral=True)
        try:
            color = int((self.color_i.value or "#5865F2").replace("#", ""), 16)
        except ValueError:
            return await interaction.response.send_message("❌ رنگ نامعتبر", ephemeral=True)
        cursor.execute("INSERT INTO panels VALUES (?, ?, ?, ?, ?, ?)",
                       (self.panel_id.value, self.title_i.value, self.desc_i.value, self.panel_type, color, self.image_i.value))
        db.commit()
        await interaction.response.send_message(
            f"✅ پنل ساخته شد. حالا با `/panel_option_add {self.panel_id.value}` گزینه اضافه کن",
            ephemeral=True
        )

class OptionAddModal(discord.ui.Modal, title="➕ افزودن گزینه"):
    label = discord.ui.TextInput(label="متن گزینه")
    response = discord.ui.TextInput(label="پاسخ", style=discord.TextStyle.paragraph)
    emoji = discord.ui.TextInput(label="ایموجی (اختیاری)", required=False)
    icon = discord.ui.TextInput(label="آیکون (URL اختیاری)",placeholder="https://example.com/icon.png",required=False)

    def __init__(self, panel_id):
        super().__init__()
        self.panel_id = panel_id

    async def on_submit(self, interaction: discord.Interaction):
        cursor.execute("SELECT COUNT(*) FROM options WHERE panel_id=?", (self.panel_id,))
        count = cursor.fetchone()[0]
        if count >= 25:
          return await interaction.response.send_message("❌ حداکثر 25 گزینه مجاز است", ephemeral=True)

        cursor.execute("INSERT INTO options (panel_id, label, response, emoji, icon) VALUES (?, ?, ?, ?, ?)",(self.panel_id, self.label.value, self.response.value, self.emoji.value or None, self.icon.value or None))

        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message("✅ گزینه اضافه شد و پنل بروزرسانی شد", ephemeral=True)


# ======================
# DELETE / EDIT VIEWS
# ======================
class OptionDeleteSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute("SELECT id, label FROM options WHERE panel_id=?", (panel_id,))
        options = [discord.SelectOption(label=r[1], value=str(r[0])) for r in cursor.fetchall()]
        super().__init__(placeholder="گزینه برای حذف انتخاب کن", options=options)
        self.panel_id = panel_id

    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT label FROM options WHERE id=? AND panel_id=?", (option_id, self.panel_id))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ گزینه پیدا نشد", ephemeral=True)
        cursor.execute("DELETE FROM options WHERE id=?", (option_id,))
        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message(f"✅ گزینه `{row[0]}` حذف شد", ephemeral=True)

class OptionDeleteView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(OptionDeleteSelect(panel_id))

class OptionEditSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute("SELECT id, label FROM options WHERE panel_id=?", (panel_id,))
        options = [discord.SelectOption(label=r[1], value=str(r[0])) for r in cursor.fetchall()]
        super().__init__(placeholder="گزینه برای ویرایش انتخاب کن", options=options)
        self.panel_id = panel_id

    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT label, response, emoji, icon FROM options WHERE id=? AND panel_id=?", (option_id, self.panel_id))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ گزینه پیدا نشد", ephemeral=True)
        label, response, emoji, icon = row
        await interaction.response.send_modal(EditOptionModal(self.panel_id, option_id, label, response, emoji, icon))


class EditOptionModal(discord.ui.Modal, title="✏️ ویرایش گزینه"):
    def __init__(self, panel_id, option_id, label, response, emoji, icon):
        super().__init__()
        self.panel_id = panel_id
        self.option_id = option_id

        self.label_i = discord.ui.TextInput(label="متن گزینه", default=label)
        self.response_i = discord.ui.TextInput(label="پاسخ", style=discord.TextStyle.paragraph, default=response)
        self.emoji_i = discord.ui.TextInput(label="ایموجی (اختیاری)", required=False, default=emoji or "")
        self.icon_i = discord.ui.TextInput(label="آیکون (URL اختیاری)", required=False, default=icon or "")

        self.add_item(self.label_i)
        self.add_item(self.response_i)
        self.add_item(self.emoji_i)
        self.add_item(self.icon_i)

    async def on_submit(self, interaction: discord.Interaction):
        cursor.execute(
            "UPDATE options SET label=?, response=?, emoji=?, icon=? WHERE id=?",
            (self.label_i.value, self.response_i.value, self.emoji_i.value or None, self.icon_i.value or None, self.option_id)
        )
        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message("✅ گزینه ویرایش شد", ephemeral=True)


class OptionEditView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(OptionEditSelect(panel_id))

# ======================
# SLASH COMMANDS
# ======================
@tree.command(name="panel_change_type", description="تغییر نوع پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_change_type(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT type FROM panels WHERE id=?", (panel_id,))
    row = cursor.fetchone()
    if not row:
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    current_type = row[0]

    class TypeSelect(discord.ui.Select):
        def __init__(self):
            options = [
                discord.SelectOption(label="Select Menu", value="select", emoji="🧩"),
                discord.SelectOption(label="Button Panel", value="button", emoji="🔘")
            ]
            super().__init__(
                placeholder=f"نوع فعلی: {current_type}",
                options=options
            )

        async def callback(self, i: discord.Interaction):
            new_type = self.values[0]
            cursor.execute("UPDATE panels SET type=? WHERE id=?", (new_type, panel_id))
            db.commit()

            cursor.execute("SELECT channel_id FROM panel_messages WHERE panel_id=?", (panel_id,))
            old = cursor.fetchone()
            if old:
                channel = client.get_channel(old[0])
                if channel:
                    await send_panel_message(panel_id, channel)

            await i.response.send_message(f"✅ نوع پنل به `{new_type}` تغییر کرد", ephemeral=True)

    view = discord.ui.View()
    view.add_item(TypeSelect())
    await interaction.response.send_message("نوع جدید پنل را انتخاب کن:", view=view, ephemeral=True)

@tree.command(name="panel_list", description="لیست همه پنل‌ها")
async def panel_list(interaction: discord.Interaction):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT id, type FROM panels")
    rows = cursor.fetchall()

    if not rows:
        return await interaction.response.send_message("❌ پنلی وجود ندارد", ephemeral=True)

    text = "\n".join([f"• `{r[0]}` | {r[1]}" for r in rows])
    embed = discord.Embed(title="📋 لیست پنل‌ها", description=text, color=0x5865F2)
    await interaction.response.send_message(embed=embed, ephemeral=True)
@tree.command(name="panel_send", description="ارسال پنل در کانال")
@app_commands.describe(panel_id="ID پنل")
async def panel_send(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT id FROM panels WHERE id=?", (panel_id,))
    if not cursor.fetchone():
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    await send_panel_message(panel_id, interaction.channel)
    await interaction.response.send_message("✅ پنل ارسال شد", ephemeral=True)

@tree.command(name="panel_create", description="ساخت پنل")
async def panel_create(interaction: discord.Interaction):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    class PanelTypeView(discord.ui.View):
        @discord.ui.select(
            placeholder="نوع پنل را انتخاب کن",
            options=[
                discord.SelectOption(label="Select Menu", value="select", emoji="🧩"),
                discord.SelectOption(label="Button Panel", value="button", emoji="🔘")
            ]
        )
        async def select_type(self, interaction: discord.Interaction, select: discord.ui.Select):
            await interaction.response.send_modal(PanelCreateModal(select.values[0]))
    await interaction.response.send_message("نوع پنل را انتخاب کن:", view=PanelTypeView(), ephemeral=True)

@tree.command(name="panel_option_add", description="افزودن گزینه به پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_add(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM panels WHERE id=?", (panel_id,))
    if not cursor.fetchone():
        return await interaction.response.send_message("❌ پنل وجود ندارد", ephemeral=True)
    await interaction.response.send_modal(OptionAddModal(panel_id))

@tree.command(name="panel_option_delete_select", description="حذف گزینه با انتخاب")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_delete_select(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM options WHERE panel_id=?", (panel_id,))
    if not cursor.fetchall():
        return await interaction.response.send_message("❌ هیچ گزینه‌ای وجود ندارد", ephemeral=True)
    await interaction.response.send_message("گزینه‌ای برای حذف انتخاب کن:", view=OptionDeleteView(panel_id), ephemeral=True)

@tree.command(name="panel_option_edit_select", description="ویرایش گزینه با انتخاب")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_edit_select(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM options WHERE panel_id=?", (panel_id,))
    if not cursor.fetchall():
        return await interaction.response.send_message("❌ هیچ گزینه‌ای وجود ندارد", ephemeral=True)
    await interaction.response.send_message("گزینه‌ای برای ویرایش انتخاب کن:", view=OptionEditView(panel_id), ephemeral=True)

# ======================
# EDIT PANEL COMMAND
# ======================
@tree.command(name="panel_edit", description="ویرایش پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_edit(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT title, description, type, color, image FROM panels WHERE id=?", (panel_id,))
    panel = cursor.fetchone()
    if not panel:
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    class EditPanelModal(discord.ui.Modal, title=f"✏️ ویرایش پنل {panel_id}"):
        title_i = discord.ui.TextInput(label="عنوان پنل", default=panel[0])
        desc_i = discord.ui.TextInput(label="توضیح پنل", style=discord.TextStyle.paragraph, default=panel[1])
        color_i = discord.ui.TextInput(label="رنگ HEX", default=f"#{panel[3]:06x}", required=False)
        image_i = discord.ui.TextInput(label="لینک عکس (اختیاری)", default=panel[4] or "", required=False)

        async def on_submit(self, modal_interaction: discord.Interaction):
            try:
                color = int((self.color_i.value or "#5865F2").replace("#", ""), 16)
            except:
                return await modal_interaction.response.send_message("❌ رنگ نامعتبر", ephemeral=True)

            cursor.execute(
                "UPDATE panels SET title=?, description=?, color=?, image=? WHERE id=?",
                (self.title_i.value, self.desc_i.value, color, self.image_i.value or None, panel_id)
            )
            db.commit()

            cursor.execute("SELECT channel_id FROM panel_messages WHERE panel_id=?", (panel_id,))
            old = cursor.fetchone()
            if old:
                channel = client.get_channel(old[0])
                if channel:
                    await send_panel_message(panel_id, channel)

            await modal_interaction.response.send_message("✅ پنل ویرایش شد", ephemeral=True)

    await interaction.response.send_modal(EditPanelModal())

# ======================
# READY
# ======================
@client.event
async def on_ready():
    await tree.sync()

    cursor.execute("SELECT id, type FROM panels")
    for panel_id, p_type in cursor.fetchall():
        if p_type == "select":
            client.add_view(SelectView(panel_id))
        else:
            client.add_view(ButtonView(panel_id))

    print(f"✅ Bot Ready | Logged in as {client.user}")

client.run(TOKEN)
Kodari AI
KodariJan 1 at 8:17 am 4,128 (v2)

من کد را بررسی کردم و مشکلات زیر را شناسایی کردم:

  1. Indentation Error در خط db.commit() بعد از تابع send_panel_message

  2. Token در کد که باید در .env باشد

  3. مشکل persistent views که بعد از ریستارت بات کار نمی‌کنند

  4. مشکل datetime.utcnow() که deprecated شده

DiscordPanelBot
A comprehensive Discord bot for creating and managing interactive panels with buttons and select menus. Features include customizable embeds, option management, click logging, persistent views, and admin controls. Supports both button-based and select menu panels with full CRUD operations and SQLite database integration.
hesammasters

یکبار دیگه همرو بنویس داخل app.py

Kodari AI
KodariJan 1 at 8:19 am 947 (v2)

فایل‌های بات دیسکورد ایجاد شدند. توکن بات خود را در فایل .env قرار دهید.

hesammasters

حالا این کد رفع خطا کن و وارد بات کن

📎 1 file 21,906 chars
📄
pasted-code-1767255581737.txt
txt 548 lines
▶
import discord
from discord import app_commands
import sqlite3
from datetime import datetime

TOKEN = ""

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

# ======================
# DATABASE
# ======================
db = sqlite3.connect("panels.db")
cursor = db.cursor()

# ======================
# PANELS
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS panels (
    id TEXT PRIMARY KEY,
    title TEXT,
    description TEXT,
    type TEXT,
    color INTEGER,
    image TEXT
)
""")

# ======================
# OPTIONS (دکمه / منو)
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS options (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    panel_id TEXT,
    label TEXT,
    response TEXT,
    emoji TEXT,
    icon TEXT
)
""")

# ======================
# PANEL MESSAGES (برای جایگزینی پیام)
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS panel_messages (
    panel_id TEXT PRIMARY KEY,
    channel_id INTEGER,
    message_id INTEGER
)
""")

# ======================
# SETTINGS
# ======================
cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
    key TEXT PRIMARY KEY,
    value TEXT
)
""")

db.commit()


# ======================
# UTILS
# ======================
def is_admin(i: discord.Interaction):
    return i.user.guild_permissions.administrator

def setting(key):
    cursor.execute("SELECT value FROM settings WHERE key=?", (key,))
    r = cursor.fetchone()
    return r[0] if r else None

def set_setting(key, value):
    cursor.execute("INSERT OR REPLACE INTO settings VALUES (?, ?)", (key, value))
    db.commit()

async def log_click(user, panel_id, option_label):
    if setting("log_enabled") != "1":
        return
    ch_id = setting("log_channel")
    if not ch_id:
        return
    try:
        ch = client.get_channel(int(ch_id))
    except (TypeError, ValueError):
       return

    if not ch:
        return
    embed = discord.Embed(title="📊 Panel Click", color=0x57F287, timestamp=datetime.utcnow())
    embed.add_field(name="User", value=user.mention, inline=False)
    embed.add_field(name="Panel", value=panel_id, inline=True)
    embed.add_field(name="Option", value=option_label, inline=True)
    await ch.send(embed=embed)

# ======================
# VIEWS
# ======================
def build_response_embed(panel_id, option_label, response_text, icon=None):
    cursor.execute("SELECT color FROM panels WHERE id=?", (panel_id,))
    panel = cursor.fetchone()
    color = panel[0] if panel else 0x5865F2

    embed = discord.Embed(
        title=option_label,
        description=response_text,
        color=color
    )

    if icon:
        embed.set_thumbnail(url=icon)

    embed.set_footer(text="📌VORIXSHOP")
    return embed


class PanelSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute(
            "SELECT id, label, emoji FROM options WHERE panel_id=?",
            (panel_id,)
        )

        options = []
        for option_id, label, emoji in cursor.fetchall():
            options.append(
                discord.SelectOption(
                    label=label,
                    value=str(option_id),
                    emoji=emoji
                )
            )

        super().__init__(
            placeholder="یک گزینه انتخاب کن",
            options=options,
            custom_id=f"select_{panel_id}"  # این خط اضافه شد
        )

        self.panel_id = panel_id



    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT response, label, icon FROM options WHERE id=?", (option_id,))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ پاسخ یافت نشد", ephemeral=True)
        response_text, label, icon = row
        embed = build_response_embed(self.panel_id, label, response_text, icon)
        await interaction.response.send_message(embed=embed, ephemeral=True)

        await log_click(interaction.user, self.panel_id, label)

class InfoButton(discord.ui.Button):
    def __init__(self, panel_id, label, response, emoji=None, icon=None):
        super().__init__(
            label=label, 
            style=discord.ButtonStyle.primary, 
            emoji=emoji,
            custom_id=f"info_{panel_id}_{label}"  # این خط اضافه شد
        )
        self.panel_id = panel_id
        self.response = response
        self.icon = icon




    async def callback(self, interaction: discord.Interaction):
        embed = build_response_embed(self.panel_id, self.label, self.response, self.icon)
        await interaction.response.send_message(embed=embed, ephemeral=True)

        await log_click(interaction.user, self.panel_id, self.label)

class SelectView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(PanelSelect(panel_id))

class ButtonView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        cursor.execute("SELECT label, response, emoji, icon FROM options WHERE panel_id=?", (panel_id,))
        for label, response, emoji, icon in cursor.fetchall():
          self.add_item(InfoButton(panel_id, label, response, emoji, icon))


# ======================
# SEND PANEL
# ======================
async def send_panel_message(panel_id: str, channel: discord.TextChannel):
    cursor.execute("SELECT title, description, type, color, image FROM panels WHERE id=?",(panel_id,))
    panel = cursor.fetchone()
    
    if not panel:
        return
    title, desc, p_type, color, image = panel

    embed = discord.Embed(title=title,description=desc,color=color)

    if image:
      embed.set_image(url=image)

    view = SelectView(panel_id) if p_type == "select" else ButtonView(panel_id)

    # حذف پیام قبلی
    cursor.execute("SELECT channel_id, message_id FROM panel_messages WHERE panel_id=?", (panel_id,))
    old = cursor.fetchone()
    if old:
      try:
          old_channel = client.get_channel(old[0])
          if old_channel:
              old_msg = await old_channel.fetch_message(old[1])
              await old_msg.delete()
      except:
        pass

    msg = await channel.send(embed=embed, view=view)

    cursor.execute(
       "INSERT OR REPLACE INTO panel_messages VALUES (?, ?, ?)",
       (panel_id, channel.id, msg.id)
    )
db.commit()

    

# ======================
# MODALS
# ======================
class PanelCreateModal(discord.ui.Modal, title="🧩 ساخت پنل"):
    panel_id = discord.ui.TextInput(label="Panel ID")
    title_i = discord.ui.TextInput(label="عنوان پنل")
    desc_i = discord.ui.TextInput(label="توضیح پنل", style=discord.TextStyle.paragraph)
    color_i = discord.ui.TextInput(label="رنگ HEX", placeholder="#5865F2", required=False)
    image_i = discord.ui.TextInput(label="لینک عکس پنل (اختیاری)",
    placeholder="https://example.com/image.png",required=False)


    def __init__(self, panel_type):
        super().__init__()
        self.panel_type = panel_type

    async def on_submit(self, interaction: discord.Interaction):
        if not is_admin(interaction):
            return await interaction.response.send_message("❌ دسترسی نداری", ephemeral=True)
        cursor.execute("SELECT id FROM panels WHERE id=?", (self.panel_id.value,))
        if cursor.fetchone():
            return await interaction.response.send_message("❌ پنل با این ID موجود است", ephemeral=True)
        try:
            color = int((self.color_i.value or "#5865F2").replace("#", ""), 16)
        except ValueError:
            return await interaction.response.send_message("❌ رنگ نامعتبر", ephemeral=True)
        cursor.execute("INSERT INTO panels VALUES (?, ?, ?, ?, ?, ?)",
                       (self.panel_id.value, self.title_i.value, self.desc_i.value, self.panel_type, color, self.image_i.value))
        db.commit()
        await interaction.response.send_message(
            f"✅ پنل ساخته شد. حالا با `/panel_option_add {self.panel_id.value}` گزینه اضافه کن",
            ephemeral=True
        )

class OptionAddModal(discord.ui.Modal, title="➕ افزودن گزینه"):
    label = discord.ui.TextInput(label="متن گزینه")
    response = discord.ui.TextInput(label="پاسخ", style=discord.TextStyle.paragraph)
    emoji = discord.ui.TextInput(label="ایموجی (اختیاری)", required=False)
    icon = discord.ui.TextInput(label="آیکون (URL اختیاری)",placeholder="https://example.com/icon.png",required=False)

    def __init__(self, panel_id):
        super().__init__()
        self.panel_id = panel_id

    async def on_submit(self, interaction: discord.Interaction):
        cursor.execute("SELECT COUNT(*) FROM options WHERE panel_id=?", (self.panel_id,))
        count = cursor.fetchone()[0]
        if count >= 25:
          return await interaction.response.send_message("❌ حداکثر 25 گزینه مجاز است", ephemeral=True)

        cursor.execute("INSERT INTO options (panel_id, label, response, emoji, icon) VALUES (?, ?, ?, ?, ?)",(self.panel_id, self.label.value, self.response.value, self.emoji.value or None, self.icon.value or None))

        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message("✅ گزینه اضافه شد و پنل بروزرسانی شد", ephemeral=True)


# ======================
# DELETE / EDIT VIEWS
# ======================
class OptionDeleteSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute("SELECT id, label FROM options WHERE panel_id=?", (panel_id,))
        options = [discord.SelectOption(label=r[1], value=str(r[0])) for r in cursor.fetchall()]
        super().__init__(placeholder="گزینه برای حذف انتخاب کن", options=options)
        self.panel_id = panel_id

    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT label FROM options WHERE id=? AND panel_id=?", (option_id, self.panel_id))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ گزینه پیدا نشد", ephemeral=True)
        cursor.execute("DELETE FROM options WHERE id=?", (option_id,))
        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message(f"✅ گزینه `{row[0]}` حذف شد", ephemeral=True)

class OptionDeleteView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(OptionDeleteSelect(panel_id))

class OptionEditSelect(discord.ui.Select):
    def __init__(self, panel_id):
        cursor.execute("SELECT id, label FROM options WHERE panel_id=?", (panel_id,))
        options = [discord.SelectOption(label=r[1], value=str(r[0])) for r in cursor.fetchall()]
        super().__init__(placeholder="گزینه برای ویرایش انتخاب کن", options=options)
        self.panel_id = panel_id

    async def callback(self, interaction: discord.Interaction):
        option_id = int(self.values[0])
        cursor.execute("SELECT label, response, emoji, icon FROM options WHERE id=? AND panel_id=?", (option_id, self.panel_id))
        row = cursor.fetchone()
        if not row:
            return await interaction.response.send_message("❌ گزینه پیدا نشد", ephemeral=True)
        label, response, emoji, icon = row
        await interaction.response.send_modal(EditOptionModal(self.panel_id, option_id, label, response, emoji, icon))


class EditOptionModal(discord.ui.Modal, title="✏️ ویرایش گزینه"):
    def __init__(self, panel_id, option_id, label, response, emoji, icon):
        super().__init__()
        self.panel_id = panel_id
        self.option_id = option_id

        self.label_i = discord.ui.TextInput(label="متن گزینه", default=label)
        self.response_i = discord.ui.TextInput(label="پاسخ", style=discord.TextStyle.paragraph, default=response)
        self.emoji_i = discord.ui.TextInput(label="ایموجی (اختیاری)", required=False, default=emoji or "")
        self.icon_i = discord.ui.TextInput(label="آیکون (URL اختیاری)", required=False, default=icon or "")

        self.add_item(self.label_i)
        self.add_item(self.response_i)
        self.add_item(self.emoji_i)
        self.add_item(self.icon_i)

    async def on_submit(self, interaction: discord.Interaction):
        cursor.execute(
            "UPDATE options SET label=?, response=?, emoji=?, icon=? WHERE id=?",
            (self.label_i.value, self.response_i.value, self.emoji_i.value or None, self.icon_i.value or None, self.option_id)
        )
        db.commit()
        await send_panel_message(self.panel_id, interaction.channel)
        await interaction.response.send_message("✅ گزینه ویرایش شد", ephemeral=True)


class OptionEditView(discord.ui.View):
    def __init__(self, panel_id):
        super().__init__(timeout=None)
        self.add_item(OptionEditSelect(panel_id))

# ======================
# SLASH COMMANDS
# ======================
@tree.command(name="panel_change_type", description="تغییر نوع پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_change_type(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT type FROM panels WHERE id=?", (panel_id,))
    row = cursor.fetchone()
    if not row:
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    current_type = row[0]

    class TypeSelect(discord.ui.Select):
        def __init__(self):
            options = [
                discord.SelectOption(label="Select Menu", value="select", emoji="🧩"),
                discord.SelectOption(label="Button Panel", value="button", emoji="🔘")
            ]
            super().__init__(
                placeholder=f"نوع فعلی: {current_type}",
                options=options
            )

        async def callback(self, i: discord.Interaction):
            new_type = self.values[0]
            cursor.execute("UPDATE panels SET type=? WHERE id=?", (new_type, panel_id))
            db.commit()

            cursor.execute("SELECT channel_id FROM panel_messages WHERE panel_id=?", (panel_id,))
            old = cursor.fetchone()
            if old:
                channel = client.get_channel(old[0])
                if channel:
                    await send_panel_message(panel_id, channel)

            await i.response.send_message(f"✅ نوع پنل به `{new_type}` تغییر کرد", ephemeral=True)

    view = discord.ui.View()
    view.add_item(TypeSelect())
    await interaction.response.send_message("نوع جدید پنل را انتخاب کن:", view=view, ephemeral=True)

@tree.command(name="panel_list", description="لیست همه پنل‌ها")
async def panel_list(interaction: discord.Interaction):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT id, type FROM panels")
    rows = cursor.fetchall()

    if not rows:
        return await interaction.response.send_message("❌ پنلی وجود ندارد", ephemeral=True)

    text = "\n".join([f"• `{r[0]}` | {r[1]}" for r in rows])
    embed = discord.Embed(title="📋 لیست پنل‌ها", description=text, color=0x5865F2)
    await interaction.response.send_message(embed=embed, ephemeral=True)
@tree.command(name="panel_send", description="ارسال پنل در کانال")
@app_commands.describe(panel_id="ID پنل")
async def panel_send(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT id FROM panels WHERE id=?", (panel_id,))
    if not cursor.fetchone():
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    await send_panel_message(panel_id, interaction.channel)
    await interaction.response.send_message("✅ پنل ارسال شد", ephemeral=True)

@tree.command(name="panel_create", description="ساخت پنل")
async def panel_create(interaction: discord.Interaction):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    class PanelTypeView(discord.ui.View):
        @discord.ui.select(
            placeholder="نوع پنل را انتخاب کن",
            options=[
                discord.SelectOption(label="Select Menu", value="select", emoji="🧩"),
                discord.SelectOption(label="Button Panel", value="button", emoji="🔘")
            ]
        )
        async def select_type(self, interaction: discord.Interaction, select: discord.ui.Select):
            await interaction.response.send_modal(PanelCreateModal(select.values[0]))
    await interaction.response.send_message("نوع پنل را انتخاب کن:", view=PanelTypeView(), ephemeral=True)

@tree.command(name="panel_option_add", description="افزودن گزینه به پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_add(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM panels WHERE id=?", (panel_id,))
    if not cursor.fetchone():
        return await interaction.response.send_message("❌ پنل وجود ندارد", ephemeral=True)
    await interaction.response.send_modal(OptionAddModal(panel_id))

@tree.command(name="panel_option_delete_select", description="حذف گزینه با انتخاب")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_delete_select(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM options WHERE panel_id=?", (panel_id,))
    if not cursor.fetchall():
        return await interaction.response.send_message("❌ هیچ گزینه‌ای وجود ندارد", ephemeral=True)
    await interaction.response.send_message("گزینه‌ای برای حذف انتخاب کن:", view=OptionDeleteView(panel_id), ephemeral=True)

@tree.command(name="panel_option_edit_select", description="ویرایش گزینه با انتخاب")
@app_commands.describe(panel_id="ID پنل")
async def panel_option_edit_select(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)
    cursor.execute("SELECT id FROM options WHERE panel_id=?", (panel_id,))
    if not cursor.fetchall():
        return await interaction.response.send_message("❌ هیچ گزینه‌ای وجود ندارد", ephemeral=True)
    await interaction.response.send_message("گزینه‌ای برای ویرایش انتخاب کن:", view=OptionEditView(panel_id), ephemeral=True)

# ======================
# EDIT PANEL COMMAND
# ======================
@tree.command(name="panel_edit", description="ویرایش پنل")
@app_commands.describe(panel_id="ID پنل")
async def panel_edit(interaction: discord.Interaction, panel_id: str):
    if not is_admin(interaction):
        return await interaction.response.send_message("❌ فقط ادمین", ephemeral=True)

    cursor.execute("SELECT title, description, type, color, image FROM panels WHERE id=?", (panel_id,))
    panel = cursor.fetchone()
    if not panel:
        return await interaction.response.send_message("❌ پنل یافت نشد", ephemeral=True)

    class EditPanelModal(discord.ui.Modal, title=f"✏️ ویرایش پنل {panel_id}"):
        title_i = discord.ui.TextInput(label="عنوان پنل", default=panel[0])
        desc_i = discord.ui.TextInput(label="توضیح پنل", style=discord.TextStyle.paragraph, default=panel[1])
        color_i = discord.ui.TextInput(label="رنگ HEX", default=f"#{panel[3]:06x}", required=False)
        image_i = discord.ui.TextInput(label="لینک عکس (اختیاری)", default=panel[4] or "", required=False)

        async def on_submit(self, modal_interaction: discord.Interaction):
            try:
                color = int((self.color_i.value or "#5865F2").replace("#", ""), 16)
            except:
                return await modal_interaction.response.send_message("❌ رنگ نامعتبر", ephemeral=True)

            cursor.execute(
                "UPDATE panels SET title=?, description=?, color=?, image=? WHERE id=?",
                (self.title_i.value, self.desc_i.value, color, self.image_i.value or None, panel_id)
            )
            db.commit()

            cursor.execute("SELECT channel_id FROM panel_messages WHERE panel_id=?", (panel_id,))
            old = cursor.fetchone()
            if old:
                channel = client.get_channel(old[0])
                if channel:
                    await send_panel_message(panel_id, channel)

            await modal_interaction.response.send_message("✅ پنل ویرایش شد", ephemeral=True)

    await interaction.response.send_modal(EditPanelModal())

# ======================
# READY
# ======================
@client.event
async def on_ready():
    await tree.sync()

    cursor.execute("SELECT id, type FROM panels")
    for panel_id, p_type in cursor.fetchall():
        if p_type == "select":
            client.add_view(SelectView(panel_id))
        else:
            client.add_view(ButtonView(panel_id))

    print(f"✅ Bot Ready | Logged in as {client.user}")

client.run(TOKEN)
Kodari can make mistakes. Review important code before using.
Files
app.py
requirements.txt
Code
2 20
app.py
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

load_dotenv()

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f'Bot is ready! Logged in as {bot.user}')

@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')

bot.run(os.getenv('DISCORD_TOKEN'))