How to Build a Music Bot for Discord Without YouTube
🔍 WiseChecker

How to Build a Music Bot for Discord Without YouTube

You want to play music in your Discord server, but you cannot rely on YouTube because of API restrictions, copyright issues, or the bot getting shut down. Many public music bots that depend on YouTube eventually break due to cease-and-desist letters or rate limits. This article explains how to build a custom music bot that plays audio from local files, streaming services with proper licensing, or direct audio sources that do not violate terms of service. You will learn the core components, step-by-step setup, and common pitfalls to avoid.

Key Takeaways: Build a Discord Music Bot Without YouTube

  • FFmpeg and discord.py v2.0+: The core tools for streaming audio from local files or direct URLs into voice channels.
  • Local file playback: Use ffmpeg to play MP3, FLAC, or WAV files stored on your machine.
  • SoundCloud or direct stream URLs: Legal alternatives to YouTube for sourcing music without API restrictions.

What You Need Before Building the Bot

A Discord music bot is a program that connects to Discord voice channels and streams audio. Without YouTube, you must use other audio sources. The most reliable options are local files, SoundCloud streams, or direct links to audio files hosted on legal platforms. You also need a Discord application registered in the Discord Developer Portal, a bot token, and Python 3.8 or later installed on your computer or server. The bot uses the discord.py library and FFmpeg to decode and stream audio. FFmpeg is a free multimedia framework that converts and streams almost any audio format.

Legal Considerations

Using YouTube as a source for a music bot violates YouTube’s Terms of Service and often leads to bot termination. By using local files you own or streams from services that allow it, you avoid legal risks. SoundCloud allows streaming of tracks that the artist has marked as downloadable or embeddable. Always verify that you have the right to play and share the audio in your server.

Steps to Build the Music Bot

Follow these steps to create a bot that plays local audio files or streams from SoundCloud. The bot will accept commands like !play with a file path or URL.

Step 1: Set Up the Discord Application and Bot Token

  1. Create a Discord Application
    Go to the Discord Developer Portal. Click New Application. Give it a name and click Create.
  2. Add a Bot User
    In the left menu, click Bot. Then click Add Bot and confirm. Copy the token shown. Store it securely.
  3. Set Bot Permissions
    In the left menu, click OAuth2 > URL Generator. Select bot under Scopes. Under Bot Permissions, select Connect, Speak, and Use Voice Activity. Copy the generated URL and open it in your browser to invite the bot to a server where you have administrator permissions.

Step 2: Install Required Software

  1. Install Python
    Download Python 3.8 or later from python.org. During installation, check Add Python to PATH.
  2. Install FFmpeg
    Download FFmpeg from ffmpeg.org. Extract the files and add the bin folder to your system PATH. Verify by opening Command Prompt and typing ffmpeg -version. You should see version information.
  3. Install discord.py and Other Packages
    Open Command Prompt or Terminal and run:
    pip install discord.py[voice]
    This installs discord.py with voice support.

Step 3: Write the Bot Code

  1. Create a Python File
    Open a text editor and create a file named music_bot.py.
  2. Add the Basic Bot Skeleton
    Paste the following code:
    import discord
    from discord.ext import commands
    import asyncio
    
    intents = discord.Intents.default()
    intents.message_content = True
    
    bot = commands.Bot(command_prefix='!', intents=intents)
    
    @bot.event
    async def on_ready():
        print(f'Logged in as {bot.user}')
    
    bot.run('YOUR_BOT_TOKEN')
  3. Add the Play Command for Local Files
    Add this before bot.run():
    @bot.command()
    async def play(ctx, , query):
        if not ctx.author.voice:
            await ctx.send('You must be in a voice channel.')
            return
        channel = ctx.author.voice.channel
        voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)
        if voice_client and voice_client.is_connected():
            await voice_client.move_to(channel)
        else:
            voice_client = await channel.connect()
    
        # For local files, query is a file path like "C:\\music\\song.mp3"
        # For streams, query is a direct URL
        if query.startswith('http'):
            # Stream from URL (e.g., SoundCloud direct link)
            source = discord.FFmpegPCMAudio(query, before_options='-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5')
        else:
            # Play local file
            source = discord.FFmpegPCMAudio(query)
        voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)
        await ctx.send(f'Now playing: {query}')
  4. Add Stop and Leave Commands
    Add these commands:
    @bot.command()
    async def stop(ctx):
        voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)
        if voice_client and voice_client.is_playing():
            voice_client.stop()
            await ctx.send('Playback stopped.')
    
    @bot.command()
    async def leave(ctx):
        voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)
        if voice_client and voice_client.is_connected():
            await voice_client.disconnect()
            await ctx.send('Disconnected from voice channel.')
  5. Run the Bot
    Save the file. In the terminal, navigate to the folder and run:
    python music_bot.py
    The bot will come online.

Step 4: Test the Bot

  1. Join a Voice Channel
    In Discord, join a voice channel.
  2. Play a Local File
    Type !play C:\music\song.mp3 (Windows) or !play /home/user/music/song.mp3 (Linux/macOS). The bot should join and start playing.
  3. Play a Stream URL
    Find a direct audio URL from a service like SoundCloud (right-click on a track, copy link, and if it ends in .mp3 or .m3u8, it may work). Type !play https://example.com/audio.mp3. The bot streams the audio.

Common Issues and Limitations

Bot Does Not Join Voice Channel

Ensure the bot has the Connect and Speak permissions. Also check that the bot token is correct and the bot is online. If using a virtual private server, verify that ports 443 and 1024-65535 are open for UDP traffic.

Audio Stutters or Skips

This happens when the internet connection is slow or the audio source is unreliable. For local files, use a wired connection or a faster hard drive. For streams, reduce the bitrate or use a CDN-hosted file. You can also increase the FFmpeg buffer by adding before_options='-buffer_size 96000'.

SoundCloud Links Do Not Play

SoundCloud does not provide direct stream URLs easily. You must use a third-party tool to extract the actual audio URL, which may violate SoundCloud’s terms. A safer approach is to download the audio file if the artist allows it, then play it locally. Alternatively, use services like Bandcamp that provide direct download links for purchased tracks.

Bot Goes Offline After a Few Minutes

Discord voice connections require periodic keep-alive packets. The discord.py library handles this automatically. If the bot disconnects, check your firewall or antivirus software. Some corporate networks block UDP traffic. Use a different network or a VPS with proper UDP support.

Audio Source Options: Local Files vs Stream URLs vs SoundCloud

Item Local Files Direct Stream URLs SoundCloud Streams
Legality Legal if you own the files Depends on the source; avoid copyrighted content without permission Only for tracks marked as downloadable or embeddable
Setup complexity Simple; just provide file path Moderate; need to find working URLs Complex; requires URL extraction tools
Reliability High; no network dependency Medium; stream may go down Low; links change or get blocked
Storage requirement High; files stored locally None None
Example command !play C:\music\song.mp3 !play https://example.com/stream.mp3 Not recommended without extraction

Now you have a working music bot that does not depend on YouTube. You can play local files or direct stream URLs. For the best experience, use local files you own. To expand the bot, add a queue system using asyncio.Queue and the after callback in voice_client.play(). A queue allows users to add multiple songs that play one after another. Also consider adding a !volume command that adjusts the audio level using FFmpeg’s volume filter.