python-3.x 如何通过HTTP向Telegram bot发送文件?

0md85ypi  于 2022-12-27  发布在  Python
关注(0)|答案(2)|浏览(113)

我想通过http电报API发送文件,并尝试以下代码:

def send_media(self, chat_id, doc):
    method = 'sendDocument'
    params = {'chat_id': chat_id, 'document': doc}
    resp = requests.post(self.api_url + method, params)
    return resp
 document = open('table.csv', 'rb')
 doc = InputFile(document)
 bot.send_media(last_chat_id, doc).json()
 document.close()

并有这样的错误要求:

{'ok': False, 'error_code': 400, 'description': 'Bad Request: wrong URL host'}

我应该怎么做才能发送文件?

egmofgnx

egmofgnx1#

这里的问题是 requests 库的错误用法,如果你发送multipart/form-data和文件,你应该使用参数files
例如

requests.post(self.api_url + method, data={'chat_id': chat_id}, files={'document': document})

文档的链接-http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

tag5nh1u

tag5nh1u2#

我决定在上面的答案之外再写一个,因为它对我有帮助,但是因为我是个新手,所以我花了一些时间来理解它。所以我希望我的代码示例能帮助那些试图解决同样问题的人保存时间:

document = open("<filename, like: 'test.txt'>", "rb")
url = f"https://api.telegram.org/bot{YOUR_BOT_TOKEN}/sendDocument"
response = requests.post(url, data={'chat_id': chat_id}, files={'document': document})
# part below, just to make human readable response for such noobies as I
content = response.content.decode("utf8")
js = json.loads(content)
print(js)

答复示例:

{'ok': True, 'result': {'message_id': 865, 'from': {'id': 111111, 'is_bot': True, 'first_name': 'BotName', 'username': 'LongBotName'}, 'chat': {'id': 111111, 'first_name': 'Name', 'last_name': 'Surname', 'username': 'user', 'type': 'private'}, 'date': 1672056973, 'document': {'file_name': 'test.txt', 'mime_type': 'text/plain', 'file_id': 'BQACAgIAAxkDAAIDYWOpkI1wkcuXMTy8hlob6Vr46UFxAALLJAACG1pJSX0tj7Ubt_sTLAQ', 'file_unique_id': 'AgADyyQAAhtaSUk', 'file_size': 239}}}

结果,bot通过我们指定的chat_id将文件发送给用户

另请注意:要发送的文件必须与执行此代码的.py文件位于同一位置

相关问题