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

使用Pyrogram为已发送文本消息添加图片报错,求替代方案

Pyrogram编辑纯文本消息添加图片报错及替代方案

问题描述

我正在开发一款Telegram机器人,需求是先发送一条文本消息,过一段时间后编辑该消息并为其添加图片。使用Pyrogram框架,代码片段如下:

@app.on_message(filters.command(["start"]))
async def start(client, message):
    test_message = await message.reply_text("Hello World")
    await test_message.edit_media(
        InputMediaPhoto(media="./img/1.png")
    )

运行时报错:

pyrogram.errors.exceptions.bad_request_400.MessageEmpty: Telegram says: [400 MESSAGE_EMPTY] - The message sent is empty or contains invalid characters (caused by "messages.EditMessage")

更新:发现无法直接为已有的纯文本消息添加图片,求可行的替代方案。

解决方案

Telegram API本身不支持将纯文本消息直接编辑为带媒体的消息,这是平台层面的限制,下面提供两种可行的替代方案:

方案一:先发送媒体消息,再编辑添加文本

先发送带图片的消息(文本可设为空占位),之后再编辑消息添加需要的文本内容,示例代码:

import asyncio
from pyrogram import Client, filters

@app.on_message(filters.command(["start"]))
async def start(client, message):
    # 先发送带图片的消息,文本暂时为空
    test_message = await message.reply_photo(
        photo="./img/1.png",
        caption=""
    )
    # 模拟延迟(根据实际需求调整或删除)
    await asyncio.sleep(5)
    # 编辑消息添加目标文本
    await test_message.edit_caption(caption="Hello World")

方案二:删除原文本消息,重新发送带图带文本的消息

先发送纯文本消息,延迟后删除原消息,再重新发送包含图片和文本的新消息,示例代码:

import asyncio
from pyrogram import Client, filters

@app.on_message(filters.command(["start"]))
async def start(client, message):
    test_message = await message.reply_text("Hello World")
    # 模拟延迟(根据实际需求调整或删除)
    await asyncio.sleep(5)
    # 删除原文本消息
    await test_message.delete()
    # 重新发送带图片和文本的消息
    await message.reply_photo(photo="./img/1.png", caption="Hello World")

方案对比

  • 方案一:保留原消息ID,不会产生消息删除的提示,用户体验更流畅,但需要调整发送顺序,先发送媒体消息。
  • 方案二:逻辑更直观,符合最初的思路,但会留下消息删除的痕迹,用户能看到原消息被移除后出现新消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:18:12