1

I'm trying to send documents via Telegram API but I'm getting an error.

The class I have created is the following:

def sendDocument(self):
        url = self.url + '/sendDocument'
        fPath = 'C:/Users/users/user/OneDrive - Personal/syslog.txt'
        params = {
            'chat_id': self.chat_id,
            'document': open(fPath, 'rb')
        }
        resp = requests.post(url, params=params)
        if resp.status_code != 200: print('Status: ', resp.status_code)

I have relied on documentation I have found on the internet, as well as on the class I have already created and IT DOES WORK, to send text messages:

def sendMessage(self, text):
        url = self.url + '/sendMessage'
        params = {
            'chat_id': self.chat_id,
            'text': text,
            'parse_mode': 'HTML'
        }
        resp = requests.post(url, params=params).
        if resp.status_code != 200: print('Status: ', resp.status_code)

Could someone help me understand where the error is? Thank you very much!

CallMeStag
  • 5,467
  • 1
  • 7
  • 22
Lleims
  • 1,275
  • 12
  • 39
  • Does this answer your question? [How to upload file with python requests?](https://stackoverflow.com/questions/22567306/how-to-upload-file-with-python-requests) – CallMeStag Aug 03 '22 at 19:12

2 Answers2

1

The params adds query parameters to url, and it's impossible to send files this way. To send files with the requests library, you should use files parameter:

def sendDocument(self):
        url = self.url + '/sendDocument'
        fPath = 'C:/Users/users/user/OneDrive - Personal/syslog.txt'

        params = {
            'chat_id': self.chat_id,
        }

        files = {
            'document': open(fPath, 'rb'),
        }
        
        resp = requests.post(url, params=params, files=files)
        
        ...
druskacik
  • 2,176
  • 2
  • 13
  • 26
0

I think you should share file name in prams like below:

c_id = '000011'   
filename = '/tmp/googledoc.docx'

context.bot.send_document(chat_id='c_id', document=open('googledoc.docx', 'rb'), filename="googledoc.docx")
Milad Gialni
  • 46
  • 1
  • 8