70-memoriaJSON.php
1<?php
2$botToken = "metti_qui_il_tuo_id";
3$sitoApi = "https://api.telegram.org/bot".$botToken;
4$content = file_get_contents("php://input");
5$ricevuto = json_decode($content, true);
6$chatId = $ricevuto['message']['chat']['id'];
7$valore = $ricevuto['message']['text'];
8
9// definisco dove leggere/scrivere i dati
10$nomeArchivio = "archivio/$chatId.json";
11if( file_exists($nomeArchivio) ){
12 $contenuto = file_get_contents($nomeArchivio);
13}else{
14 // se il file non esiste è una conversazione nuova:
15 // un oggetto senza proprietà
16 $contenuto="{}";
17}
18$oggetto = JSON_decode($contenuto, true);
19
20if(is_numeric($valore)){
21 $oggetto['numero']=$valore;
22 $testoRisposta = "ok, ora scrivi un testo";
23} else {
24 $oggetto['testo']=$valore;
25 $testoRisposta = "ok, ora scrivi un numero";
26}
27
28if( isset($oggetto['numero']) && isset($oggetto['testo']) ){
29 $testoRisposta = "${oggetto['testo']}#${oggetto['numero']}\n";
30 // conversazione conclusa: cancello il file
31 unlink( $nomeArchivio );
32} else {
33 $dati = JSON_encode($oggetto);
34 file_put_contents($nomeArchivio, $dati);
35}
36
37sendMessage($chatId, $testoRisposta);
38
39function sendMessage($chatId,$text){
40 $url=$GLOBALS['sitoApi']
41 ."/sendMessage?chat_id=$chatId&parse_mode=HTML&text="
42 .urlencode($text);
43 file_get_contents($url);
44}
45