如何使用pytelegrambotapi在Telegram中回复带图片的消息
pyTelegramBotAPI回复消息附带图片实现方案
核心实现逻辑为调用send_photo方法时传入reply_to_message_id参数指定需要回复的目标消息ID,即可实现回复消息同时附带图片的效果,以下是不同场景的可运行示例:
前置准备
先完成bot基础初始化:
import telebot # 替换为你自己的Bot Token BOT_TOKEN = "你的bot_token" bot = telebot.TeleBot(BOT_TOKEN)
场景1:发送本地存储的图片
@bot.message_handler(content_types=["text"]) def reply_local_photo(message): # 打开本地图片文件,替换为你自己的图片路径 photo = open("./test.jpg", "rb") bot.send_photo( chat_id=message.chat.id, photo=photo, caption="图片附带的说明文字,可选参数", reply_to_message_id=message.message_id # 核心参数,指定要回复的消息ID ) photo.close()
场景2:发送Telegram服务器已存储的图片(无需重复上传)
如果之前已经上传过该图片到Telegram,可以直接使用返回的file_id发送,速度更快:
@bot.message_handler(content_types=["text"]) def reply_photo_by_fileid(message): # 替换为你自己的图片file_id PHOTO_FILE_ID = "AgACAgUAAxkDAAMwY..." bot.send_photo( chat_id=message.chat.id, photo=PHOTO_FILE_ID, caption="通过file_id发送的图片", reply_to_message_id=message.message_id )
场景3:发送公网可访问的在线图片
直接传入图片的公网URL即可,SDK会自动下载并发送:
@bot.message_handler(content_types=["text"]) def reply_online_photo(message): # 替换为实际的公网图片URL PHOTO_URL = "https://example.com/test.png" bot.send_photo( chat_id=message.chat.id, photo=PHOTO_URL, caption="公网在线图片", reply_to_message_id=message.message_id )
启动bot
if __name__ == "__main__": bot.infinity_polling()
常见注意事项
- 单张图片大小不能超过10MB,支持JPG、PNG等常见图片格式
- 如果目标回复消息已被删除,接口会返回错误,可自行添加
try-except捕获异常 - 若在群组中发送,需要确保bot拥有群组的发送消息权限
内容的提问来源于stack exchange,提问作者Lalan Kumar
相关产品推荐
相关产品推荐

