Shogunsoul

this is my discord bot it got many features but i ts not a 10/10 bot can you make it way better like music system is so glitchy when i stop the it it join again and again and it dont even play music in channels when 24/7 hosting and things

Kodari AI
KodariOct 20 at 6:27 am 1
DiscordUltimateBot
Creates a feature-rich Discord bot with a robust music playback system that handles 24/7 hosting without glitches. Includes a queue-based audio player with proper stop/start state management, per-channel playback isolation, and automatic reconnection handling. Features include music playback with volume control, skip, pause, and queue management; moderation tools; leveling system; economy with currency and shops; welcome messages; auto-roles; and customizable prefix system. The bot uses asyncio for concurrent task handling, maintains persistent voice client connections, and implements error recovery to prevent music from restarting unexpectedly. Includes comprehensive admin commands, user profiles, and server management utilities.
  1. Build a clean discord.py bot with slash-command music controls.

  2. Make playback state safe so /stop clears playback without disconnecting or rejoining.

  3. Add queueing, looping, volume, error handling, and the required hosting files.

Built a fresh discord.py music bot with /play, /queue, /skip, /stop, /pause, /resume, /loop, /volume, and /leave.

/stop now clears playback and the queue but keeps the bot in voice. It won’t rejoin on its own; /play is what connects it. Track failures are handled so the queue can continue.

Add your token to .env and make sure FFmpeg is available on PATH for audio playback. Slash commands use default intents, so no privileged intents are needed.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
requirements.txt
Code
3 448
bot.py
import asyncio
import logging
import os
from collections import deque
from dataclasses import dataclass

import discord
import yt_dlp
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("kodari_music_bot")

load_dotenv()

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
commands_synced = False

YTDL_OPTIONS = {
    "format": "bestaudio/best",
    "default_search": "ytsearch1",
    "noplaylist": True,
    "quiet": True,
    "no_warnings": True,
    "socket_timeout": 15,
    "retries": 2,
    "fragment_retries": 2,
}


@dataclass
class Track:
    query: str
    requester_id: int
    channel_id: int
    title: str = ""
    webpage_url: str = ""


def extract_track(query: str) -> dict:
    with yt_dlp.YoutubeDL(YTDL_OPTIONS) as ydl:
        result = ydl.extract_info(query, download=False)
    if result and result.get("entries"):
        result = next((entry for entry in result["entries"] if entry), None)
    if not result or not result.get("url"):
        raise ValueError("No playable audio was found for that search.")
    return result


class GuildPlayer:
    def __init__(self, guild: discord.Guild):
        self.guild = guild
        self.queue = deque()
        self.current = None
        self.volume = 0.5
        self.loop_current = False
        self.generation = 0
        self.lock = asyncio.Lock()
        self.voice_lock = asyncio.Lock()

    async def connect(self, channel: discord.VoiceChannel) -> None:
        async with self.voice_lock:
            voice = self.guild.voice_client
            if voice and voice.is_connected():
                if voice.channel != channel:
                    raise ValueError("I'm already playing in another voice channel.")
                return
            if voice:
                try:
                    await voice.disconnect(force=True)
                except discord.DiscordException:
                    logger.exception("Could not clean up a disconnected voice client")
            await channel.connect(timeout=20.0, reconnect=True)

    async def enqueue(self, track: Track) -> int:
        async with self.lock:
            self.queue.append(track)
            position = len(self.queue) + (1 if self.current else 0)
        asyncio.create_task(self._start_next())
        return position

    async def _start_next(self) -> None:
        while True:
            async with self.lock:
                voice = self.guild.voice_client
                if self.current is not None or not self.queue:
                    return
                if voice is None or not voice.is_connected():
                    return
                track = self.queue.popleft()
                self.current = track
                self.generation += 1
                token = self.generation

            try:
                info = await asyncio.to_thread(extract_track, track.query)
            except Exception as error:
                logger.exception("Could not resolve requested audio")
                async with self.lock:
                    if token != self.generation or self.current is not track:
                        return
                    self.current = None
                    self.loop_current = False
                await self._notify(track, f"Couldn't load **{discord.utils.escape_markdown(track.query)}**. Try another search or link.")
                continue

            track.title = info.get("title") or track.query
            track.webpage_url = info.get("webpage_url") or track.query
            failure = None
            started = False
            async with self.lock:
                if token != self.generation or self.current is not track:
                    return
                voice = self.guild.voice_client
                if voice is None or not voice.is_connected():
                    self.current = None
                    self.loop_current = False
                    return
                source = None
                try:
                    source = discord.PCMVolumeTransformer(
                        discord.FFmpegPCMAudio(
                            info["url"],
                            before_options="-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
                            options="-vn",
                        ),
                        volume=self.volume,
                    )
                    event_loop = asyncio.get_running_loop()

                    def after(error):
                        try:
                            asyncio.run_coroutine_threadsafe(
                                self._after_track(token, error), event_loop
                            )
                        except RuntimeError:
                            logger.debug("Event loop closed before audio callback completed")

                    voice.play(source, after=after)
                    started = True
                except Exception as error:
                    if source is not None:
                        source.cleanup()
                    self.current = None
                    self.loop_current = False
                    failure = error

            if failure is not None:
                logger.exception("Could not start audio", exc_info=failure)
                await self._notify(
                    track,
                    "I couldn't start the audio. Make sure FFmpeg is installed and available on PATH.",
                )
                continue
            if started:
                await self._notify(
                    track,
                    f"▶️ Now playing: **[{discord.utils.escape_markdown(track.title)}]({track.webpage_url})**",
                )
            return

    async def _after_track(self, token: int, error) -> None:
        async with self.lock:
            if token != self.generation:
                return
            track = self.current
            self.current = None
            if error:
                self.loop_current = False
                logger.error("Audio playback ended with an error: %s", error)
            elif self.loop_current and track is not None:
                self.queue.appendleft(track)
            else:
                self.loop_current = False

        if error and track is not None:
            await self._notify(track, "Playback ran into an audio error; I'll try the next queued track.")
        await self._start_next()

    async def _notify(self, track: Track, message: str) -> None:
        channel = self.guild.get_channel(track.channel_id)
        if channel is None:
            return
        try:
            await channel.send(message)
        except discord.DiscordException:
            logger.debug("Could not send playback update to channel %s", track.channel_id)

    async def stop(self) -> bool:
        async with self.lock:
            had_audio = self.current is not None or bool(self.queue)
            self.generation += 1
            self.current = None