Files
bot.py
requirements.txt
Code
2 202
bot.py
import asyncio
import logging
import os
import re
import discord
import yt_dlp
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("kodari_bot")
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
YTDL_OPTIONS = {
"format": "bestaudio/best",
"noplaylist": True,
"quiet": True,
"default_search": "ytsearch",
}
ytdl = yt_dlp.YoutubeDL(YTDL_OPTIONS)
TRIGGERS = {
"hello": "Hey {mention}! 👋",
"good morning": "Good morning, {mention}! ☀️",
"good night": "Good night, {mention}! 🌙",
"help": "Try `/play` for music, `/ticket` for support, or `/close_ticket` to close your ticket.",
}
@bot.event
async def on_ready():
try:
await bot.tree.sync()
except discord.HTTPException:
logger.exception("Could not sync slash commands")
logger.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.event
async def on_message(message: discord.Message):
if message.author.bot:
return
content = message.content.casefold()
for trigger, reply in TRIGGERS.items():
if re.search(rf"(?<!\w){re.escape(trigger)}(?!\w)", content):
await message.reply(reply.format(mention=message.author.mention), mention_author=False)
break
await bot.process_commands(message)
@bot.tree.command(name="play", description="Play a song from a URL or search phrase")
@app_commands.guild_only()
async def play(interaction: discord.Interaction, query: str):
member = interaction.user
if not isinstance(member, discord.Member) or member.voice is None or member.voice.channel is None:
await interaction.response.send_message("Join a voice channel first.", ephemeral=True)
return
await interaction.response.defer()
try:
info = await asyncio.to_thread(ytdl.extract_info, query, download=False)
if "entries" in info:
info = next((entry for entry in info["entries"] if entry), None)
if not info:
await interaction.followup.send("I couldn't find a playable track for that.")
return
voice_client = interaction.guild.voice_client
if voice_client is None or not voice_client.is_connected():
voice_client = await member.voice.channel.connect()
elif voice_client.channel != member.voice.channel:
await voice_client.move_to(member.voice.channel)
if voice_client.is_playing() or voice_client.is_paused():
await interaction.followup.send("I'm already playing something. Use `/stop` first.")
return
audio = discord.FFmpegPCMAudio(
info["url"],
before_options="-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
options="-vn",
)
voice_client.play(audio, after=lambda error: logger.error("Audio playback failed: %s", error) if error else None)
await interaction.followup.send(f"▶️ Now playing **{info.get('title', 'Unknown track')}**")
except Exception:
logger.exception("Could not play requested track")
await interaction.followup.send("I couldn't play that track. Check the URL and try again.")
@bot.tree.command(name="stop", description="Stop the current song")
@app_commands.guild_only()
async def stop(interaction: discord.Interaction):
voice_client = interaction.guild.voice_client
if voice_client is None or not voice_client.is_playing():
await interaction.response.send_message("Nothing is playing right now.", ephemeral=True)
return
voice_client.stop()
await interaction.response.send_message("⏹️ Playback stopped.")
@bot.tree.command(name="leave", description="Disconnect the bot from voice chat")
@app_commands.guild_only()
async def leave(interaction: discord.Interaction):
voice_client = interaction.guild.voice_client
if voice_client is None:
await interaction.response.send_message("I'm not in a voice channel.", ephemeral=True)
return
await voice_client.disconnect()
await interaction.response.send_message("👋 Left the voice channel.")
@bot.tree.command(name="ticket", description="Create a private support ticket")
@app_commands.guild_only()
async def ticket(interaction: discord.Interaction):
guild = interaction.guild
member = interaction.user
if guild is None or not isinstance(member, discord.Member):
await interaction.response.send_message("Tickets can only be opened in a server.", ephemeral=True)
return
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
member: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True),
}
if guild.me is not None:
overwrites[guild.me] = discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True, manage_channels=True)
support_role_id = os.getenv("SUPPORT_ROLE_ID", "").strip()
if support_role_id.isdigit():
support_role = guild.get_role(int(support_role_id))
if support_role is not None:
overwrites[support_role] = discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
safe_name = re.sub(r"[^a-z0-9-]", "-", member.name.casefold()).strip("-") or "member"
try:
channel = await guild.create_text_channel(
name=f"ticket-{safe_name[:85]}",
overwrites=overwrites,
topic=f"ticket owner: {member.id}",
)
await interaction.response.send_message(f"Your private ticket is ready: {channel.mention}", ephemeral=True)
await channel.send(f"Hi {member.mention}! Tell us what you need help with. Use `/close_ticket` when you're done.")
except discord.HTTPException:
logger.exception("Could not create ticket")
if not interaction.response.is_done():
await interaction.response.send_message("I couldn't create a ticket. Please check my channel permissions.", ephemeral=True)
@bot.tree.command(name="close_ticket", description="Close this support ticket")
@app_commands.guild_only()
async def close_ticket(interaction: discord.Interaction):
channel = interaction.channel
guild = interaction.guild
if not isinstance(channel, discord.TextChannel) or guild is None:
await interaction.response.send_message("This command only works in a ticket channel.", ephemeral=True)
return
match = re.fullmatch(r"ticket owner: (\d+)", channel.topic or "")
if match is None:
await interaction.response.send_message("This channel isn't a ticket.", ephemeral=True)
return
is_owner = interaction.user.id == int(match.group(1))
is_staff = isinstance(interaction.user, discord.Member) and interaction.user.guild_permissions.manage_channels
if not is_owner and not is_staff:
await interaction.response.send_message("Only the ticket owner or a channel manager can close this ticket.", ephemeral=True)
return
await interaction.response.send_message("🔒 Closing this ticket.", ephemeral=True)
try:
await channel.delete(reason=f"Ticket closed by {interaction.user}")
except discord.HTTPException:
logger.exception("Could not close ticket channel %s", channel.id)
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
logger.error("Slash command failed", exc_info=(type(error), error, error.__traceback__))
message = "Something went wrong. Please try again."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing. Add it to your .env file.")
bot.run(token)