ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

电报webhook php bot无法回答

2019-11-18 22:31:10  阅读:310  来源: 互联网

标签:telegram-bot telegram webhooks php


我正在尝试使用网络钩子建立一个电报机器人.我可以使其与getUpdates一起使用,但是我希望它与webhook一起使用.

我的网站(托管了bot php脚本)具有SSL证书正常运行(地址栏中显示绿色锁定):

我用

https://api.telegram.org/bot<token>/setwebhook?url=https://www.example.com/bot/bot.php

我得到:{“ ok”:true,“ result”:true,“ description”:“ Webhook已设置”}

(我不知道这是否重要,但是我已授予rwx文件夹和脚本的权限)

PHP机器人程序:(https://www.example.com/bot/bot.php)

<?php

$botToken = <token>;
$website = "https://api.telegram.org/bot".$botToken;

#$update = url_get_contents('php://input');
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);

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

switch($message) {
    case "/test":
        sendMessage($chatId, "test");
        break;
    case "/hi":
        sendMessage($chatId, "hi there!");
        break;
    default:
        sendMessage($chatId, "default");
}

function sendMessage ($chatId, $message) {
    $url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
    url_get_contents($url);

}

function url_get_contents($Url) {
    if(!function_exists('curl_init')) {
        die('CURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

?>

但是当我向机器人写任何东西时,我都没有得到答案…

有什么想法吗?

谢谢

解决方法:

在您的问题中,尚不清楚脚本位置.看到您的代码,您似乎尝试通过url_get_contents加载请求以检索电报服务器响应.如果您的漫游器无需网络钩子,则此方法是正确的.否则,在设置webhook之后,您必须处理传入的请求.

即,如果将webhook设置为https://example.com/mywebhook.php,则在https://example.com/mywebhook.php脚本中,您必须编写以下内容:

<?php

$request = file_get_contents( 'php://input' );
#          ↑↑↑↑ 
$request = json_decode( $request, TRUE );

if( !$request )
{
    // Some Error output (request is not valid JSON)
}
elseif( !isset($request['update_id']) || !isset($request['message']) )
{
    // Some Error output (request has not message)
}
else
{
    $chatId  = $request['message']['chat']['id'];
    $message = $request['message']['text'];

    switch( $message )
    {
        // Process your message here
    }
}

标签:telegram-bot,telegram,webhooks,php
来源: https://codeday.me/bug/20191118/2031554.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有