0

为了使用 PHP 集成 Telegram Chatbot,我已经按照以下步骤操作。

之后,我使用以下代码行制作了简单的 PHP 文件。

<?php 
define('BOT_TOKEN', 'CHANGE-ME');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');


// This is to read incoming message and fetch chatid
$content    = file_get_contents("php://input");
$update     = json_decode($content, true);
$chatID     = $update["message"]["chat"]["id"];
$message    = $update["message"]["text"];

// compose reply
$reply ="";
switch ($message) {
    case "/start":
        $reply =  "Welcome to chatbot world. Type /help to see commands";
        break;
    case "/test":
        $reply =  "test message";
        break;
    case "/hi":
        $reply =  "Hello from ChatBot";
        break;
    case "/help":
        $reply =  "commands: /start , /test , /hi , /help "; 
        break;
    default:
        $reply =  "Something wrong";
}

// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);

// Create a debug log.txt to check the response/reply from Telegram in JSON format.
// You can disable it by commenting checkJSON.
checkJSON($chatID,$update);
function checkJSON($chatID,$update){

    $myFile = "log.txt";
    $updateArray = print_r($update,TRUE);
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, $chatID ."nn");
    fwrite($fh, $updateArray."nn");
    fclose($fh);
}

虽然,我没有正确接收消息。

4

1 回答 1

0

不确定,但您可能就是这种情况。

您只需要确保在 Telegram ChatBot 中发送消息之前已成功运行开始侦听您的请求的 webhook URL 。

网址https ://api.telegram.org/bot/setWebhook?url=https://mywebsite.com/path/to/filename.php

到目前为止,我终于成功地使用 PHP 创建了 Telegram Chatbot 的演示。

于 2017-09-15T10:46:22.180 回答