ffmpeg: Download and install from here (required for audio processing)
Here's the bot code:
python
import discord
from discord.ext import commands
import youtube_dl
import os
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # ipv6 addresses cause issues sometimes
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take the first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.queue = []
@commands.command(name='join', help='Join the voice channel')
async def join(self, ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
@commands.command(name='leave', help='Leave the voice channel')
async def leave(self, ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_connected():
await voice_client.disconnect()
else:
await ctx.send("The bot is not connected to a voice channel.")
@commands.command(name='play', help='Play a song from YouTube')
async def play(self, ctx, url):
try:
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('**Now playing:** {}'.format(player.title))
except Exception as e:
await ctx.send(str(e))
@commands.command(name='pause', help='Pause the music')
async def pause(self, ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_playing():
await voice_client.pause()
else:
await ctx.send("The bot is not playing anything at the moment.")
@commands.command(name='resume', help='Resume the music')
async def resume(self, ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_paused():
await voice_client.resume()
else:
await ctx.send("The bot was not playing anything before this. Use play command")
@commands.command(name='stop', help='Stop the music')
async def stop(self, ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_playing():
await voice_client.stop()
else:
await ctx.send("The bot is not playing anything at the moment.")
@commands.command(name='skip', help='Skip the current song')
async def skip(self, ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_playing():
voice_client.stop()
await self.play_next(ctx)
else:
await ctx.send("The bot is not playing anything at the moment.")
async def play_next(self, ctx):
if self.queue:
url = self.queue.pop(0)
await self.play(ctx, url)
@commands.command(name='queue', help='Show the song queue')
async def queue(self, ctx):
if self.queue:
await ctx.send("Current queue: \n" + "\n".join(self.queue))
else:
await ctx.send("Queue is empty")
@commands.command(name='add', help='Add a song to the queue')
async def add(self, ctx, url):
self.queue.append(url)
await ctx.send(f"Added {url} to the queue")
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
bot.add_cog(Music(bot))
# Replace 'YOUR_TOKEN' with your bot token from Discord Developer Portal
bot.run('YOUR_TOKEN')