Bot que notifique en telegram los nuevos temas y respuestas

En este hilo responderé preguntas sobre el bot, además de compartir el código cuando esté listo.

ya, acá está el código. edité las partes sensibles obviamente :wink: dejé un par de comentarios para quien quiera reutilizar parte del código.

<?php
//foropost.php v0.1
//recibe json desde webhook de discourse, lo parsea y lo reenvía como msje por telegram

$json = file_get_contents('php://input');
$data = json_decode($json);

function stdToArray($obj){
    $reaged = (array)$obj;
    foreach($reaged as $key => &$field){
        if(is_object($field))$field = stdToArray($field);
    }
    return $reaged;
}

$msg = stdToArray($data);
$msg = $msg[post];
$topic_id = $msg[topic_id]; // id del tema
$topic_title = $msg[topic_title]; // titulo del tema
$post_number = $msg[post_number]; // si 1, es tema nuevo
$cat_slug = $msg[category_slug]; // nombre categoria
$username = $msg[username]; // nombre autor
$eol= PHP_EOL;

$token = "1111111111:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // token del bot
$cid = "x222222222222"; // id del canal, grupo o usuario que vara a recibir los msjs

function sendMethod($token, $method, $params = array()) {
    $ch = curl_init("https://api.telegram.org/bot$token/$method");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux i686; rv:32.0) Gecko/20100101 Firefox/40.0');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5000);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    return curl_exec($ch);
}

if ($post_number == 1){
    $msg = "NUEVO TEMA en %$cat_slug% $eol 📄 [$topic_title](https://discourse.cuatrolibertades.org/t/$topic_id/) $eol 🆔 $username.";
} elseif ($post_number >=2 ) {
    $msg = "NUEVA RESPUESTA en  %$cat_slug% $eol 💭 [$topic_title](https://discourse.cuatrolibertades.org/t/$topic_id/$post_number) $eol 🆔 $username.";
}

$params = array(
    "chat_id" => $cid,
    "parse_mode" => "Markdown", // la otra opción es HTML
    "text" => $msg,
    disable_web_page_preview => true 
// en https://core.telegram.org/bots/api#sendmessage hay más documentación de lo que se puede enviar
);
sendMethod($token, "sendMessage", $params);
// de superbad para 4lib, con cariño.
// gpl 3 o sgtes ;-)
?>

Anoche hice una votación en el grupo de tg sobre dónde notificar los nuevos temas/respuestas. Habían diez votos empatados (5-5) entre que fuera en el grupo mismo y en un canal aparte. Para echar a andar el bot y no esperar más, lo dejé en un canal (t.me/foro4lib) pero ahora revisé de nuevo la votación y va ganando las notificaciones en el grupo, por dos votos. Si el delta aumenta, cambiaré la config para estar acorde a la voluntad soberana del pueblo de 4lib.

Respecto a otros sitios en que se puedan replicar las notificaciones, que es algo que me preguntaron por interno, la verdad es que las opciones son infinitas siempre que exista una api que reciba contenido (por ejemplo, una cuenta en mastodon).

1 me gusta

retomo esto más de un año después para comentarles que actualicé el código:

<?php
// discourse 2 telegrambot - gpl3
// cvillavicencio.com

$token = ""; // bot_token
$cid   = ""; // chat_id

function sendMethod($token, $method, $params = array()) {
  $ch = curl_init("https://api.telegram.org/bot$token/$method");
	curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux i686; rv:32.0) Gecko/20100101 Firefox/40.0');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5000);
  curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  return curl_exec($ch);
}

if ($_POST){
	$_POST = json_decode(file_get_contents('php://input'), true);
	$info = $_POST["post"];

	$url = 'https://discourse.cuatrolibertades.org/t/'.$info["topic_id"].'/'.$info["post_number"];

	$texto = intval($info["post_number"]) == "1" ? 'Nuevo tema en el foro: '.$info['topic_title'].PHP_EOL.'creado por: '.$info['username'] .'.': 'Nueva respuesta en: '.$info['topic_title'].PHP_EOL.'por: '.$info['username'].'.';
	$texto = PHP_EOL . $texto . PHP_EOL . "url: $url";
	$params = array(
		"chat_id" => $cid,
		"parse_mode" => "HTML",
		"text" => $texto
	);

	sendMethod($token, "sendMessage", $params);
}

?>

Lo dejé en el grupo mientras, total el foro recibe tan poquita atención :frowning: que dificilmente habrá flood con notificaciones de nuevos temas/mensajes. Si se pone molesto, se saca :wink:

1 me gusta