ammyx

can you fix the issues in my Python skripts plelase

Kodari AI
KodariMar 31 at 6:18 pm 1,966 (v2)

I donโ€™t see any files in the current project - it appears to be empty. To help fix your Python scripts, I need to either:

  1. See the existing files - If you have Python scripts youโ€™d like me to fix, please share them by:

    • Pasting the code here, or

    • Letting me know if they should be in a specific location

  2. Start a new project - If youโ€™d like me to create a Discord bot or Python project from scratch, let me know what you need it to do.

Could you please either:

  • Share the Python code that has issues, or

  • Describe what youโ€™re trying to build?

Iโ€™ll be happy to fix any errors once I can see the code! ๐Ÿ

ammyx

can you fix this

import asyncio import os from dotenv import load_dotenv import discord

load_dotenv()

intents = discord.Intents.default() intents.message_content = True

client = discord.Client(intents=intents)

#getting the secret token async def on_ready(): async with client: await client.start(os.getenv("<redacted>"))

asyncio.run(main())

Kodari AI
KodariMar 31 at 6:20 pm 1,461 (v2)

Iโ€™ll fix your Discord bot code. The main issues are: using os.getenv() incorrectly (passing the token instead of the variable name), missing event decorator, and calling a non-existent main() function.

DiscordBot
A Discord bot built with discord.py that connects to Discord servers and responds to events. Features proper token management via environment variables, message content intents for reading messages, and event handling for bot initialization and user interactions.

Fixed! The main issues were:

  • Token was hardcoded in os.getenv() instead of using an environment variable name

  • Missing @client.event decorator

  • Incorrect async startup pattern - should just use client.run()

  • Non-existent main() function call

Now the bot will properly load the token from .env and start correctly. Run with python bot.py after installing dependencies with pip install -r requirements.txt.

ammyx

aswell as this

async def runner(): async with self: await self.start(<redacted>, reconnect=reconnect)

if log_handler is not None: utils.setup_logging( handler=log_handler, formatter=log_formatter, level=log_level, root=root_logger, )

try: asyncio.run(runner()) except KeyboardInterrupt: # nothing to do here # asyncio.run handles the loop cleanup # and self.start closes all sockets and the HTTPClient instance. return

Kodari AI
KodariMar 31 at 6:21 pm 2,252 (v2)

๐Ÿšจ CRITICAL SECURITY ALERT ๐Ÿšจ

Your Discord bot token is hardcoded and exposed in your code! This token should be regenerated immediately on the Discord Developer Portal:

  1. Select your bot

  2. Go to โ€œBotโ€ section

  3. Click โ€œReset Tokenโ€ to generate a new one

  4. Never share or commit this new token

Let me read your existing files to fix this security issue:

I can see you have TWO exposed tokens:

  1. In the code you just showed: <redacted>

  2. In your .env file: <redacted>

Both tokens must be regenerated immediately.


โœ… Hereโ€™s the corrected approach:

Your bot.py is already correct - it properly uses os.getenv("DISCORD_TOKEN").


๐Ÿ“‹ Steps to fix:

  1. Regenerate your token on Discord Developer Portal

  2. Paste the NEW token into your .env file (replace your_new_token_here)

  3. Never hardcode tokens in Python files - always use environment variables

  4. Add .env to .gitignore if using version control

The code snippet you showed with the hardcoded token should use os.getenv('DISCORD_TOKEN') instead - never pass raw tokens to start() or run() methods.

ammyx

How do i fix this issue

1 image attached
Kodari AI
KodariMar 31 at 6:23 pm 2,065 (v2)

I can see you have an IndentationError in the discord.py library itself (line 933 in client.py). This usually means the discord.py installation is corrupted.

Let me first read your existing files to see your bot structure:

The issue is a corrupted discord.py installation. The error is in the discord.py library itself, not your code. Your bot code looks fine!

Fix:

Run these commands to fix it:

Shell
pip uninstall discord.py -y
pip uninstall discord -y
pip cache purge
pip install -r requirements.txt --force-reinstall

Or if youโ€™re using a hosting service:

  1. Delete your virtual environment folder (venv or similar)

  2. Reinstall all dependencies fresh

Alternative quick fix:

Shell
pip install --upgrade --force-reinstall discord.py==2.3.2

Why this happened: The discord.py library file got corrupted during installation or an update. Reinstalling with a specific stable version will fix it.

Your bot code is correct - donโ€™t forget to replace your_new_token_here in .env with your actual Discord bot token!

ammyx

How do i fix those issues

Kodari AI
KodariMar 31 at 6:25 pm 1,551 (v2)

I donโ€™t see any previous context about issues youโ€™re experiencing. Let me first read your project files to understand what youโ€™re working with:

I can see your Discord bot project, but I need more information to help you fix the issues. Could you please provide:

  1. What error messages are you seeing? (Copy and paste the full error)

  2. Whatโ€™s not working? (Bot wonโ€™t start, commands not responding, etc.)

  3. When does the issue occur? (On startup, when using a command, etc.)

Possible issues I notice:

  • Your .env file has your_new_token_here - you need to replace this with your actual Discord bot token from the Discord Developer Portal

If youโ€™re getting specific error messages, please share them so I can provide the exact fix!

ammyx

File "/usr/local/lib/python3.12/site-packages/discord/client.py", line 777, in start await self.login(token) File "/usr/local/lib/python3.12/site-packages/discord/client.py", line 612, in login data = await self.http.static_login(token) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/discord/http.py", line 807, in static_login raise LoginFailure('Improper token has been passed.') from exc

Kodari AI
KodariMar 31 at 6:26 pm 2,077 (v2)

I need to check your current bot files to diagnose the token issue. Let me read them first.

The issue is clear: your .env file contains your_new_token_here which is a placeholder, not your actual Discord bot token.

To fix this:

  1. Select your application

  2. Go to the Bot section in the left sidebar

  3. Click Reset Token (or Copy if you havenโ€™t reset it before)

  4. Copy your bot token

  5. Replace the placeholder in your .env file with the real token

Iโ€™ll update your files to include better error handling and instructions:

Now update your .env file with your actual bot token from Discord Developer Portal. The bot will show helpful error messages if the token is still invalid.

ammyx

Done

Kodari AI
KodariMar 31 at 6:27 pm 1,720 (v2)

Iโ€™ll help you with your Discord bot! Let me first check the current project structure to see what weโ€™re working with.

Perfect! I can see your Discord bot is set up with:

โœ… Discord bot token configured in .env โœ… Basic bot structure in bot.py with token validation โœ… Dependencies listed in requirements.txt

Your bot is ready to run! It will:

  • Connect using your Discord token

  • Enable message content intents

  • Log when itโ€™s ready

What would you like me to help you add next? Some common features:

  • Commands (e.g., !hello, !help)

  • Event handlers (message reactions, member joins, etc.)

  • Moderation features

  • Fun commands

  • Database integration

  • Or something else?

Let me know what functionality youโ€™d like, and Iโ€™ll implement it for you!

ammyx

i need this aswell

๐Ÿ“Ž 1 file 52,353 chars
๐Ÿ“„
pasted-code-1774981702850.txt
txt 1336 lines
โ–ถ
import os
import asyncio
from datetime import datetime

