在向 Telegram 发送包含加号“+”的字符串时在 Python 上获取 <Response [200]>
Getting <Response [200]> on Python when sending to Telegram a string containing the plus sign "+"
从 Python 向 Telegram 频道发送消息非常简单,只需创建一个 Telegram 机器人,保存其令牌 ID 并将机器人作为管理员添加到频道,然后 Python 代码是
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)
但是,例如使用 MSG = "test+8"
时,发送到 Telegram 频道的消息是 test 8
(使用空格而不是加号)并且在 Python 上我得到以下输出
<Response [200]>
我尝试将加号替换为减号并且有效,但是加号有什么问题?是特殊字符吗?
这与 URL 编码有关 - 您可以通过自己 MSG
的 urlencode 来绕过“missrepersented”:
import urllib.parse
MSG = 'message + 42'
enc = urllib.parse.quote(MSG)
print(enc)
输出:
message%20%2B%204
并发送此编码消息。
参见 f.e。 Characters allowed in a URL 了解更多信息。
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.
从 Python 向 Telegram 频道发送消息非常简单,只需创建一个 Telegram 机器人,保存其令牌 ID 并将机器人作为管理员添加到频道,然后 Python 代码是
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)
但是,例如使用 MSG = "test+8"
时,发送到 Telegram 频道的消息是 test 8
(使用空格而不是加号)并且在 Python 上我得到以下输出
<Response [200]>
我尝试将加号替换为减号并且有效,但是加号有什么问题?是特殊字符吗?
这与 URL 编码有关 - 您可以通过自己 MSG
的 urlencode 来绕过“missrepersented”:
import urllib.parse
MSG = 'message + 42'
enc = urllib.parse.quote(MSG)
print(enc)
输出:
message%20%2B%204
并发送此编码消息。
参见 f.e。 Characters allowed in a URL 了解更多信息。
According to RFC 3986 the character
+
belongs to reserved characters ofsub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
and needs to be quoted when used in the query part of an uri.