Microsoft Bot Framework:无需重新启动对话框即可再次询问

时间:2017-01-31 12:05:01

标签: c# dialog botframework

我有一个机器人,它会在数据库中寻找一个人。如果那个人不是一个已知的名字,我想让Bot再次问:“名字不详,请再次给出名字”

以下是我现在所做的步骤:

public class MessagesController : ApiController
{
    /// <summary>
    /// POST: api/Messages
    /// Receive a message from a user and reply to it
    /// </summary>
    public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {
        await Conversation.SendAsync(activity, () => new RootDialog());   
    }
.... (more code here)
RootDialog中的

   public async Task StartAsync(IDialogContext context)
   {
        context.Wait(this.MessageReceivedAsync);

    }
    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        var message = await result;
        if (message.Text.ToLower().Contains("help") 
            || message.Text.ToLower().Contains("support") 
            || message.Text.ToLower().Contains("problem"))
        {
            await context.Forward(new SupportDialog(), this.ResumeAfterSupportDialog, message, CancellationToken.None);
        }
        else
        {
            context.Call(new SearchDialog(), this.ResumeAfterOptionDialog);
        }
    }

在SearchDialog中:

public async Task StartAsync(IDialogContext context)
    {
        await context.PostAsync($"Hi {context.Activity.From.Name}, Looking for someone?.");
        var SearchFormDialog = FormDialog.FromForm(this.BuildSearchForm, FormOptions.PromptInStart);
        context.Call(SearchFormDialog, this.ResumeAfterSearchFormDialog);
    }


private IForm<SearchQuery> BuildSearchForm()
    {
        OnCompletionAsyncDelegate<SearchQuery> processSearch = async (context, persoon) =>
        {
            await context.PostAsync($"There we go...");
        };

        return new FormBuilder<SearchQuery>()
            .Field(nameof(SearchQuery.Name))
            .Message($"Just a second...")
            .AddRemainingFields()
            .OnCompletion(processSearch)
            .Build();
    }


private async Task ResumeAfterSearchFormDialog(IDialogContext context, IAwaitable<SearchQuery> result)
    {
        try
        {
            var searchQuery = await result;

            var found = await new BotDatabaseEntities().GetAllWithText(searchQuery.Name);
            var resultMessage = context.MakeMessage();

            var listOfPersons = foundPersons as IList<Person> ?? foundPersons.ToList();

            if (!listOfPersons.Any())
            {
                await context.PostASync($"No one found");
            }
            else if (listOfPersons.Count > 1)
            {
                resultMessage.AttachmentLayout = AttachmentLayoutTypes.List;
                resultMessage.Attachments = new List<Attachment>();
                this.ShowNames(context, listOfPersons.Select(foundPerson => foundPerson.FullName.ToString()).ToArray());
            }
            else
            {
                await OnePersonFound(context, listOfPersons.First(), resultMessage);
            }
        }
        catch (FormCanceledException ex)
        {
            string reply;
            reply = ex.InnerException == null ? "You have canceled the operation";
            await context.PostAsync(reply);
        }
    }

这是SearchQuery:

[Serializable]
public class SearchQuery
{
    [Prompt("Please give the {&} of the person your looking for.")]
    public string Name { get; set; }
}

现在。当我提供一个不存在的名称时,我不想重新开始对话,而只是在此之后Bot再次询问问题。

if (!listOfPersons.Any())
        {
            await context.PostASync($"No one found");
        }

真的不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

嗯,我现在修理了这个:

if (!listOfPersons.Any())
            {
                await context.PostAsync($"Sorry, no one was found with this text");
                var SearchFormDialog = FormDialog.FromForm(this.BuildSearchForm, FormOptions.PromptInStart);
                context.Call(SearchFormDialog, this.ResumeAfterSearchFormDialog);
            }

答案 1 :(得分:0)

您可以使用验证委托检查给定名称是否有效

private IForm<SampleForm> BuildFeedbackModelForm()
    {
        var builder = new FormBuilder<SampleForm>();
        return builder.Field(new FieldReflector<SampleForm>(nameof(SampleForm.Question))
                .SetType(typeof(string))
                .SetDefine(async (state, field) => await SetOptions(state, nameof(SampleForm.Answer), field))
                .SetValidate(async (state, value) => await ValidateFdResponseAsync(value, state, nameof(SampleForm.Answer)))).Build();

    }

    private async Task<bool> SetOptions(SampleForm state, string v, Field<SampleForm> field)
    {
    return true;
    }

    private async Task<ValidateResult> ValidateFdResponseAsync(object response, SyncfusionBotFeedbackForm state, string v)
    {
        bool isValid = false; // chcek if valid


        ValidateResult validateResult = new ValidateResult
        {
            IsValid = isValid,
            Value = isValid?locresult:null
        };
        if (!isValid)
            validateResult.Feedback = $"message to user.";
        return validateResult;
    }