skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. I found the following issues with the given code:

    1. url contains a space.
    2. 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 prepend 100 after the minus sign.
    3. &text=1111 should be removed from the URL, as text is specified in the body when using the requests.post() method.
    4. data should be a dictionary containing key name text.
    5. You can not specify "Content-Type": "application/json" in headers unless your data dictionary has been transcoded to json. This can be solved in the requests.post() call by either changing data= to json=, or by not specifying headers at all.

    Working:

    import requests
    from requests.structures import CaseInsensitiveDict
    
    url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
    headers = CaseInsensitiveDict()
    headers["Content-Type"] = "application/json"
    data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
    resp = requests.post(url, headers=headers, json=data)
    print(resp.status_code)
    

    Working:

    import requests
    
    url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
    data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
    resp = requests.post(url, data=data)
    print(resp.status_code)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search