import discord
from discord import (
    ButtonStyle,
    Color,
    Embed,
    Interaction,
    TextChannel,
    CategoryChannel,
    PermissionOverwrite,
)
from discord.ext import commands
from discord.ui import Button, Select, TextInput, View, Modal

# ================= BOT SETUP =================
TOKEN = os.getenv("")

PREFIX = "!"
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix=PREFIX, intents=intents)

# ================= CONFIG =================
GUILD_ID = 1444657552477392988
UPDATE_CHANNEL_ID = 0  # Set this to your update channel ID

# ---- Application channels ----
APPLY_PANEL_CHANNEL_ID = 1445436817955623244      # Where the main panel is posted
APPLICATIONS_CATEGORY_ID = 1444657553291350016    # Category for application channels

# ---- Review channels (where final apps are sent for review) ----
STAFF_REVIEW_CHANNEL_ID = 1445439637450522625
MEDIA_REVIEW_CHANNEL_ID = 1445439637450522625
BUILDER_REVIEW_CHANNEL_ID = 1445439637450522625

# ---- Announcement channels (where accept/deny announcements go) ----
STAFF_ANNOUNCE_CHANNEL_ID = 1445436901057106102
MEDIA_ANNOUNCE_CHANNEL_ID = 1445436901057106102
BUILDER_ANNOUNCE_CHANNEL_ID = 1445436901057106102

# ---- Role IDs for pings ----
STAFF_REVIEW_ROLE_ID = 1336335303824380034
MEDIA_REVIEW_ROLE_ID = 1392669793965969488
BUILDER_REVIEW_ROLE_IDS = [1312096582111465513, 1358442574192316467, 1383473486609121411]

# ---- Storage for active builder applications ----
active_builder_apps = {}
# Format:
# {
#   channel_id: {
#       "applicant_id": int,
#       "answers": dict,
#       "images": list[str],
#       "status": "active",
#       "questions_answered": bool
#   }
# }


# ================= OPTIONAL LOG HELPER =================
async def send_log(guild: discord.Guild, category: str, message: str):
    """Simple placeholder logger. Replace with your own logging system if needed."""
    print(f"[{category.upper()}] {guild.name if guild else 'Unknown Guild'}: {message}")


