skip to Main Content

I am trying to upload picture using Telegram Bot API using the following code

if(file_exists($_FILES['fileToUpload']['tmp_name'])){
        $new = fopen($_FILES['fileToUpload']['tmp_name'], "rb");
        $contents = fread($new, $_FILES['fileToUpload']['size']);
        fclose($new);
        $client = new Client();
        $response = $client->post("https://api.telegram.org/botMyApiKey/sendPhoto", [
            'body'    => ['chat_id' => '11111111', 'photo' => $contents]
        ]);
        var_dump($response);
}else{
        echo("No File");
}

I am getting Nginx 502 Bad Gateway. Am I using the correct method? I have no issues in obtaining getMe using the API.

P.S I am using Guzzle 5.3.0 for php compatibility.

2

Answers


  1. Chosen as BEST ANSWER

    I finally found a solution. Pasting my solution for others.

    move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__."/temp/".$_FILES['photo']['name']); //Important for Form Upload
    $client = new Client();
    $request = $client->createRequest('POST', 'https://api.telegram.org/botMyApiKey/sendPhoto');
    $postBody = $request->getBody();
    $postBody->setField('chat_id', '11111111');
    $postBody->addFile(new PostFile('photo', fopen(__DIR__."/temp/".$_FILES['photo']['name'], "r") ));
    try{
         $response = $client->send($request);
         var_dump($response);
    }catch(Exception $e){
         echo('<br><strong>'.$e->getMessage().'</strong>');
    }
    

    I am puzzled as to why this works with this kind of Guzzle approach and not the other one. I suspect Guzzle not setting the correct header type with the first approach.


  2. Try doing it as a multipart post.

    $client->post(
        'https://api.telegram.org/botMyApiKey/sendPhoto', 
        array(
            'multipart' => array(
                array(
                    'name'     => 'chat_id',
                    'contents' => '1111111'
                ),
                array(
                    'name'     => 'photo',
                    'contents' => $contents
                )
            )
        )
    );
    

    Guzzle documentation reference

    For Guzzle 5.3

    use GuzzleHttpClient;
    
    $client = new Client(['defaults' => [
        'verify' => false
    ]]);
    
    $response = $client->post('https://api.telegram.org/bot[token]/sendPhoto', [
        'body' => [
            'chat_id' => 'xxxxx',
            'photo' => fopen(__DIR__ . '/test.jpg', 'r')
        ]
    ]);
    
    var_dump($response);
    

    Note: you must pass the file handle to the ‘photo’ attribute and not the contents of the file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search