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

如何基于python-telegram-bot(ASYNC)向机器人用户发送媒体(图片)?

使用python-telegram-bot异步版本发送图片的方法

1. 安装异步版本

首先安装支持异步的python-telegram-bot(v13及以上为异步优先版本):

pip install python-telegram-bot[asyncio]

2. 核心实现方法

异步版本中发送图片主要依赖context.bot.send_photo()方法,支持网络URL、本地文件、字节流三种图片来源,以下是具体场景的代码示例:

场景1:发送网络图片

触发指定命令时向用户发送网络图片:

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

async def send_net_pic(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 替换为实际可访问的图片URL
    pic_url = "https://example.com/your-image.jpg"
    # 发送图片并附带说明文字
    await context.bot.send_photo(
        chat_id=update.effective_chat.id,
        photo=pic_url,
        caption="这是一张网络图片"
    )

async def main():
    # 替换为你的机器人Token
    app = ApplicationBuilder().token("YOUR_BOT_TOKEN").build()
    app.add_handler(CommandHandler("sendnetpic", send_net_pic))
    await app.run_polling()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

场景2:发送本地图片

读取本地存储的图片文件发送给用户:

async def send_local_pic(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 替换为本地图片的实际路径
    local_pic_path = "./local-image.jpg"
    await context.bot.send_photo(
        chat_id=update.effective_chat.id,
        photo=open(local_pic_path, 'rb'),
        caption="这是一张本地图片"
    )

场景3:回复消息时发送图片

在回复用户某条消息的同时发送图片:

async def reply_with_pic(update: Update, context: ContextTypes.DEFAULT_TYPE):
    pic_url = "https://example.com/reply-image.jpg"
    await context.bot.send_photo(
        chat_id=update.effective_chat.id,
        photo=pic_url,
        caption="回复你的图片",
        reply_to_message_id=update.effective_message.id
    )

3. 注意事项

  • 网络图片需确保URL可公开访问,否则机器人无法获取资源
  • 本地图片需保证机器人进程拥有文件读取权限
  • 单张图片大小不能超过Telegram限制的10MB
  • 可捕获TelegramError异常处理发送失败的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:19:53