Is there any way to send an attachment along with the BOT message from Telegram?

Asked

Viewed 679 times

0

I am using the Telegram API to send error logs from my applications.

I display some key information but would also like to display the trace exception. The problem is that Telegram returns an error 400, showing that the value exceeds the maximum size (which is 4096, if I’m not mistaken).

In case, I wanted to continue displaying the key log information and add that snippet from trace exception (which is large) in a file txt.

It would be possible, in addition to sending the message, to attach a text file together?

The code I have is this::

function telegram_log($chat_id, $text, $parse_mode = 'markdown')
{
    $cli = new \GuzzleHttp\Client([
        'base_url' => TELEGRAM_URL_API,
    ]);


    $response = $cli->post('sendMessage', [
        'query' => compact('text', 'parse_mode', 'chat_id'),
        'timeout'         => 5,
        'connect_timeout' => 5,
    ]);



    return json_decode( (string) $response->getBody() );
}

1 answer

0


As indicated in the comments by @fernandosavio and also in the documentation of Telegram, it is possible to use the method sendDocument.

A few points should be observed:

  • The field caption may have to 0 to 1024 characters. This must be sent as Query String.

  • The field document must be in themultipart/form-data request. For photos, the maximum size allowed is 10MB, and for archives, 50MB.

My code with Guzzle went like this:

function telegram_send_document($token, $chat_id, $file, $caption = null)
{

    $client = new \GuzzleHttp\Client([
        'base_uri' => sprintf('https://api.telegram.org/bot%s/', $token),
    ]);

    $client->post('sendDocument', [
        'query' => [
            'chat_id'    => $chat_id,
            'caption'    => $caption,
            'parse_mode' => 'markdown'
        ],

        'multipart' => [
            [
                'name'     => 'document',
                'contents' => fopen($file, 'r'),
                'filename' => basename($file)
            ]
        ]
    ]);

}

To use would just do that:

telegram_send_document('TOKEN', 'CHAT_ID', 'log.txt', 'APP Lorem Ipsum');

In the case of GuzzleHttp\Client you can pass a string in the parameter contents of fopen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.