skip to Main Content

I’m trying to implement a python script which will set a webhook with the setWebhook 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?

2

Answers


  1. Chosen as BEST ANSWER

    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)
    

  2. The exact curl query taking two file parameters -F can be converted into python-requests into

    import requests
    
    files = {
        'url': 'https://<YOURDOMAIN.EXAMPLE>/<WEBHOOKLOCATION>',
        'certificate': open('<YOURCERTIFICATE>.pem', 'rb')
    }
    
    requests.get('https://api.telegram.org/bot<YOURTOKEN>/setWebhook', files=files)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search