Message not receiving automatically for Telegram CHATBOT funciton using PHP

纵饮孤独 提交于 2019-12-23 04:33:31

问题


In order to integrate Telegram Chatbot using PHP, I have already followed below steps.

  • Server with SSL certificate
  • Webhook with working condition URL : https://api.telegram.org/bot/setWebhook?url=https://mywebsite.com/path/to/filename.php
  • Created ChatBot and have a valid Token

After that, I have made simple PHP file using following line of code.

<?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);
}

Although, I am not receiving message properly.


回答1:


Not sure but this might be the case for you.

You just need to make sure that you have successfully run webhook URL that start listening your request before messaging in Telegram ChatBot.

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

As of now, finally, I have successfully created demo of Telegram Chatbot using PHP.



来源:https://stackoverflow.com/questions/46237746/message-not-receiving-automatically-for-telegram-chatbot-funciton-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!