【问题标题】:send Message to a user by Username in telegram bot通过电报机器人中的用户名向用户发送消息
【发布时间】:2021-05-04 05:48:26
【问题描述】:

我使用php-telegram-bot/core 在电报中创建了一个购物机器人。

我想要做的是,当用户下订单时,机器人会向频道管理员发送新订单的通知。

假设管理员频道用户名类似于@admin_username,并存储在一个全局变量中(意味着一段时间内可能会发生变化)。为此我写了这个:

    static public function showOrderToConfirm ($order)
    {

        if ($order) {
            Request::sendMessage([
                'chat_id'    => '@admin_username',
                'text'       => 'New Order registered',
                'parse_mode' => 'HTML'
            ]);
        }

    }

但这不起作用,也没有任何作用。

【问题讨论】:

    标签: php telegram telegram-bot


    【解决方案1】:

    Telegram bot API 不支持使用用户名发送消息,因为它不是一个稳定的项目,可以由用户更改。另一方面,机器人只能向之前至少向机器人发送过一条消息的用户发送消息。

    您知道,当用户向机器人发送消息时(例如用户点击开始按钮),机器人可以获取他/她的用户名和 ChatID(如您所知,ChatID 与用户名不同;ChatID 很长number) 所以我认为解决此问题的最佳方法是将聊天 ID 和相关用户名存储在数据库中,并将消息发送到您最喜欢的用户名的 chatID。

    顺便去网上搜索一下,看看有没有支持向用户名发送消息的API。但据我所知,这是不可能的。

    【讨论】:

    • chat_id Integer or String Yes Unique identifier for the target chat or username of the target channel (in the format @channelusername)。看起来您只能指定频道的“用户名”,而不是单个用户。
    【解决方案2】:

    这个例子效果很好:

    <?php
    $token = 'YOUR_TOCKEN_HERE';
    $website = 'https://api.telegram.org/bot' . $token;
    
    $input = file_get_contents('php://input');
    $update = json_decode($input, true);
    
    $chatId = $update['message']['chat']['id'];
    $message = $update['message']['text'];
    
    switch ($message) {
    case '/start':
        $response = 'now bot is started';
        sendMessage($chatId, $response);
        break;
    case '/info':
        $response = 'Hi, i am  @trecno_bot';
        sendMessage($chatId, $response);
        break;
    default:
        $response = 'Sorry, i can not understand you';
        sendMessage($chatId, $response);
        break;
    }
    
    function sendMessage($chatId, $response){
        $url = $GLOBALS['website'] . '/sendMessage?chat_id=' . $chatId .         
        '&parse_mode=HTML&text=' . urlencode($response);
        file_get_contents($url);
     }
    
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 2016-05-03
      • 2018-11-23
      • 2019-06-27
      • 2017-05-30
      • 2017-03-19
      • 2017-05-11
      • 1970-01-01
      相关资源
      最近更新 更多