LoginSignup
0
1

DialogFlow のwebhook(cloudfunctions)のpython関数の書き方

Last updated at Posted at 2023-04-13

1. はじめに

  • dialogflow CXのwebhookで、pythonを使ったCloudFunctionの書き方を覚えた。

2. 経緯

  • dialogflow CXのチュートリアルをやっていると、webhookでレスポンスを作れるとのこと。
  • チュートリアルでは、webhookの先のCloudFunctionsではGoで書かれていたので、そのままコピペしてたけれど、自分で書くならpythonになるだろうなと思い、サンプルを調べる。
    まず、Goのサンプルはここに記載のとおり
    ⇓このへんがメインのところと思われます。
// confirm handles webhook calls using the "confirm" tag.
func confirm(request webhookRequest) (webhookResponse, error) {
	// Create a text message that utilizes the "size" and "color"
	// parameters provided by the end-user.
	// This text message is used in the response below.
	t := fmt.Sprintf("You can pick up your order for a %s %s shirt in 5 days.",
		request.SessionInfo.Parameters["size"],
		request.SessionInfo.Parameters["color"])

	// Create session parameters that are populated in the response.
	// The "cancel-period" parameter is referenced by the agent.
	// This example hard codes the value 2, but a real system
	// might look up this value in a database.
	p := map[string]interface{}{"cancel-period": "2"}

	// Build and return the response.
	response := webhookResponse{
		FulfillmentResponse: fulfillmentResponse{
			Messages: []responseMessage{
				{
					Text: text{
						Text: []string{t},
					},
				},
			},
		},
		SessionInfo: sessionInfo{
			Parameters: p,
		},
	}
	return response, nil
}


3. こんな感じに書けばよい

import functions_framework

@functions_framework.http
def hello_http(request):
    """Handles a Dialogflow CX webhook request."""
    request_dict = request.get_json()
    size = request_dict["sessionInfo"]['parameters']["size"]
    color = request_dict["sessionInfo"]['parameters']["color"]

    return json.dumps(
        {
            "fulfillment_response": {
                "messages": [
                    {
                        "text": {
                            "text": ["You can pick up your order for a {} {} shirt in 5 days.".format(size,color)],
                            "allow_playback_interruption": False,
                        }
                    }
                ]
            },
            "session_info": {
                "parameters": {"cancel-period": "500"}
            }
        }
    )


良く見たらここにもちょっと書き方があった。

20230707追加;
rich messageにして返したい場合のレスポンスの書き方:
fulfillment_response = {
'messages': [{
までは上と同様。

    response_json = jsonify(
       fulfillment_response = {
            'messages': [{
               "payload": {
                   "richContent": [[{
                       "actionLink": "https://assistant.google.com/",
                       "subtitle": "This is the body text of a card.  You can even use line\n  breaks and emoji! 💁",
                       "title": "Title: this is a card title",
                       "type": "info"
                   }]]
               }
            }]   
           
       }    
       
    )
    return response_json
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1