Php 如何为电报机器人定义来自服务器的命令

Php 如何为电报机器人定义来自服务器的命令,php,telegram,telegram-bot,Php,Telegram,Telegram Bot,我用@botfather创建了一个机器人,一切正常。现在我想把主机的命令设置为电报。我在根目录中创建了一个Bot.php Bot.php $string = json_decode(file_get_contents('php://input')); function objectToArray( $object ) { if( !is_object( $object ) && !is_array( $object ) ) {

我用@botfather创建了一个机器人,一切正常。现在我想把主机的命令设置为电报。我在根目录中创建了一个Bot.php

Bot.php

$string = json_decode(file_get_contents('php://input'));

    function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) )
        {
            return $object;
        }
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }
        return array_map( 'objectToArray', $object );
    }

    $result = objectToArray($string);
    $user_id = $result['message']['from']['id'];
    $text = $result['message']['text'];
    if($text == 'Hi')
    $text_reply = 'Hi';
if($text == 'Your name')
    $text_reply = 'jJoe';

    $token = '';
    $text_reply = 'Got you Buddy.';

    $url = 'https://api.telegram.org/bot'.tokenNumber.'/sendMessage?chat_id='.$user_id;
    $url .= '&text=' .$text_reply;


    $res = file_get_contents($url);  
现在当我浏览这个:
https://api.telegram.org/bot112186325:tokenNumber/setWebhook?url=https://partamsms.ir/bot.php

我得到这个:
{“确定”:真,“结果”:真,“描述”:“设置了Webhook”}

但是我不能在我的电报帐户中运行这些命令

如何从服务器运行命令


万分感谢根据您的评论,您希望根据用户键入的消息做出不同的响应。因此,使用示例代码,您可以将其更改为以下内容:

// NOTE: you can pass 'true' as the second argument to decode as array
$result= json_decode(file_get_contents('php://input'), true);
error_log(print_r($result, 1), 3, '/path/to/logfile.log');

$user_id = $result['message']['from']['id'];
$text = $result['message']['text'];

// TODO: use something like strpos() or strcmp() for more flexibility
switch (true)
{
    case $text == '/hi':
        $text_reply = 'Hello';
        break;

    case $text == '/yourname':
        // TODO: use the getMe API call to get the bot information
        $text_reply = 'jJoe';
        break;

    default:
        $text_reply = 'not sure what you want?';
        break;
}

$token = '';
$url = 'https://api.telegram.org/bot'.tokenNumber.'/sendMessage?chat_id='.$user_id;
$url .= '&text=' .$text_reply;
$res = file_get_contents($url);  
因此,这几乎是对您已有内容的轻微重构……如果问题是您的Bot.php脚本没有触发,可能是因为页面不是公共的。指定给电报的webhook必须是可公开访问的URL。我试着打,但打不到


另一种方法是使用
getUpdates
方法,并对脚本进行cron,使其每隔5秒左右运行一次。

您能否澄清一下“命令”的含义?你的意思是你没有收到“得到你的朋友”的消息,还是你想发送一条消息而不是对收到的消息的响应?是的,当然,例如,当我在telegram@ChrisBrand Thank中写下/你的名字时,我想得到“jJoe”谢谢谢谢Hanks,一个noob问题:如果我在telegram中键入hi,应该得到Hello?是的,如果您的webhook工作正常。我用一些错误日志信息更新了脚本。如果指定的文件包含消息信息,则表示您的webhook正在接收来自电报的数据,如果消息为“hi”…则应接收“Hello”。如果日志文件为空,则表示无法通过internet访问脚本。有关添加的调试日志记录,请参阅示例代码的第二行。现在,当我在我的telegram bot中键入hi时,我没有得到任何信息,webhook工作正常。如果您在群聊或私人聊天中与bot聊天,您会在telegram中向bot键入什么?您可能需要包含“/”如果这是您的前缀,则调试
$text
变量以查看传递给您的电报。