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

Discord音乐Bot关键词搜索超时问题求助

缩短ytdlp ytsearch搜索时长的优化方案

针对你的Discord音乐Bot搜索超时问题,以下是几个直接有效的优化方向:

  • 精简元数据抓取
    ytdlp默认会获取视频的完整元数据(如评论、高清缩略图、详细描述等),但搜索菜单只需要基础信息。在配置中开启extract_flat=True,让ytdlp只返回搜索结果的表层数据,跳过每个视频的深度抓取,能大幅减少请求时间:

    ydl_opts = {
        'extract_flat': True,
        'quiet': True,
        'no_warnings': True,
        'default_search': 'ytsearch5',  # 直接指定返回前5条结果
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        search_result = ydl.extract_info(your_search_query, download=False)
    
  • 收紧超时与重试配置
    减少不必要的等待和重试次数,避免耗时过长:

    ydl_opts.update({
        'socket_timeout': 2.5,  # 套接字超时设为2.5秒,接近Discord的3秒阈值
        'retries': 1,
        'fragment_retries': 0,
        'skip_unavailable_fragments': True
    })
    
  • 缓存高频搜索关键词
    对用户常搜的关键词做短期缓存(比如5分钟),避免重复请求YouTube:

    from cachetools import TTLCache
    
    # 缓存100条结果,5分钟后过期
    search_cache = TTLCache(maxsize=100, ttl=300)
    
    def get_search_results(query):
        if query in search_cache:
            return search_cache[query]
        # 执行ytdlp搜索逻辑
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            result = ydl.extract_info(query, download=False)
        search_cache[query] = result
        return result
    
  • 异步化搜索任务+临时响应
    Discord交互有3秒响应限制,先发送临时提示再异步处理搜索,避免触发超时失败:

    import asyncio
    
    async def handle_search_interaction(interaction, query):
        # 先发送临时响应,告知用户正在搜索
        await interaction.response.defer(ephemeral=False)
        # 在后台线程执行搜索,不阻塞Bot主循环
        search_result = await asyncio.to_thread(get_search_results, query)
        # 编辑消息返回搜索菜单
        await interaction.edit_original_response(embed=build_search_menu_embed(search_result))
    
  • 优化网络连接
    如果服务器访问YouTube延迟高,可配置ytdlp使用代理(确保合规):

    ydl_opts['proxy'] = 'http://your-proxy-server:port'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:27:43