如何使用c#和google.cloud.dialogflow.cx.v3生成有效的Google DialogFlow CX Webhook响应JSON

发布于 2025-01-25 05:15:31 字数 4533 浏览 2 评论 0 原文

我已经使用C#和ASP.NET Core创建了一个Webhook,以尝试生成对DialogFlow的Webhook响应,但是我确实在使用Google.cloud.dialogflow.cx.v3来创建类似于有效负载的有效负载我知道我需要生产。我意识到我可以落在“创建” JSON字符串上,但是如果可以的话,我宁愿使用库。这是我需要创建的响应:

{
  fulfillmentResponse: {
    messages: [
      {
        payload: {
          plainText: "Details for order ID: {order_id}",
          richContent: [
            {
              type: "card",
              title: "{order_id}",
              text: [
                "<span class='subtitle'>Ordered</span>",
                "{order_date}",
                "<span class='subtitle'>Status</span>",
                "{order_status}",
                "<span class='subtitle'>Store</span>",
                "{order_store}",
                
              ],
              link: {
                url: "{tracking_link}"text: "Track Shipment"
              }
            }
          ]
        }
      }
    ]
  }
}

这是我的代码当前产生的(如目前,我只是想重新创建明文部分。我什至还没有到达Richcontent

{
    "webhookResponse": {
        "fulfillmentResponse": {
            "messages": [
                {
                    "text": null,
                    "payload": {
                        "fields": {
                            "plainText": {
                                "nullValue": 0,
                                "numberValue": 0,
                                "stringValue": "Details for Order: 11607",
                                "boolValue": false,
                                "structValue": null,
                                "listValue": null,
                                "kindCase": 3
                            }
                        }
                    },
                    "conversationSuccess": null,
                    "outputAudioText": null,
                    "liveAgentHandoff": null,
                    "endInteraction": null,
                    "playAudio": null,
                    "mixedAudio": null,
                    "telephonyTransferCall": null,
                    "messageCase": 2
                }
            ],
            "mergeBehavior": 0
        },
        "pageInfo": null,
        "sessionInfo": null,
        "payload": null,
        "targetPage": "",
        "targetFlow": "",
        "transitionCase": 0,
        "targetPageAsPageName": null,
        "targetFlowAsFlowName": null
    }
}

)字段以及信息似乎包裹在“ Webhookresponse”中,而不是从ExhullmentResponse开始。我有点卡住。这是我到目前为止创建响应的代码:

public class OrderStatusResponse : DialogFlowResponse
{

    public OrderStatusResponse(OrderStatusDto orderStatus, string requestId)
    {
        this.webhookResponse = new WebhookResponse();
        WebhookResponse.Types.FulfillmentResponse fulfillmentResponse = new WebhookResponse.Types.FulfillmentResponse();
        this.webhookResponse.FulfillmentResponse = fulfillmentResponse;
        var plainText = new Google.Protobuf.WellKnownTypes.Value();
        var payload = new Google.Protobuf.WellKnownTypes.Struct();
        plainText.StringValue = $"Details for Order: {orderStatus.OrderResults.First().OrderId}";
        var responseItem = new ResponseMessage();
        responseItem.Payload = payload; 
        responseItem.Payload.Fields.Add("plainText", plainText);
        fulfillmentResponse.Messages.Add(responseItem);

    }
}

我只是将其返回为'响应'在下面的控制器中 iActionResult

[HttpPost]
[SwaggerResponse(200, "OrderStatusResponse", typeof(Api.Internal.Orders.Responses.OrderStatusResponse))]
[SwaggerResponse(400, "OrderNotFoundException", typeof(OrderNotFoundException))]
[SwaggerResponse(400, "InvalidRequestException", typeof(InvalidRequestException))]
[Route("search/")]
public async Task<IActionResult> GetOrdersBySearch([FromBody] OrderStatusRequest request)
{
    requestId = ControllerHelper.GetRequestId(Request.HttpContext);

    try
    {
        _logger.LogInformation($"Starting request {requestId}");
        var response = await _orderService.GetOrdersBySearch(request, requestId);
        return Ok(response);
    }
    catch (OrderNotFoundException oex)
    {
        _logger.LogError(oex.ToString());
        return BadRequest(oex.Problem);
    }
    catch (InvalidRequestException irex)
    {
        _logger.LogError(irex.ToString());
        return BadRequest(irex.Problem);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.ToString());
        return StatusCode(500, new FriendlyErrorException(requestId).Problem);
    }
}

I've created a webhook using C# and ASP.NET Core in order to try to generate the webhook response to DialogFlow, but I'm really struggling with using Google.Cloud.Dialogflow.Cx.V3 to create a payload that resembles the payload I know I need to produce. I realise I could just fall back on 'hand creating' the JSON string, but I'd rather use the library if I can. Here is the response I need to create:

