1

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

Juan π
  • 13
  • 2
  • **That is not _remotely_ an ASCII character.** There are [only 95 printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Character_set) -- and [URLs can only use _some_ of them](https://en.wikipedia.org/wiki/Percent-encoding). For others see https://docs.python.org/3/library/urllib.parse.html#url-quoting . – dave_thompson_085 Jul 09 '22 at 04:29

1 Answers1

0

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.

SuB
  • 2,250
  • 3
  • 22
  • 37