Skip to content

Instantly share code, notes, and snippets.

@salvatorecordiano
Last active April 7, 2020 19:43
Show Gist options
  • Save salvatorecordiano/714bdcdf93ac489d0f55611adf6de337 to your computer and use it in GitHub Desktop.
Save salvatorecordiano/714bdcdf93ac489d0f55611adf6de337 to your computer and use it in GitHub Desktop.
Sample Telegram Bot (4)
<?php
// insert here your Bot API token
define("BOT_TOKEN", "...");
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if(!$update)
{
exit;
}
$message = isset($update['message']) ? $update['message'] : "";
$chatId = isset($message['chat']['id']) ? $message['chat']['id'] : "";
$text = isset($message['text']) ? $message['text'] : "";
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/sendPhoto";
// change image name and path
$postFields = array('chat_id' => $chatId, 'photo' => new CURLFile(realpath("image.png")), 'caption' => $text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
// read curl response
$output = curl_exec($ch);
@gioxx
Copy link

gioxx commented Jun 7, 2016

Ciao Salvatore. Domanda: e se al posto di image.png volessi un URL? Immagino sia fattibile in modo abbastanza trasparente, corretto? Io ho una variabile PHP che contiene un URL al quale corrisponde un'immagine JPG, basta sostituire "image.png" con $nomeVar oppure va fatto altro?
Grazie mille in anticipo.

@salvatorecordiano
Copy link
Author

Ciao @gioxx, ho letto solo adesso.
Nell'esempio viene usato CURLFile che non supporta la possibilità di indicare una URL dalla quale effettuare il download dell'immagine. Dovresti quindi procedere a scaricare la foto in locale e poi utilizzare lo snippet da me proposto.

A presto,
Salvatore

@albertointer
Copy link

Ciao Salvatore,
grazie per la guida! volevo chiederti se è possibile realizzare un bot che in base al messaggio ricevuto, possa rispondere con un messaggio di testo o con un'immagine a seconda dei casi.
Grazie

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment