Using YT-DLP in discord.py but the songs stop

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật