Python Flask server getting 'code 400' errors (POST request sent from Telegram-webhook)

JaFizz

Context

I'm currently following this tutorial. - Telegram Bot with Python Tutorial #3: Creating Bot and Webhook | Project


FIRST STEP

I have set-up a Flask server using the following python code:

from flask import Flask
from flask import request
from flask import Response
import json

app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':

        print(request)

        message = request.json()

        with open('telegram_request.json', 'w', encoding='utf-8') as filename:
            json.dump(message, filename, ensure_ascii=False, indent=4)

        # prevents telegram from spamming
        return Response('Ok', status=200)
    else:
        return """
            <h1> Flask Server </h1>
            <h2> Up and running </h2>
        """


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8443)


SECOND STEP

I port forwarded port 8443 in my router to make the server visible to the outside world (tunneling step in tutorial).

The domain name "myprivatedomain.com:8443" now redirects/refers to the flask server that is set-up.


THIRD STEP

I set-up the Telegram-API webhook correctly, getting the following response code from Telegram:

{"ok":true,"result":true,"description":"Webhook was set"}


NOW

Before sending a message in the Telegram chat: there were no errors.

After sending a message in the chat, the following errors popped up:

code 400, message Bad HTTP/0.9 request type ('RANDOM BYTE VALUES like \x00\x03')

code 400, message Bad request syntax ('RANDOM BYTE VALUES like \x00\x03')

code 400, message Bad request version ('RANDOM BYTE VALUES like \x00\x03')


WHAT I WANT

According to the tutorial, you can write a .json file when Telegram makes a POST request (see example: here). I want to save the message object provided by the Telegram webhook (as showcased in the tutorial video). Using the webhook for getting updates is better than constantly querying the getUpdates() method; that method returns old messages also.


WHAT I'VE TRIED

I've tried to add:

ssl_context='adhoc'

to

app.run(debug=True, host='0.0.0.0', port=8443)

to make the connection HTTPS.

While using this ssl_context, loading the homepage isn't possible either..


PREFERABLE OUTPUT

When the user sends a message inside the Telegram chat --> Python saves a .json file of the message object.

jgeigerm

You need to have SSL enabled for this to work. Telegram is trying to initiate an SSL session with your server, but you don't have SSL enabled, so you are seeing the bad request.

ssl_context='adhoc' may work for a test app, but I also have a hunch that telegram requires a VALID SSL certificate, not just an ad-hoc (or self-signed one). Notice the lock to the left of the URL in the video and the lack of a security warning that would be present with an invalid or self-signed certificate.

To make sure SSL is working set the ssl_context to adhoc, start the app, and browse to https://myprivatedomain.com:8443/index. If you can browse to it, then Telegram will also be able to browse to it, after getting a valid certificate, of course.

Next, to get a valid (and free) SSL certificate you can use LetsEncrypt.

Once you have a valid SSL certificate and key file you can pass the ssl_context argument to app.run with a tuple of the path to the certificate file and the path to the key file ("/path/to/fullchain.pem", "/path/to/privkey.pem")

Your full run function should look like this

app.run(debug=True, host='0.0.0.0', port=8443, ssl_context=("/path/to/fullchain.pem", "/path/to/privkey.pem"))

Alternatively you can use Apache or Nginx to secure your site with SSL, and reverse proxy to your bot. Those options would normally be used in a final product, so I understand if you don't want to get into the weeds with them right now, but it is good practice regardless.

Hopefully that helps.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From PHP

$_POST variable is empty when code is executed using Telegram webhook

From Dev

'400 Bad Request' when post json in Flask

From Dev

POST flask server with XML from python

From Dev

flask returns 400 on post request from postman

From Dev

Getting 400 Bad Request for Spring RestTemplate POST

From Dev

python post request throwing '400 Bad Request'

From Dev

POST request getting 400 error code with pydev Eclipse but working on Postman

From Dev

Getting 400 request from api server

From Dev

Why does this Python POST Request returns 400 Bad Request Code?

From Dev

sending compressed numpy array (zlib) to flask server with post request [python]

From Dev

How can I get a return value from a post request sent from javascript to flask

From Dev

url request from python getting "blocked" by server

From Dev

Telegram Bot: Wrong response from the webhook: 404 Bad Request

From Dev

Post Request to web server with Flask

From Dev

MEAN : Getting Error 400 (Bad Request) on POST

From Dev

POST request with python 400 Bad Request

From Dev

Retrofit getting 400 bad request in local iis server but 200 in post man

From Dev

400 Bad Request: The browser (or proxy) sent a request that this server could not understand

From Dev

POST request to flask server for automated testing. 400 Bad Request, KeyError 'files'

From Dev

Flask JSON not working: BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

From Dev

Why does Telegram give me an empty POST request on the webhook?

From Dev

Flask - getting value from radio button? werkzeug.exceptions.BadRequestKeyError: 400 Bad Request

From Dev

Bad Request (400) for POST request to ASP.NET Core 6, minimal API, sent from Postman

From Dev

Flask responds to all POST requests with code 400

From Dev

Getting 400 from Axios Post request

From Dev

Flask python - Bad Request: The browser (or proxy) sent a request that this server could not understand

From Dev

flask error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

From Dev

flask error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

From Dev

POST request from python to nodeJS server

Related Related

  1. 1

    $_POST variable is empty when code is executed using Telegram webhook

  2. 2

    '400 Bad Request' when post json in Flask

  3. 3

    POST flask server with XML from python

  4. 4

    flask returns 400 on post request from postman

  5. 5

    Getting 400 Bad Request for Spring RestTemplate POST

  6. 6

    python post request throwing '400 Bad Request'

  7. 7

    POST request getting 400 error code with pydev Eclipse but working on Postman

  8. 8

    Getting 400 request from api server

  9. 9

    Why does this Python POST Request returns 400 Bad Request Code?

  10. 10

    sending compressed numpy array (zlib) to flask server with post request [python]

  11. 11

    How can I get a return value from a post request sent from javascript to flask

  12. 12

    url request from python getting "blocked" by server

  13. 13

    Telegram Bot: Wrong response from the webhook: 404 Bad Request

  14. 14

    Post Request to web server with Flask

  15. 15

    MEAN : Getting Error 400 (Bad Request) on POST

  16. 16

    POST request with python 400 Bad Request

  17. 17

    Retrofit getting 400 bad request in local iis server but 200 in post man

  18. 18

    400 Bad Request: The browser (or proxy) sent a request that this server could not understand

  19. 19

    POST request to flask server for automated testing. 400 Bad Request, KeyError 'files'

  20. 20

    Flask JSON not working: BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

  21. 21

    Why does Telegram give me an empty POST request on the webhook?

  22. 22

    Flask - getting value from radio button? werkzeug.exceptions.BadRequestKeyError: 400 Bad Request

  23. 23

    Bad Request (400) for POST request to ASP.NET Core 6, minimal API, sent from Postman

  24. 24

    Flask responds to all POST requests with code 400

  25. 25

    Getting 400 from Axios Post request

  26. 26

    Flask python - Bad Request: The browser (or proxy) sent a request that this server could not understand

  27. 27

    flask error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

  28. 28

    flask error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand

  29. 29

    POST request from python to nodeJS server

HotTag

Archive