I only get the text "1111" mentioned in the url as the output inside telegram chat and not the json data written inside the code.
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage? chat_id=@alerttest&text=1111"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = """
{
"stocks": "SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO"
}
""""
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
2
Answers
You are probably confused about the working of HTTP methods and Telegram API methods.
First step: Telegram sendMessage works with POST HTTP method.
It requires the text parameter, passed as GET parameter: otherwise you’ll send an empty message.
This means, that if you’re willing to include the JSON payload as text message you have to include your JSON attribute’s values into the Telegram sendMessage text parameter, otherwise you won’t be able to see that into the final message.
I found the following issues with the given code:
url
contains a space.chat_id
value should be numeric. Use https://web.telegram.org/ to get the chat_id from the URL. It should be a negative number. If it’s a channel or supergroup, you should prepend100
after the minus sign.&text=1111
should be removed from the URL, astext
is specified in the body when using therequests.post()
method.data
should be a dictionary containing key nametext
."Content-Type": "application/json"
in headers unless yourdata
dictionary has been transcoded to json. This can be solved in the requests.post() call by either changingdata=
tojson=
, or by not specifyingheaders
at all.Working:
Working: