⚠️ Security Alert: Bot Token Exposure
Your bot token is currently exposed in the code you provided:
bot.run('MTI5MTQ2ODMyNTk4MDg2ODcyMA.GRP1jU.mbMMiUIUSJd_bb9_PK6_laSnrja_r4LzUNOuTM') # Replace with your actual bot token
Immediate Action Required:
-
Revoke the Exposed Token Immediately:
- Go to the Discord Developer Portal.
- Select your application.
- Navigate to the "Bot" section.
- Click on "Regenerate" to obtain a new token.
-
Secure Your New Token:
- Never share your bot token publicly or commit it to version control systems like GitHub.
- Consider using environment variables or a separate configuration file to store sensitive information.
Improved Bot Code with [Dev] Prefix for Developer Names
Below is the enhanced version of your bot code with the following improvements:
-
Security Enhancements:
- Removed the hardcoded bot token.
- Added suggestions for secure token management.
-
Code Improvements:
- Enhanced error handling and logging.
- Optimized the
relay_message function to prepend [Dev] to developer names, displaying their server nicknames.
- Refactored repetitive code into reusable functions for better maintainability.
- Added type hints for better code clarity.
-
Feature Enhancement:
- Developer names in relayed messages are now prefixed with
[Dev] followed by their server nickname (e.g., [Dev] JohnDoe).
Updated Code
import discord
from discord import app_commands
from discord.ext import commands
import json
import emoji
import asyncio
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO)
# Ensure you set your bot token as an environment variable for security
BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN')
if not BOT_TOKEN:
logging.error("Bot token not found! Please set the DISCORD_BOT_TOKEN environment variable.")
exit(1)
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
class SupportBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=intents)
self.bot_data = self.load_bot_data()
async def setup_hook(self):
await self.tree.sync()
self.add_view(TicketView()) # Add the view for persistent buttons
def load_bot_data(self):
try:
with open('bot_data.json', 'r') as f:
return json.load(f)
except FileNotFoundError:
return {
"CLIENT_SERVER_ID": 1291468217075765269, # Replace with actual client server ID
"DEV_SERVER_ID": 1291468171823284224, # Replace with actual dev server ID
"TICKET_CHANNEL_ID": 1291773767856558141, # Replace with actual ticket channel ID
"CLIENT_TICKET_CATEGORY_ID": 1291772678595809415, # Replace with actual client ticket category ID
"DEV_TICKET_CATEGORY_ID": 1291772638083158087, # Replace with actual dev ticket category ID
"ADMIN_ROLE_ID": 968955869008101436, # Replace with actual admin role ID in the dev channel
"TICKET_OPTIONS": [
{"name": "Builder/Modeller", "emoji": "🏗️", "color": 0x1abc9c},
{"name": "VFX", "emoji": "✨", "color": 0x3498db},
{"name": "Scripter/Programmer", "emoji": "💻", "color": 0xe74c3c},
{"name": "Animations", "emoji": "🎬", "color": 0xf1c40f},
{"name": "GUI", "emoji": "🖥️", "color": 0x9b59b6}
],
"tickets": {},
"ticket_message_id": None,
"dev_id_counter": 0, # New field to keep track of dev IDs
"dev_id_mapping": {} # New field to store dev ID mappings
}
def save_bot_data(self):
with open('bot_data.json', 'w') as f:
json.dump(self.bot_data, f, indent=4)
def get_next_dev_id(self):
self.bot_data["dev_id_counter"] += 1
return self.bot_data["dev_id_counter"]
bot = SupportBot()
@bot.event
async def on_ready():
logging.info(f'{bot.user} has connected to Discord!')
class TicketButton(discord.ui.Button):
def __init__(self, option):
super().__init__(style=discord.ButtonStyle.primary, label=option["name"], emoji=option["emoji"], custom_id=f"ticket_{option['name']}")
self.option = option
async def callback(self, interaction: discord.Interaction):
await create_ticket(interaction.user, self.option)
await interaction.response.send_message(f"Creating a ticket for {self.option['name']}...", ephemeral=True)
class TicketView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.update_buttons()
def update_buttons(self):
self.clear_items()
for option in bot.bot_data["TICKET_OPTIONS"]:
self.add_item(TicketButton(option))
async def create_ticket(member: discord.Member, option: dict):
client_guild = bot.get_guild(bot.bot_data["CLIENT_SERVER_ID"])
dev_guild = bot.get_guild(bot.bot_data["DEV_SERVER_ID"])
if not client_guild or not dev_guild:
logging.error("Client or Dev guild not found. Please check your server IDs.")
return
# Create ticket prefix
prefix = option['name'].lower().replace(" ", "-")
channel_name = f"{prefix}-{member.name.lower()}"
# Create ticket channels
client_category = discord.utils.get(client_guild.categories, id=bot.bot_data["CLIENT_TICKET_CATEGORY_ID"])
dev_category = discord.utils.get(dev_guild.categories, id=bot.bot_data["DEV_TICKET_CATEGORY_ID"])
if not client_category or not dev_category:
logging.error("Ticket categories not found. Please check your category IDs.")
return
client_channel = await client_guild.create_text_channel(channel_name, category=client_category)
dev_channel = await dev_guild.create_text_channel(channel_name, category=dev_category)
# Set permissions
await set_channel_permissions(client_channel, client_guild, member, is_client=True)
await set_channel_permissions(dev_channel, dev_guild, member, is_client=False)
# Store ticket info
ticket_id = str(len(bot.bot_data["tickets"]) + 1)
bot.bot_data["tickets"][ticket_id] = {
"client_channel_id": client_channel.id,
"dev_channel_id": dev_channel.id,
"client_id": member.id,
"support_type": option['name'],
"dev_ids": []
}
bot.save_bot_data()
# Notify client
embed = discord.Embed(
title=f"{option['emoji']} {option['name']} Support",
description=f"Your ticket has been created. A developer will be with you shortly.",
color=option['color']
)
await client_channel.send(embed=embed)
# Notify developers
dev_notification_channel = discord.utils.get(dev_guild.text_channels, name=prefix)
if dev_notification_channel:
embed = discord.Embed(
title="New Support Ticket",
description=f"New {option['name']} support ticket opened: {channel_name}",
color=option['color']
)
dev_notification = await dev_notification_channel.send(embed=embed)
await dev_notification.add_reaction("✅")
async def set_channel_permissions(channel: discord.TextChannel, guild: discord.Guild, member: discord.Member, is_client: bool):
if is_client:
await channel.set_permissions(guild.default_role, read_messages=False, send_messages=False)
await channel.set_permissions(member, read_messages=True, send_messages=True)
else:
await channel.set_permissions(guild.default_role, read_messages=True, send_messages=True)
# Additional permissions can be set here if needed
@bot.tree.command(name="ticket_post", description="Post or update the ticket message with buttons")
@app_commands.checks.has_role("Admin")
async def ticket_post(interaction: discord.Interaction):
channel = bot.get_channel(bot.bot_data["TICKET_CHANNEL_ID"])
if not channel:
await interaction.response.send_message("Ticket channel not found. Please check the configuration.", ephemeral=True)
return
embed = discord.Embed(
title="Create a Support Ticket",
description="Click a button below to create a ticket:",
color=0x00ff00
)
for option in bot.bot_data["TICKET_OPTIONS"]:
embed.add_field(name=f"{option['emoji']} {option['name']}", value="\u200b", inline=False)
view = TicketView()
try:
if bot.bot_data["ticket_message_id"]:
message = await channel.fetch_message(bot.bot_data["ticket_message_id"])
await message.edit(embed=embed, view=view)
await interaction.response.send_message("Ticket message updated successfully.", ephemeral=True)
else:
message = await channel.send(embed=embed, view=view)
bot.bot_data["ticket_message_id"] = message.id
bot.save_bot_data()
await interaction.response.send_message("Ticket message created successfully.", ephemeral=True)
except discord.NotFound:
message = await channel.send(embed=embed, view=view)
bot.bot_data["ticket_message_id"] = message.id
bot.save_bot_data()
await interaction.response.send_message("Ticket message created successfully.", ephemeral=True)
except Exception as e:
logging.error(f"Error in ticket_post command: {e}")
await interaction.response.send_message("An error occurred while posting the ticket message.", ephemeral=True)
@bot.event
async def on_message(message: discord.Message):
if message.author.bot:
return
if isinstance(message.channel, discord.TextChannel) and (
(message.guild.id == bot.bot_data["CLIENT_SERVER_ID"] and message.channel.category_id == bot.bot_data["CLIENT_TICKET_CATEGORY_ID"]) or
(message.guild.id == bot.bot_data["DEV_SERVER_ID"] and message.channel.category_id == bot.bot_data["DEV_TICKET_CATEGORY_ID"])
):
await relay_message(message)
async def relay_message(message: discord.Message):
ticket_id = next((tid for tid, t in bot.bot_data["tickets"].items() if t['client_channel_id'] == message.channel.id or t['dev_channel_id'] == message.channel.id), None)
if not ticket_id:
logging.warning(f"Message in unknown channel: {message.channel.id}")
return
ticket = bot.bot_data["tickets"][ticket_id]
if message.channel.id == ticket['client_channel_id']: # Client channel
target_channel = bot.get_channel(ticket['dev_channel_id']) # Dev channel
display_name = "Client"
else: # Dev channel
target_channel = bot.get_channel(ticket['client_channel_id']) # Client channel
# Fetch the member to get their nickname
dev_member = message.guild.get_member(message.author.id)
if dev_member:
nickname = dev_member.nick or dev_member.name
display_name = f"[Dev] {nickname}"
else:
display_name = "[Dev] Unknown"
embed = discord.Embed(description=message.content, color=discord.Color.blue())
embed.set_author(name=display_name, icon_url=message.author.display_avatar.url)
await target_channel.send(embed=embed)
# Relay attachments
for attachment in message.attachments:
try:
await target_channel.send(f"**{display_name}** sent an attachment:", file=await attachment.to_file())
except Exception as e:
logging.error(f"Failed to relay attachment: {e}")
@bot.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
if payload.member.bot:
return
if str(payload.emoji) == "✅" and payload.guild_id == bot.bot_data["DEV_SERVER_ID"]:
channel = bot.get_channel(payload.channel_id)
if not channel:
logging.error("Channel not found for reaction.")
return
try:
message = await channel.fetch_message(payload.message_id)
except discord.NotFound:
logging.error("Message not found for reaction.")
return
if not message.embeds:
return
embed = message.embeds[0]
if "New Support Ticket" not in embed.title:
return
ticket_type = embed.description.split()[1] # Extract ticket type from embed
ticket_id = next((tid for tid, t in bot.bot_data["tickets"].items() if t['support_type'].lower() == ticket_type.lower()), None)
if not ticket_id:
await channel.send("Ticket type not recognized.")
return
ticket = bot.bot_data["tickets"][ticket_id]
dev_channel = bot.get_channel(ticket['dev_channel_id'])
if not dev_channel:
logging.error("Dev channel not found.")
return
# Set permissions for the dev
await dev_channel.set_permissions(payload.member, read_messages=True, send_messages=True)
# Assign a unique dev number
dev_id = str(payload.member.id)
if dev_id not in bot.bot_data["dev_id_mapping"]:
new_dev_number = bot.get_next_dev_id()
bot.bot_data["dev_id_mapping"][dev_id] = new_dev_number
bot.save_bot_data()
dev_number = bot.bot_data["dev_id_mapping"][dev_id]
nickname = payload.member.nick or payload.member.name
dev_display_name = f"[Dev] {nickname}"
await dev_channel.send(f"{dev_display_name} has joined the ticket.")
bot.bot_data["tickets"][ticket_id]['dev_ids'].append(payload.member.id)
bot.save_bot_data()
@bot.tree.command(name="close_ticket", description="Close the current ticket")
@app_commands.checks.has_role("Admin")
async def close_ticket(interaction: discord.Interaction):
ticket_id = next((tid for tid, t in bot.bot_data["tickets"].items() if t['client_channel_id'] == interaction.channel_id or t['dev_channel_id'] == interaction.channel_id), None)
if not ticket_id:
await interaction.response.send_message("This is not a valid ticket channel.", ephemeral=True)
return
ticket = bot.bot_data["tickets"][ticket_id]
client_channel = bot.get_channel(ticket['client_channel_id'])
dev_channel = bot.get_channel(ticket['dev_channel_id'])
if client_channel:
try:
await client_channel.send("This ticket is now closed. Thank you for using our support system!")
await client_channel.delete()
except discord.NotFound:
logging.warning("Client channel already deleted.")
except Exception as e:
logging.error(f"Error deleting client channel: {e}")
if dev_channel:
try:
await dev_channel.delete()
except discord.NotFound:
logging.warning("Dev channel already deleted.")
except Exception as e:
logging.error(f"Error deleting dev channel: {e}")
del bot.bot_data["tickets"][ticket_id]
bot.save_bot_data()
await interaction.response.send_message("Ticket closed successfully.", ephemeral=True)
@bot.tree.command(name="add_ticket_option", description="Add a new ticket option")
@app_commands.describe(name="Name of the ticket option")
@app_commands.describe(emoji_input="Emoji for the ticket option")
@app_commands.describe(color="Hex color code for the embed (e.g., #FF5733)")
@app_commands.checks.has_role("Admin")
async def add_ticket_option(interaction: discord.Interaction, name: str, emoji_input: str, color: str):
try:
# Check if the provided emoji is valid
if not emoji.is_emoji(emoji_input):
raise ValueError("Invalid emoji")
color_value = int(color.strip('#'), 16)
bot.bot_data["TICKET_OPTIONS"].append({"name": name, "emoji": emoji_input, "color": color_value})
bot.save_bot_data()
# Update the ticket message with the new option
channel = bot.get_channel(bot.bot_data["TICKET_CHANNEL_ID"])
if not channel:
await interaction.response.send_message("Ticket channel not found. Please check the configuration.", ephemeral=True)
return
if bot.bot_data["ticket_message_id"]:
try:
message = await channel.fetch_message(bot.bot_data["ticket_message_id"])
view = TicketView()
await message.edit(view=view)
except discord.NotFound:
message = await channel.send(embed=discord.Embed(
title="Create a Support Ticket",
description="Click a button below to create a ticket:",
color=0x00ff00
), view=TicketView())
bot.bot_data["ticket_message_id"] = message.id
bot.save_bot_data()
await interaction.response.send_message(f"New ticket option added: {emoji_input} {name}", ephemeral=True)
except ValueError as e:
if str(e) == "Invalid emoji":
await interaction.response.send_message("Invalid emoji. Please provide a valid emoji.", ephemeral=True)
else:
await interaction.response.send_message("Invalid color format. Please use a hexadecimal color code (e.g., #FF0000 for red).", ephemeral=True)
except Exception as e:
logging.error(f"Error in add_ticket_option command: {e}")
await interaction.response.send_message("An unexpected error occurred while adding the ticket option.", ephemeral=True)
# Run the bot with a secure method to provide the token
bot.run(BOT_TOKEN)
Key Changes and Enhancements
-
Security Improvements:
- Removed the Hardcoded Bot Token: Instead of hardcoding the bot token, the updated code retrieves it from an environment variable
DISCORD_BOT_TOKEN. This prevents accidental exposure of the token.
- Logging Added: Utilizes Python's
logging module for better debugging and error tracking.
-
Developer Name Prefix ([Dev]):
- When relaying messages from developers to clients, the developer's display name is now prefixed with
[Dev] followed by their server nickname.
- Implementation Details:
- In the
relay_message function, when the message is from a dev channel, it fetches the member's nickname and formats the display name accordingly.
- In the
on_raw_reaction_add event, when a developer joins a ticket, their display name in the dev channel message is also prefixed with [Dev].
-
Code Refactoring for Maintainability:
- Permission Setting: Extracted permission settings into a separate
set_channel_permissions function to avoid repetition.
- Type Hints: Added type hints to function signatures for better code clarity and potential IDE integrations.
- Enhanced Error Handling: Added comprehensive error handling and logging to assist in debugging and ensure the bot handles unexpected scenarios gracefully.
-
Additional Enhancements:
- Environment Variable for Bot Token: Ensures that the bot token isn't exposed in the codebase and encourages secure practices.
- Descriptive Command Parameters: Added descriptions to command parameters for better usability and clarity within Discord's slash command interface.
- Attachment Relay Error Handling: Added try-except blocks around attachment relaying to handle potential errors without crashing the bot.
Setting Up Environment Variables
To securely manage your bot token, follow these steps:
-
Create a .env File:
-
Load the .env File in Your Script:
-
Add .env to .gitignore:
- If you're using Git for version control, add the
.env file to your .gitignore to prevent it from being committed:
# .gitignore
.env
Final Notes
- Testing: After implementing these changes, thoroughly test each feature to ensure everything works as expected.
- Dependencies: Ensure all required libraries (
discord.py, emoji, python-dotenv, etc.) are installed and up to date.
- Permissions: Verify that your bot has the necessary permissions in both the client and dev servers to manage channels, send messages, and manage reactions.
By implementing these improvements, your Discord support bot will be more secure, maintainable, and user-friendly, with developer names clearly prefixed for easy identification.