User Tools

Site Tools


informatica:telegram:bot

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
informatica:telegram:bot [2021/12/01 13:57] joseinformatica:telegram:bot [2023/03/20 14:13] (current) jose
Line 1: Line 1:
 +Fuentes:
 +
 +https://atareao.es/tutorial/crea-tu-propio-bot-para-telegram/un-bot-de-telegram-con-php/
 +
 ====== Crear el bot ====== ====== Crear el bot ======
 Buscamos @botfather en Telegram Buscamos @botfather en Telegram
Line 4: Line 8:
 Escribimos Escribimos
   /newbot   /newbot
-Nos contesta que ahora le tenemos que poner un nombre que acabe con la palabra "bot":+Nos contesta que ahora le tenemos que poner un nombre. El nombre puede ser largo y tener espacios:
   Alright, a new bot. How are we going to call it? Please choose a name for your bot.   Alright, a new bot. How are we going to call it? Please choose a name for your bot.
-Ponemos el nombre del bot +Ponemos el nombre: 
-  jurjurbot+  Bot de pruebas
 Nos contesta: Nos contesta:
   Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.   Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
-Le ponemos:+El username no puede tener espacios y tiene que acaba con la palabra **bot**:Le ponemos:
   jurjurbot   jurjurbot
 Nos dice que está creado y nos da el token del bot que debemos guardar. Nos dice que está creado y nos da el token del bot que debemos guardar.
Line 23: Line 27:
 </code> </code>
  
-Metemos usuario en el grupo y sacamos el nombre del grupo con el comando:+Metemos usuario en un grupo. Escribimos /start en el grupoy sacamos el nombre del grupo con el comando:
   curl -X GET https://api.telegram.org/bot<token>/getUpdates|jq   curl -X GET https://api.telegram.org/bot<token>/getUpdates|jq
 Por ejemplo: Por ejemplo:
Line 66: Line 70:
 </code> </code>
  
-====== Añadir comandos ======+====== Interactuar BOT ======
 Podemos ver las actualizaciones del bot con la API getUpdates como hemos visto antes: Podemos ver las actualizaciones del bot con la API getUpdates como hemos visto antes:
   curl -X GET https://api.telegram.org/bot<token>/getUpdates|jq   curl -X GET https://api.telegram.org/bot<token>/getUpdates|jq
Line 105: Line 109:
 <code> <code>
 <?php <?php
-define('BOT_TOKEN', '2143053637:AAHX3BhheQifNTDbJSvhLlYp-dGvnTxmPtk');+define('BOT_TOKEN', '2143053637:AAHX3BasdasdDbJSvhLlYp-dGvnTxmPtk');
 define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/'); define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
  
Line 112: Line 116:
 $update     = json_decode($content, true); $update     = json_decode($content, true);
 $chatID     = $update["message"]["chat"]["id"]; $chatID     = $update["message"]["chat"]["id"];
-//$chatID     = "-648162144"; 
 $message    = $update["message"]["text"]; $message    = $update["message"]["text"];
  
