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

如何在aiogram中修改音频缩略图?已实现代码但未生效

问题分析与解决方案

问题原因

直接使用Telegram已存储音频的file_id调用send_audio时,服务器会复用该音频的原始元数据(包括缩略图),你传入的thumb参数不会生效——因为Telegram不会重新处理已存在的文件资源。

解决步骤

要替换音频缩略图,必须重新上传音频文件(而非复用已有file_id),同时指定新的缩略图。具体修改如下:

修改后的完整代码

import os
from telegram import types
from telegram.ext import CallbackContext

# 假设你的状态定义不变
GET_IMAGE = 1

@dp.message_handler(content_types=['audio'], state=None)
async def get_music(message: types.Message, state: CallbackContext):
    async with state.proxy() as data:
        data['audio_id'] = message.audio.file_id
        data['chat_id'] = message.chat.id

    await message.answer("send photo...")
    await state.set_state(GET_IMAGE)

@dp.message_handler(content_types=['photo'], state=GET_IMAGE)
async def send_audio_with_thumb(message: types.Message, state: CallbackContext):
    async with state.proxy() as data:
        audio_id = data['audio_id']
        chat_id = data['chat_id']
        # 获取最高分辨率的图片file_id
        image_file_id = message.photo[-1].file_id

        # 1. 下载原音频到本地临时文件
        audio_file = await bot.get_file(audio_id)
        temp_audio_path = 'temp_audio.mp3'
        await audio_file.download_to_drive(temp_audio_path)

        try:
            # 2. 上传本地音频并指定新缩略图
            await bot.send_audio(
                chat_id=chat_id,
                audio=open(temp_audio_path, 'rb'),
                thumb=image_file_id,
                # 可选:保留原音频的标题、表演者等信息
                title=message.audio.title,
                performer=message.audio.performer
            )
        finally:
            # 3. 清理临时文件
            if os.path.exists(temp_audio_path):
                os.remove(temp_audio_path)

    await state.finish()

关键说明

  • 必须下载原音频文件到本地,再通过本地文件对象上传,Telegram才会重新生成音频的元数据并应用新缩略图。
  • 使用download_to_drive方法下载文件,完成后记得删除临时文件避免磁盘占用。
  • 可选保留原音频的标题、表演者等信息,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:40:17