How to determine the command from the server for the telegram BOT

I created a bot with @botfather and everything is fine. Now I want to set a command from my host to telegram. I created Bot.php in the root directory.

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

      

Now when I view this: https://api.telegram.org/bot112186325:tokenNumber/setWebhook?url=https://partamsms.ir/bot.php

I get this: {"ok":true,"result":true,"description":"Webhook was set"}

But I cannot run these commands on my telegram account.

How can I run commands from my server?

Thanks a million

+3


source to share


1 answer


As per your comment, you want something that will react differently based on the user's input. Therefore, using your example code, you can change it this way:

// 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);  

      



So this is pretty much a little refactoring of what you already had ... if the problem is that your Bot.php script won't run, perhaps because the page is not public. The website that you specify for Telegram must be public. I tried to click https://partamsms.ir/bot.php and I can't get to it.

An alternative is to use a method getUpdates

instead and cron for the script to run every 5 seconds or so.

+4


source







All Articles