I've created a bot with @botfather and it's all okay . Now i want to set command from my host to telegram . i created a Bot.php in my 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 browse 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 can't run these commands in my telegram account .
How can i Run commands from my server ?
Thanks a million
According to your comment, you want something that will respond differently based on the message the user typed. So using your example code, you can change it to be something like this:
// 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 slight refactor of what you already had...if the issue is that your Bot.php script is not triggering, it is possibly because the page is not public. The webhook you specify to Telegram must be a publicly accessible URL. I tried to hit https://partamsms.ir/bot.php and I can't get to it.
An alternative is to use the getUpdates method instead and to cron the script to run every 5 seconds or so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With