Search code examples
pythonurlpython-requeststagstelegram

How to send full strings from python to telegram which contain the substring"#"


I have this function:

import requests
def sendTelegram(message):
        token = "********************"
        chat_id = "**********"
        url = f"https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={message}"
        requests.get(url).json()

Which prints a message to my telegram chat via bot. But I have a problem, the strings that I want to print to my chat are not full sometimes. When the substring "#" is met within the string that needs to be printed, the print of the string closes there.

Example:

sendTelegram('https://www.coolwebsite/page1#page2') -> prints 'https://www.coolwebsite/page1'

Any solve to this situation, please?


Solution

  • Telegram supports both passing arguments throught query string and JSON body, but using the query string version exposes you to special characters, like #?= for example

    So to avoid any url escaping requirement, use the POST version

    def sendTelegram(message):
        token = "********************"
        chat_id = "**********"
        url = f"https://api.telegram.org/bot{token}/sendMessage"
        content = {"chat_id": chat_id, "text", message}
        requests.post(url, json=content)