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

Discord Bot优化:从Genius随机选艺术家歌曲并发送歌词片段

Discord Bot Lyrics命令优化方案

现有代码问题

原代码用嵌套的on_message监听获取用户输入,容易引发监听冲突,而且search_artist默认会抓取艺术家的大量歌曲,导致等待时间过长,也没实现随机选歌和发送歌词片段的核心需求。

优化后的完整代码

import random
import asyncio
import lyricsgenius
from discord.ext import commands

@client.command()
async def lyrics(ctx):
    genius = lyricsgenius.Genius(api_key)
    # 发送歌手名称询问
    await ctx.send("**请输入歌手名称:**")
    
    try:
        # 等待用户输入,30秒超时自动取消
        msg = await client.wait_for("message", check=lambda m: m.author == ctx.author, timeout=30.0)
        artist_name = msg.content.strip()
        
        # 搜索艺术家,限制最多抓取20首热门歌曲(减少耗时)
        artist = genius.search_artist(artist_name, max_songs=20, sort="popularity", include_features=False)
        if not artist:
            await ctx.send(f"未找到名为「{artist_name}」的歌手,请检查名称是否正确。")
            return
        
        # 随机选一首歌曲
        random_song = random.choice(artist.songs)
        # 加载歌曲歌词
        random_song.lyrics
        
        # 提取歌词片段(取前10行,避免内容过长)
        lyric_lines = random_song.lyrics.split("\n")
        lyric_snippet = "\n".join(lyric_lines[:10])
        
        # 发送结果
        await ctx.send(f"🎵 **{artist.name} - {random_song.title}**\n\n{lyric_snippet}\n\n...(完整歌词请前往Genius查看)")
    
    except asyncio.TimeoutError:
        await ctx.send("超时未输入,命令已取消。")
    except Exception as e:
        await ctx.send(f"获取歌词时出错:{str(e)}")

优化说明

  • 用wait_for替代嵌套监听:这是Discord.py处理命令内用户输入的标准方式,避免全局监听冲突,还自带超时处理
  • 限制抓取歌曲数量:通过max_songs=20减少search_artist的工作量,大幅缩短等待时间,同时按热度排序优先获取热门歌曲
  • 随机选歌逻辑:用random.choice从艺术家的歌曲列表里随机挑一首
  • 歌词片段提取:把歌词按行分割后取前10行,避免刷屏,同时提示完整歌词的获取途径
  • 错误处理:覆盖了超时、歌手不存在、未知错误等场景,提升命令稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:10:33