php-如何从服务器定义用于电报BOT的命令
作者:互联网
我用@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
我得到这个:{“ ok”:true,“ result”:true,“ description”:“ 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脚本未触发,则可能是因为该页面不是公共的.您指定给Telegram的Webhook必须是可公开访问的URL.我试图达到https://partamsms.ir/bot.php,但我无法达到.
一种替代方法是改为使用getUpdates方法,并计划脚本每5秒左右运行一次.
标签:telegram-bot,telegram,php 来源: https://codeday.me/bug/20191028/1949573.html