如何使用Python通过Telegram API通过URL发送图像?

发布于 2025-01-23 11:25:04 字数 569 浏览 1 评论 0原文

我有以下代码发送图像,但是我只能发送本地映像,如何通过指定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}))

如何通过链接发送图像?

先感谢您。

I have the following code to send image, but I can send only local images, how can I send image by specifying just 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}))

How can I send image by link?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晒暮凉 2025-01-30 11:25:04

您可以做这样的事情:

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)

You could do something like this:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文