Search code examples
phpdialogflow-es

How to get rich text response dialogflow php api


hello I am trying to get rich text response from dialogflow using php api my sample code

$session = $sessionsClient->sessionName('agentId', $sessionId ?: uniqid());
$textInput = new TextInput();
$textInput->setText('question');
$textInput->setLanguageCode('en-US');

$queryInput = new QueryInput();
$queryInput->setText($textInput);

$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$fulfilmentText = $queryResult->getFulfillmentText();
echo fulfilmentText;
$sessionsClient->close();

above code works fine but when i replace $fulfilmentText = $queryResult->getFulfillmentText(); with $fulfillmentMessages = $queryResult->getFulfillmentMessages(); and when i print i get error as

Object of class Google\Protobuf\Internal\RepeatedField could not be converted to string

any input will be appreciated


Solution

  • In the default response, there is NO rich text!
    Rich Text response is for other channels (Facebook messenger, Skype ...)

    You can use something like this:

    $fulfilmentMessages = $queryResult->getFulfillmentMessages();
    $output = [];
    foreach ($fulfilmentMessages as $number => $message) {
        switch ($message->getMessage()) {
            case 'text':
                $output[] = ['text' => $message->getText()->getText()->offsetGet(0)];
                break; 
            case 'card':
                $card = $message->getCard();
                $buttons = [];
                foreach ($card->getButtons() as $button) {
                     $buttons[] = [
                         'text' => $button->getText(),
                         'postback' => $button->getPostback()
                     ];
                 }
                 $output[] = ['card' => [
                    'title' => $card->getTitle(),
                    'subtitle' => $card->getSubTitle(),
                    'image' => $card->getImageUri(),
                    'buttons' => $buttons
                 ]];
                 break;
          }
    }
    

    $output will contain an array with normal text plus rich text responses. You need to make a nice custom view for it.