Python / Send message to specific telegram user?
Asked Answered
M

1

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 e.g. 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 always 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 always the same chat-id?

Mucoid answered 26/1, 2022 at 12:56 Comment(0)
R
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

Ragtime answered 26/1, 2022 at 13:1 Comment(1)
Yes but as i said this is allways the same chat-id when opening the siteMucoid

© 2022 - 2024 — McMap. All rights reserved.