6

i would like to send a message to a specific telegram-user -

So i create a bot called Rapid1898Bot and get the api-key for it. I also send a message in the bot and get with

https://api.telegram.org/bot<Bot\_token>/getUpdates

the chat-id

With the following code it is now working that i send a message to the bot - what is fine:

    import os
    from dotenv import load_dotenv, find_dotenv
    import requests
    
    load_dotenv(find_dotenv()) 
    TELEGRAM_API = os.environ.get("TELEGRAM_API")
    # CHAT_ID = os.environ.get("CHAT_ID_Rapid1898Bot")
    CHAT_ID = os.environ.get("CHAT_ID_Rapid1898")
    
    print(CHAT_ID)
    
    botMessage = "This is a test message from python!"
    sendText = f"https://api.telegram.org/bot{TELEGRAM_API}/sendMessage?chat_id={CHAT_ID}&parse_mode=Markdown&text={botMessage}"
    response = requests.get(sendText)
    print(response.json())

But now i want to also send a message to a specific telegram-user. According to this explanation:

How can I send a message to someone with my telegram bot using their Username

i was expecting to

a) send a message from eg. my telegram account to the bot

b) and then open

https://api.telegram.org/bot<Bot\_token>/getUpdates 

But unfortunately it seems that it is allways the same chat-id, with which i can send the message to the rapid1898bot - but NOT to MY telegram account.

Why is this not working and why i am getting allways the same chat-id?

Rapid1898
  • 895
  • 1
  • 10
  • 32

1 Answers1

4

you already have a bot and its token

after that you need to get the chat_id:

  1. write message in the chat
  2. Visit https://api.telegram.org/bot<YourBOTToken>/getUpdates and get the chat_id under the key message['chat']['id']
    import requests
    
    def telegram_bot_sendtext(bot_message):
    
       bot_token = ''
       bot_chatID = ''
       send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message
    
       response = requests.get(send_text)
    
       return response.json()
    
    test = telegram_bot_sendtext("Testing Telegram bot")
    print(test)

more info - https://medium.com/@ManHay_Hong/how-to-create-a-telegram-bot-and-send-messages-with-python-4cf314d9fa3e

Tal Folkman
  • 2,368
  • 1
  • 7
  • 21