{
  fulfillmentResponse: {
    messages: [
      {
        payload: {
          plainText: "Details for order ID: {order_id}",
          richContent: [
            {
              type: "card",
              title: "{order_id}",
              text: [
                "<span class='subtitle'>Ordered</span>",
                "{order_date}",
                "<span class='subtitle'>Status</span>",
                "{order_status}",
                "<span class='subtitle'>Store</span>",
                "{order_store}",
                
              ],
              link: {
                url: "{tracking_link}"text: "Track Shipment"
              }
            }
          ]
        }
      }
    ]
  }
}

Here is what my code currently produces (As it stands, I'm only trying to recreate the plainText part. I haven't even gotten to the richContent as yet)

{
    "webhookResponse": {
        "fulfillmentResponse": {
            "messages": [
                {
                    "text": null,
                    "payload": {
                        "fields": {
                            "plainText": {
                                "nullValue": 0,
                                "numberValue": 0,
                                "stringValue": "Details for Order: 11607",
                                "boolValue": false,
                                "structValue": null,
                                "listValue": null,
                                "kindCase": 3
                            }
                        }
                    },
                    "conversationSuccess": null,
                    "outputAudioText": null,
                    "liveAgentHandoff": null,
                    "endInteraction": null,
                    "playAudio": null,
                    "mixedAudio": null,
                    "telephonyTransferCall": null,
                    "messageCase": 2
                }
            ],
            "mergeBehavior": 0
        },
        "pageInfo": null,
        "sessionInfo": null,
        "payload": null,
        "targetPage": "",
        "targetFlow": "",
        "transitionCase": 0,
        "targetPageAsPageName": null,
        "targetFlowAsFlowName": null
    }
}

There are all kinds of additional fields, as well as the message seeming to be wrapped in 'webhookResponse' rather than starting at fulfillmentResponse. I'm a bit stuck. Here is the code I have so far to create the response:

public class OrderStatusResponse : DialogFlowResponse
{

    public OrderStatusResponse(OrderStatusDto orderStatus, string requestId)
    {
        this.webhookResponse = new WebhookResponse();
        WebhookResponse.Types.FulfillmentResponse fulfillmentResponse = new WebhookResponse.Types.FulfillmentResponse();
        this.webhookResponse.FulfillmentResponse = fulfillmentResponse;
        var plainText = new Google.Protobuf.WellKnownTypes.Value();
        var payload = new Google.Protobuf.WellKnownTypes.Struct();
        plainText.StringValue = 
quot;Details for Order: {orderStatus.OrderResults.First().OrderId}";
        var responseItem = new ResponseMessage();
        responseItem.Payload = payload; 
        responseItem.Payload.Fields.Add("plainText", plainText);
        fulfillmentResponse.Messages.Add(responseItem);

    }
}

And I am just returning that as 'response' inside an IActionResult from the controller below:

[HttpPost]
[SwaggerResponse(200, "OrderStatusResponse", typeof(Api.Internal.Orders.Responses.OrderStatusResponse))]
[SwaggerResponse(400, "OrderNotFoundException", typeof(OrderNotFoundException))]
[SwaggerResponse(400, "InvalidRequestException", typeof(InvalidRequestException))]
[Route("search/")]
public async Task<IActionResult> GetOrdersBySearch([FromBody] OrderStatusRequest request)
{
    requestId = ControllerHelper.GetRequestId(Request.HttpContext);

    try
    {
        _logger.LogInformation(
quot;Starting request {requestId}");
        var response = await _orderService.GetOrdersBySearch(request, requestId);
        return Ok(response);
    }
    catch (OrderNotFoundException oex)
    {
        _logger.LogError(oex.ToString());
        return BadRequest(oex.Problem);
    }
    catch (InvalidRequestException irex)
    {
        _logger.LogError(irex.ToString());
        return BadRequest(irex.Problem);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.ToString());
        return StatusCode(500, new FriendlyErrorException(requestId).Problem);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

思慕 2025-02-01 05:15:31

最后,对我的解决方案只是使用标准的C#Pocos,而System.Text.json进行序列化 /挑选。这很好,我不需要参考Google Protobuf库。

In the end, the solution for me was just to use standard C# POCOs, and System.Text.JSON for serialising / deserialising. This works fine, I have not needed to refer to the Google protobuf libraries.

戴着白色围巾的女孩 2025-02-01 05:15:31

客户端库(或任何 google cloud .net .net库)类是来自 protobuf定义 - 使用

这样的东西,其中响应是SDK对象

using Google.Protobuf;

...

JsonFormatter jf = new JsonFormatter(new JsonFormatter.Settings(true));
Console.WriteLine(jf.Format(response));

The Google.Cloud.Dialogflow.Cx.V3 client library (or any Google Cloud .NET library) classes are derived from Protobuf definitions - Use the Google.Protobuf.JsonFormatter to create valid JSON objects.

Something like this, where response is a SDK object

using Google.Protobuf;

...

JsonFormatter jf = new JsonFormatter(new JsonFormatter.Settings(true));
Console.WriteLine(jf.Format(response));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文