Good morning everybody. I’d like to send a document using Python and the API from Telegram Bot. The Bot has been successfully created and I can also send messages, but unfortunately I’m not managing to send documents that are on my Laptop.
My Code is the following:
import requests
def telegram_bot_send_document():
bot_token = '####'
bot_chatID = '####'
file = open('test.txt', 'rb')
send_document = 'https://api.telegram.org/bot' + bot_token + '/sendDocument?chat_id=' + bot_chatID + '&multipart/form-data=' + str(file.read())
r = requests.post(send_document)
print(r.url)
return r.json()
The Output is always:
{'ok': False, 'error_code': 400, 'description': 'Bad Request: there is no document in the request'}
3
Answers
First of all, I have never used the telegramm API oder send documents with telegram.
From their documentation:
(source: https://core.telegram.org/bots/api#sending-files)
You need to upload first the file and reference the ID or you need a
POST
-Request, not attached to theURL
.Though its late, I thought I must share for others who might face the same problem as I did.
From Antonio’s code there are two major modifications:
Passing stream=True in post()
When uploading files, requests requires us to pass the stream=True parameter so that the file can be downloaded on the server side. You can read more about it Here. Also, since it is a post request with multipart/form-data, we are required to pass the data parameter which carries the data(chat_id, caption, parse_mode etc) as well as the files parameter which carries the document in binary.
Opening the file within post()
This is weird and I have not found out why, but when I opened my file into a varible like
file = open('text.txt','rb)
and reference it in files parameter likerequests.post(url, data=data, files=file)
, Telegram would throw a Bad Request saying no document found, But when I opened the file within the files parameter likerequests.post(url, data=data, files=open('text.txt','rb'))
, It worked fine.So the final code should look like this:
I have tried all of the above and spent a day searching for the right answer to the question but found nothing anywhere. Weird!
But finally after testing and modifying the answer of @Nengha here’s my solution that works perfectly fine.