Esta biblioteca é inspirada em dialogflow/dialogflow-fulfillment-nodejs.
Ele oferece suporte a solicitações e respostas JSON de webhook de atendimento do Dialogflow para agentes v1 e v2.
Para referência completa da aula, consulte o documento.
Instale via compositor: composer require eristemena/dialogflow-fulfillment-webhook-php
.
Para iniciar o agente, use o construtor DialogflowWebhookClient
com parâmetro de entrada como matriz de solicitação proveniente do Dialogflow.
No Vanilla PHP, isso pode ser feito da seguinte maneira,
use Dialogflow WebhookClient ;
$ agent = new WebhookClient ( json_decode ( file_get_contents ( ' php://input ' ), true ));
// or
$ agent = WebhookClient :: fromData ( $ _POST );
ou se você estiver usando Laravel,
$ agent = Dialogflow WebhookClient :: fromData ( $ request -> json ()-> all ());
$ intent = $ agent -> getIntent ();
$ action = $ agent -> getAction ();
$ query = $ agent -> getQuery ();
$ parameters = $ agent -> getParameters ();
$ session = $ agent -> getSession ();
$ contexts = $ agent -> getContexts ();
$ language = $ agent -> getLocale ();
google
, facebook
, slack
, etc) $ originalRequest = $ agent -> getRequestSource ();
$ originalRequest = $ agent -> getOriginalRequest ();
$ agentVersion = $ agent -> getAgentVersion ();
Para enviar uma resposta, use o método reply()
.
$ agent -> reply ( ' Hi, how can I help? ' );
Em seguida, use render()
para obter resposta no array. Tudo que você precisa fazer é imprimir o array como JSON,
header ( ' Content-type: application/json ' );
echo json_encode ( $ agent -> render ());
ou em Laravel,
return response ()-> json ( $ agent -> render ());
A carga útil da resposta será formatada automaticamente de acordo com a versão do agente da solicitação.
$ text = Dialogflow RichMessage Text :: create ()
-> text ( ' This is text ' )
-> ssml ( ' <speak>This is <say-as interpret-as="characters">ssml</say-as></speak> ' )
;
$ agent -> reply ( $ text );
$ image = Dialogflow RichMessage Image :: create ( ' https://www.example.com/image.png ' );
$ agent -> reply ( $ image );
$ card = Dialogflow RichMessage Card :: create ()
-> title ( ' This is title ' )
-> text ( ' this is text body ' )
-> image ( ' https://www.example.com/image.png ' )
-> button ( ' This is a button ' , ' https://docs.dialogflow.com/ ' )
;
$ agent -> reply ( $ card );
$ suggestion = Dialogflow RichMessage Suggestion :: create ([ ' Suggestion one ' , ' Suggestion two ' ]);
$ agent -> reply ( $ suggestion );
if ( $ agent -> getRequestSource ()== ' google ' ) {
$ agent -> reply ( Dialogflow RichMessage Payload :: create ([
' expectUserResponse ' => false
]));
}
Esta biblioteca também oferece suporte a funcionalidades específicas do Actions on Google. Ainda está em desenvolvimento, portanto mais recursos serão adicionados no futuro.
Para usar o objeto Actions on Google Dialogflow Conversation, primeiro você precisa garantir que requestSource
seja proveniente do Google Assistant,
if ( $ agent -> getRequestSource ()== ' google ' ) {
$ conv = $ agent -> getActionConversation ();
// here you can use the rest of Actions on Google responses and helpers
$ agent -> reply ( $ conv );
}
ou você pode simplesmente chamar o método getActionConversation()
e ele retornará null
se a solicitação não vier do Google Assistente.
$ conv = $ agent -> getActionConversation ();
if ( $ conv ) {
// here you can use the rest of Actions on Google responses and helpers
} else {
// the request does not come from Google Assistant
}
Usando o objeto Dialogflow Conversation, você pode enviar uma resposta de duas maneiras,
$ conv -> close ( ' Have a nice day! ' );
$ conv -> ask ( ' Hi, how can I help? ' );
Por favor, veja a documentação aqui.
use Dialogflow Action Responses SimpleResponse ;
$ conv -> ask ( SimpleResponse :: create ()
-> displayText ( ' Hello, how can i help? ' )
-> ssml ( ' <speak>Hello,<break time="0.5s"/> <prosody rate="slow">how can i help?</prosody></speak> ' )
);
use Dialogflow Action Responses Image ;
$ conv -> close ( Image :: create ( ' https://picsum.photos/400/300 ' ));
Por favor, veja a documentação aqui.
use Dialogflow Action Responses BasicCard ;
$ conv -> close ( BasicCard :: create ()
-> title ( ' This is a title ' )
-> formattedText ( ' This is a subtitle ' )
-> image ( ' https://picsum.photos/400/300 ' )
-> button ( ' This is a button ' , ' https://docs.dialogflow.com/ ' )
);
Por favor, veja a documentação aqui.
A lista de seleção única apresenta ao usuário uma lista vertical de vários itens e permite que o usuário selecione um único. Selecionar um item da lista gera uma consulta do usuário (balão de bate-papo) contendo o título do item da lista.
use Dialogflow Action Questions ListCard ;
use Dialogflow Action Questions ListCard Option ;
$ conv -> ask ( ' Please choose below ' );
$ conv -> ask ( ListCard :: create ()
-> title ( ' This is a title ' )
-> addOption ( Option :: create ()
-> key ( ' OPTION_1 ' )
-> title ( ' Option 1 ' )
-> synonyms ([ ' option one ' , ' one ' ])
-> description ( ' Select option 1 ' )
-> image ( ' https://picsum.photos/48/48 ' )
)
-> addOption ( Option :: create ()
-> key ( ' OPTION_2 ' )
-> title ( ' Option 2 ' )
-> synonyms ([ ' option two ' , ' two ' ])
-> description ( ' Select option 2 ' )
-> image ( ' https://picsum.photos/48/48 ' )
)
);
Para capturar a opção selecionada pelo usuário, crie uma intent do Dialogflow com o evento actions_intent_OPTION
. Supondo que você nomeie a intenção como Get Option
, você pode obter o argumento da seguinte maneira,
if ( ' Get Option ' == $ agent -> getIntent ()) {
$ conv = $ agent -> getActionConversation ();
$ option = $ conv -> getArguments ()-> get ( ' OPTION ' );
switch ( $ option ) {
case ' OPTION_1 ' :
$ conv -> close ( ' You choose option 1 ' );
break ;
case ' OPTION_2 ' :
$ conv -> close ( ' You choose option 2 ' );
break ;
default :
$ conv -> close ( ' Sorry, i do not understand ' );
break ;
}
}
Por favor, veja a documentação aqui.
O carrossel rola horizontalmente e permite selecionar um item. Comparado ao seletor de lista, ele possui blocos grandes, permitindo um conteúdo mais rico. As peças que compõem um carrossel são semelhantes ao cartão básico com imagem. Selecionar um item do carrossel irá simplesmente gerar um balão de bate-papo como resposta, assim como no seletor de lista.
use Dialogflow Action Questions Carousel ;
use Dialogflow Action Questions Carousel Option ;
$ conv -> ask ( ' Please choose below ' );
$ conv -> ask (
Carousel :: create ()
-> Option (
Option :: create ()
-> key ( ' OPTION_1 ' )
-> title ( ' Option 1 ' )
-> synonyms ([ ' option one ' , ' one ' ])
-> description ( ' Select option 1 ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
-> Option (
Option :: create ()
-> key ( ' OPTION_2 ' )
-> title ( ' Option 2 ' )
-> synonyms ([ ' option two ' , ' two ' ])
-> description ( ' Select option 2 ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
-> Option (
Option :: create ()
-> key ( ' OPTION_3 ' )
-> title ( ' Option 3 ' )
-> synonyms ([ ' option three ' , ' three ' ])
-> description ( ' Select option 3 ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
-> Option (
Option :: create ()
-> key ( ' OPTION_4 ' )
-> title ( ' Option 4 ' )
-> synonyms ([ ' option four ' , ' four ' ])
-> description ( ' Select option 4 ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
);
Para verificar se o usuário concedeu as informações e depois acessar os dados, crie uma intent do Dialogflow com o evento actions_intent_OPTION
. Supondo que você nomeie a intenção como Get Option
, você pode obter o argumento da seguinte maneira,
if ( ' Get Option ' == $ agent -> getIntent ()) {
$ conv = $ agent -> getActionConversation ();
$ option = $ conv -> getArguments ()-> get ( ' OPTION ' );
switch ( $ option ) {
case ' OPTION_1 ' :
$ conv -> close ( ' You choose option 1 ' );
break ;
case ' OPTION_2 ' :
$ conv -> close ( ' You choose option 2 ' );
break ;
case ' OPTION_3 ' :
$ conv -> close ( ' You choose option 3 ' );
break ;
case ' OPTION_4 ' :
$ conv -> close ( ' You choose option 4 ' );
break ;
default :
$ conv -> close ( ' Sorry, i do not understand ' );
break ;
}
}
Por favor, veja a documentação aqui.
Um carrossel de navegação é uma resposta rica, semelhante à resposta do carrossel, pois rola horizontalmente e permite que os usuários selecionem um bloco. Os carrosséis de navegação são projetados especificamente para conteúdo da Web, abrindo o bloco selecionado em um navegador da Web (ou em um navegador AMP, se todos os blocos estiverem habilitados para AMP). O carrossel de navegação também persistirá na superfície do Assistente do usuário para navegação posterior.
use Dialogflow Action Responses BrowseCarousel ;
use Dialogflow Action Responses BrowseCarousel Option ;
$ conv -> ask ( ' Please choose below ' );
$ conv -> ask (
BrowseCarousel :: create ()
-> imageDisplayOptions ( ' CROPPED ' )
-> addOption (
Option :: create ()
-> title ( ' Title of item 1 ' )
-> description ( ' Description of item 1 ' )
-> footer ( ' Item 1 footer ' )
-> url ( ' http://www.example.com ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
-> addOption (
Option :: create ()
-> title ( ' Title of item 2 ' )
-> description ( ' Description of item 2 ' )
-> footer ( ' Item 2 footer ' )
-> url ( ' http://www.example.com ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
-> addOption (
Option :: create ()
-> title ( ' Title of item 3 ' )
-> description ( ' Description of item 3 ' )
-> footer ( ' Item 3 footer ' )
-> url ( ' http://www.example.com ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
-> addOption (
Option :: create ()
-> title ( ' Title of item 4 ' )
-> description ( ' Description of item 4 ' )
-> footer ( ' Item 4 footer ' )
-> url ( ' http://www.example.com ' )
-> image ( ' https://picsum.photos/300/300 ' )
)
);
Nenhum cumprimento de acompanhamento é necessário para interações do usuário com itens do carrossel de navegação, pois o carrossel cuida da transferência do navegador.
Por favor, veja a documentação aqui.
use Dialogflow Action Responses LinkOutSuggestion ;
use Dialogflow Action Responses Suggestions ;
$ conv -> ask ( ' Please choose ' );
$ conv -> ask ( new Suggestions ([ ' Suggestion 1 ' , ' Suggestion 2 ' ]));
$ conv -> ask ( new Suggestions ( ' Suggestion 3 ' ));
$ conv -> ask ( new LinkOutSuggestion ( ' Website ' , ' http://www.example.com ' ));
Por favor, veja a documentação aqui.
As respostas de mídia permitem que suas ações reproduzam conteúdo de áudio com duração superior ao limite de 120 segundos do SSML. O principal componente de uma resposta da mídia é o cartão single-track.
use Dialogflow Action Responses MediaObject ;
use Dialogflow Action Responses MediaResponse ;
use Dialogflow Action Responses Suggestions ;
$ conv -> ask ( ' Here you go ' );
$ conv -> ask (
new MediaResponse (
MediaObject :: create ( ' http://storage.googleapis.com/automotive-media/Jazz_In_Paris.mp3 ' )
-> name ( ' Jazz in Paris ' )
-> description ( ' A funky Jazz tune ' )
-> icon ( ' http://storage.googleapis.com/automotive-media/album_art.jpg ' )
-> image ( ' http://storage.googleapis.com/automotive-media/album_art.jpg ' )
)
);
$ conv -> ask ( new Suggestions ([ ' Pause ' , ' Stop ' , ' Start over ' ]));
Por favor, veja a documentação aqui.
use Dialogflow Action Questions Permission ;
$ conv -> ask ( Permission :: create ( ' To address you by name and know your location ' , [ ' NAME ' , ' DEVICE_PRECISE_LOCATION ' ]));
Para verificar se o usuário concedeu as informações e depois acessar os dados, crie uma intent do Dialogflow com o evento actions_intent_PERMISSION
. Supondo que você nomeie a intenção como Get Permission
, você pode obter as informações a seguir,
if ( ' Get Permission ' == $ agent -> getIntent ()) {
$ conv = $ agent -> getActionConversation ();
$ approved = $ conv -> getArguments ()-> get ( ' PERMISSION ' );
if ( $ approved ) {
$ name = $ conv -> getUser ()-> getName ()-> getDisplay ();
$ latlng = $ conv -> getDevice ()-> getLocation ()-> getCoordinates ();
$ lat = $ latlng -> getLatitude ();
$ lng = $ latlng -> getLongitude ();
$ conv -> close ( ' Got it, your name is ' . $ name . ' and your coordinates are ' . $ lat . ' , ' . $ lng );
} else {
$ conv -> close ( ' Never mind then ' );
}
}
Por favor, veja a documentação aqui.
use Dialogflow Action Questions DateTime ;
$ conv -> ask ( new DateTime ( ' When do you want to come in? ' , ' What is the best date to schedule your appointment? ' , ' What time of day works best for you? ' ));
Para verificar se o usuário concedeu acesso e depois acessar os dados, crie uma intent do Dialogflow com o evento actions_intent_DATETIME
. Supondo que você nomeie a intenção como Get Date Time
, você pode obter as informações a seguir,
if ( ' Get Date Time ' == $ agent -> getIntent ()) {
$ conv = $ agent -> getActionConversation ();
$ date = $ conv -> getArguments ()-> get ( ' DATETIME ' );
if ( $ date ) {
$ conv -> close ( ' Ok, got it, i will see you at ' . $ date -> format ( ' r ' ));
} else {
$ conv -> close ( ' Never mind then ' );
}
}
Por favor, veja a documentação aqui.
use Dialogflow Action Questions Place ;
$ conv -> ask ( new Place ( ' Where do you want to have lunch? ' , ' To find lunch locations ' ));
Para verificar se o usuário concedeu acesso e depois acessar os dados, crie uma intent do Dialogflow com o evento actions_intent_PLACE
. Supondo que você nomeie a intenção como Get Place
, você pode obter as informações a seguir,
if ( ' Get Place ' == $ agent -> getIntent ()) {
$ conv = $ agent -> getActionConversation ();
$ place = $ conv -> getArguments ()-> get ( ' PLACE ' );
if ( $ place ) {
$ conv -> close ( ' Ok, got it, we ' ll meet at ' . $ place -> getFormattedAddress ());
} else {
$ conv -> close ( ' Never mind then ' );
}
}
Por favor, veja a documentação aqui.
use Dialogflow Action Questions Confirmation ;
$ conv -> ask ( new Confirmation ( ' Can you confirm? ' ));
Para verificar se o usuário confirmou ou não, crie uma intent do Dialogflow com o evento actions_intent_CONFIRMATION
. Supondo que você nomeie a intenção como Get Confirmation
, você pode obter as informações a seguir,
if ( ' Get Confirmation ' == $ agent -> getIntent ()) {
$ conv = $ agent -> getActionConversation ();
$ confirmed = $ conv -> getArguments ()-> get ( ' CONFIRMATION ' );
if ( $ confirmed ) {
$ conv -> close ( ' Ok, it is confirmed ' );
} else {
$ conv -> close ( ' Alright then, it is canceled ' );
}
}
O Google Assistente pode ser usado em diversas superfícies, como dispositivos móveis compatíveis com experiências de áudio e exibição ou um dispositivo Google Home compatível com experiências apenas de áudio.
Para projetar e criar conversas que funcionem bem em todas as superfícies, use os recursos de superfície para controlar e definir o escopo de suas conversas de maneira adequada.
$ surface = $ conv -> getSurface ();
if ( $ surface -> hasScreen ()) {
// surface has screen
} elseif ( $ surface -> hasAudio ()) {
// surface has audio
} elseif ( $ surface -> hasMediaPlayback ()) {
// surface can play audio
} elseif ( $ surface -> hasWebBrowser ()) {
// user can interact with the content in a web browser
}