Line 119: Line 122:
 switch ($message) { switch ($message) {
     case "/start":     case "/start":
-        $reply =  urlencode("Bienvenido al bot del EKO.\nEscribe /ayuda para ver los comandos posibles");+        $reply =  urlencode("Bienvenido al mi bot.\nEscribe /ayuda para ver los comandos posibles");
         break;         break;
     case "/ayuda":     case "/ayuda":
-        $reply =  urlencode("commandos:\n/internet Consulta si hay internet ahora\n/baterias Nivel actual de las baterias\n/paneles Producción actual paneles\n/consumo Consumo total actual\n/ayuda Esta ayuda");+        $reply =  urlencode("commandos:\n/consulta1 Lee el fichero fichero1.txt\n/consulta2 Lee el fichero fichero1.txt\n/ayuda Esta ayuda");
         break;         break;
-    case "/internet": +    case "/consulta1": 
-        $reply = trim(file_get_contents("https://apitelegram.lobo99.info/internet"), "\r\n");+        $reply = "Fichero 1: ".trim(file_get_contents("https://api.midominio.com/fichero1.txt"), "\r\n");
         break;         break;
-    case "/baterias": +    case "/consulta2": 
-        $reply = "Carga baterias: ".trim(file_get_contents("https://apitelegram.lobo99.info/baterias"), "\r\n")."%"; +        $reply = "Fichero 2: ".trim(file_get_contents("https://api.midominio.com/fichero2.txt"), "\r\n");
-        break; +
-    case "/paneles": +
-        $reply = "Paneles generando: ".trim(file_get_contents("https://apitelegram.lobo99.info/paneles"),"\r\n")." Wh"; +
-        break; +
-    case "/consumo": +
-        $reply = "El consumo total es de: ".trim(file_get_contents("https://apitelegram.lobo99.info/consumo"),"\r\n")." Wh";+
         break;         break;
     default:     default:
Line 159: Line 156:
  
 Cositas de PHP: Cositas de PHP:
-  Ponemos+  Ponemos urlencode para poder poner \n y escribir un salto de línea 
 +  * Usamos trim para quitar una _ que aparece al leer una url como si fuera un salto de línea 
 +<code> 
 +trim(file_get_contents("https://api.midominio.com/fichero.txt"), "\r\n"
 +</code> 
 + 
 +====== Menus con botfather ====== 
 +Desde el bot @botfather podemos añadir los menús para que aparezcan los comandos. 
 + 
 +====== API en PHP ====== 
 +El webhook de telegram lanza peticiones a la API de PHP de este tipo con todas las acciones que pasan. Metiendo el bot @RawDataBot se pueden sacar de cada grupo. Va bien para saber el chatID por ejemplo: 
 +<code> 
 +
 +    "update_id": 816025253, 
 +    "message":
 +        "message_id": 974009, 
 +        "from":
 +            "id": 4982505, 
 +            "is_bot": false, 
 +            "first_name": "I Want to be Freak", 
 +            "username": "IWantToBeFreak" 
 +        }, 
 +        "chat":
 +            "id": -699088581, 
 +            "title": "Jur123 group", 
 +            "type": "group", 
 +            "all_members_are_administrators": true 
 +        }, 
 +        "date": 1638376574, 
 +        "new_chat_participant":
 +            "id": 211246197, 
 +            "is_bot": true, 
 +            "first_name": "Telegram Bot Raw", 
 +            "username": "RawDataBot" 
 +        }, 
 +        "new_chat_member":
 +            "id": 211246197, 
 +            "is_bot": true, 
 +            "first_name": "Telegram Bot Raw", 
 +            "username": "RawDataBot" 
 +        }, 
 +        "new_chat_members":
 +            { 
 +                "id": 211246197, 
 +                "is_bot": true, 
 +                "first_name": "Telegram Bot Raw", 
 +                "username": "RawDataBot" 
 +            } 
 +        ] 
 +    } 
 +
 +</code> 
 + 
 +A nosotros solo nos interesa uno como este 
 +<code> 
 +
 +    "message":
 +        "chat":
 +            "id": -699088581 
 +        }, 
 +        "text":"/consulta2" 
 +    } 
 +
 +</code> 
 + 
 +Si lo lanzamos a la API de PHP haría el comando **/consulta2** El chat id tiene que ser el de la API 
 +  curl -X POST -d@peticion.json "https://api.midominio.com/bot.php" 
 +   
 +====== ERRORES ====== 
 +El bot no da respuesta y en nginx da 499 
 +  curl -s -X GET https://api.telegram.org/bot2143053637:AAHX3BhheQifNTDbJSvhLlYp-dGvnTxmPtk/getWebhookInfo |jq 
 + 
 +Da error "Read timeout expired", 
 + 
 +<code> 
 +
 +  "ok": true, 
 +  "result":
 +    "url": "https://apitelegram.lobo99.info/bot.php", 
 +    "has_custom_certificate": false, 
 +    "pending_update_count": 37, 
 +    "last_error_date": 1639677248, 
 +    "last_error_message": "Read timeout expired", 
 +    "max_connections": 40, 
 +    "ip_address": "87.217.220.23" 
 +  } 
 +
 +</code> 
 + 
 +Era un problema de DNS pero para vaciar los mensajes pendientes he puesto en el fichero bot.php 
 +<code> 
 +  $update = json_decode(file_get_contents('php://input')); 
 +       if(isset($update->message) || isset($update->edited_message)) { 
 +                if(time()-((@$update->message->date)?:(@$update->edited_message->date)) > 59) { 
 +                   exit('Update Time Out !'); # print json update 
 +                } 
 +            } 
 + 
 +</code>
informatica/telegram/bot.1638367038.txt.gz · Last modified: 2021/12/01 13:57 by jose