【问题标题】:Telegram Bot Bad Gateway电报机器人坏网关
【发布时间】:2015-09-22 03:20:33
【问题描述】:

我正在尝试使用以下代码使用 Telegram Bot API 上传图片

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");
}

我收到 Nginx 502 Bad Gateway。我使用正确的方法吗?我使用 API 获取 getMe 没有问题。

P.S 我使用 Guzzle 5.3.0 来实现 php 兼容性。

【问题讨论】:

    标签: php guzzle telegram telegram-bot


    【解决方案1】:

    尝试将其作为一个多部分的帖子。

    $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

    对于 Guzzle 5.3

    use GuzzleHttp\Client;
    
    $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);
    

    注意:您必须将文件句柄传递给“照片”属性,而不是文件的内容。

    【讨论】:

    • 我正在使用 Guzzle 5.3 。多部分选项仅在最新版本中可用。我正在使用旧的 guzzle 版本来兼容 php。
    • guzzle3.readthedocs.org/http-client/request.html 请参阅“POST 请求”部分。 Telegram API 要求您在 multipart/form-data 中上传照片
    • 见我编辑,你必须传递文件句柄而不是文件内容。
    • 我尝试传递文件句柄,结果是 [status code] 400 [reason phrase] Bad Request。我不知道为什么。
    • 我用我使用的完整代码 sn-p 更新了我的答案。这对我来说非常有效。但是,当我传递文件内容时,我确实收到了 502 错误。
    【解决方案2】:

    我终于找到了解决办法。为其他人粘贴我的解决方案。

    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>');
    }
    

    我很困惑为什么这适用于这种 Guzzle 方法而不是另一种方法。我怀疑 Guzzle 没有使用第一种方法设置正确的标题类型。

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 2018-07-22
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2017-06-07
      • 2020-08-20
      相关资源
      最近更新 更多