Using Guzzle with Telegram Bot API - Issue with 'GetMe' method returning response instead of user object

I have the following code snippet:

public function createClient() {
    $botToken = getenv('TELEGRAM_TOKEN');
    $apiEndpoint = 'https://api.telegram.org/bot' . $botToken . '/';
    $client = new Client(['base_uri' => $apiEndpoint]);
    return $client;
}

public function fetchBotInfo() {
    $client = $this->createClient();
    $result = $client->get('/getMe');
    dd($result);
}

However, instead of receiving the expected user object as outlined in the documentation, I am getting a ‘response’ object.

Response {#188 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -effectiveUrl: "https://core.telegram.org/bots"
  -headers: array:9 [▼
    "server" => array:1 [▶]
    "date" => array:1 [▶]
    "content-type" => array:1 [▶]
    "content-length" => array:1 [▶]
    "connection" => array:1 [▶]
    "pragma" => array:1 [▶]
    "cache-control" => array:1 [▶]
    "x-frame-options" => array:1 [▶]
    "strict-transport-security" => array:1 [▶]
  ]
  -body: Stream {#189 ▼
    -stream: :stream {@280 ▶}
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
  }
}

Is there a way to extract the user object from this response? I am working with PHP 5.4, Guzzle version 5.3, and Laravel 5.0.

Additionally, I attempted to use the getBody() method along with getBody()->getContents() but met with issues. The getBody() method only shows the stream details, while getContents() returns an unexpected HTML document. JSON decoding fails with error code 4 (JSON_ERROR_SYNTAX). Shouldn’t the response be in JSON format?

From your code snippet, it looks like you are successfully making the request but not processing the response correctly. The response should indeed be in JSON format. After obtaining the response object, you need to correctly handle its body. You can access the JSON content by using:

$responseBody = $result->getBody();
$json = json_decode($responseBody, true);

If you still encounter the syntax error, it’s possible that an HTML response might be returned due to an issue with the token or endpoint. Verify that your token is correct and the endpoint is properly configured. Double-check that Guzzle uses the correct API URL and token. Ensure error handling is in place to differentiate between valid JSON responses and possible errors returned as HTML.

Could you be hitting some rate limit causing different response formats? I’ve had strange responses when limits are reached. Also, check for unexpected redirects which might give you HTML. A ['debug' => true] in the client can show headers & response in requests. May help fix this.