50-foto.php

1<?php
2// in risposta a qualsiasi messaggio invia una foto
3
4$botToken = "metti_qui_il_tuo_id";
5$sitoApi = "https://api.telegram.org/bot" . $botToken;
6$contentutoRichiesta = file_get_contents("php://input");
7$messaggioRicevuto = json_decode($contentutoRichiesta, true);
8
9$chatId=$messaggioRicevuto['message']['chat']['id'];
10
11sendFile($chatId, "spalla.jpeg", "spalla da sfilacciare");
12
13function sendFile($chatId, $nomeFile, $testo){
14    // questa è la url per le foto, esiste anche "sendDocument"
15    $botUrl = $GLOBALS['sitoApi']."/sendPhoto";
16
17    // imposto i parametri che verranno mandati in POST [3]
18    $postFields = array(
19        'chat_id' => $chatId,
20        // https://www.php.net/manual/en/class.curlfile.php
21        "photo" => new CURLFile(realpath($nomeFile)),
22        'caption' => $testo
23    );
24
25    // https://www.php.net/manual/en/function.curl-init.php
26    $ch = curl_init(); // [4]
27
28    curl_setopt($ch, CURLOPT_URL, $botUrl);
29    // se è false l'output di curl_exec() viene stampato (e non lo voglio)
30    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
31    // imposto i campi da inviare
32    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); // [1]
33
34    $output = curl_exec($ch); // [2]
35}
36

1

https://www.php.net/manual/en/function.curl-setopt.php "If value is an array, the Content-Type header will be set to multipart/form-data" così evito di usare anche CURLOPT_HTTPHEADER

2

non se ne fa niente di "output, se le cose non vanno potrebbe essere comodo un "error_log($output);" subito dopo

3

sulla documentazione non trovo conferma esplicita del metodo http che usa, il fatto però oltre che essere ovvio l'ho verificato nel file di debug.

4

par fare debug sulla richiesta di curl aggiungere dopo curl_init() curl_setopt($ch, CURLOPT_VERBOSE, 1); $fileDebug = fopen('debug.txt', 'w'); curl_setopt($ch, CURLOPT_STDERR, $fileDebug); e in fondo alla funzione, dopo curl_exec fclose( $fileDebug );