【问题标题】:Python / Send message to specific telegram user?Python /向特定电报用户发送消息?
【发布时间】:2022-01-26 21:01:16
【问题描述】:

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

所以我创建了一个名为 Rapid1898Bot 的机器人并为其获取 api-key。 我也在 bot 中发送消息并获取

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

聊天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())

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

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

我期待

a) 从例如发送消息。我的电报帐户给机器人

b) 然后打开

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

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

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

【问题讨论】:

    标签: python api bots telegram


    【解决方案1】:

    你已经有一个机器人和它的令牌

    之后你需要得到chat_id:

    1. 在聊天中写消息
    2. 访问https://api.telegram.org/bot&lt;YourBOTToken&gt;/getUpdates 并在message['chat']['id'] 键下获取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)
    

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

    【讨论】:

    • 是的,但正如我所说,打开网站时,这始终是相同的聊天 ID
    猜你喜欢
    • 2015-07-15
    • 2019-07-24
    • 1970-01-01
    • 2019-11-20
    • 2018-09-13
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多