Files
cogs
data
models
utils
bot.py
README.md
requirements.txt
Code
15 2,559
bot.py
import discord
from discord.ext import commands
import os
import sys
import logging
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
TEST_GUILD_ID = 1021127857281441852
if not TOKEN or TOKEN == "your_discord_bot_token_here":
print("ERROR: DISCORD_TOKEN not set in .env file!")
print("Create a .env file with: DISCORD_TOKEN=your_bot_token_here")
sys.exit(1)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("TicketBot")
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"),
intents=intents,
help_command=None,
activity=discord.Activity(
type=discord.ActivityType.watching,
name="tickets | /panel",
),
)
@bot.event
async def on_ready():
log.info(f"Logged in as {bot.user} (ID: {bot.user.id})")
log.info(f"Connected to {len(bot.guilds)} guild(s)")
for guild in bot.guilds:
log.info(f" - {guild.name} (ID: {guild.id})")
try:
guild = discord.Object(id=TEST_GUILD_ID)
bot.tree.copy_global_to(guild=guild)
synced = await bot.tree.sync(guild=guild)
log.info(f"Synced {len(synced)} slash command(s) to guild {TEST_GUILD_ID}")
synced_global = await bot.tree.sync()
log.info(f"Synced {len(synced_global)} slash command(s) globally")
except Exception as e:
log.error(f"Failed to sync slash commands: {e}")
log.info("TicketBot is ready!")
@bot.event
async def on_guild_join(guild: discord.Guild):
log.info(f"Joined new guild: {guild.name} (ID: {guild.id})")
from utils.helpers import load_guild_config
await load_guild_config(guild.id)
@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Permission Denied",
description="You don't have permission to use this command.",
color=discord.Color.red(),
)
await ctx.send(embed=embed, ephemeral=True)
return
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="Missing Argument",
description=f"Usage: `{ctx.prefix}{ctx.command.name} {ctx.command.signature}`",
color=discord.Color.orange(),
)
await ctx.send(embed=embed, ephemeral=True)
return
if isinstance(error, commands.BadArgument):
embed = discord.Embed(
title="Invalid Argument",
description=str(error),
color=discord.Color.orange(),
)
await ctx.send(embed=embed, ephemeral=True)
return
log.error(f"Unhandled error in {ctx.command}: {error}")
embed = discord.Embed(
title="Error",
description="An unexpected error occurred. Please try again later.",
color=discord.Color.red(),
)
await ctx.send(embed=embed, ephemeral=True)
async def load_extensions():
cogs_dir = os.path.join(os.path.dirname(__file__), "cogs")
if not os.path.exists(cogs_dir):
os.makedirs(cogs_dir)
cog_files = [f.replace(".py", "") for f in os.listdir(cogs_dir) if f.endswith(".py") and not f.startswith("_")]
for cog in cog_files:
try:
await bot.load_extension(f"cogs.{cog}")
log.info(f"Loaded cog: {cog}")
except Exception as e:
log.error(f"Failed to load cog {cog}: {e}")
async def main():
async with bot:
await load_extensions()
try:
await bot.start(TOKEN)
except discord.PrivilegedIntentsRequired:
log.error(
"Privileged intents are not enabled for this bot. "
"Go to https://discord.com/developers/applications -> your app -> Bot, "
"and enable 'Server Members Intent' and 'Message Content Intent', then restart."
)
sys.exit(1)
if __name__ == "__main__":
import asyncio
try:
asyncio.run(main())
except KeyboardInterrupt:
log.info("Bot stopped by user")
except Exception as e:
log.error(f"Fatal error: {e}")
sys.exit(1)