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

2

8

I want my Telegram bot to send a URL to a channel. However, the url contains the "&" character which cuts the message that it's trying to send short. The Telegram API documentation says I need to use & amp; (without the space) to replace & but either I don't understand something or it doesn't work.

Here's what I'm doing:

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

And movieSearch is:

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

You can see that in movieSearch after the release_date there is &user_rating=... and so on. However, the bot will only send the URL until just before that & character (so until "2018-12-31").

I've tried replacing & with & amp; but it still won't send the whole URL. I've tried without the parse_mode=HTML but it didn't work either.

Faydra answered 10/5, 2018 at 21:18 Comment(8)
you have a , next to the &genres.. get rid of the commaUnknit
@Unknit Here's an example of a real URL and it has the comma too, I tried removing it but it doesn't have an effect: imdb.com/search/…Faydra
What happens when you try the link you posted instead of movieSearch into the request..Unknit
What if you escape it as &Grahamgrahame
@Unknit it sends: imdb.com/search/title?release_date=1990-01-01,2018-12-31Faydra
@PauloScardine if I simply replace & with &, it does the same as with &Faydra
You must escape it as %26amp; instead. This is because you are not letting the requests library escape it for you.Grahamgrahame
@PauloScardine wow, %26amp; worked. Had no idea the requests library had an effect, thank you!Faydra
G
7

Instead of:

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

Do this:

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

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

I think the problem happens because you have & in the value of the "text" parameter in the URL but are not escaping it as %26. It is better to use a dictionary instead and let the requests library escape it for you. You still have to escape the & as &:

movieSearch = "https://www.imdb.com/search/title?release_date={}"
              "-01-01,2018-12-31&user_rating={}&genres={}".format(
                    year, score, genres)
Grahamgrahame answered 10/5, 2018 at 21:41 Comment(1)
Alright thank you sir. Escaping as %26amp; works, I'm gonna use the dictionary from now on as well.Faydra
D
0

you sholud use the ASCII Encoding of char.

more info: URL Encoding

Duenna answered 6/3, 2021 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.