Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Telegram Bot PHP sendMediaGroup Method

Tags:

php

bots

telegram

I was trying to send some Local images into one message with my Telegram bot. I used sendMediaGroup method to send, but unfortunately doesn't work. Here is my code:

<?php

$url = "https://api.telegram.org/bot" . "TOKEN" . "/sendMediaGroup";
$postContent = [
    'chat_id' => $GLOBALS['chatId'],
    'media' => json_encode([
        ['type' => 'photo', 'media' => new \CURLFile(__DIR__ . '/img1.png')], // Not working
        ['type' => 'photo', 'media' => new \CURLFile('attach://' . __DIR__ . 'jpg1.png')], // Not working
        ['type' => 'video', 'media' => new CURLFile(realpath('mp4.mp4'))], // Not working
    ])
];
post($url, $postContent);


function post($url, $postContent)
{

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postContent);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

?>
like image 889
mdarmanam Avatar asked Apr 22 '26 10:04

mdarmanam


1 Answers

To upload your media using sendMediaGroup method of Telegram bot APIs, you need to use attach://fileName way and also attach the file contents to your request. Something like this:

$postContent = [
    'chat_id' => $GLOBALS['chatId'],
    'media' => json_encode([
        ['type' => 'photo', 'media' => 'attach://file1.png' ],
        ['type' => 'photo', 'media' => 'attach://file2.png' ],
    ]),
    'file1.png' => new CURLFile(realpath($filePath1)),
    'file2.png' => new CURLFile(realpath($filePath2)),
];
post($url, $postContent);
like image 110
Ali Khalili Avatar answered Apr 25 '26 07:04

Ali Khalili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!