Python / 向特定电报用户发送消息?

Rap*_*898 6 python bots telegram

我想向特定的电报用户发送消息 -

因此,我创建了一个名为 Rapid1898Bot 的机器人并获取它的 api 密钥。我还在机器人中发送消息并进行处理

https://api.telegram.org/bot<Bot\_token>/getUpdates
Run Code Online (Sandbox Code Playgroud)

聊天 ID

使用以下代码,我现在可以向机器人发送消息 - 这很好:

    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())
Run Code Online (Sandbox Code Playgroud)

但现在我还想向特定的电报用户发送消息。根据这个解释:

如何使用我的电报机器人使用他们的用户名向某人发送消息

我本来期待着

a)从我的电报帐户向机器人发送消息

b) 然后打开

https://api.telegram.org/bot<Bot\_token>/getUpdates 
Run Code Online (Sandbox Code Playgroud)

但不幸的是,它似乎总是相同的聊天 ID,我可以用它将消息发送到rapid1898bot - 但不能发送到我的电报帐户。

为什么这不起作用以及为什么我总是得到相同的聊天 ID?

Tal*_*man 4

你已经有一个机器人及其令牌

之后你需要得到chat_id

  1. 在聊天中写消息
  2. 访问https://api.telegram.org/bot<YourBOTToken>/getUpdates并获取chat_id密钥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)
Run Code Online (Sandbox Code Playgroud)

更多信息 - https://medium.com/@ManHay_Hong/how-to-create-a-telegram-bot-and-send-messages-with-python-4cf314d9fa3e