Lleims
Lleims

Reputation: 1353

Sending documents with python and Telegram

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!

Upvotes: 0

Views: 1332

Answers (2)

druskacik
druskacik

Reputation: 2497

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)
        
        ...

Upvotes: 1

Milad Gialni
Milad Gialni

Reputation: 66

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")

Upvotes: 0

Related Questions