# ================= APPLICATION PANEL =================
class ApplicationTypeSelect(Select):
    def __init__(self):
        super().__init__(
            placeholder="Choose an application type...",
            min_values=1,
            max_values=1,
            custom_id="hex_apply_select",
            options=[
                discord.SelectOption(
                    label="Staff Application",
                    value="staff",
                    emoji="๐Ÿ› ๏ธ",
                    description="Apply for staff - fill out form",
                ),
                discord.SelectOption(
                    label="Media Application",
                    value="media",
                    emoji="๐Ÿ“ธ",
                    description="Apply for media - fill out form",
                ),
                discord.SelectOption(
                    label="Builder Application",
                    value="builder",
                    emoji="๐Ÿ—๏ธ",
                    description="Apply for builder - private channel will be created",
                ),
            ],
        )

    async def callback(self, interaction: Interaction):
        value = self.values[0]

        if value == "staff":
            class StaffAppModal(Modal, title="DriftMC | Staff Application"):
                ign = TextInput(label="What's your IGN?", required=True, max_length=64)
                age = TextInput(label="How old are you?", required=True, max_length=10)
                why_choose = TextInput(
                    label="Why should we choose you?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                experience = TextInput(
                    label="Prior staff experience?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                ss_method = TextInput(
                    label="How do you Screen-Share (SS)?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )

                async def on_submit(self, inter: Interaction):
                    await send_application_to_review(
                        inter,
                        "staff",
                        [
                            ("1. What is your IGN?", self.ign.value),
                            ("2. How old are you?", self.age.value),
                            ("3. Why should we choose you over others?", self.why_choose.value),
                            ("4. What previous staff experience have you had?", self.experience.value),
                            ("5. How do you Screen-Share (SS) someone?", self.ss_method.value),
                        ],
                    )

            await interaction.response.send_modal(StaffAppModal())
            return

        if value == "media":
            class MediaAppModal(Modal, title="DriftMC | Media Application"):
                ign = TextInput(label="What is your IGN?", required=True, max_length=64)
                why_media = TextInput(
                    label="Why be a media in driftmc?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                why_choose = TextInput(
                    label="Why should we choose you?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                requirements = TextInput(
                    label="Do you meet the requirements?",
                    required=True,
                    max_length=100,
                )
                tiktok_link = TextInput(
                    label="Your TikTok link",
                    required=True,
                    max_length=200,
                )

                async def on_submit(self, inter: Interaction):
                    await send_application_to_review(
                        inter,
                        "media",
                        [
                            ("1. What is your IGN?", self.ign.value),
                            ("2. Why do you want to be a media in driftmc?", self.why_media.value),
                            ("3. Why should we choose you?", self.why_choose.value),
                            ("4. Do you meet the requirements?", self.requirements.value),
                            ("5. Send your TikTok link here!", self.tiktok_link.value),
                        ],
                    )

            await interaction.response.send_modal(MediaAppModal())
            return

        # builder
        await interaction.response.defer(ephemeral=True)

        guild = interaction.guild
        applicant = interaction.user

        if guild is None:
            await interaction.followup.send("โŒ Guild not found.", ephemeral=True)
            return

        category = guild.get_channel(APPLICATIONS_CATEGORY_ID)
        if not category or not isinstance(category, CategoryChannel):
            await interaction.followup.send("โŒ Applications category not found!", ephemeral=True)
            return

        for channel_id, app_data in list(active_builder_apps.items()):
            if app_data["applicant_id"] == applicant.id and app_data["status"] == "active":
                channel = guild.get_channel(channel_id)
                if channel:
                    await interaction.followup.send(
                        f"โŒ You already have an active builder application in {channel.mention}!",
                        ephemeral=True,
                    )
                else:
                    del active_builder_apps[channel_id]
                    await interaction.followup.send(
                        "โŒ You already have an active builder application.",
                        ephemeral=True,
                    )
                return

        overwrites = {
            guild.default_role: PermissionOverwrite(read_messages=False),
            applicant: PermissionOverwrite(
                read_messages=True,
                send_messages=True,
                attach_files=True,
                view_channel=True,
            ),
            guild.me: PermissionOverwrite(
                read_messages=True,
                send_messages=True,
                manage_messages=True,
                manage_channels=True,
                view_channel=True,
            ),
        }

        try:
            safe_name = "".join(c for c in applicant.name.lower() if c.isalnum() or c == "-")[:20]
            channel_name = f"builder-{safe_name or applicant.id}"

            channel = await guild.create_text_channel(
                name=channel_name,
                category=category,
                overwrites=overwrites,
                topic=f"Builder Application | Applicant: {applicant.id}",
            )

            active_builder_apps[channel.id] = {
                "applicant_id": applicant.id,
                "answers": {},
                "images": [],
                "status": "active",
                "questions_answered": False,
            }

            embed = Embed(
                title="๐Ÿ—๏ธ Builder Application Process",
                description=(
                    f"Welcome {applicant.mention} to your private builder application channel!\n\n"
                    "**Follow these steps:**\n"
                    "1. **Click '๐Ÿ“ Answer Questions' button below** to fill out the application form\n"
                    "2. **Attach your build images** in this channel (drag & drop)\n"
                    "3. **Click 'โœ… Submit Application' button** when ready\n\n"
                    "**Required:**\n"
                    "โ€ข Complete the question form\n"
                    "โ€ข Attach at least 3 build images\n"
                    "โ€ข Then submit your application"
                ),
                color=Color.blue(),
            )
            embed.set_footer(text="You have 24 hours to complete your application")

            view = BuilderChannelView(channel.id, applicant.id)
            await channel.send(content=applicant.mention, embed=embed, view=view)

            await interaction.followup.send(
                f"โœ… Builder application channel created: {channel.mention}\nGo there to complete your application!",
                ephemeral=True,
            )
        except Exception as e:
            await interaction.followup.send(f"โŒ Error creating channel: {str(e)}", ephemeral=True)
            print(f"Error creating builder channel: {e}")


class BuilderQuestionsModal(Modal, title="๐Ÿ—๏ธ Builder Application Questions"):
    ign = TextInput(
        label="What is your Minecraft IGN?",
        placeholder="Enter your Minecraft username",
        required=True,
        max_length=32,
    )

    building_time = TextInput(
        label="How long have you been building for?",
        placeholder="e.g., 2 years, 6 months, etc.",
        required=True,
        max_length=100,
    )

    prior_experience = TextInput(
        label="What's your prior building experience?",
        placeholder="Describe your previous building projects...",
        style=discord.TextStyle.long,
        required=True,
        max_length=500,
    )

    def __init__(self, channel_id: int):
        super().__init__(timeout=None)
        self.channel_id = channel_id

    async def on_submit(self, interaction: Interaction):
        guild = interaction.guild
        if guild is None:
            await interaction.response.send_message("โŒ Guild not found!", ephemeral=True)
            return

        channel = guild.get_channel(self.channel_id)
        if not channel:
            await interaction.response.send_message("โŒ Channel not found!", ephemeral=True)
            return

        if self.channel_id not in active_builder_apps:
            await interaction.response.send_message("โŒ Application not found!", ephemeral=True)
            return

        app_data = active_builder_apps[self.channel_id]

        app_data["answers"] = {
            "ign": self.ign.value,
            "building_time": self.building_time.value,
            "prior_experience": self.prior_experience.value,
        }
        app_data["questions_answered"] = True

        await channel.edit(
            topic=f"Builder Application | Applicant: {interaction.user.id} | IGN: {self.ign.value}"
        )

        await interaction.response.send_message(
            "โœ… **Questions submitted successfully!**\n\n"
            "**Next steps:**\n"
            "1. **Attach your build images** in this channel (drag & drop)\n"
            "2. **Click 'โœ… Submit Application' button** when ready\n\n"
            "**Remember:** You need at least 3 build images!",
            ephemeral=True,
        )

        exp_preview = self.prior_experience.value
        if len(exp_preview) > 200:
            exp_preview = exp_preview[:200] + "..."

        embed = Embed(
            title="๐Ÿ“ธ Attach Your Build Images",
            description=(
                f"โœ… {interaction.user.mention} has completed the questions!\n\n"
                "**Now please attach your build images:**\n"
                "โ€ข Drag and drop your build screenshots here\n"
                "โ€ข Minimum 3 images recommended\n"
                "โ€ข Show different angles and details\n"
                "โ€ข Images should showcase your best work\n\n"
                "**After attaching images, click the 'โœ… Submit Application' button below!**"
            ),
            color=Color.green(),
        )
        embed.add_field(
            name="Your Answers",
            value=(
                f"**IGN:** {self.ign.value}\n"
                f"**Building Time:** {self.building_time.value}\n"
                f"**Experience:** {exp_preview}"
            ),
            inline=False,
        )

        await channel.send(embed=embed)


class BuilderChannelView(View):
    def __init__(self, channel_id: int, applicant_id: int):
        super().__init__(timeout=None)
        self.channel_id = channel_id
        self.applicant_id = applicant_id

    @discord.ui.button(
        label="๐Ÿ“ Answer Questions",
        style=ButtonStyle.primary,
        emoji="โ“",
        custom_id="builder_questions",
    )
    async def answer_questions_button(self, interaction: Interaction, button: Button):
        if interaction.user.id != self.applicant_id:
            await interaction.response.send_message("โŒ This is not your application!", ephemeral=True)
            return

        if (
            self.channel_id in active_builder_apps
            and active_builder_apps[self.channel_id]["questions_answered"]
        ):
            answers = active_builder_apps[self.channel_id]["answers"]
            exp = answers.get("prior_experience", "Not set")
            if len(exp) > 100:
                exp = exp[:100] + "..."

            await interaction.response.send_message(
                f"โŒ You've already answered the questions!\n\n"
                f"**Your answers:**\n"
                f"โ€ข **IGN:** {answers.get('ign', 'Not set')}\n"
                f"โ€ข **Building Time:** {answers.get('building_time', 'Not set')}\n"
                f"โ€ข **Experience:** {exp}\n\n"
                "Please attach images and click 'Submit Application'!",
                ephemeral=True,
            )
            return

        modal = BuilderQuestionsModal(channel_id=self.channel_id)
        await interaction.response.send_modal(modal)

    @discord.ui.button(
        label="โœ… Submit Application",
        style=ButtonStyle.success,
        emoji="๐Ÿ“ค",
        custom_id="builder_submit",
    )
    async def submit_application_button(self, interaction: Interaction, button: Button):
        if interaction.user.id != self.applicant_id:
            await interaction.response.send_message("โŒ This is not your application!", ephemeral=True)
            return

        if self.channel_id not in active_builder_apps:
            await interaction.response.send_message("โŒ Application not found!", ephemeral=True)
            return

        app_data = active_builder_apps[self.channel_id]

        if not app_data["questions_answered"]:
            await interaction.response.send_message(
                "โŒ **Please answer the questions first!**\nClick the '๐Ÿ“ Answer Questions' button to fill out the form.",
                ephemeral=True,
            )
            return

        if len(app_data["images"]) == 0:
            await interaction.response.send_message(
                "โŒ **Please attach build images first!**\nDrag and drop your build screenshots in this channel before submitting.",
                ephemeral=True,
            )
            return

        if len(app_data["images"]) < 3:
            await interaction.response.send_message(
                f"โš ๏ธ **Only {len(app_data['images'])} image(s) attached!**\nWe recommend at least 3 build images. Submit anyway?",
                view=ConfirmSubmitView(self.channel_id),
                ephemeral=True,
            )
            return

        await interaction.response.defer(ephemeral=True)
        await submit_builder_application(interaction, self.channel_id, app_data)

    @discord.ui.button(
        label="๐Ÿ–ผ๏ธ View Attached Images",
        style=ButtonStyle.secondary,
        emoji="๐Ÿ“ท",
        custom_id="builder_view_images",
    )
    async def view_images_button(self, interaction: Interaction, button: Button):
        if interaction.user.id != self.applicant_id:
            await interaction.response.send_message("โŒ This is not your application!", ephemeral=True)
            return

        if self.channel_id not in active_builder_apps:
            await interaction.response.send_message("โŒ Application not found!", ephemeral=True)
            return

        app_data = active_builder_apps[self.channel_id]
        if len(app_data["images"]) == 0:
            await interaction.response.send_message("โŒ No images attached yet!", ephemeral=True)
            return

        embed = Embed(
            title=f"๐Ÿ“ธ Your Attached Images ({len(app_data['images'])} total)",
            description="**Image Preview:**",
            color=Color.blue(),
        )

        for i, img_url in enumerate(app_data["images"][:5], 1):
            embed.add_field(name=f"Image {i}", value=f"[Click to view]({img_url})", inline=True)

        if len(app_data["images"]) > 5:
            embed.set_footer(text=f"And {len(app_data['images']) - 5} more images...")

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @discord.ui.button(
        label="โŒ Cancel",
        style=ButtonStyle.danger,
        emoji="๐Ÿ—‘๏ธ",
        custom_id="builder_cancel",
    )
    async def cancel_application(self, interaction: Interaction, button: Button):
        if interaction.user.id != self.applicant_id:
            await interaction.response.send_message("โŒ This is not your application!", ephemeral=True)
            return

        embed = Embed(
            title="โš ๏ธ Confirm Cancellation",
            description="Are you sure you want to cancel your builder application? This cannot be undone!",
            color=Color.red(),
        )

        view = ConfirmCancelView(self.channel_id, self.applicant_id)
        await interaction.response.send_message(embed=embed, view=view, ephemeral=True)


class ConfirmSubmitView(View):
    def __init__(self, channel_id: int):
        super().__init__(timeout=60)
        self.channel_id = channel_id

    @discord.ui.button(label="โœ… Yes, Submit Anyway", style=ButtonStyle.success)
    async def confirm_submit(self, interaction: Interaction, button: Button):
        if self.channel_id not in active_builder_apps:
            await interaction.response.send_message("โŒ Application not found!", ephemeral=True)
            return

        app_data = active_builder_apps[self.channel_id]
        if interaction.user.id != app_data["applicant_id"]:
            await interaction.response.send_message("โŒ This is not your application!", ephemeral=True)
            return

        await interaction.response.defer(ephemeral=True)
        await submit_builder_application(interaction, self.channel_id, app_data)

    @discord.ui.button(label="โŒ No, Add More Images", style=ButtonStyle.secondary)
    async def deny_submit(self, interaction: Interaction, button: Button):
        await interaction.response.send_message("โœ… Add more images before submitting!", ephemeral=True)


class ConfirmCancelView(View):
    def __init__(self, channel_id: int, applicant_id: int):
        super().__init__(timeout=60)
        self.channel_id = channel_id
        self.applicant_id = applicant_id

    @discord.ui.button(label="โœ… Yes, Cancel", style=ButtonStyle.danger, emoji="๐Ÿ—‘๏ธ")
    async def confirm_cancel(self, interaction: Interaction, button: Button):
        if interaction.user.id != self.applicant_id:
            await interaction.response.send_message("โŒ This is not your application!", ephemeral=True)
            return

        channel = interaction.guild.get_channel(self.channel_id) if interaction.guild else None

        if self.channel_id in active_builder_apps:
            del active_builder_apps[self.channel_id]

        if channel:
            try:
                await channel.delete()
            except Exception as e:
                await interaction.response.send_message(
                    f"โŒ Failed to delete channel: {e}",
                    ephemeral=True,
                )
                return

        await interaction.response.send_message(
            "โœ… Your builder application has been cancelled and the channel deleted.",
            ephemeral=True,
        )

    @discord.ui.button(label="โŒ No, Keep", style=ButtonStyle.secondary)
    async def deny_cancel(self, interaction: Interaction, button: Button):
        await interaction.response.send_message(
            "โœ… Application kept! Continue with your application.",
            ephemeral=True,
        )


class ApplicationPanelView(View):
    def __init__(self):
        super().__init__(timeout=None)
        self.add_item(ApplicationTypeSelect())


# ================= IMAGE HANDLER FOR BUILDER CHANNELS =================
@bot.event
async def on_message(message: discord.Message):
    if message.author.bot:
        await bot.process_commands(message)
        return

    if message.channel.id in active_builder_apps:
        app_data = active_builder_apps[message.channel.id]

        if message.author.id == app_data["applicant_id"]:
            if message.attachments:
                image_attachments = [
                    att for att in message.attachments
                    if att.content_type and att.content_type.startswith("image/")
                ]

                for attachment in image_attachments:
                    if attachment.url not in app_data["images"]:
                        app_data["images"].append(attachment.url)

                if image_attachments:
                    try:
                        await message.add_reaction("๐Ÿ“ธ")
                    except Exception:
                        pass

                    await message.channel.send(
                        f"โœ… {message.author.mention} added **{len(image_attachments)} build image(s)**!\n"
                        f"**Total images:** {len(app_data['images'])}"
                    )

                    channel = message.channel
                    try:
                        async for msg in channel.history(limit=15):
                            if msg.author.id == bot.user.id and msg.embeds:
                                embed = msg.embeds[0]
                                if embed.title and "Attach Your Build Images" in embed.title:
                                    new_embed = Embed(
                                        title="๐Ÿ“ธ Attach Your Build Images",
                                        description=(
                                            f"โœ… {message.author.mention} has completed the questions!\n\n"
                                            f"**Attached images so far:** {len(app_data['images'])}\n"
                                            "โ€ข Drag and drop more build screenshots here\n"
                                            "โ€ข Minimum 3 images recommended\n"
                                            "โ€ข Show different angles and details\n\n"
                                            "**When ready, click the 'โœ… Submit Application' button below!**"
                                        ),
                                        color=Color.green(),
                                    )

                                    if "answers" in app_data:
                                        exp = app_data["answers"].get("prior_experience", "Not set")
                                        if len(exp) > 200:
                                            exp = exp[:200] + "..."

                                        new_embed.add_field(
                                            name="Your Answers",
                                            value=(
                                                f"**IGN:** {app_data['answers'].get('ign', 'Not set')}\n"
                                                f"**Building Time:** {app_data['answers'].get('building_time', 'Not set')}\n"
                                                f"**Experience:** {exp}"
                                            ),
                                            inline=False,
                                        )

                                    await msg.edit(embed=new_embed)
                                    break
                    except Exception:
                        pass

    await bot.process_commands(message)


# ================= BUILDER SUBMIT =================
async def submit_builder_application(interaction: Interaction, channel_id: int, app_data: dict):
    channel = interaction.guild.get_channel(channel_id) if interaction.guild else None
    if not channel:
        await interaction.followup.send("โŒ Channel not found!", ephemeral=True)
        return

    guild = interaction.guild
    if guild is None:
        await interaction.followup.send("โŒ Guild not found!", ephemeral=True)
        return

    review_channel = guild.get_channel(BUILDER_REVIEW_CHANNEL_ID)
    if not review_channel or not isinstance(review_channel, TextChannel):
        await channel.send("โŒ Builder review channel not found! Contact admin.")
        return

    embed = Embed(
        title="๐Ÿ—๏ธ New Builder Application",
        color=Color.blue(),
        timestamp=datetime.utcnow(),
    )

    applicant = guild.get_member(app_data["applicant_id"])
    applicant_name = f"{applicant.name}#{applicant.discriminator}" if applicant else "Unknown#0000"

    embed.add_field(
        name="๐Ÿ‘ค Applicant",
        value=f"{applicant.mention if applicant else 'Unknown'}\n{applicant_name}",
        inline=True,
    )
    embed.add_field(name="๐Ÿ†” User ID", value=f"`{app_data['applicant_id']}`", inline=True)
    embed.add_field(
        name="๐Ÿ“… Applied",
        value=f"",
        inline=True,
    )

    answers = app_data.get("answers", {})
    embed.add_field(name="๐ŸŽฎ Minecraft IGN", value=answers.get("ign", "Not provided"), inline=True)
    embed.add_field(name="โฐ Building Time", value=answers.get("building_time", "Not provided"), inline=True)

    prior_exp = answers.get("prior_experience", "Not provided")
    if len(prior_exp) > 400:
        prior_exp = prior_exp[:400] + "..."
    embed.add_field(name="๐Ÿ“š Prior Experience", value=prior_exp, inline=False)

    if app_data["images"]:
        embed.add_field(
            name="๐Ÿ–ผ๏ธ Build Images",
            value=f"**{len(app_data['images'])} image(s) attached** - See below",
            inline=True,
        )
    else:
        embed.add_field(
            name="โš ๏ธ WARNING",
            value="**NO BUILD IMAGES ATTACHED!**",
            inline=False,
        )

    if applicant:
        embed.set_thumbnail(url=applicant.display_avatar.url)

    embed.set_footer(text=f"Application ID: {channel.id}")

    view = ApplicationReviewView(
        applicant_id=app_data["applicant_id"],
        app_type="builder",
        review_channel_id=BUILDER_REVIEW_CHANNEL_ID,
        announce_channel_id=BUILDER_ANNOUNCE_CHANNEL_ID,
        application_channel_id=channel.id,
    )

    ping_mentions = ""
    for role_id in BUILDER_REVIEW_ROLE_IDS:
        role = guild.get_role(role_id)
        if role:
            ping_mentions += f"{role.mention} "

    review_msg = await review_channel.send(
        content=f"{ping_mentions.strip()} **New Builder Application!**" if ping_mentions else "**New Builder Application!**",
        embed=embed,
        view=view,
    )

    view.review_message_id = review_msg.id

    if app_data["images"]:
        images_embed = Embed(
            title="๐Ÿ—๏ธ Builder Portfolio Images",
            description=f"Build images from {applicant.mention if applicant else 'applicant'}'s application",
            color=Color.green(),
        )
        images_embed.set_footer(text=f"Total images: {len(app_data['images'])}")
        await review_channel.send(embed=images_embed)

        for i, image_url in enumerate(app_data["images"][:10], 1):
            try:
                embed_img = Embed(color=Color.blue())
                embed_img.set_image(url=image_url)
                embed_img.set_footer(text=f"Image {i} of {len(app_data['images'])}")
                await review_channel.send(embed=embed_img)
            except Exception:
                pass

    await channel.send(
        "โœ… **Application Submitted Successfully!**\n"
        f"Your application has been sent for review to {review_channel.mention}\n"
        "This channel will close in 10 seconds..."
    )

    await asyncio.sleep(10)

    try:
        await channel.delete()
    except Exception:
        pass

    if channel.id in active_builder_apps:
        del active_builder_apps[channel.id]

    await interaction.followup.send(
        "โœ… Your builder application has been submitted for review!",
        ephemeral=True,
    )


# ================= STAFF & MEDIA APPLICATIONS =================
async def send_application_to_review(interaction: Interaction, app_type: str, qa: list[tuple[str, str]]):
    if interaction.guild is None:
        await interaction.response.send_message("โŒ Guild not found!", ephemeral=True)
        return

    if app_type == "staff":
        review_channel_id = STAFF_REVIEW_CHANNEL_ID
        review_role_id = STAFF_REVIEW_ROLE_ID
        announce_channel_id = STAFF_ANNOUNCE_CHANNEL_ID
        title = "DriftMC | Staff Application"
    elif app_type == "media":
        review_channel_id = MEDIA_REVIEW_CHANNEL_ID
        review_role_id = MEDIA_REVIEW_ROLE_ID
        announce_channel_id = MEDIA_ANNOUNCE_CHANNEL_ID
        title = "DriftMC | Media Application"
    else:
        await interaction.response.send_message("โŒ Invalid application type.", ephemeral=True)
        return

    review_channel = interaction.guild.get_channel(review_channel_id)
    if not review_channel or not isinstance(review_channel, TextChannel):
        await interaction.response.send_message("โŒ Review channel not found!", ephemeral=True)
        return

    embed = Embed(
        title=f"๐Ÿ“„ {title}",
        color=Color.blue(),
        timestamp=datetime.utcnow(),
    )

    embed.add_field(
        name="๐Ÿ‘ค Applicant",
        value=f"{interaction.user.mention}\n{interaction.user.name}#{interaction.user.discriminator}",
        inline=True,
    )
    embed.add_field(name="๐Ÿ†” User ID", value=f"`{interaction.user.id}`", inline=True)
    embed.add_field(
        name="๐Ÿ“… Applied",
        value=f"",
        inline=True,
    )

    for q, a in qa:
        embed.add_field(name=q, value=a or "โ€”", inline=False)

    embed.set_thumbnail(url=interaction.user.display_avatar.url)
    embed.set_footer(text=f"Application ID: {interaction.id}")

    view = ApplicationReviewView(
        applicant_id=interaction.user.id,
        app_type=app_type,
        review_channel_id=review_channel_id,
        announce_channel_id=announce_channel_id,
        application_channel_id=None,
    )

    role = interaction.guild.get_role(review_role_id)
    ping_mentions = f"{role.mention}" if role else ""

    if ping_mentions:
        review_msg = await review_channel.send(
            content=f"{ping_mentions} **New Application for Review!**",
            embed=embed,
            view=view,
        )
    else:
        review_msg = await review_channel.send(embed=embed, view=view)

    view.review_message_id = review_msg.id

    await interaction.response.send_message(
        f"โœ… Your {app_type} application has been submitted! Our team will review it soon.",
        ephemeral=True,
    )


# ================= APPLICATION REVIEW VIEW =================
class ApplicationReviewView(View):
    def __init__(
        self,
        applicant_id: int,
        app_type: str,
        review_channel_id: int,
        announce_channel_id: int,
        application_channel_id: int | None = None,
    ):
        super().__init__(timeout=None)
        self.applicant_id = applicant_id
        self.app_type = app_type
        self.review_channel_id = review_channel_id
        self.announce_channel_id = announce_channel_id
        self.application_channel_id = application_channel_id
        self.review_message_id = None

        if applicant_id and app_type and review_channel_id:
            self.add_item(
                Button(
                    label="โœ… Accept",
                    style=ButtonStyle.success,
                    custom_id=f"app_accept:{applicant_id}:{app_type}:{review_channel_id}",
                )
            )
            self.add_item(
                Button(
                    label="โŒ Deny",
                    style=ButtonStyle.danger,
                    custom_id=f"app_deny:{applicant_id}:{app_type}:{review_channel_id}",
                )
            )


class DenyReasonModal(Modal, title="Deny Application - Reason Required"):
    reason = TextInput(
        label="Reason for denial",
        placeholder="Please provide constructive feedback for the applicant...",
        style=discord.TextStyle.long,
        required=True,
        max_length=1000,
    )

    def __init__(self, review_view: ApplicationReviewView, reviewer: discord.Member):
        super().__init__(timeout=None)
        self.review_view = review_view
        self.reviewer = reviewer

    async def on_submit(self, interaction: Interaction):
        await interaction.response.defer(ephemeral=True)

        guild = interaction.guild
        if guild is None:
            await interaction.followup.send("โŒ Guild not found.", ephemeral=True)
            return

        applicant = guild.get_member(self.review_view.applicant_id)
        announce_channel = guild.get_channel(self.review_view.announce_channel_id)

        try:
            review_channel = guild.get_channel(self.review_view.review_channel_id)
            if review_channel and self.review_view.review_message_id:
                review_msg = await review_channel.fetch_message(self.review_view.review_message_id)
                await review_msg.edit(view=None)
        except Exception:
            pass

        if self.review_view.application_channel_id:
            app_channel = guild.get_channel(self.review_view.application_channel_id)
            if app_channel:
                try:
                    await app_channel.delete()
                except Exception:
                    pass

            if self.review_view.application_channel_id in active_builder_apps:
                del active_builder_apps[self.review_view.application_channel_id]

        if announce_channel and isinstance(announce_channel, TextChannel):
            embed = Embed(
                title=f"โŒ {self.review_view.app_type.capitalize()} Application Denied",
                color=Color.red(),
                timestamp=datetime.utcnow(),
            )

            embed.set_author(
                name=f"Reviewed by {self.reviewer.display_name}",
                icon_url=self.reviewer.display_avatar.url,
            )

            if applicant:
                embed.add_field(name="๐Ÿ‘ค Applicant", value=applicant.mention, inline=True)

            embed.add_field(
                name="๐Ÿ“‹ Position",
                value=self.review_view.app_type.capitalize(),
                inline=True,
            )
            embed.add_field(name="๐Ÿ“Š Status", value="Denied", inline=True)
            embed.add_field(name="๐Ÿ“ Reason", value=self.reason.value, inline=False)

            await announce_channel.send(embed=embed)

        if applicant:
            try:
                dm_embed = Embed(
                    title=f"๐Ÿ“ฌ {self.review_view.app_type.capitalize()} Application Update",
                    description="Your application has been reviewed.",
                    color=Color.red(),
                    timestamp=datetime.utcnow(),
                )
                dm_embed.add_field(name="Decision", value="โŒ **Denied**", inline=True)
                dm_embed.add_field(
                    name="Position",
                    value=self.review_view.app_type.capitalize(),
                    inline=True,
                )
                dm_embed.add_field(name="Reason", value=self.reason.value, inline=False)
                dm_embed.set_footer(text="You may reapply after addressing the feedback above")
                await applicant.send(embed=dm_embed)
            except Exception:
                pass

        await interaction.followup.send(
            f"โœ… Application denied. Announcement posted in {announce_channel.mention if announce_channel else 'announcement channel'}.",
            ephemeral=True,
        )


# ================= UPDATE COMMAND =================
class UpdateModal(Modal, title="๐Ÿ“ข Create Update Announcement"):
    def __init__(self) -> None:
        super().__init__(timeout=None)

        self.whats_added = TextInput(
            label="โœจ What's Added",
            placeholder="List new features, items, or content...",
            style=discord.TextStyle.long,
            required=True,
            max_length=1024,
        )

        self.whats_changed = TextInput(
            label="โš™๏ธ What's Changed",
            placeholder="List improvements, fixes, or modifications...",
            style=discord.TextStyle.long,
            required=True,
            max_length=1024,
        )

        self.whats_removed = TextInput(
            label="๐Ÿ—‘๏ธ What's Removed",
            placeholder="List removed features, items, or content...",
            style=discord.TextStyle.long,
            required=True,
            max_length=1024,
        )

        self.add_item(self.whats_added)
        self.add_item(self.whats_changed)
        self.add_item(self.whats_removed)

    async def on_submit(self, interaction: Interaction) -> None:
        await interaction.response.defer(ephemeral=True)

        if interaction.guild is None:
            await interaction.followup.send("โŒ Guild not found.", ephemeral=True)
            return

        update_channel = interaction.guild.get_channel(UPDATE_CHANNEL_ID)

        if not update_channel or not isinstance(update_channel, discord.TextChannel):
            await interaction.followup.send(
                "โŒ Update channel not found or invalid. Please check the configuration.",
                ephemeral=True,
            )
            return

        embed = Embed(
            title="๐Ÿ†• **DRIFTMC UPDATE** ๐Ÿ†•",
            color=Color.blurple(),
            timestamp=datetime.utcnow(),
        )

        embed.set_author(
            name=f"Announced by {interaction.user.display_name}",
            icon_url=interaction.user.display_avatar.url,
        )

        embed.description = (
            "๐ŸŒŸ **Exciting news from the DriftMC team!** ๐ŸŒŸ\n"
            "We've just rolled out some updates to enhance your gaming experience!\n"
        )

        embed.add_field(
            name="โœจ **WHAT'S ADDED**",
            value=self.whats_added.value or "*No new additions*",
            inline=False,
        )
        embed.add_field(
            name="โš™๏ธ **WHAT'S CHANGED**",
            value=self.whats_changed.value or "*No changes*",
            inline=False,
        )
        embed.add_field(
            name="๐Ÿ—‘๏ธ **WHAT'S REMOVED**",
            value=self.whats_removed.value or "*Nothing removed*",
            inline=False,
        )

        current_time = datetime.utcnow()
        embed.set_footer(
            text=f"DriftMC Update โ€ข {current_time.strftime('%B %d, %Y โ€ข %I:%M %p')}"
        )

        try:
            await update_channel.send(embed=embed)

            await interaction.followup.send(
                f"โœ… Update announcement posted in {update_channel.mention}!",
                ephemeral=True,
            )

            await send_log(
                interaction.guild,
                "commands",
                f"๐Ÿ“ข **{interaction.user}** posted an update announcement in {update_channel.mention}",
            )
        except Exception as e:
            await interaction.followup.send(
                f"โŒ Failed to post update: {str(e)}",
                ephemeral=True,
            )


@bot.command(name="update")
@commands.has_permissions(administrator=True)
async def update_command(ctx: commands.Context):
    modal = UpdateModal()
    try:
        await ctx.send("๐Ÿ“ Opening update creation form...", delete_after=3)
    except Exception:
        pass

    try:
        await ctx.message.delete()
    except Exception:
        pass

    class UpdateButtonView(View):
        def __init__(self):
            super().__init__(timeout=60)

        @discord.ui.button(label="๐Ÿ“ Create Update", style=ButtonStyle.primary, emoji="๐Ÿ“ข")
        async def open_update_modal(self, button_interaction: Interaction, button: Button):
            if button_interaction.user.id == ctx.author.id:
                await button_interaction.response.send_modal(modal)
            else:
                await button_interaction.response.send_message(
                    "โŒ Only the command author can create updates.",
                    ephemeral=True,
                )

    await ctx.send(
        f"{ctx.author.mention}, click the button below to create your update announcement:",
        view=UpdateButtonView(),
        delete_after=60,
    )


# ================= INTERACTION HANDLER =================
@bot.event
async def on_interaction(interaction: Interaction):
    if interaction.type == discord.InteractionType.component:
        custom_id = interaction.data.get("custom_id", "")

        if custom_id.startswith("app_accept:"):
            try:
                _, applicant_id_str, app_type, review_channel_id_str = custom_id.split(":")
                applicant_id = int(applicant_id_str)
                review_channel_id = int(review_channel_id_str)
            except ValueError:
                return

            await interaction.response.defer(ephemeral=True)

            guild = interaction.guild
            if guild is None:
                await interaction.followup.send("โŒ Guild not found.", ephemeral=True)
                return

            applicant = guild.get_member(applicant_id)

            if app_type == "staff":
                announce_channel_id = STAFF_ANNOUNCE_CHANNEL_ID
            elif app_type == "media":
                announce_channel_id = MEDIA_ANNOUNCE_CHANNEL_ID
            else:
                announce_channel_id = BUILDER_ANNOUNCE_CHANNEL_ID

            try:
                await interaction.message.edit(view=None)
            except Exception:
                pass

            if app_type == "builder":
                # Clean up any remaining active builder app for this user
                for channel_id, app_data in list(active_builder_apps.items()):
                    if app_data["applicant_id"] == applicant_id:
                        del active_builder_apps[channel_id]

            announce_channel = guild.get_channel(announce_channel_id)

            if announce_channel and isinstance(announce_channel, TextChannel):
                embed = Embed(
                    title=f"๐ŸŽ‰ {app_type.capitalize()} Application Accepted",
                    color=Color.green(),
                    timestamp=datetime.utcnow(),
                )

                embed.set_author(
                    name=f"Reviewed by {interaction.user.display_name}",
                    icon_url=interaction.user.display_avatar.url,
                )

                if applicant:
                    embed.add_field(name="๐Ÿ‘ค Applicant", value=applicant.mention, inline=True)

                embed.add_field(name="๐Ÿ“‹ Position", value=app_type.capitalize(), inline=True)
                embed.add_field(name="๐Ÿ“Š Status", value="Accepted", inline=True)
                embed.add_field(
                    name="\u200b",
                    value="**Congratulations!** ๐ŸŽŠ\nWelcome to the team!",
                    inline=False,
                )

                await announce_channel.send(embed=embed)

            if applicant:
                try:
                    dm_embed = Embed(
                        title=f"๐ŸŽ‰ {app_type.capitalize()} Application Accepted!",
                        description=f"Congratulations! Your {app_type} application has been **accepted**!",
                        color=Color.green(),
                        timestamp=datetime.utcnow(),
                    )
                    dm_embed.add_field(
                        name="Next Steps",
                        value="A staff member will contact you shortly with onboarding instructions.",
                        inline=False,
                    )
                    dm_embed.set_footer(text="Welcome to the team! ๐ŸŽŠ")
                    await applicant.send(embed=dm_embed)
                except Exception:
                    pass

            await interaction.followup.send(
                f"โœ… Application accepted! Announcement posted in {announce_channel.mention if announce_channel else 'announcement channel'}.",
                ephemeral=True,
            )

        elif custom_id.startswith("app_deny:"):
            try:
                _, applicant_id_str, app_type, review_channel_id_str = custom_id.split(":")
                applicant_id = int(applicant_id_str)
                review_channel_id = int(review_channel_id_str)
            except ValueError:
                return

            if app_type == "staff":
                announce_channel_id = STAFF_ANNOUNCE_CHANNEL_ID
            elif app_type == "media":
                announce_channel_id = MEDIA_ANNOUNCE_CHANNEL_ID
            else:
                announce_channel_id = BUILDER_ANNOUNCE_CHANNEL_ID

            application_channel_id = None
            if app_type == "builder":
                for channel_id, app_data in list(active_builder_apps.items()):
                    if app_data["applicant_id"] == applicant_id:
                        application_channel_id = channel_id
                        break

            review_view = ApplicationReviewView(
                applicant_id=applicant_id,
                app_type=app_type,
                review_channel_id=review_channel_id,
                announce_channel_id=announce_channel_id,
                application_channel_id=application_channel_id,
            )
            review_view.review_message_id = interaction.message.id

            modal = DenyReasonModal(review_view, interaction.user)
            await interaction.response.send_modal(modal)

    await bot.process_application_commands(interaction)


# ================= BOT EVENTS =================
@bot.event
async def on_ready():
    print(f"Bot is online as {bot.user}")

    bot.add_view(ApplicationPanelView())

    await ensure_application_panel()

    print("Application system ready!")


async def ensure_application_panel():
    channel = bot.get_channel(APPLY_PANEL_CHANNEL_ID)
    if not isinstance(channel, TextChannel):
        print(f"Application panel channel not found: {APPLY_PANEL_CHANNEL_ID}")
        return

    embed = Embed(
        title="๐Ÿ“ฅ DriftMC Applications",
        description=(
            "## ๐Ÿ› ๏ธ DriftMC Applications\n\n"
            "### ๐Ÿ› ๏ธ | Staff\n"
            "**Requirements**\n"
            "> - You have to be atleast 14 years old.\n"
            "> - Must have previous experience on servers.\n"
            "> - Know how to SS by Process Hacker & Easy Journal Viewer.\n"
            "> - You need to play on Java Edition.\n\n"
            "### ๐Ÿ“ธ | Media\n"
            "**Requirements**\n"
            "> - Must have atleast 700 views on a driftmc clip.\n"
            "> - Your videoclip must have the server IP at the end or the start.\n"
            "> - Must have a kinda active channel.\n"
            "> - You have to post atleast 1 clip of driftmc.\n\n"
            "### ๐Ÿ—๏ธ | Builder\n"
            "**Requirements**\n"
            "> - Must have at least 3 previous builds to show\n"
            "> - Knowledge of WorldEdit/VoxelSniper\n"
            "> - Creative and detail-oriented\n"
            "> - **MUST SUBMIT IMAGES OF YOUR BUILDS**"
        ),
        color=Color.blurple(),
    )

    embed.add_field(
        name="๐Ÿ“‹ How to Apply",
        value=(
            "**Staff/Media:** Select below and fill out the form\n"
            "**Builder:** Select below - a private channel will be created for your application"
        ),
        inline=False,
    )

    embed.set_footer(text="Our team will review your application within 24-48 hours")

    try:
        async for msg in channel.history(limit=50):
            if msg.author.id == bot.user.id and msg.embeds:
                e0 = msg.embeds[0]
                if e0.title and "Applications" in e0.title:
                    await msg.edit(embed=embed, view=ApplicationPanelView())
                    print(f"Updated application panel in #{channel.name}")
                    return
    except Exception as e:
        print(f"Failed checking existing panel: {e}")

    try:
        await channel.send(embed=embed, view=ApplicationPanelView())
        print(f"Posted application panel to #{channel.name}")
    except Exception as e:
        print(f"Failed to post application panel: {e}")


# ================= START BOT =================
if __name__ == "__main__":
    if not TOKEN:
        raise ValueError("DISCORD_TOKEN is missing. Set it as an environment variable before starting the bot.")

    bot.run()
Kodari AI
KodariMar 31 at 6:31 pm 27,649 (v2)

Iโ€™ll set up this Discord bot application system properly with correct token handling and file structure.

Iโ€™ll create the Discord bot with proper security and file structure. The main issues in your code are:

  • Token exposed directly in code (security risk)

  • Incorrect os.getenv() usage

  • Wrong bot.run() call

โœ… Discord bot setup complete!

Fixed issues:

  • Token now properly loaded from .env file using os.getenv("DISCORD_TOKEN")

  • Removed hardcoded token from code (security risk)

  • Fixed bot.run() to use the TOKEN variable

  • Added python-dotenv dependency

  • Created .gitignore to protect your token

To run:

Shell
pip install -r requirements.txt
python bot.py

โš ๏ธ IMPORTANT: Your token is now exposed. You should:

  1. Go to Discord Developer Portal

  2. Regenerate your bot token immediately

  3. Update the token in .env file

  4. Never share your .env file

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
requirements.txt
Code
3 1,324
bot.py
import os
import asyncio
from datetime import datetime

import discord
from discord import (
    ButtonStyle,
    Color,
    Embed,
    Interaction,
    TextChannel,
    CategoryChannel,
    PermissionOverwrite,
)
from discord.ext import commands
from discord.ui import Button, Select, TextInput, View, Modal
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.getenv("DISCORD_TOKEN")

PREFIX = "!"
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix=PREFIX, intents=intents)

