TelegramBot.php

  1. <?php
  2.  
  3. ini_set('display_errors', 1);
  4. header("Content-Type: application/json");
  5.  
  6. class TelegramBot {
  7.  
  8. const BOT = "@caliban_bot";
  9. const TOKEN = "123456789:A1bC2dEf3GhIj4KlMnO5pQrStU6vWxYz789";
  10. const TELEGRAM = "https://api.telegram.org:443/bot".self::TOKEN;
  11. const WEBHOOK = "https://midominio.es/webhook.php/".self::TOKEN;
  12.  
  13. //--------------------------------------------
  14. // MAIN
  15.  
  16. public static function main() {
  17. if (self::checkToken()) {
  18. $request = self::receiveRequest();
  19. $chatId = $request->message->chat->id;
  20. $text = $request->message->text;
  21. $message = self::execute($text);
  22. self::sendMessage($chatId, $message);
  23. }
  24. }
  25.  
  26. public static function execute($input) {
  27. $output = $input;
  28. return $output;
  29. }
  30.  
  31. private static function checkToken() {
  32. $pathInfo = ltrim($_SERVER['PATH_INFO'] ?? '', '/');
  33. return $pathInfo == self::TOKEN;
  34. }
  35.  
  36. private static function receiveRequest() {
  37. $json = file_get_contents("php://input");
  38. $request = json_decode($json, $assoc=false);
  39. return $request;
  40. }
  41.  
  42. private static function sendMessage($chatId, $text) {
  43. $query = http_build_query([
  44. 'chat_id'=> $chatId,
  45. 'text'=> $text,
  46. 'parse_mode'=> "Markdown",
  47. ]);
  48. $response = file_get_contents(self::TELEGRAM."/sendMessage?$query");
  49. return $response;
  50. }
  51.  
  52. //--------------------------------------------
  53. // CONFIGURE
  54.  
  55. public static function setWebHook() {
  56. $setWebHook = self::TELEGRAM.'/setwebhook?url='.self::WEBHOOK;
  57. $response = file_get_contents($setWebHook);
  58. return $response;
  59. }
  60.  
  61. //--------------------------------------------
  62. // HELPER
  63.  
  64. private static function saveLog($message) {
  65. $FILE = "webhook.log";
  66. $date = date('Y-m-d H:i:s');
  67. $content = "$date\n$message\n\n";
  68. file_put_contents($FILE, $content, FILE_APPEND);
  69. }
  70.  
  71. } // TelegramBot
  72.  
  73. //------------------------------------------------
  74. // MAIN
  75.  
  76. ////echo TelegramBot::setWebHook(); // Comentar
  77. TelegramBot::main();
  78.  

Proinf.net