I’m having a problem with this, I’m new and I want to make a discord bot using Python. The problem is when the bot enters a vc and starts the song it stops a few seconds after starting. I tried with youtube-dl but I read that they discontinued it and it didn’t work when I tried it either
So that’s the problem, any help please? this is the code:
<code>import discord
from discord.ext import commands
import yt_dlp
import config
import asyncio
bot = commands.Bot(command_prefix='m!', intents=discord.Intents.all())
#Bot startup
@bot.event
async def on_ready():
print(f'{bot.user} ready')
ffmpeg_options = {'options': '-vn'}
ydl_opts = {
'format': 'bestaudio/best',
'quiet': False,
'noplaylist': False,
'ignoreerrors': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
class Queue:
def __init__(self):
self.queue = []
def add(self, item):
self.queue.append(item)
def remove(self):
if self.queue:
return self.queue.pop(0)
return None
queue = Queue()
@bot.command()
async def ping(ctx):
await ctx.send("!Pong")
@bot.command()
async def join(ctx):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("¡Necesitas estar en un canal de voz!")
return
voice_channel = ctx.author.voice.channel
if ctx.voice_client is not None:
await ctx.voice_client.move_to(voice_channel)
else:
await voice_channel.connect()
await ctx.send(f"Me he unido a {voice_channel}")
@bot.command()
async def leave(ctx):
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.send("Bye Bye")
else:
await ctx.send("No estoy en un canal de voz")
#Using play
@bot.command()
async def play(ctx, *, query):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("¡Necesitas estar en un canal de voz para usar este comando!")
return
voice_channel = ctx.author.voice.channel
try:
vc = ctx.voice_client
if not vc:
await voice_channel.connect()
vc = ctx.voice_client
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(f"ytsearch:{query}", download=False)
url = info['entries'][0]['url']
queue.add(url)
if not vc.is_playing():
play_next(ctx)
await ctx.send(f"Reproduciendo: {info['entries'][0]['title']}")
else:
await ctx.send(f"{info['entries'][0]['title']} añadida a la cola de reproducción")
except Exception as e:
print(f"Error al reproducir audio: {e}")
await ctx.send("Ocurrió un error al reproducir el audio.")
@bot.command()
async def skip(ctx):
if ctx.voice_client is None or not ctx.voice_client.is_playing():
await ctx.send("No hay nada reproduciéndose que se pueda saltar.")
return
ctx.voice_client.stop()
await ctx.send("Canción skipped")
play_next(ctx)
def play_next(ctx):
url = queue.remove()
if url:
ctx.voice_client.play(discord.FFmpegPCMAudio(url), after=lambda e: play_next(ctx))
@bot.command()
async def disconnect(ctx):
if ctx.voice_client is None:
await ctx.send("No estoy en un canal de voz.")
return
await ctx.voice_client.disconnect()
await ctx.send("Me he desconectado del canal de voz.")
#Disconnect when nobody is in the vc
@bot.event
async def on_voice_state_update(member, before, after):
if bot.user in member.guild.voice_channels and len(member.guild.voice_channels) == 1:
await asyncio.sleep(20)
if len(member.guild.voice_channels) == 1 and bot.user in member.guild.voice_channels:
await member.guild.voice_client.disconnect()
bot.run(config.TOKEN)
</code>
<code>import discord
from discord.ext import commands
import yt_dlp
import config
import asyncio
bot = commands.Bot(command_prefix='m!', intents=discord.Intents.all())
#Bot startup
@bot.event
async def on_ready():
print(f'{bot.user} ready')
ffmpeg_options = {'options': '-vn'}
ydl_opts = {
'format': 'bestaudio/best',
'quiet': False,
'noplaylist': False,
'ignoreerrors': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
class Queue:
def __init__(self):
self.queue = []
def add(self, item):
self.queue.append(item)
def remove(self):
if self.queue:
return self.queue.pop(0)
return None
queue = Queue()
@bot.command()
async def ping(ctx):
await ctx.send("!Pong")
@bot.command()
async def join(ctx):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("¡Necesitas estar en un canal de voz!")
return
voice_channel = ctx.author.voice.channel
if ctx.voice_client is not None:
await ctx.voice_client.move_to(voice_channel)
else:
await voice_channel.connect()
await ctx.send(f"Me he unido a {voice_channel}")
@bot.command()
async def leave(ctx):
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.send("Bye Bye")
else:
await ctx.send("No estoy en un canal de voz")
#Using play
@bot.command()
async def play(ctx, *, query):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("¡Necesitas estar en un canal de voz para usar este comando!")
return
voice_channel = ctx.author.voice.channel
try:
vc = ctx.voice_client
if not vc:
await voice_channel.connect()
vc = ctx.voice_client
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(f"ytsearch:{query}", download=False)
url = info['entries'][0]['url']
queue.add(url)
if not vc.is_playing():
play_next(ctx)
await ctx.send(f"Reproduciendo: {info['entries'][0]['title']}")
else:
await ctx.send(f"{info['entries'][0]['title']} añadida a la cola de reproducción")
except Exception as e:
print(f"Error al reproducir audio: {e}")
await ctx.send("Ocurrió un error al reproducir el audio.")
@bot.command()
async def skip(ctx):
if ctx.voice_client is None or not ctx.voice_client.is_playing():
await ctx.send("No hay nada reproduciéndose que se pueda saltar.")
return
ctx.voice_client.stop()
await ctx.send("Canción skipped")
play_next(ctx)
def play_next(ctx):
url = queue.remove()
if url:
ctx.voice_client.play(discord.FFmpegPCMAudio(url), after=lambda e: play_next(ctx))
@bot.command()
async def disconnect(ctx):
if ctx.voice_client is None:
await ctx.send("No estoy en un canal de voz.")
return
await ctx.voice_client.disconnect()
await ctx.send("Me he desconectado del canal de voz.")
#Disconnect when nobody is in the vc
@bot.event
async def on_voice_state_update(member, before, after):
if bot.user in member.guild.voice_channels and len(member.guild.voice_channels) == 1:
await asyncio.sleep(20)
if len(member.guild.voice_channels) == 1 and bot.user in member.guild.voice_channels:
await member.guild.voice_client.disconnect()
bot.run(config.TOKEN)
</code>
import discord
from discord.ext import commands
import yt_dlp
import config
import asyncio
bot = commands.Bot(command_prefix='m!', intents=discord.Intents.all())
#Bot startup
@bot.event
async def on_ready():
print(f'{bot.user} ready')
ffmpeg_options = {'options': '-vn'}
ydl_opts = {
'format': 'bestaudio/best',
'quiet': False,
'noplaylist': False,
'ignoreerrors': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
class Queue:
def __init__(self):
self.queue = []
def add(self, item):
self.queue.append(item)
def remove(self):
if self.queue:
return self.queue.pop(0)
return None
queue = Queue()
@bot.command()
async def ping(ctx):
await ctx.send("!Pong")
@bot.command()
async def join(ctx):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("¡Necesitas estar en un canal de voz!")
return
voice_channel = ctx.author.voice.channel
if ctx.voice_client is not None:
await ctx.voice_client.move_to(voice_channel)
else:
await voice_channel.connect()
await ctx.send(f"Me he unido a {voice_channel}")
@bot.command()
async def leave(ctx):
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.send("Bye Bye")
else:
await ctx.send("No estoy en un canal de voz")
#Using play
@bot.command()
async def play(ctx, *, query):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("¡Necesitas estar en un canal de voz para usar este comando!")
return
voice_channel = ctx.author.voice.channel
try:
vc = ctx.voice_client
if not vc:
await voice_channel.connect()
vc = ctx.voice_client
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(f"ytsearch:{query}", download=False)
url = info['entries'][0]['url']
queue.add(url)
if not vc.is_playing():
play_next(ctx)
await ctx.send(f"Reproduciendo: {info['entries'][0]['title']}")
else:
await ctx.send(f"{info['entries'][0]['title']} añadida a la cola de reproducción")
except Exception as e:
print(f"Error al reproducir audio: {e}")
await ctx.send("Ocurrió un error al reproducir el audio.")
@bot.command()
async def skip(ctx):
if ctx.voice_client is None or not ctx.voice_client.is_playing():
await ctx.send("No hay nada reproduciéndose que se pueda saltar.")
return
ctx.voice_client.stop()
await ctx.send("Canción skipped")
play_next(ctx)
def play_next(ctx):
url = queue.remove()
if url:
ctx.voice_client.play(discord.FFmpegPCMAudio(url), after=lambda e: play_next(ctx))
@bot.command()
async def disconnect(ctx):
if ctx.voice_client is None:
await ctx.send("No estoy en un canal de voz.")
return
await ctx.voice_client.disconnect()
await ctx.send("Me he desconectado del canal de voz.")
#Disconnect when nobody is in the vc
@bot.event
async def on_voice_state_update(member, before, after):
if bot.user in member.guild.voice_channels and len(member.guild.voice_channels) == 1:
await asyncio.sleep(20)
if len(member.guild.voice_channels) == 1 and bot.user in member.guild.voice_channels:
await member.guild.voice_client.disconnect()
bot.run(config.TOKEN)
Listen complete songs
New contributor
Mikusita UwU is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1