通过电报机器人

时间:2018-03-17 17:19:15

标签: php telegram telegram-bot

我使用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'
            ]);
        }

    }

但这不起作用,也没有。

2 个答案:

答案 0 :(得分:1)

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

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

顺便说一句,尝试在线搜索是否有支持向用户名发送消息的API。但据我所知,这是不可能的。

答案 1 :(得分:0)

这个例子效果很好:

<?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);
 }


?>