Consenso Cookie

Questo sito utilizza i cookie per garantire la migliore esperienza possibile. Continuando a navigare, acconsenti al loro utilizzo. Leggi la nostra Privacy Policy.

Vorrei ritornare brevemente sull'API di Telegram già introdotta in un precedente post per mostrare un esempio pratico di come realizzare un semplice Bot che risponde al comando /orario restituendo l'ora corrente. Il linguaggio utilizzato è PHP.

 


define('TOKEN', 'botabcdefghilmno:z123456789');  // Da sostituire col token del BOT

require_once("telegram.php");	// Telegram Utils (vedi dopo)

$request = json_decode(file_get_contents('php://input'));
if(!$request)
{
	echo "Bad request\n";
	return;
}

if(!isset($request->message, $request->message->chat->id))
	return;

try {
	$TELEGRAM = new Telegram();

	$chatId = (int) $request->message->chat->id;

	if(!isset($request->message->text))
		return;

	$message = $request->message->text;

	switch($message)
	{
		case "/orario":
		case "/orario@SimpleBot":
			$giorno = date("j");
			$mese =  date("n");
			$anno = date("Y");
			$ora = date("H:i:s");
			$internettime = date("B");
			$settimana = date("w");
			$giornosettimana = array ("Domenica", 
"Lunedi",
"Martedi",
"Mercoledi",
"Giovedi",
"Venerdi",
"Sabato"); $nomemese = array (1 => "gennaio",
"febbraio", "marzo",
"aprile", "maggio",
"giugno", "luglio",
"agosto", "settembre",
"ottobre", "novembre",
"dicembre"); $TELEGRAM->sendMessage($chatId,
"$giornosettimana[$settimana]" . "," . " " .
"$giorno" . " " . "$nomemese[$mese]" . " " .
"$anno" . " ore $ora",
TOKEN); break; default: break; } } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; return; }

La classe TELEGRAM utilizzata in questo esempio è semplicemente un contenitore di funzioni utili per l'interazione col server di Telegram e contiene l'implementazione delle chiamate REST (POST HTTP) necessarie per l'invio di messaggi, audio e immagini. Il codice relativo, riunito attraverso altri esempi reperiti in rete, è disponibile di seguito:


class Telegram {

	public function sendMessage($chatID, $messaggio, $token) {
	    echo "sending message to ".$chatID."\n";

	    $data = array("chat_id" => intval($chatID), "text" => (string)$messaggio);
		$data_string = json_encode($data);

		$ch = curl_init("https://api.telegram.org/".$token."/sendMessage");
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		    'Content-Type: application/json',
		    'Content-Length: '.strlen($data_string))
		);

		$result = curl_exec($ch);
		curl_close($ch);
	}

	public function sendPicture($_chatID, $file_on_server, $token) {
	    $target_url = 'https://api.telegram.org/'.$token.'/sendPhoto';

	    $file_name_with_full_path = realpath('./'.$file_on_server);

	    $post = array(
	        'chat_id'   => $_chatID,
	        'photo'     => '@'.$file_name_with_full_path
	    );

	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $target_url);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    $result = curl_exec($ch);
	    curl_close ($ch);
	}

	/* Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when the fields title and performer are both empty and the mime-type of the file to be sent is not audio/mpeg, the file will be sent as a playable voice message. For this to work, the audio must be in an .ogg file encoded with OPUS. This behavior will be phased out in the future. For sending voice messages, use the sendVoice method instead.
	*/
	public function sendAudio($_chatID, $file_on_server, $token) {
	    $target_url = 'https://api.telegram.org/'.$token.'/sendAudio';

	    $file_name_with_full_path = realpath('./'.$file_on_server);

	    $post = array(
	        'chat_id'   => $_chatID,
	        'audio'     => '@'.$file_name_with_full_path
	    );

	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $target_url);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    $result = curl_exec($ch);
	    curl_close ($ch);
	}
	
}

Il risultato finale è qualcosa di simile:

Per ampliare i comandi di questo semplice Bot è possibile aggiungere altri case allo switch del primo listato per eseguire funzioni diverse e far fare al Bot altre cose.

Basta un pò di fantasia... ;)