首页 > 解决方案 > 如何使用电报 api 在我的机器人上发送图像?

问题描述

谁能告诉我如何使用python中的请求库从互联网发送照片?

我目前正在尝试将照片发送为:

https://api.telegram.org/bot<token>/sendPhoto-Fchat_id=<MY-ID>-Fphoto=https://random.dog/7e1527a4-9c07-48df-a877-4c6e4681adc1.jpg

先感谢您

标签: python-3.xtelegram-bot

解决方案


您传递了错误的 url 参数。

而是sendPhoto-Fchat_id使用?and&符号。如果您想添加多个参数;看看Python 中使用请求的查询字符串数组参数

sendPhoto?chat_id=123&photo=somelink

要回答这个问题,您可以像这样使用请求库:

import requests
from requests.exceptions import HTTPError

url="https://api.telegram.org/bot<MY-TOKEN>/sendPhoto?chat_id=<MY-CHAT-ID>&photo=http://via.placeholder.com/100x100"

try:
    response = requests.get(url)

    # If the response was successful, no Exception will be raised
    response.raise_for_status()
except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')  # Python 3.6
except Exception as err:
    print(f'Other error occurred: {err}')  # Python 3.6
else:
    print('Success!')


推荐阅读