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

Discord.py开发音乐机器人时如何获取播放队列的上一首歌曲信息

Discord音乐机器人previous命令修正方案

核心问题说明

你提供的原有代码存在两处逻辑错误,导致无法正确获取上一首歌曲的信息:

  • 执行顺序颠倒:先调用歌词接口,后判断是否存在历史播放记录,无历史记录时仍会发起无效的网络请求
  • 取值对象错误:使用当前正在播放的曲目player.queue.current_track请求接口,没有读取历史播放队列中的上一首曲目

修正逻辑

  1. 先获取播放器实例后立刻判断历史队列是否为空,无历史记录直接抛出异常
  2. 从player.queue.history末尾取出最近播放的上一首曲目对象(标准lavalink队列实现中,history按播放顺序存储,最新播放的曲目在队列尾部)
  3. 用上一首曲目的标题请求歌词接口,获取对应的封面、作者信息
  4. 执行切歌逻辑后填充Embed信息返回

修正后完整代码

import typing as t
import datetime as dt
import aiohttp
import discord
from discord.ext import commands

# 请确保你已提前定义好LYRICS_URL、NoLyricsFound、NoPreviousTracks这些常量和自定义异常
@commands.command(name="previous", aliases=["zurück"])
async def previous_command(self, ctx, name: t.Optional[str]):
    player = self.get_player(ctx)
    
    # 先判断是否有历史记录,避免无效逻辑执行
    if not player.queue.history:
        raise NoPreviousTracks
    
    # 获取上一首播放的曲目对象
    previous_track = player.queue.history[-1]
    # 优先用用户传入的名称,没有的话用上一首曲目的标题
    name = name or previous_track.title

    async with ctx.typing():
        async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
            if not 200 <= r.status <= 299:
                raise NoLyricsFound
            data = await r.json() 

    # 执行切歌逻辑,标准lavalink队列实现下该逻辑生效
    player.queue.position -= 2
    await player.stop()
    
    embed = discord.Embed(
        title="Vorheriges Lied",
        colour=ctx.author.colour,
        timestamp=dt.datetime.utcnow(),
    )
    embed.set_thumbnail(url=data["thumbnail"]["genius"])
    embed.set_author(name=data["author"])
    embed.set_footer(text=f"Angefordert von {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

补充说明

  • 如果你的lavalink队列实现自定义了history的存储规则,调整player.queue.history[-1]的索引取值即可获取正确的上一首曲目
  • 修正了原有代码中data = await r.json() 缩进错误、embed.set_author末尾多余逗号的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:27:03