Wednesday, January 27, 2021

Telegram Bot Won't Send URL Containing Hash Symbol #

I maintain a Telegram bot. I found it was unable to send a URL while the URL contained a # symbol.

For example,  if I want the bot to send a response to a Telegram user but the response contains a URL like, www.domain.com/test#123, Telegram will not send the response to the user. The problem is that Telegram doesn't like the hash # symbol in the URL, or that the Python 3 requests library doesn't encode it properly. If I remove the #, then the response is sent to the user.

The solution I eventually found required me to import quote_plus library from requests, and then use it to encode the hash symbol # to a variable.

import requests

from urllib.parse import quote_plus


Next I encoded the html symbol for #:

h = quote_plus("#")

 

Now I include it in the url f'string, like:

f'www.domain.com/test{h}123'


The result for me is that now Telegram will accept the string and return it to the user.

Hope this helps!