skip to Main Content

I am using Python for sending message to a telegram group, the URL returns 404. Below is the code:

import requests
from config import API, CHAT_ID

# telegram url
url = "https://api.telegram.org/bot{}".format(API)

print(url)


def send_mess(text):
    params = {'chat_id': CHAT_ID, 'text': text}
    response = requests.post(url + 'sendMessage', data=params, timeout=20)
    return response


if __name__ == '__main__':
    d = send_mess('Hi')

    print(d)

2

Answers


  1. it looks like the API or the CHAT_ID are not well configured. Even though, I would like to suggest using the telegram library:

    pip install python-telegram-bot

    import telegram
    
    def send_mess(text):
        token = "XXXXXX"
        chat_id = "XXXXXX"
        bot = telegram.Bot(token=token)
        bot.sendMessage(chat_id=chat_id, text=text)
    
    if __name__ == '__main__':
        d = send_mess('Hi')
    
        print(d)
    
    Login or Signup to reply.
  2. There’s a simple typo in your code, lets take a look at the following lines:

    url = "https://api.telegram.org/bot{}".format(API)
    ...
    response = requests.post(url + 'sendMessage', data=params, timeout=20)
    

    This wel produce an url like;

    https://api.telegram.org/bot123456:QWERTYsendMessage
    

    Here, the url is missing an / between the token and the method, would recommend changing;
    url + 'sendMessage' to url + '/sendMessage' to get the correct url:

    https://api.telegram.org/bot123456:QWERTY/sendMessage
                                             ^
    

    Then your code send the message as expected.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search