2015-07-04 26 views
4

我尝试使用下面的代码Telgram博特错误网关

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使用TelegramBot API上传图片。我使用正确的方法吗?我在使用API​​获取getMe时没有问题。

P.S我使用Guzzle 5.3.0进行php兼容。

回答

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

对于狂饮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); 

注意:您必须将文件句柄传递到 '照片' 属性和文件不是内容。

+0

我正在使用Guzzle 5.3。多部分选项仅在最新版本中可用。我使用旧的guzzle版本来兼容php。 –

+0

http://guzzle3.readthedocs.org/http-client/request.html请参阅“POST请求”一节。电报API要求你上传照片的多部分/表格数据 – Pete

+0

看我编辑,你必须通过文件句柄,而不是文件内容。 –

0

Guzzle 3 documentation:如果POST领域 存在,但没有文件在POST发送

在狂饮POST请求与 application/x-www-form-urlencoded Content-Type头发送。如果POST请求中指定的文件为 ,那么Content-Type标头将 变为multipart/form-data

客户端对象的post()方法接受四个参数:URL, 可选标题,发布字段和一组请求选项。要在POST请求中发送文件 ,请将@符号前置到数组 值(就像您使用PHP curl_setopt 函数一样)。 例子:

$request = $client->post('http://httpbin.org/post', array(), array(
    'custom_field' => 'my custom value', 
    'file_field' => '@/path/to/file.xml' 
)); 

所以对于电报API,这将成为:

$request = $client->post('https://api.telegram.org/botMyApiKey/sendPhoto', array(), array(
    'chat_id' => 'xxxx', 
    'photo' => '@/path/to/photo.jpg' 
)); 
+0

现在它导致*** [状态码] 400 [reason phrase]错误的请求***。我不知道为什么。 –

+0

请参阅我的解决方案。 –

1

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

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没有使用第一种方法设置正确的标题类型。