sehrob sehrob - 4 years ago 126
Python Question

How to turn curl command into python equivalent?

I'm trying to implement a python script which will set a webhook with the

method of telegram bot api. As it is explained here after creating a self-signed certificate we can achieve this with this curl command:

curl -F "url=https://<YOURDOMAIN.EXAMPLE>/<WEBHOOKLOCATION>" \
-F "certificate=@<YOURCERTIFICATE>.pem" https://api.telegram.org/bot<YOURTOKEN>/setWebhook


Calling this curl command set the webhook without any problem and I get updates through it.

But now I'm trying to achieve this with the python script so I could just call it with some command line arguments so it set webhook for me, get info about it or delete it. What I wrote so far is this:

files = {
'file': ('certificate', open(configuration.CERTFILE, 'rb'))
}

headers = {'Content-Type': 'multipart/form-data'}

data = {
'url': configuration.WEBHOOK_URL,
}

url = configuration.API % 'setWebhook'
rp = requests.post(url, headers=headers, data=data, files=files)

print('result of setWebhook: ', rp.status_code)


The status code of the response is
400 Bad Request
. I think that I'm sending the request the wrong way.

Any ideas about what is wrong with my
requests
request to telegram bot api?

Answer Source

Removing headers parameter and renaming the key of the files parameter did the trick. So, now my code looks like this:

files = {
    'certificate': ('certificate', open(configuration.CERTFILE, 'rb'))
}

data = {
    'url': configuration.WEBHOOK_URL,
}

url = configuration.API % 'setWebhook'
rp = requests.post(url, data=data, files=files)

and it works as intended. Thanks gays!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download