1

Sending messages to a Telegram channel from Python is quite easy, just create a Telegram bot, save its token id and add the bot to the channel as admin, then the Python code is

import requests
TOKEN = "..." # bot token ID to access the HTTP API
CHANNEL_ID = "..." # for example @durov
MSG = "..."
url = "https://api.telegram.org/bot" + TOKEN + "/sendMessage?chat_id=" + CHANNEL_ID + "&text=" + MSG
requests.post(url)

However, when using for example MSG = "test+8", the message sent to the Telegram channel is test 8 (with a whitespace instead of the plus sign) and on Python I get the following output

<Response [200]>

I tried to replace the plus sign with the minus sign and that works, but what is the problem with the plus sign? Is it a special character?

sound wave
  • 3,191
  • 3
  • 11
  • 29

1 Answers1

2

This has to do with URL encoding - you can circumvent the "missrepersented" + by urlencode your MSG yourself:

import urllib.parse
MSG = 'message + 42'
enc = urllib.parse.quote(MSG)
print(enc)

Output:

message%20%2B%204

and send this encoded message.

See f.e. Characters allowed in a URL for more informations on that.

According to RFC 3986 the character + belongs to reserved characters of

  sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"   
              / "*" / "+" / "," / ";" / "="

and needs to be quoted when used in the query part of an uri.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69