Telegram 机器人应该发送包含“&”字符的 URL,但它只发送 URL 直到该字符,然后将其缩短

Telegram bot should send URL that contains "&" character, but it sends the URL only until that character and then cuts it short

我希望我的 Telegram 机器人向频道发送 URL。但是,url 包含“&”字符,它缩短了它试图发送的消息。 Telegram API documentation 说我需要使用 & (没有 space)来替换 & 但要么我不明白某些东西,要么它不起作用。

这是我正在做的事情:

requests.get("https://api.telegram.org/"+botID+"/sendMessage?chat_id="+chatid+"&text="+movieSearch+"&parse_mode=HTML")

电影搜索是:

movieSearch = ("https://www.imdb.com/search/title?release_date="+year+"-01-01,2018-12-31&user_rating="+score+",&genres="+genres)

可以看到在movieSearch中release_date后面有&user_rating=...等等。但是,机器人只会发送 URL 直到 & 字符之前(直到“2018-12-31”)。

我试过将 & 替换为 & amp;但它仍然不会发送整个 URL。我试过没有 parse_mode=HTML 但它也没有用。

而不是:

requests.get("https://api.telegram.org/"+botID+"/sendMessage?chat_id="
             +chatid+"&text="+movieSearch+"&parse_mode=HTML")

这样做:

params = {
    "chat_id": chatid,
    "text": movieSearch,
    "parse_mode": "HTML",
}

requests.get(
    "https://api.telegram.org/{}/sendMessage".format(botID),
    params=params
)

我认为问题的发生是因为 URL 中 "text" 参数的值中有 &,但没有将其转义为 %26。最好改用字典,让 requests 库为您转义。您仍然必须将 & 转义为 &:

movieSearch = "https://www.imdb.com/search/title?release_date={}"
              "-01-01,2018-12-31&user_rating={}&genres={}".format(
                    year, score, genres)

你应该使用字符的ASCII Encoding

更多信息: URL Encoding