skip to Main Content

To send a message to Telegram, I use this template:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

urlphoto = f'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'
botalert = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
chatalert = 'yyyyyyyyyyyyyyyy'
urlalert = f"https://api.telegram.org/bot" + botalert + "/sendMessage?text=" + urlphoto + "&chat_id=" + chatalert + "&parse_mode=HTML"
requests.get(urlalert, headers=headers)

But when the message is sent, the link received there does not come together as the %20 is converted into spaces:

enter image description here

How should I proceed so that the link is delivered perfectly like that:

http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html

3

Answers


  1. Try this:

    import requests
    from requests.utils import quote
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
    
    urlphoto = 'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'
    botalert = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    chatalert = 'yyyyyyyyyyyyyyyy'
    urlalert = f"https://api.telegram.org/bot{botalert}/sendMessage"
    requests.get(urlalert, params=quote(f"?text={urlphoto}&chat_id={chatalert}&parse_mode=HTML"), headers=headers)
    
    Login or Signup to reply.
  2. You can define urlphoto like this:

    urlphoto = f'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'.replace('%20', '%2520')
    

    This will print the percent sign with 20 after it.

    Login or Signup to reply.
  3. Use a parameters dictionary, and the parameters will be encoded correctly for you:

    import requests
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
    
    urlphoto = f'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'
    botalert = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    chatalert = 'yyyyyyyyyyyyyyyy'
    urlalert = f'https://api.telegram.org/bot{botalert}/sendMessage'
    params = {'text':urlphoto, 'chat_id':chatalert, 'parse_mode':'HTML'}
    requests.get(urlalert, headers=headers, params=params)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search