Попытка совместить Луиса и аттачмент в C # - PullRequest
1 голос
/ 07 ноября 2019

Я пытаюсь настроить пример CoreBot (https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/13.core-bot), чтобы он также мог получать изображения в дополнение к тексту.

Хотя есть много хорошей документации (ниже) и ответов на stackoverflowЯ новичок в C # и испытываю трудности с объединением нескольких частей кода с синтаксисом C #.

В приведенном ниже коде я вставляю этот фрагмент кода в CoreBot:

var activity = stepContext.Context.Activity
            var reply = activity.CreateReply();
            if (activity.Attachments != null && activity.Attachments.Any())
                {
                var messageText = stepContext.Options?.ToString() ?? "this seems to be an image an i am not yet able to understand it";
                var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput);
                return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken);
            }

Ниже приведен блок кода, в который я вставил "ifimage, затем "

private async Task<DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {


             if (!_luisRecognizer.IsConfigured)
            {
                // LUIS is not configured, we just run the BookingDialog path with an empty BookingDetailsInstance.
                return await stepContext.BeginDialogAsync(nameof(BookingDialog), new BookingDetails(), cancellationToken);
            }

            var activity = stepContext.Context.Activity;
            if (activity.Attachments != null && activity.Attachments.Any())
                {
                var messageText = stepContext.Options?.ToString() ?? "this seems to be an image an i am not yet able to understand it";
                var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput);
                return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken);
            }



            // Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
            var luisResult = await _luisRecognizer.RecognizeAsync<FlightBooking>(stepContext.Context, cancellationToken);
            switch (luisResult.TopIntent().intent)
            {
                case FlightBooking.Intent.BookFlight:
                    await ShowWarningForUnsupportedCities(stepContext.Context, luisResult, cancellationToken);

                    // Initialize BookingDetails with any entities we may have found in the response.
                    var bookingDetails = new BookingDetails()
                    {
                        // Get destination and origin from the composite entities arrays.
                        Destination = luisResult.ToEntities.Airport,
                        Origin = luisResult.FromEntities.Airport,
                        TravelDate = luisResult.TravelDate,
                    };

                    // Run the BookingDialog giving it whatever details we have from the LUIS call, it will fill out the remainder.
                    return await stepContext.BeginDialogAsync(nameof(BookingDialog), bookingDetails, cancellationToken);


Проблема в том, что код, который я добавил, ничего не делает.

Как уже упоминалось, я новичок в C # и любое предложение или замечаниеБуду очень признателен!

1 Ответ

1 голос
/ 07 ноября 2019

Я удивлен, что даже позволяет компилировать с Any(). В моем тестировании Visual Studio выдавала ошибки сборки.

Изменение:

if (activity.Attachments != null && activity.Attachments.Any())

на

if (activity.Attachments != null && activity.Attachments.Count > 0)


Приведенный выше ответ предполагает, что activity содержит вложение, но его просто не поймали. Если activity даже не содержит вложения, значит что-то не так. В этом случае, пожалуйста, включите весь диалог или, желательно, ссылку на ваш код / ​​репо.

...