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

2022年11月:Discord音乐机器人youtube_dl暂停/续播功能故障求助

Discord音乐机器人暂停/续播问题修复

问题定位

你的代码存在两个核心问题导致暂停/续播功能失效:

  • pause 命令的装饰器缺少括号,应为 @client.command(),否则命令无法被正确注册
  • 未做前置判断:直接调用pause()/resume()前,没有检查机器人是否已连接语音频道、是否处于播放/暂停状态,会引发无意义报错

修改后的完整代码

import discord
from discord.ext import commands
import youtube_dl

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())


@client.event
async def on_ready():
    print(f"{client.user} 已连接到Discord!")

@client.command()
async def echo(ctx, *, message):
    await ctx.send(f"{message}")
    await ctx.message.delete()

@client.command()
async def play(ctx, url):
    # 检查用户是否在语音频道
    if not ctx.author.voice:
        await ctx.send("你得先加入一个语音频道!")
        return
    # 连接语音频道或切换到用户所在频道
    if ctx.voice_client is None:
        await ctx.author.voice.channel.connect()
    elif ctx.voice_client.channel != ctx.author.voice.channel:
        await ctx.voice_client.move_to(ctx.author.voice.channel)
    
    ctx.voice_client.stop()
    
    FFMPEG_OPTIONS = {
      'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
      'options': '-vn'
    }
    YDL_OPTIONS = {'format': "bestaudio"}
    vc = ctx.voice_client

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
        info = ydl.extract_info(url, download=False)
        url2 = info['formats'][0]['url']
        source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
        vc.play(source)
    await ctx.send(f"正在播放: {info['title']}")

@client.command()
async def pause(ctx):
    # 校验机器人状态后执行暂停
    if ctx.voice_client and ctx.voice_client.is_playing():
        ctx.voice_client.pause()
        await ctx.send("已暂停播放")
    else:
        await ctx.send("我现在没在播放音频哦!")

@client.command()
async def resume(ctx):
    # 校验机器人状态后执行续播
    if ctx.voice_client and ctx.voice_client.is_paused():
        ctx.voice_client.resume()
        await ctx.send("已恢复播放")
    else:
        await ctx.send("没有暂停的音频可以恢复!")

# 可选补充:让机器人退出语音频道的命令
@client.command()
async def leave(ctx):
    if ctx.voice_client:
        await ctx.voice_client.disconnect()
        await ctx.send("已退出语音频道")
    else:
        await ctx.send("我现在不在任何语音频道里!")

client.run("你的机器人Token")

关键修改说明

  1. 修复命令注册问题:补全pause命令装饰器的括号,确保命令能被Discord Bot正确识别
  2. 添加状态校验逻辑:
    • 所有语音操作前先判断机器人和用户的状态,避免无意义报错
    • 给用户清晰的操作反馈,比如当前无播放内容时的提示
  3. 优化播放体验:play命令新增频道切换逻辑,机器人会自动移动到用户所在的语音频道
  4. 补充实用功能:新增leave命令,方便用户主动让机器人退出语音频道

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:30:52