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

Discord歌词机器人:移除歌词元数据后显示不符预期问题排查

Discord歌词机器人歌词过滤问题排查求助

我开发了一款基于Discord的歌词查询机器人,调用Genius API获取歌词后,意图移除所有以「[」开头的元数据信息,实现干净的歌词显示,但实际输出仍残留这类元数据,请求协助排查问题。

问题代码

def get_song_and_lyrics(song_name):
        song = genius.search_song(song_name)
        if song is not None:
            lyrics = '\n'.join(line for line in song.lyrics.split('\n') if not line.startswith('['))
            return lyrics, song.song_art_image_url, song
        else:
            return "Couldn't find lyrics for " + song_name, None, None
    def chunk_string(s, length):
        chunks = []
        while s:
            if len(s) > length:
                idx = s.rfind('\n', 0, length)
                if idx == -1:
                    idx = length
                chunks.append(s[:idx])
                s = s[idx:]
            else:
                chunks.append(s)
                s = ''
        return chunks
    class LyricsView(discord.ui.View):
        def __init__(self, embed, chunks, author):
            super().__init__()
            self.embed = embed
            self.chunks = chunks
            self.current_page = 0
            self.author = author
        async def interaction_check(self, interaction: discord.Interaction) -> bool:
            if interaction.user != self.author:
                await interaction.response.send_message("You can't use these buttons.", ephemeral=True)
                return False
            return True
        @discord.ui.button(label="⬅️", style=discord.ButtonStyle.secondary)
        async def previous_button(self, interaction: discord.Interaction, button: discord.ui.Button):
            if self.current_page > 0:
                self.current_page -= 1
            else:
                self.current_page = len(self.chunks) - 1
            self.embed.description = self.chunks[self.current_page]
            await interaction.response.edit_message(embed=self.embed)
        @discord.ui.button(label="➡️", style=discord.ButtonStyle.secondary)
        async def next_button(self, interaction: discord.Interaction, button: discord.ui.Button):
            if self.current_page < len(self.chunks) - 1:
                self.current_page += 1
            else:
                self.current_page = 0
            self.embed.description = self.chunks[self.current_page]
            await interaction.response.edit_message(embed=self.embed)
    @bot.tree.command(name="lyrics", description="Get lyrics from any song")
    async def lyrics(interaction: discord.Interaction, song_name: str):
        await interaction.response.defer()
        lyrics, album_art_url, song = get_song_and_lyrics(song_name)
        if lyrics.startswith("Couldn't find lyrics for"):
            title = song_name
        else:
            artist = song.artist
            title = f'{song.title}: by {artist}'
        chunks = chunk_string(lyrics, 512)
        embed = discord.Embed(
            title=title,
            description=chunks[0],
            color=discord.Color(0x2b2d31)
        )
        if album_art_url:
            embed.set_thumbnail(url=album_art_url)
            embed.set_footer(text=bot.user.name, icon_url=bot.user.avatar.url)
        view = LyricsView(embed, chunks, interaction.user)
        await interaction.edit_original_response(embed=embed, view=view)

问题分析

当前代码的过滤逻辑if not line.startswith('[')仅检查行的第一个字符是否为「[」,但Genius返回的部分元数据行开头会带有空格或制表符(比如 [Chorus]),这类行无法被现有逻辑过滤,导致残留。

修复方案

修改get_song_and_lyrics函数中的歌词过滤逻辑,先去除每行首尾的空白字符,再判断是否以「[」开头,同时可额外移除过滤后产生的空行,让歌词更整洁:

def get_song_and_lyrics(song_name):
    song = genius.search_song(song_name)
    if song is not None:
        # 先去除每行首尾空白,再过滤以[开头的行
        filtered_lines = [line for line in song.lyrics.split('\n') if not line.strip().startswith('[')]
        # 移除多余空行
        cleaned_lyrics = '\n'.join(line for line in filtered_lines if line.strip())
        return cleaned_lyrics, song.song_art_image_url, song
    else:
        return "Couldn't find lyrics for " + song_name, None, None

验证说明

修改后,无论元数据行是否带有前置空白,都会被正确过滤,同时空行被移除,歌词显示会符合预期的干净效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:45:20