botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

support for formflow call or luis dialog call

Open stelazh opened this issue 9 years ago • 2 comments

I want to call a dialog after the user choose an option from my quick reply.

Here is my code in Messagecontroller.cs :

`namespace ContosoFlowers {

[BotAuthentication]
public class MessagesController : ApiController
{
    private IMessageActivity activity;

    public string cityRange { get; private set; }

    private static IForm<Enquiry> buildEnquiryForm()
    {
        var builder = new FormBuilder<Enquiry>();

        return builder
            .Field(nameof(StartParking.Time))
            .Field(nameof(StartParking.PlaceNumber))
               .Field(nameof(StartParking.Platenumber))
            .AddRemainingFields()
            .Confirm("Would you like to start parking at {Time}, {PlaceNumber} , {Platenumber}", null)
            .Build()
            ;
    }

    /// <summary>
    /// POST: api/Messages
    /// Receive a message from a user and reply to it
    /// </summary>
    /// 

    public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {
        if (activity.Type == ActivityTypes.Message)
        {

            // *************************
            // Log to Database
            // *************************
            // Instantiate the BotData dbContext
            Models.BotDataEntities DB = new Models.BotDataEntities();
            // Create a new UserLog object
            Models.UserLog NewUserLog = new Models.UserLog();
            // Set the properties on the UserLog object
            NewUserLog.Channel = activity.ChannelId;
            NewUserLog.UserID = activity.From.Id;
            NewUserLog.UserName = activity.From.Name;
            NewUserLog.created = DateTime.UtcNow;
            NewUserLog.Message = activity.Text.Truncate(500);
            // Add the UserLog object to UserLogs
            DB.UserLogs.Add(NewUserLog);
            // Save the changes to the database
            DB.SaveChanges();
            // Call NumberGuesserDialog
            //   await Conversation.SendAsync(activity, () => new RootDialog());

            // The Configured IISExpressSSLPort property in this project file

    const int ConfiguredHttpsPort = 44371;

            var link = Url.Link("CheckOut", new { controller = "CheckOut", action = "Index" });
            var uriBuilder = new UriBuilder(link)
            {
                Scheme = Uri.UriSchemeHttps,
                Port = ConfiguredHttpsPort
            };
            var checkOutRouteUri = uriBuilder.Uri.ToString();

            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
            {
                var dialog = scope.Resolve<IDialog<object>>(TypedParameter.From(checkOutRouteUri));
                await Conversation.SendAsync(activity, () => dialog);
            }
        }
        else
        {
            await this.HandleSystemMessage(activity);
        }

        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

    //internal static IDialog<ContactMessage> dialog()
    //{
    //    return Chain.From(() => FormDialog.FromForm(ContactMessage.BuildForm));
    //}

    internal static IDialog<StartParking> MakeRoot()
    {
        return Chain.From(() => new Enquiry(buildEnquiryForm));
    }

    private async Task HandleSystemMessage(Activity message)
    {
        if (message.Type == ActivityTypes.DeleteUserData)
        {
            // Implement user deletion here
            // If we handle user deletion, return a real message
        }
        else if (message.Type == ActivityTypes.ConversationUpdate)
        {
            if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
            {
                var reply = message.CreateReply(Resources.RootDialog_Welcome_Message);

                ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

                await connector.Conversations.ReplyToActivityAsync(reply);
            }

            //if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
            //{
            //    await Conversation.SendAsync(activity, () => { return Chain.From(() => FormDialog.FromForm(ProfileForm.BuildForm)); });
            //}
        }
        else if (message.Type == ActivityTypes.ContactRelationUpdate)
        {
            // Handle add/remove from contact lists
            // Activity.From + Activity.Action represent what happened
        }
        else if (message.Type == ActivityTypes.Typing)
        {
            // Handle knowing tha the user is typing
        }
        else if (message.Type == ActivityTypes.Ping)
        {
        }
    }
}

}`

enquiry.cs

`namespace ContosoFlowers.FormFlow { [LuisModel("5aaaaa", "12b678082ee54eaaaaaaaaaaa080b8", LuisApiVersion.V2)]

[Serializable]
public class Enquiry : LuisDialog<StartParking>
{
    private Func<IForm<Enquiry>> buildEnquiryForm;
    public Enquiry(Func<IForm<Enquiry>> buildEnquiryForm)
    {
        this.buildEnquiryForm = buildEnquiryForm;
    }

    public Enquiry()
    {
    }

    [Prompt("What time")]
    public DateTime Time { get; set; }
    [Prompt("Placenumber?")]
    public string PlaceNumber { get; set; }
    [Prompt("Platenumber?")]
    public string Platenumber { get; set; }
    

   
    public IEnumerable<EntityRecommendation> Entities { get; internal set; }

      public static IForm<Enquiry> BuildEnquiryForm()
    {
        return new FormBuilder<Enquiry>()
           
            .AddRemainingFields()
            .Build();
    }
}

}`

rootdialog.cs

` private async Task WelcomeMessageAsync(IDialogContext context) { var reply = context.MakeMessage();

        var options = new[]
        {

        Resources.RootDialog_Welcome_Start,
            Resources.RootDialog_Welcome_Stop,
       
        };
        reply.AddHeroCard(
            Resources.RootDialog_Welcome_Title,
            Resources.RootDialog_Welcome_Subtitle,
            options,
            new[] { "" });

        await context.PostAsync(reply);

        context.Wait(this.OnOptionSelected);
    }

    private async Task OnOptionSelected(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        var message = await result;

        //if you choose start parking
        if (message.Text == Resources.RootDialog_Welcome_Start)
        {
            this.order = new Models.Order();

            var promptOptions = new PromptOptions<string>(
                "Please select the city where you want to park:",
                options: new[] { "A", "B", "C" },
                promptStyler: new FacebookQuickRepliesPromptStyler());

            PromptDialog.Choice(context, this.ResumeAfterSelection, promptOptions);

        }

        else if (message.Text == Resources.RootDialog_Welcome_Stop)
        {
            DateTime localDate = DateTime.Now;
            //Chain.From(() => FormDialog.FromForm(StopParkingOrder.BuildForm));

            // DateTime localDate = Datetime.Now;
            // reply = context.MakeMessage();
            //   var message = await argument;
            await context.PostAsync("You stop at: " + localDate);
            context.Wait(MessageReceivedAsync);

        }
    }



    private async Task ResumeAfterSelection(IDialogContext context, IAwaitable<string> result)
    {
        try
        {
            var cityRange = await result;
            if (cityRange == "A")
            {
                var message = $"You choose A"; 

//** HERE I WANT TO CALL MY FORMFLOW

                await Conversation.SendAsync(activity, () => new Enquiry());
            }            
        }
        catch (TooManyAttemptsException)
        {
        }
        context.Wait(this.MessageReceivedAsync);
    }
}`

stelazh avatar Feb 17 '17 15:02 stelazh

@stelazh What is the specific question or problem you're facing, could you please clarify?

carlosscastro avatar Mar 09 '17 18:03 carlosscastro

Please take a look at my answer in https://github.com/Microsoft/BotBuilder/issues/2284.

willportnoy avatar Mar 09 '17 23:03 willportnoy