如何使用 python 通过 telegram API 通过 URL 发送图像?

Mar*_*nez 5 python api telegram

我有以下代码来发送图像,但我只能发送本地图像,如何通过仅指定 URL 来发送图像?

from PIL import Image
import requests

img = open("https://images.unsplash.com/photo-1498050108023-c5249f4df085?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1172&q=80")

TOKEN = "token"
CHAT_ID = "@channel_id"

url = f'https://api.telegram.org/bot{TOKEN}/sendPhoto?chat_id={CHAT_ID}'


print(requests.get(url, files={'photo': img}))
Run Code Online (Sandbox Code Playgroud)

如何通过链接发送图像?

先感谢您。

PCD*_*Man 0

你可以这样做:

import io
from PIL import Image
import requests

TOKEN = "token"
CHAT_ID = "@channel_id"
url = f"https://api.telegram.org/bot{TOKEN}/sendPhoto?chat_id={CHAT_ID}"

img_url = "https://images.unsplash.com/photo-1498050108023-c5249f4df085?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1172&q=80"
response = requests.get(img_url)
img = Image.open(response.content)

# save image in memory
img_bytes = io.BytesIO()
img.save(img_bytes, format="PNG")
img_bytes.seek(0)


files = {"photo": img_bytes}
requests.post(url, files=files)
Run Code Online (Sandbox Code Playgroud)