You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py音乐机器人搜索耗时过长报Not connected to voice错误如何解决

问题原因

  • 代码中使用了同步阻塞的sleep(1),会卡住discord.py的异步事件循环,导致语音连接的心跳包无法正常发送,搜索耗时久了会被discord服务端断开连接,触发Not connected to voice报错
  • 没有处理slash命令的3秒响应时限:discord要求slash命令调用后3秒内必须给出响应,搜索耗时超过3秒会导致命令会话被强制终止,连带影响语音连接状态
  • 缺少语音连接有效性校验,仅判断了初始连接状态,没有处理连接中途断开的异常场景

修复方案

替换同步sleep为异步非阻塞的asyncio.sleep,增加slash命令延迟响应逻辑,播放前补充语音连接有效性校验,异常时自动重连,修复后的代码如下:

import asyncio
# 其余原有导入保持不变

@slash.slash()
@commands.cooldown(1,6,commands.BucketType.channel)
async def igraj(ctx, *, url):
    # 延迟响应,突破slash命令3秒响应限制
    await ctx.defer()
    voicetrue = ctx.guild.me.voice
    
    # 未连接或连接失效时重新连接
    if voicetrue is None or not voicetrue.is_connected():
        await ctx.author.voice.channel.connect()

    player = music.get_player(guild_id=ctx.guild.id)
    if not player:
        player = music.create_player(ctx, ffmpeg_error_betterfix=False)

    if not ctx.voice_client.is_playing():
        embed = discord.Embed(description='Iscem...', colour=0xf1c40f)
        msg = await ctx.send(embed=embed)
        # 替换为异步sleep,不阻塞事件循环
        await asyncio.sleep(1)
        await player.queue(url, search=True)
        # 播放前二次校验语音连接状态
        if not ctx.guild.me.voice or not ctx.guild.me.voice.is_connected():
            await ctx.author.voice.channel.connect()
            player = music.create_player(ctx, ffmpeg_error_betterfix=False)
        song = await player.play()
        desc = f'Igram {song.name}'
        songe = discord.Embed(description = desc, colour=0xf1c40f)
        await msg.edit(embed=songe)

    else:
        song = await player.queue(url, search=True)
        embed=discord.Embed(description=f'{song.name} je v cakalni vrsti!', colour=0xf1c40f)
        await ctx.send(embed=embed)

如果仍偶发断开问题,可以将创建player时的ffmpeg_error_betterfix参数设置为True,开启ffmpeg错误自动修复能力,适配网络波动场景。

内容的提问来源于stack exchange,提问作者luci muci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:39:03