K
K
KitCat122021-12-30 18:47:05
Python
KitCat12, 2021-12-30 18:47:05

Why is the archive not sent via urllib.request?

I'm trying to send an archive to Telegram via urllib, I get an error about closing the connection without a response.

RemoteDisconnected('Remote end closed connection without response')


What am I doing wrong?

from os import stat
from urllib import request, parse

token = ""
user_id = 0

with open("files.zip", "rb") as f:

    headers = {'Content-Type': 'application/zip',  'Content-Length': stat("files.zip").st_size}

    r = request.Request(
        url=f"https://api.telegram.org/bot{token}/sendDocument?chat_id={user_id}",
        data=parse.urlencode({"document": f}).encode("utf-8"),
        headers=headers
    )
    request.urlopen(r)

file.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2021-12-30
@KitCat12

I haven't used urllib for 30 years (and the offline documentation recommends using requests), so I advise you to use requests too:

import requests

user_id = 121495485
token = ''

files = {'document': open('files.zip', 'rb')}
response = requests.post(f'https://api.telegram.org/bot{token}/sendDocument?chat_id={user_id}',files=files)

print(response.text)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question