I'm making a telegram bot that sends messages to a Channel, everything works fine until I try to send a message with an ASCII character (like an emoji) inside the URL message parameter, whenever I try to run something like this:
botMessage = '🚨'
urlRequest = f'https://api.telegram.org/bot{telegram_token}/sendMessage?chat_id={chat_id}&text={botMessage}'
urlRequest = urlRequest.replace(" ", "%20")
urllib.request.urlopen(urlRequest)
I get this error:
UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f6a8' in position 95: ordinal not in range(128)
Here is the full pic of all the errors I got before the one I wrote above
Non-ASCII character is forbidden in URL. This is a limitation in HTTP
protocol and it is not related to Telegram. Use urllib.parse.quote
function to encode from UTF-8 to ASCII as follow:
import urllib.request
botMessage = urllib.parse.quote('🚨')
urlRequest = f'https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={botMessage}'
urlRequest = urlRequest.replace(" ", "%20")
urllib.request.urlopen(urlRequest)
There are many python library for Telegram Bot. They are easy to use and they hide these details.