ionicies

host a discord bot for streaming

Kodari AI
KodariNov 9 at 9:15 am 1
StreamBotHost
A Discord bot that streams live video content directly into voice channels. It connects to voice channels, plays audio streams from URLs or files, manages playback queues, and provides commands for play, pause, resume, skip, and stop. The bot uses discord.py with voice client support, includes a command prefix system, handles permissions, and offers a simple setup for server administrators to host their own streaming sessions.

I’ll create a slash-command music bot with YouTube search/playback, per-server queues, and pause/skip/stop controls.

  • Use discord.py voice support with only default intents.

  • Add environment-based token configuration and Python dependencies.

  • Include playback error handling and Kodari’s startup-ready signal.

[Generation stopped]

Kodari can make mistakes. Review important code before using.
Files
main.py
requirements.txt
Code
2 313
main.py
import asyncio
import logging
import os
from collections import deque
from dataclasses import dataclass

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


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

YTDL_OPTIONS = {
    "format": "bestaudio/best",
    "noplaylist": True,
    "quiet": True,
    "no_warnings": True,
    "default_search": "ytsearch1",
}
FFMPEG_BEFORE_OPTIONS = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
FFMPEG_OPTIONS = "-vn"


@dataclass
class Track:
    title: str
    stream_url: str
    webpage_url: str
    requester: str
    text_channel: discord.abc.Messageable


def extract_track(query: str, requester: str, text_channel: discord.abc.Messageable) -> Track:
    with yt_dlp.YoutubeDL(YTDL_OPTIONS) as ytdl:
        info = ytdl.extract_info(query, download=False)
        if info is None:
            raise ValueError("No audio result was found.")
        if "entries" in info:
            entries = info.get("entries") or []
            if not entries:
                raise ValueError("No audio result was found.")
            info = entries[0]
        if not info.get("url"):
            raise ValueError("The audio source did not provide a playable stream.")
        return Track(
            title=info.get("title") or "Untitled stream",
            stream_url=info["url"],
            webpage_url=info.get("webpage_url") or query,
            requester=requester,
            text_channel=text_channel,
        )


class GuildPlayer:
    def __init__(self, guild: discord.Guild):
        self.guild = guild
        self.queue: deque[Track] = deque()
        self.condition = asyncio.Condition()
        self.current: Track | None = None

    async def enqueue(self, track: Track) -> None:
        async with self.condition:
            self.queue.append(track)
            self.condition.notify()

    async def clear_queue(self) -> None:
        async with self.condition:
            self.queue.clear()

    async def snapshot(self) -> tuple[Track | None, list[Track]]:
        async with self.condition:
            return self.current, list(self.queue)

    async def run(self) -> None:
        while True:
            async with self.condition:
                await self.condition.wait_for(lambda: bool(self.queue))
                track = self.queue.popleft()
                self.current = track

            voice_client = self.guild.voice_client
            if voice_client is None or not voice_client.is_connected():
                await self._notify(track, "Playback stopped because the bot is no longer connected to voice.")
                self.current = None
                continue

            try:
                source = discord.FFmpegPCMAudio(
                    track.stream_url,
                    before_options=FFMPEG_BEFORE_OPTIONS,
                    options=FFMPEG_OPTIONS,
                )
                loop = asyncio.get_running_loop()
                finished = loop.create_future()
                playback_errors: list[Exception] = []

                def after(error: Exception | None) -> None:
                    if error is not None:
                        playback_errors.append(error)

                    def resolve() -> None:
                        if not finished.done():
                            finished.set_result(None)

                    loop.call_soon_threadsafe(resolve)

                voice_client.play(source, after=after)
                await finished
                if playback_errors:
                    logger.error("Audio playback failed for %s: %s", track.title, playback_errors[0])
                    await self._notify(track, f"Could not finish playing **{track.title[:150]}**.")
            except asyncio.CancelledError:
                if voice_client.is_playing() or voice_client.is_paused():
                    voice_client.stop()
                raise
            except Exception:
                logger.exception("Could not play %s", track.title)
                await self._notify(
                    track,
                    "Playback failed. Make sure FFmpeg is available on the host and try another stream.",
                )
            finally:
                self.current = None

    @staticmethod
    async def _notify(track: Track, message: str) -> None:
        try:
            await track.text_channel.send(message)
        except (discord.HTTPException, discord.Forbidden):
            logger.info("Could not send a playback notice to the request channel.")


intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
players: dict[int, GuildPlayer] = {}


def get_player(guild: discord.Guild) -> GuildPlayer:
    player = players.get(guild.id)
    if player is None:
        player = GuildPlayer(guild)
        players[guild.id] = player
        asyncio.create_task(player.run(), name=f"music-player-{guild.id}")
    return player


async def get_voice_channel(interaction: discord.Interaction) -> discord.VoiceChannel | discord.StageChannel | None:
    if interaction.guild is None:
        await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
        return None
    if not isinstance(interaction.user, discord.Member) or interaction.user.voice is None:
        await interaction.response.send_message("Join a voice channel first.", ephemeral=True)
        return None
    return interaction.user.voice.channel


@bot.event
async def on_ready() -> None:
    await bot.tree.sync()
    logger.info("Logged in as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.tree.command(name="play", description="Play a YouTube link or search for audio")
@app_commands.describe(query="A YouTube URL or search terms")
async def play(interaction: discord.Interaction, query: str) -> None:
    channel = await get_voice_channel(interaction)
    if channel is None:
        return

    await interaction.response.defer(thinking=True)
    try:
        track = await asyncio.to_thread(
            extract_track,
            query,
            interaction.user.display_name,
            interaction.channel,
        )
    except (yt_dlp.utils.DownloadError, ValueError) as error:
        await interaction.followup.send(f"Could not find playable audio: {str(error)[:300]}", ephemeral=True)
        return
    except Exception:
        logger.exception("Audio search failed for query %r", query)
        await interaction.followup.send("Audio search failed. Please try again later.", ephemeral=True)
        return

    guild = interaction.guild
    if guild is None:
        await interaction.followup.send("This command can only be used in a server.", ephemeral=True)
        return

    voice_client = guild.voice_client
    try:
        if voice_client is None:
            await channel.connect()