Python Syntax Error : Invalid Syntax in My Code

Question:

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
Asked By: B.Akshay Kumar

||

Answers:

Use simple quote ' when wrapping around double quote ''

Answered By: Sparkling Marcel

The { and } has special meaning inside the f-string. So change it with double braces({{}}) wherever you don’t need to use variables. Here’s how to write it for eg:

msgid = "1"
print(f'{{"inline_keyboard": [[{{"text": "Rename", "callback_data": "/rename_link_start {msgid}"}}]]}}')

This will output

{"inline_keyboard": [[{"text": "Rename", "callback_data": "/rename_link_start 1"}]]}
Answered By: defiant

As said by @Sparkling Marcel, you have to use single quotes ' inside double quotes "". If you use double quotes inside double quotes, python can not know where the strings begin and ends. Also, you can not use {} inside f-strings because braquets are reserved for string formatting. Instead of braquets you can use other types of string formatting such as % (see example below). In your particular code:

msgid = 123
obj = "{'inline_keyboard': [[{'text': 'Rename','callback_data': '/rename_link_start %s'}]]}" % 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}"

Answered By: Cuartero

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)
Answered By: Anentropic
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.