gpt4 book ai didi

php - 如何从服务器为 Telegram BOT 定义命令

转载 作者:可可西里 更新时间:2023-11-01 00:59:28 26 4
gpt4 key购买 nike

我用@botfather 创建了一个机器人,一切正常。现在我想将主机的命令设置为 Telegram 。我在我的根目录中创建了一个 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 was set"}

但我无法在我的 Telegram 帐户中运行这些命令。

如何从我的服务器运行命令?

感谢一百万

最佳答案

根据您的评论,您想要根据用户键入的消息做出不同响应的内容。因此,使用您的示例代码,您可以将其更改为如下所示:

// 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 秒左右运行一次。

关于php - 如何从服务器为 Telegram BOT 定义命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com