6

几天前我在 youtube 上看到了这个教程。这很有趣,所以我决定制作一个自己的机器人。我使用教程中的代码作为模板:

<?php

$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;


$update = file_get_contents('php://input');

$updatearray = json_decode($update, TRUE);

$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];

if($text == 'hy'){
    file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
} 
elseif($text == 'ciao'){
    file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}

如果我手动执行脚本,该脚本就可以工作。但是,当我使用 webhook 时,它不再起作用了。教程说$update = file_get_contents('php://input');是正确的方法,之前要使用$update = file_get_contents($website."/getupdates");。我的问题如何使用php://input自动执行我的脚本?该脚本位于“one.com”的服务器上,证书也来自“one.com”。

4

5 回答 5

2

如果您使用自签名 ssl,则必须指向 ssl 路径,使用 ssh 在填充真实数据后运行此命令,,

curl -F "url=https://example.com/myscript.php" -F "certificate=@/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
于 2015-12-10T22:24:40.587 回答
1

更改为 WebHook 方法后,您需要如下放置,因为现在我们将一次处理一条消息。对我来说完美无缺。

反而

$chatId = $updateArray["result"][0]["message"]["chat"]["id"];

$chatID = $update["message"]["chat"]["id"];
于 2016-01-02T01:43:57.317 回答
0

抱歉这么热情地挖掘这个老问题,我和你的问题完全一样。

我认为实际上答案可能更简单,但不如我们希望的那样令人满意:我认为在使用 webhook 时不可能获得机器人的先前消息列表。即:它的作用是在机器人收到消息后直接运行 PHP 脚本。没有任何内容存储在可访问的数据库中,因此不会返回 updateArray。

我遇到了这个例子,它展示了 php://input 是如何工作的。我想显示消息列表的解决方案是,每次通过 webhook “转发”消息时,让 php 脚本将消息存储在数据库中。

如果有人发现别的东西:我很感兴趣。

于 2017-02-04T16:54:19.050 回答
0

根据我对上面代码片段的理解,您需要在双引号中使用 php://input 而不是单引号。在 php 中,我们在这个用例中有 bing 的区别。

于 2017-05-17T17:45:58.930 回答
0

这是您所有问题的答案。获得机器人的秘密令牌后,请按照以下步骤操作:

  1. 在您的网站https://yourdomain.com/secret-folder/index.php中创建文件

像这样创建你的 php 文件:

<?php

    $website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
    $content = file_get_contents("php://input");
    $update = json_decode($content, true);

    if (isset($update["message"])){

        $chatID = $update["message"]["chat"]["id"];
        $text = $update["message"]["text"];

        if ( $text == '/start' ) {
            // send welcome message
            file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
        }else{
            // send another message or do your logic (up to you)
            file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
        }
    }

?>
  1. 从此机器人 @set_webhookbot 设置您的Webhook
  2. 选择命令或输入“ستوبهوک”
  3. 回复您的秘密机器人令牌例如:'123456789:1234567890ABCDEF1234567890ABCDEF123'
  4. 回复您的 webhook 地址“ https://yourdomain.com/secret-folder/index.php
  5. 回复 /setwebhook

如果您按步骤进行操作,它将起作用。

好好享受 !!

于 2019-04-09T08:03:21.677 回答