sending files and images to Telegram

/*токен который выдаётся при регистрации бота */
$token = "5340791844:AAEXXDdu324vInvQrlWHyk8V91USOQSevrPVU";

$arrayQuery = array(
    'chat_id' => 1424646511,
    'caption' => 'Проверка работы',
    'photo' => curl_file_create(__DIR__ . '/cat.jpg', 'image/jpg' , 'cat.jpg')
);		
$ch = curl_init('https://api.telegram.org/bot'. $token .'/sendPhoto');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrayQuery);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);

Here we, like last time, collect in an array $arrayQuery parameters for sending requests. To send an image, we need to pass the chat id, message text (for images, it is passed in the parameter caption), and the new parameter photo to which we pass the formed one, using the function curl_file_create()an image object.

Below we indicate that all data must be transmitted by the POST method and do not forget to pass the token in the request URL.

Thus, we send a compressed image to the chat with the specified caption.

Let’s look at the additional options that the Telegram documentation offers us.

protect_content — this option prohibits saving and sending the image.

reply_markup – allows you to add buttons under the image

Sending files to Telegram chat

Sending documents is done in the same way, only the sending method and parameter are changed. photo is replaced by document.

/*токен который выдаётся при регистрации бота */
$token = "5340791844:AAEXXDdu324vInvQrlWHyk8V91USOQSevrPVU";

$arrayQuery = array(
    'chat_id' => 1424646511,
    'caption' => 'Проверка работы',
    'document' => curl_file_create(__DIR__ . '/cat.jpg', 'image/jpg' , 'cat.jpg')
);		
$ch = curl_init('https://api.telegram.org/bot'. $token .'/sendDocument');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrayQuery);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);

Parsing the response when sending a file

Let’s now analyze the response received from the server when sending a file to the chat.

In this example, I get the following response:

{
  "ok": true,
  "result": {
    "message_id": 20,
    "from": {
      "id": 5340791844,
      "is_bot": true,
      "first_name": "test_prog_time",
      "username": "test_prog_time_bot"
    },
    "chat": {
      "id": 1424646511,
      "first_name": "Илья",
      "last_name": "Лящук",
      "username": "iliyalyachuk",
      "type": "private"
    },
    "date": 1658991191,
    "document": {
      "file_name": "cat.jpg",
      "mime_type": "image/jpeg",
      "thumb": {
        "file_id": "AAMCAgADGQMAAxRi4jJXqhVVPzULdQ1xw_LeYcZGRwACGhkAAmCwEEuw8OvQNNsHDQEAB20AAykE",
        "file_unique_id": "AQADGhkAAmCwEEty",
        "file_size": 24268,
        "width": 320,
        "height": 320
      },
      "file_id": "BQACAgIAAxkDAAMUYuIyV6oVVT81C3UNccPy3mHGRkcAAhoZAAJgsBBLsPDr0DTbBw0pBA",
      "file_unique_id": "AgADGhkAAmCwEEs",
      "file_size": 132208
    },
    "caption": "Проверка работы"
  }
}

In the response, we see many familiar parameters that we discussed in the lesson on sending text messages. This is information about the chat, about the recipient, about the date of sending and the text of the message.

The new parameter for us, in this case is − documentwhich contains information about the uploaded file.

In order not to duplicate the sending of files from the server, you can refer to a previously sent file by specifying its identifier.

The ID of the sent file is stored in the response array, in the parameter document -> file_id.

It looks like this

$arrayQuery = array(
    'chat_id' => 1424646511,
    'caption' => 'Проверка работы',
    'document' => "BQACAgIAAxkDAAMUYuIyV6oVVT81C3UNccPy3mHGRkcAAhoZAAJgsBBLsPDr0DTbBw0pBA",
);		
$ch = curl_init('https://api.telegram.org/bot'. $token .'/sendDocument');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrayQuery);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);

Group sending of images and files

To group send images to a chat, we need to use the method sendMediaGroup() and slightly alter our array with query parameters.

This is what our next example will look like.

/*токен который выдаётся при регистрации бота */
$token = "5340791844:AAEXXDduvInvQrlWHRXykV91USOQSevrPVU";

$arrayQuery = [
    'chat_id' => 1424646511,
    'media' => json_encode([
	    ['type' => 'photo', 'media' => 'attach://cat.jpg' ],
	    ['type' => 'photo', 'media' => 'attach://cat_2.jpg' ],
	    ['type' => 'photo', 'media' => 'attach://cat_3.jpg' ],
    ]),
    'cat.jpg' => new CURLFile(__DIR__ . '/cat.jpg'),
    'cat_2.jpg' => new CURLFile(__DIR__ . '/cat_2.jpg'),
    'cat_3.jpg' => new CURLFile(__DIR__ . '/cat_3.jpg'),
];


$ch = curl_init('https://api.telegram.org/bot'. $token .'/sendMediaGroup');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrayQuery);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);

echo $res;

To transfer a group of files, we need to pass as a parameter media an array with image parameters to be grouped.

Each array nested in the media parameter has the following parameters:

  • type – the type of file to be transferred (in our case it is photo)

  • media — a string indicating the attached file. Adding a substring attach:// is a mandatory rule.

Next, specify the files to be transferred. The name of the parameter is equal to the name of the transferred file.

To form an image object, we will use an analogue of the function curl_file_create() – Class CURLFile()which simply takes the path to the image.

After sending the request, we get the following result.

Let’s summarize. In the new lesson we have learned:

  • work with a function curl_file_create() and class CURLFile()

  • send documents to Telegram chat

  • send compressed images to Telegram

  • send grouped images in one message

In the following lessons, I will teach you how to process hooks and receive information about user actions to our server.

Original on Prog-Time website – https://prog-time.ru/course/bot-v-telegram-4/

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *