Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

API send photo to telegram bot by URL

hi I want to send a photo by telegram API to my bot and I must use API URL to send and can not use library.

I tried:

token = " "
chat_id = " "
pic = ("C:\Windows\pic\hello.jpg")

url = requests.post("https://api.telegram.org/bot"+token+"/sendPhoto?chat_id="+chat_id+"&photo="+pic)

print(url)

And result:

{"ok":false,"error_code":400,"description":"Bad Request: wrong HTTP URL specified"}
question from:https://stackoverflow.com/questions/66051610/api-send-photo-to-telegram-bot-by-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, It is sendPhoto not sendphoto.

Here is the link for docs for your reference.

Notice that you are giving the url for post requets as: https://api.telegram.org/bot"+token+"/sendphoto?chat_id="+chat_id+"&photo="+pic but it actually should be https://api.telegram.org/bot"+token+"/sendPhoto?chat_id="+chat_id+"&photo="+pic


Secondly, you are trying to send a locally hosted image. Its a bit different to send locally hosted images than to send the URLs for online images.

You have to send the image file as a dictionary along with the post request like this:

import requests

img = open(your/local/image, 'rb')
TOKEN = 
CHAT_ID = 

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


print(requests.post(url, files={'photo': img}))

Output:

<Response [200]>



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...