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

0

I'm using the Telegram API to send error logs to my applications.

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

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

Would it be possible, in addition to sending the message, to attach a text file together?

The code I have is the following:

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() );
}
    
asked by anonymous 13.09.2018 / 20:37

1 answer

0

As indicated in the comments by @fernandosavio and also in the Telegram documentation, you can use the sendDocument .

A few points should be noted:

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

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

My code with Guzzle looks 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 it would just do this:

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

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

    
01.11.2018 / 19:58