Home > Enterprise >  Python Telegram Bot - Calling variable in URL?
Python Telegram Bot - Calling variable in URL?

Time:01-15

am having difficulty calling a variable as part of the url in a message I intend to send via the Python Telegram bot. Due to the nature of my code, the 'webpage' variable varies and the url has to be called as a variable. Placing the `url' variable in curly brackets did not work and some searching online has been in vain. Appreciate any pointers.

webpage = "abc"
url = "https://www.example.com/"   webpage
message = *Website*: "   "[click here]({url})"
parse_mode = 'markdown'
url = f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&text={message}&parse_mode={parse_mode}"
requests.get(url).json()

CodePudding user response:

Try this:

message = f"*Website*: [click here]({url})"

The f before the " causes the {url} to be parsed, otherwise it is handled as a simple string and {} are not getting replaced.

You can read more details about "Formatted String Literals" or simple "f-strings", e.g. here

  • Related