简体   繁体   English

使用 Python 请求将照片上传到 Telegram API

[英]Upload photo to Telegram API with Python Requests

I've seen the other questions on this but I can't figure out where I'm going wrong.我已经看到了关于此的其他问题,但我无法弄清楚我哪里出错了。 I can upload a file no problem using a PHP page that looks like this:我可以使用如下所示的 PHP 页面毫无问题地上传文件:

<form action="https://api.telegram.org/bot190705145:AAH17XDRrPtDO1W1qHCoZ8i0_KqAAAAAAA/sendPhoto" method="post" enctype="multipart/form-data">

    <input type="text" name="chat_id" value="XXXXXXXX" />
    <input type="file" name="photo" />
    <input type="submit" value="send" />

</form>

But I want to do it from Python with Requests:但我想通过请求从 Python 中做到这一点:

url = 'https://api.telegram.org/bot190705145:AAH17XDRrPtDO1W1qHCoZ8i0_KAAAAAAAAA/sendPho    to?chat_id=XXXXXXXXX'
files = {'file':open('/Users/stephen/desktop/Sample.png', 'rb')}
r = requests.post(url, files=files)

Which then gives me the r.text error:然后给了我 r.text 错误:

u'{"ok":false,"error_code":400,"description":"[Error]: Bad Request: there is no photo in request"}'

And I'm thinking I am mishandling the chat_id parameter also and it needs to be passed in a different way.而且我认为我也对 chat_id 参数处理不当,它需要以不同的方式传递。

Any guidance much appreciated!非常感谢任何指导!

You can use the following code:您可以使用以下代码:

import requests

_TOKEN = "YOUR TOKEN HERE"


def send_photo(chat_id, image_path, image_caption=""):
    data = {"chat_id": chat_id, "caption": image_caption}
    url = "https://api.telegram.org/%s/sendPhoto" % _TOKEN
    with open(image_path, "rb") as image_file:
        ret = requests.post(url, data=data, files={"photo": image_file})
    return ret.json()

Cheers干杯

It's from a comment from Ashwini Chaudhary (it seems so obvious once said, thank you very much).这是来自 Ashwini Chaudhary 的评论(曾经说过似乎很明显,非常感谢)。 Changing: files = {'file':open('/Users/stephen/desktop/Sample.png', 'rb')} to: files = {'photo':open('/Users/stephen/desktop/Sample.png', 'rb')} Worked for me and it seems that it was the issue for several others.更改:files = {'file':open('/Users/stephen/desktop/Sample.png', 'rb')} 到:files = {'photo':open('/Users/stephen/desktop/Sample. png', 'rb')} 为我工作,这似乎是其他几个人的问题。 Thank you谢谢

this error related to file type.此错误与文件类型有关。 like this(in html):像这样(在 html 中):

 <input type="file" name="photo" />

you should change file type to image or photo, but i don't know python.您应该将文件类型更改为图像或照片,但我不知道 python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM