Search code examples
pythonsyntax-error

Python Syntax Error : Invalid Syntax in My Code


I am getting errors in my code. Please Help me, I am trying to hit the given api in the code.

msgid = 123
obj = f"{"inline_keyboard": [[{"text": "Rename","callback_data": "/rename_link_start {msgid}"}]]}"
obj2 = urllib.parse.quote_plus(obj)
hit = requests.get(f"https://api.telegram.org/bot{token}/sendMessage?chat_id={id}&text=streaam&reply_markup={obj}"

Error:

Traceback (most recent call last):
      File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
        return _run_code(code, main_globals, None,
      File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
        exec(code, run_globals)
      File "/home/akshay/moine/TGBot/__main__.py", line 8, in <module>
        from .server import web_server
      File "/home/akshay/moine/TGBot/server/__init__.py", line 2, in <module>
        from .routes import routes
      File "/home/akshay/moine/TGBot/server/routes.py", line 80
        obj = f"{"inline_keyboard": [[{"text": "Rename","callback_data": "/rename_link_start {msg.i
    d}"}]]}"
                  ^
    SyntaxError: invalid syntax

Solution

  • If you have a look at the docs for the API you are using: https://core.telegram.org/bots/api#sendmessage

    ...you can see that the reply_markup field is "a JSON-serialized object".

    So don't bother struggling against the problems of escaping quote marks and f-string variable delimiters ({ } which are also used by dictionary literals)

    Just use Python's json module to serialize a JSON object, as specified in the API docs.

    Also, you do not need to use an f-string to output querystring params for the GET request, the requests lib can do that for you also. See https://requests.readthedocs.io/en/latest/user/quickstart/#passing-parameters-in-urls

    import json
    
    msgid = 123
    obj = {
      "inline_keyboard": [
        [{"text": "Rename", "callback_data": f"/rename_link_start {msgid}"}]
      ]
    }
    params = {
      "chat_id": id,
      "text": "streaam",
      "reply_markup": json.dumps(obj)
    }
    hit = requests.get(f"https://api.telegram.org/bot{token}/sendMessage", params=params)