GUILD_ID = 1444657552477392988
UPDATE_CHANNEL_ID = 0

APPLY_PANEL_CHANNEL_ID = 1445436817955623244
APPLICATIONS_CATEGORY_ID = 1444657553291350016

STAFF_REVIEW_CHANNEL_ID = 1445439637450522625
MEDIA_REVIEW_CHANNEL_ID = 1445439637450522625
BUILDER_REVIEW_CHANNEL_ID = 1445439637450522625

STAFF_ANNOUNCE_CHANNEL_ID = 1445436901057106102
MEDIA_ANNOUNCE_CHANNEL_ID = 1445436901057106102
BUILDER_ANNOUNCE_CHANNEL_ID = 1445436901057106102

STAFF_REVIEW_ROLE_ID = 1336335303824380034
MEDIA_REVIEW_ROLE_ID = 1392669793965969488
BUILDER_REVIEW_ROLE_IDS = [1312096582111465513, 1358442574192316467, 1383473486609121411]

active_builder_apps = {}

async def send_log(guild: discord.Guild, category: str, message: str):
    print(f"[{category.upper()}] {guild.name if guild else 'Unknown Guild'}: {message}")


class ApplicationTypeSelect(Select):
    def __init__(self):
        super().__init__(
            placeholder="Choose an application type...",
            min_values=1,
            max_values=1,
            custom_id="hex_apply_select",
            options=[
                discord.SelectOption(
                    label="Staff Application",
                    value="staff",
                    emoji="๐Ÿ› ๏ธ",
                    description="Apply for staff - fill out form",
                ),
                discord.SelectOption(
                    label="Media Application",
                    value="media",
                    emoji="๐Ÿ“ธ",
                    description="Apply for media - fill out form",
                ),
                discord.SelectOption(
                    label="Builder Application",
                    value="builder",
                    emoji="๐Ÿ—๏ธ",
                    description="Apply for builder - private channel will be created",
                ),
            ],
        )

    async def callback(self, interaction: Interaction):
        value = self.values[0]

        if value == "staff":
            class StaffAppModal(Modal, title="DriftMC | Staff Application"):
                ign = TextInput(label="What's your IGN?", required=True, max_length=64)
                age = TextInput(label="How old are you?", required=True, max_length=10)
                why_choose = TextInput(
                    label="Why should we choose you?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                experience = TextInput(
                    label="Prior staff experience?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                ss_method = TextInput(
                    label="How do you Screen-Share (SS)?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )

                async def on_submit(self, inter: Interaction):
                    await send_application_to_review(
                        inter,
                        "staff",
                        [
                            ("1. What is your IGN?", self.ign.value),
                            ("2. How old are you?", self.age.value),
                            ("3. Why should we choose you over others?", self.why_choose.value),
                            ("4. What previous staff experience have you had?", self.experience.value),
                            ("5. How do you Screen-Share (SS) someone?", self.ss_method.value),
                        ],
                    )

            await interaction.response.send_modal(StaffAppModal())
            return

        if value == "media":
            class MediaAppModal(Modal, title="DriftMC | Media Application"):
                ign = TextInput(label="What is your IGN?", required=True, max_length=64)
                why_media = TextInput(
                    label="Why be a media in driftmc?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                why_choose = TextInput(
                    label="Why should we choose you?",
                    style=discord.TextStyle.long,
                    required=True,
                    max_length=500,
                )
                requirements = TextInput(
                    label="Do you meet the requirements?",
                    required=True,
                    max_length=100,
                )
                tiktok_link = TextInput(
                    label="Your TikTok link",
                    required=True,
                    max_length=200,
                )

                async def on_submit(self, inter: Interaction):
                    await send_application_to_review(
                        inter,
                        "media",
                        [
                            ("1. What is your IGN?", self.ign.value),
                            ("2. Why do you want to be a media in driftmc?", self.why_media.value),
                            ("3. Why should we choose you?", self.why_choose.value),
                            ("4. Do you meet the requirements?", self.requirements.value),
                            ("5. Send your TikTok link here!", self.tiktok_link.value),
                        ],
                    )

            await interaction.response.send_modal(MediaAppModal())
            return

        await interaction.response.defer(ephemeral=True)

        guild = interaction.guild
        applicant = interaction.user

        if guild is None:
            await interaction.followup.send("โŒ Guild not found.", ephemeral=True)
            return

        category = guild.get_channel(APPLICATIONS_CATEGORY_ID)
        if not category or not isinstance(category, CategoryChannel):
            await interaction.followup.send("โŒ Applications category not found!", ephemeral=True)
            return

        for channel_id, app_data in list(active_builder_apps.items()):
            if app_data["applicant_id"] == applicant.id and app_data["status"] == "active":
                channel = guild.get_channel(channel_id)
                if channel:
                    await interaction.followup.send(
                        f"โŒ You already have an active builder application in {channel.mention}!",
                        ephemeral=True,
                    )
                else:
                    del active_builder_apps[channel_id]
                    await interaction.followup.send(
                        "โŒ You already have an active builder application.",
                        ephemeral=True,
                    )
                return

        overwrites = {
            guild.default_role: PermissionOverwrite(read_messages=False),
            applicant: PermissionOverwrite(
                read_messages=True,
                send_messages=True,