示例#1
0
        public OutlookDialog(string id, BotAccessors _accessors) : base(id)
        {
            //InitialDialogId = Id;
            InitialDialogId = id;
            accessors       = _accessors;
            // Define the conversation flow using a waterfall model.
            WaterfallStep[] waterfallSteps = new WaterfallStep[]
            {
                EnviarAccionesOutlook,
                ReemplazarDialog,
                PromptStepAsync,

                CorreosStepAsync
                //EnviarAccionesOutlook
            };
            WaterfallStep[] waterfallStepsOtro = new WaterfallStep[]
            {
                OtroOutlook,
                ConfirmacionOtroOutlook
                //CorreosStepAsync
                //EnviarAccionesOutlook
            };
            //AddDialog(OAuthHelpers.Prompt(ConnectionSettingName));
            AddDialog(new WaterfallDialog(Id, waterfallSteps));
            AddDialog(new WaterfallDialog("waterfallStepsOtro", waterfallStepsOtro));
            AddDialog(Prompt(ConnectionSettingName));
            AddDialog(new ChoicePrompt("EnviarAccionesOutlook"));
            AddDialog(new TextPrompt("ReemplazarDialog"));
            AddDialog(new TextPrompt("OtroOutlook"));
            AddDialog(new ConfirmPrompt("ConfirmacionOtroOutlook"));
        }
示例#2
0
    public void ConfigureServices(IServiceCollection services)
    {
        // Set up the service configuration
        var builder = new ConfigurationBuilder()
                      .SetBasePath(ContentRootPath)
                      .AddJsonFile("appsettings.json")
                      .AddEnvironmentVariables();
        var configuration = builder.Build();

        services.AddSingleton(configuration);

        services.AddBot <BankingBot>(options =>
        {
            var conversationState = new ConversationState(new MemoryStorage());
            options.State.Add(conversationState);

            options.CredentialProvider = new ConfigurationCredentialProvider(configuration);
        });

        services.AddSingleton(serviceProvider =>
        {
            var options           = serviceProvider.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
            var conversationState = options.State.OfType <ConversationState>().FirstOrDefault();

            var accessors = new BotAccessors(conversationState)
            {
                DialogStateAccessor          = conversationState.CreateProperty <DialogState>(BotAccessors.DialogStateAccessorName),
                BankingBotStateStateAccessor = conversationState.CreateProperty <BankingBotState>(BotAccessors.BankingBotStateAccessorName)
            };

            return(accessors);
        });
    }
示例#3
0
        public HotelBot(BotAccessors botAccessors)
        {
            _botAccessors = botAccessors;

            _dialogs = new DialogSet(botAccessors.DialogStateAccessor);
            _dialogs
                .Add(new TextPrompt(Constants.NamePrompt))
                .Add(new NumberPrompt<int>(Constants.AgePrompt))
                .Add(new ChoicePrompt(Constants.RoomTypeSelectionPrompt))
                .Add(new ChoicePrompt(Constants.PaymentTypeSelectionPrompt))
                .Add(new ChoicePrompt(Constants.ConfirmPrompt));

            // Add the dialogs we need to the dialog set.
            _dialogs.Add(new WaterfallDialog(Constants.RootDialog)
                .AddStep(NameStepAsync)
                .AddStep(AgeStepAsync)
                .AddStep(RoomTypeSelectionStepAsync)
                .AddStep(PaymentTypeSelectionStepAsync)
                .AddStep(FormCompletedStepAsync));

            _dialogs.Add(new WaterfallDialog(Constants.ReviewDialog)
                .AddStep(BookingConfirmationStepAsync)
                .AddStep(FinishStepAsync));

            _dialogs.Add(new WaterfallDialog(Constants.OnHoldDialog)
                .AddStep(OnHoldStepAsync)
                .AddStep(ContinueToHoldStepAsync));
        }
示例#4
0
 public MessagesController(BotAccessors accessors, ICredentialProvider credentialProvider)
 {
     _credentialProvider = credentialProvider;
     this.Accessors      = accessors;
     Dialogs             = new DialogSet(accessors.DialogData);
     Dialogs.Add(new RootDialog(Accessors));
 }
示例#5
0
        public SimpleBot(BotAccessors botAccessors)
        {
            var dialogState = botAccessors.DialogStateAccessor;

            dialogs = new DialogSet(dialogState);
            dialogs.Add(new TextPrompt("textPrompt"));
            dialogs.Add(new ChoicePrompt("choicePrompt"));
            dialogs.Add(new ConfirmPrompt("confirmPrompt"));
            dialogs.Add(new DateTimePrompt("dateTimePrompt"));
            dialogs.Add(new AttachmentPrompt("attachmentPrompt"));
            dialogs.Add(new NumberPrompt <int>("numberPrompt"));
            dialogs.Add(new WaterfallDialog("greetings", new WaterfallStep[]
            {
                async(stepContext, cancellationToken) =>
                {
                    return(await stepContext.PromptAsync("choicePrompt",
                                                         new PromptOptions
                    {
                        Prompt = stepContext.Context.Activity.CreateReply("Which prompt would you like to test :-)"),
                        Choices = new[]
                        {
                            new Choice {
                                Value = "dateTimePrompt"
                            },
                            new Choice {
                                Value = "textPrompt"
                            },
                            new Choice {
                                Value = "confirmPrompt"
                            },
                            new Choice {
                                Value = "attachmentPrompt"
                            },
                            new Choice {
                                Value = "numberPrompt"
                            }
                        }.ToList()
                    }));
                },
                async(stepContext, cancellationToken) =>
                {
                    var choice = stepContext.Result as FoundChoice;

                    return(await stepContext.PromptAsync(choice.Value,
                                                         new PromptOptions
                    {
                        Prompt = stepContext.Context.Activity.CreateReply($"Please provide a response")
                    }));
                },
                async(stepContext, cancellationToken) =>
                {
                    await stepContext.Context.SendActivityAsync($"Handle response data here = {stepContext.Result.ToString()}");
                    return(await stepContext.EndDialogAsync());
                }
            }));
            BotAccessors = botAccessors;
        }
        public async void AskForATopicTest()
        {
            var storage = new MemoryStorage();

            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

            // Adding LUIS Router accessor
            LuisRouterAccessor luisRouterAccessor = null;

            using (LuisRouterHelper luisRouterHelper = new LuisRouterHelper(Startup.EnvironmentName, Startup.ContentRootPath))
            {
                luisRouterAccessor = luisRouterHelper.BuildAccessor(userState, null);
            }

            // Adding QnAMaker Router accessor
            QnAMakerAccessor qnaMakerAccessor = null;

            using (QnAMakerHelper qnaMakerHelper = new QnAMakerHelper(Startup.EnvironmentName, Startup.ContentRootPath))
            {
                qnaMakerAccessor = qnaMakerHelper.BuildAccessor();
            }

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState)
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new LuisQnADialog(accessors, luisRouterAccessor, qnaMakerAccessor));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(LuisQnADialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("What topic would you like to know more about?")
            .Send("what do i need to consider for an interview?")
            .AssertReply("In interviews, your job is to convince a recruiter that you have the skills, knowledge and experience for the job. Show motivation and convince a recruiter that you fit the organization's culture and job description, and you get that much closer to an offer.")
            .StartTestAsync();
        }
示例#7
0
 public MessagesController(ICredentialProvider credentialProvider, BotAccessors accessors)
     : base(accessors)
 {
     _credentialProvider = credentialProvider;
     //todo: add dialogs
     Dialogs.Add(new RootDialog());
     Dialogs.Add(new HotelsDialog());
     Dialogs.Add(new SupportDialog());
 }
示例#8
0
            /// <summary>
            /// Initializes a new instance of the <see cref="FacebookEventsBot"/> class.
            /// </summary>
            /// <param name="accessors">The state accessors this instance will be needing at runtime.</param>
            /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#windows-eventlog-provider"/>
            public FacebookEventsBot(BotAccessors accessors)
            {
                if (accessors == null)
                {
                    throw new ArgumentNullException(nameof(accessors));
                }

                _dialogs = new DialogSet(accessors.ConversationDialogState);
                _dialogs.Add(new AttachmentPrompt(DialogId));
            }
示例#9
0
        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <created>10/21/2018</created>
        public void ConfigureServices(IServiceCollection services)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(ContentRootPath)
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            var configuration = builder.Build();

            services.AddSingleton(configuration);

            // add your state bot to your app
            services.AddBot <DialogBot>(options =>
            {
                options.CredentialProvider = new ConfigurationCredentialProvider(configuration);

                // The Memory Storage used here is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.
                IStorage dataStore = new MemoryStorage();

                // Create Conversation State object.
                // The Conversation State object is where we persist anything at the conversation-scope.
                var conversationState = new ConversationState(dataStore);

                options.State.Add(conversationState);
            });

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            // https://github.com/Microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/04.simple-prompt/
            services.AddSingleton <BotAccessors>(serviceProvider =>
            {
                var options = serviceProvider.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors");
                }

                var conversationState = options.State.OfType <ConversationState>().FirstOrDefault();
                if (conversationState == null)
                {
                    throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                // The dialogs will need a state store accessor. Creating it here once (on-demand) allows the dependency injection
                // to hand it to our IBot class that is create per-request.
                var accessors = new BotAccessors(conversationState)
                {
                    DialogStateAccessor = conversationState.CreateProperty <DialogState>(BotAccessors.DialogStateAccessorName),
                };

                return(accessors);
            });
        }
示例#10
0
        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <created>10/20/2018</created>
        public void ConfigureServices(IServiceCollection services)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(ContentRootPath)
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            var configuration = builder.Build();

            services.AddSingleton(configuration);

            // add your state bot to your app
            services.AddBot <StateBot>(options =>
            {
                options.CredentialProvider = new ConfigurationCredentialProvider(configuration);

                // The Memory Storage used here is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.
                IStorage dataStore = new MemoryStorage();

                // Create Conversation State object.
                // The Conversation State object is where we persist anything at the conversation-scope.
                var conversationState = new ConversationState(dataStore);

                options.State.Add(conversationState);
            });

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            // https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/02.echo-with-counter
            services.AddSingleton <BotAccessors>(serviceProvider =>
            {
                var options = serviceProvider.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors");
                }

                var conversationState = options.State.OfType <ConversationState>().FirstOrDefault();
                if (conversationState == null)
                {
                    throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(conversationState)
                {
                    CounterStatePropertyAccessor = conversationState.CreateProperty <CounterState>(BotAccessors.CounterStateName),
                };

                return(accessors);
            });
        }
示例#11
0
        public OneDriveDialog(string id, BotAccessors _accessors) : base(id)
        {
            //InitialDialogId = Id;
            InitialDialogId = id;
            accessors       = _accessors;
            var waterfallSteps = new WaterfallStep[]
            {
            };

            AddDialog(new WaterfallDialog(OneDriveDialogID, waterfallSteps));
            // Define the conversation flow using a waterfall model.
            AddDialog(new ChoicePrompt("servicioOffice365"));
        }
示例#12
0
        public BankingBot(BotAccessors botAccessors)
        {
            var dialogState = botAccessors.DialogStateAccessor;

            // compose dialogs
            dialogs = new DialogSet(dialogState);
            dialogs.Add(MainDialog.Instance);
            dialogs.Add(Yillikizin.Instance);
            dialogs.Add(new ChoicePrompt("choicePrompt"));
            dialogs.Add(new TextPrompt("textPrompt"));
            //dialogs.Add(new TextPrompt("textPrompt"));
            dialogs.Add(new NumberPrompt <int>("numberPrompt"));
            BotAccessors = botAccessors;
        }
示例#13
0
        public Bot(BotServices services, BotAccessors accessors)
            : base(accessors, nameof(RootDialog))
        {
            var recognizer = services.Recognizers[TraktBotNLP.ModelName];
            var traktTv    = services.TraktTv;
            var telemetry  = services.Telemetry;

            dialogs.Add(new RootDialog(recognizer, traktTv, telemetry));
            dialogs.Add(new ConfirmationDialog(recognizer, telemetry));
            dialogs.Add(new ChooseShowDialog(recognizer, traktTv, telemetry));
            dialogs.Add(new ChooseSeasonDialog(recognizer, telemetry));
            dialogs.Add(new ChooseEpisodeDialog(recognizer, telemetry));
            dialogs.Add(new TraktTvLoginPrompt());
        }
示例#14
0
 public RootDialog(BotAccessors accessors)
     : base(nameof(RootDialog))
 {
     _accessors = accessors;
     AddDialog(new WaterfallDialog("choiceswaterfall", new WaterfallStep[]
     {
         PromptForOptions,
         ShowOptionDialog
     }));
     AddDialog(new InstallAppDialog(_accessors));
     AddDialog(new LocalAdminDialog());
     AddDialog(new ResetPasswordDialog());
     AddDialog(new ChoicePrompt("options", ValidateChoiceAsync));
 }
示例#15
0
        public async void SendTextInsteadImageTest()
        {
            var storage = new MemoryStorage();

            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState, new Dictionary <string, LuisRecognizer>(), new Dictionary <string, QnAMaker>())
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                DetectedFaceIdPreference  = conversationState.CreateProperty <string>("DetectedFaceIdPreference"),
                ImageUriPreference        = conversationState.CreateProperty <string>("ImageUriPreference"),
                HashPreference            = conversationState.CreateProperty <string>("HashPreference"),
                IsNewPreference           = conversationState.CreateProperty <bool>("IsNewPreference"),
                FullnamePreference        = userState.CreateProperty <string>("FullnamePreference"),
                NamePreference            = userState.CreateProperty <string>("NamePreference"),
                LastnamePreference        = userState.CreateProperty <string>("LastnamePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new AskForFaceImageDialog(accessors));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(AskForFaceImageDialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("Let's go to identify you, send me a picture of you")
            .Send("hello")
            .AssertReply("Sorry, but I'm expecting an attachment image file, try again with other picture")
            .StartTestAsync();
        }
示例#16
0
        public BankingBot(BotAccessors botAccessors)
        {
            var dialogState = botAccessors.DialogStateAccessor;

            // compose dialogs
            dialogs = new DialogSet(dialogState);
            dialogs.Add(MainDialog.Instance);
            dialogs.Add(MakePaymentDialog.Instance);
            dialogs.Add(CheckBalanceDialog.Instance);
            dialogs.Add(CheckCurrentAccountBalanceDialog.Instance);
            dialogs.Add(CheckSavingsAccountBalanceDialog.Instance);
            dialogs.Add(new ChoicePrompt("choicePrompt"));
            dialogs.Add(new TextPrompt("textPrompt"));
            dialogs.Add(new NumberPrompt <int>("numberPrompt"));
            BotAccessors = botAccessors;
        }
示例#17
0
        public Office365Dialog(string id, BotAccessors _accessors) : base(id)
        {
            //InitialDialogId = Id;
            InitialDialogId = id;
            accessors       = _accessors;
            var waterfallSteps = new WaterfallStep[]
            {
                ConsultarTecnologiaAsync,
                DerivarTecnologiaAsync
            };

            AddDialog(new WaterfallDialog(Office365DialogID, waterfallSteps));
            AddDialog(new PowerAppsDialog(PowerAppsDialogID, _accessors));
            // Define the conversation flow using a waterfall model.
            AddDialog(new ChoicePrompt("servicioOffice365"));
        }
示例#18
0
        public static async Task directAnswer(string lastEvent, BotAccessors accessors, string score, WaterfallStepContext step, CancellationToken cancellationToken = default(CancellationToken))
        {
            var recognizerResult = await accessors.LuisServices[Settings.LuisName01].RecognizeAsync(step.Context, cancellationToken);
            var topIntent        = recognizerResult?.GetTopScoringIntent();

            string LastSearch = step.Context.Activity.Text;

            if (lastEvent.ToString().ToLower() != "postback")
            {
                await accessors.LastSearchPreference.SetAsync(step.Context, LastSearch);

                await accessors.UserState.SaveChangesAsync(step.Context, false, cancellationToken);
            }
            step.Context.Activity.Text = score;
            var response = await accessors.QnAServices[Settings.QnAName01].GetAnswersAsync(step.Context);

            if (response != null && response.Length > 0)
            {
                string responseType = "text";

                if (!string.IsNullOrEmpty(responseType))
                {
                    string LastAnswer = response[0].Answer;
                    if (lastEvent.ToString().ToLower() != "postback")
                    {
                        await accessors.LastAnswerPreference.SetAsync(step.Context, LastAnswer);

                        await accessors.UserState.SaveChangesAsync(step.Context, false, cancellationToken);
                    }
                    //if (true)
                    //{

                    //}
                    TrackEvents.TrackConversation(LastSearch, LastAnswer, "Direct Answer", topIntent.Value.score.ToString(), topIntent.Value.intent, from: step.Context.Activity.From);
                    await step.Context.SendCustomResponseAsync(response[0].Answer, responseType);

                    await step.BeginDialogAsync(FeedbackDialog.dialogId, null, cancellationToken);
                }
            }
            else
            {
                var message = QNABotSettings.sorrynextrelease;
                await step.Context.SendCustomResponseAsync(message);
            }
        }
示例#19
0
    public void ConfigureServices(IServiceCollection services)
    {
        // Set up the service configuration
        var builder = new ConfigurationBuilder()
                      .SetBasePath(ContentRootPath)
                      .AddJsonFile("appsettings.json")
                      .AddEnvironmentVariables();

        var configuration = builder.Build();

        services.AddSingleton(configuration);

        // Add your SimpleBot to your application
        services.AddBot <StateBot>(options =>
        {
            IStorage storage = new MemoryStorage();

            var conversationState = new ConversationState(storage);
            var userState         = new UserState(storage);

            options.CredentialProvider = new ConfigurationCredentialProvider(configuration);

            options.State.Add(conversationState);
            options.State.Add(userState);
        });

        services.AddSingleton <BotAccessors>(serviceProvider =>
        {
            var options           = serviceProvider.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
            var conversationState = options.State.OfType <ConversationState>().FirstOrDefault();

            var accessors = new BotAccessors(conversationState)
            {
                DemoStateAccessor = conversationState.CreateProperty <DemoState>(BotAccessors.DemoStateName),
            };

            // var userState = options.State.OfType<UserState>().FirstOrDefault();

            return(accessors);
        });
    }
示例#20
0
        public PowerAppsDialog(string id, BotAccessors _accessors) : base(id)
        {
            //InitialDialogId = Id;
            InitialDialogId = id;
            accessors       = _accessors;
            var waterfallSteps = new WaterfallStep[]
            {
                PreguntaBasicaStepAsync,
                ConfirmacionStepAsync,
                FinalStepAsync
            };

            AddDialog(new WaterfallDialog(PowerAppsDialogID, waterfallSteps));
            // Define the conversation flow using a waterfall model.
            AddDialog(new ChoicePrompt("PreguntaBasica"));
            ConfirmPrompt asd = new ConfirmPrompt("confirm");

            asd.ConfirmChoices = new Tuple <Choice, Choice>(new Choice("Sí 😄"), new Choice("No 😞"));
            AddDialog(asd);
            //AddDialog(new ChoicePrompt("PreguntaBasica"));
        }
        public BummblebeeBot(BotAccessors botAccessors, IConfiguracionGlobal configuracionGlobal)
        {
            var dialogState = botAccessors.DialogStateAccessor;

            _configuracionGlobal = configuracionGlobal ?? throw new ArgumentNullException(nameof(configuracionGlobal));

            //Resolver la URI
            Uri = _configuracionGlobal.GetAbsoluteUri().ToString();

            // compose dialogs
            dialogs = new DialogSet(dialogState);
            dialogs.Add(PrincipalDialog.Instance);
            dialogs.Add(PrincipalAlternativoDialog.Instance);
            //Admision
            dialogs.Add(ExamenServicioDialog.Instance);
            dialogs.Add(InscripcionServicioDialog.Instance);
            dialogs.Add(ResultadoServicioDialog.Instance);
            dialogs.Add(AdmisionDialog.Instance);


            //Campus
            dialogs.Add(CampusPiuraDialog.Instance);
            dialogs.Add(CampusTrujilloDialog.Instance);

            //Matrícula
            dialogs.Add(MatriculaDialog.Instance);
            dialogs.Add(PagoMatriculaServiceDialog.Instance);
            dialogs.Add(InformacionMatriculaServiceDialog.Instance);
            dialogs.Add(MiMatriculaServiceDialog.Instance);

            //Preguntas
            dialogs.Add(PreguntasDialog.Instance);

            dialogs.Add(new ChoicePrompt("choicePrompt"));
            dialogs.Add(new TextPrompt("textPrompt"));
            dialogs.Add(new NumberPrompt <int>("numberPrompt"));


            BotAccessors = botAccessors;
        }
示例#22
0
        /// <summary>
        /// Register the bot framework with Asp.net.
        /// </summary>
        /// <param name="config">Represents the configuration of the HttpServer.</param>
        public static void Register(HttpConfiguration config)
        {
            BotAccessors accessors = null;

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var credentialProvider = new SimpleCredentialProvider(ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppIdKey],
                                                                  ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppPasswordKey]);

            builder.RegisterInstance(credentialProvider).As <ICredentialProvider>();

            // The Memory Storage used here is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            // Create Conversation State object.
            // The Conversation State object is where we persist anything at the conversation-scope.
            var conversationState        = new ConversationState(dataStore);
            var userState                = new UserState(dataStore);
            var privateConversationState = new PrivateConversationState(dataStore);

            // Create the custom state accessor.
            // State accessors enable other components to read and write individual properties of state.
            accessors = new BotAccessors(conversationState, privateConversationState, userState)
            {
                UserData                = userState.CreateProperty <BotDataBag>(BotAccessors.UserDataPropertyName),
                ConversationData        = conversationState.CreateProperty <BotDataBag>(BotAccessors.ConversationDataPropertyName),
                PrivateConversationData = privateConversationState.CreateProperty <BotDataBag>(BotAccessors.PrivateConversationDataPropertyName),
                DialogData              = conversationState.CreateProperty <DialogState>(nameof(DialogState))
            };

            builder.RegisterInstance(accessors).As <BotAccessors>();
            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = resolver;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="QnABot"/> class.
        /// </summary>
        /// <param name="services">A <see cref="BotServices"/> configured from the ".bot" file.</param>
        public QnAMakerActiveLearningBot(BotServices services, BotAccessors accessors)
        {
            _services = services ?? throw new ArgumentNullException(nameof(services));
            if (!_services.QnAServices.ContainsKey(QnAMakerKey))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a QnA service named '{QnAMakerKey}'.");
            }

            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            // QnA Maker dialog options
            _qnaMakerOptions = new QnAMakerOptions
            {
                Top            = 3,
                ScoreThreshold = 0.03F,
            };

            _dialogs = new DialogSet(_accessors.ConversationDialogState);

            _dialogHelper = new DialogHelper(services, QnAMakerKey);

            _dialogs.Add(_dialogHelper.QnAMakerActiveLearningDialog);
        }
示例#24
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Load external services.
            var botConfig   = Configuration.LoadBotConfiguration();
            var botServices = new BotServices(botConfig, isProduction);

            var(appId, appPassword) = botServices.AppCredentials;
            var conversationState = new ConversationState(botServices.Storage);
            var userState         = new UserState(botServices.Storage);
            var botAccessors      = new BotAccessors(userState, conversationState);
            var telemetry         = botServices.Telemetry;

            // Register the external services.
            services.AddSingleton(sp => botServices);

            // Register the bot's state and state property accessor objects.
            services.AddSingleton(sp => botAccessors);

            // Register and configure the bot.
            services.AddBot <Bot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(appId, appPassword);

                options.OnTurnError = async(context, exception) =>
                {
                    telemetry.TrackException(context.Activity, exception);
                    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
                };

                options.Middleware.Add(new RandomizeReplyMiddleware());
                options.Middleware.Add(new DebugLoggerMiddleware());
                options.Middleware.Add(new TelemetryLoggerMiddleware(telemetry));

                options.State.Add(conversationState);
                options.State.Add(userState);
            });
        }
        public async void AskForATopicSampleTest()
        {
            var storage = new MemoryStorage();

            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

            var luisServices = new Dictionary <string, LuisRecognizer>();
            var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
            var recognizer   = new LuisRecognizer(app);

            luisServices.Add(Settings.LuisName01, recognizer);

            var qnaEndpoint = new QnAMakerEndpoint()
            {
                KnowledgeBaseId = Settings.QnAKbId01,
                EndpointKey     = Settings.QnAEndpointKey01,
                Host            = Settings.QnAHostname01,
            };

            var qnaOptions = new QnAMakerOptions
            {
                ScoreThreshold = 0.3F
            };

            var qnaServices = new Dictionary <string, QnAMaker>();
            var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);

            qnaServices.Add(Settings.QnAName01, qnaMaker);

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState, luisServices, qnaServices)
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                DetectedFaceIdPreference  = conversationState.CreateProperty <string>("DetectedFaceIdPreference"),
                ImageUriPreference        = conversationState.CreateProperty <string>("ImageUriPreference"),
                HashPreference            = conversationState.CreateProperty <string>("HashPreference"),
                IsNewPreference           = conversationState.CreateProperty <bool>("IsNewPreference"),
                FullnamePreference        = userState.CreateProperty <string>("FullnamePreference"),
                NamePreference            = userState.CreateProperty <string>("NamePreference"),
                LastnamePreference        = userState.CreateProperty <string>("LastnamePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            List <MediaUrl> mediaList = new List <MediaUrl>();

            mediaList.Add(new MediaUrl("https://www.youtube.com/watch?v=CmTSY9oO3dw"));

            VideoCard videoCard = new VideoCard
            {
                Title     = "Interview Sample",
                Text      = "Each interview takes on a life of its own, but there are certain standard questions that arise. By reviewing them in advance, you can arrive confident and ready to articulate your skills and qualifications. Take a look at the sample questions here, and then bolster them with those specific to your goals and the organization. Both your answers to the interviewer's questions and those you post to them can provide a mechanism by which to communicate your qualifications.",
                Autostart = false,
                Media     = mediaList
            };

            Activity activity = new Activity
            {
                Type        = ActivityTypes.Message,
                Attachments = new List <Attachment> {
                    videoCard.ToAttachment()
                }
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new LuisQnADialog(accessors));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(LuisQnADialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("What topic would you like to know more about?")
            .Send("i would like to see a sample about the considerations for a human resources interview")
            .AssertReply((ac) =>
            {
                if (ac.AsMessageActivity().Attachments != null)
                {
                    var contentType = ac.AsMessageActivity().Attachments[0].ContentType;
                    Assert.Equal("application/vnd.microsoft.card.video", contentType);
                }
                else
                {
                    Assert.NotNull(ac.AsMessageActivity().Attachments);
                }
            })
            .StartTestAsync();
        }
示例#26
0
 public ModeratedContentSearchDialog(BotAccessors botAccessors)
 {
     _accessors = botAccessors;
 }
        public async void AskForATopicSampleTest()
        {
            var storage = new MemoryStorage();

            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

            // Adding LUIS Router accessor
            LuisRouterAccessor luisRouterAccessor = null;

            using (LuisRouterHelper luisRouterHelper = new LuisRouterHelper(Startup.EnvironmentName, Startup.ContentRootPath))
            {
                luisRouterAccessor = luisRouterHelper.BuildAccessor(userState, null);
            }

            // Adding QnAMaker Router accessor
            QnAMakerAccessor qnaMakerAccessor = null;

            using (QnAMakerHelper qnaMakerHelper = new QnAMakerHelper(Startup.EnvironmentName, Startup.ContentRootPath))
            {
                qnaMakerAccessor = qnaMakerHelper.BuildAccessor();
            }

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState)
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            List <MediaUrl> mediaList = new List <MediaUrl>();

            mediaList.Add(new MediaUrl("https://www.youtube.com/watch?v=CmTSY9oO3dw"));

            VideoCard videoCard = new VideoCard
            {
                Title     = "Interview Sample",
                Text      = "Each interview takes on a life of its own, but there are certain standard questions that arise. By reviewing them in advance, you can arrive confident and ready to articulate your skills and qualifications. Take a look at the sample questions here, and then bolster them with those specific to your goals and the organization. Both your answers to the interviewer's questions and those you post to them can provide a mechanism by which to communicate your qualifications.",
                Autostart = false,
                Media     = mediaList
            };

            Activity activity = new Activity
            {
                Type        = ActivityTypes.Message,
                Attachments = new List <Attachment> {
                    videoCard.ToAttachment()
                }
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new LuisQnADialog(accessors, luisRouterAccessor, qnaMakerAccessor));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(LuisQnADialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("What topic would you like to know more about?")
            .Send("i would like to see a sample about the considerations for a human resources interview")
            .AssertReply((ac) =>
            {
                if (ac.AsMessageActivity().Attachments != null)
                {
                    var contentType = ac.AsMessageActivity().Attachments[0].ContentType;
                    Assert.Equal("application/vnd.microsoft.card.video", contentType);
                }
                else
                {
                    Assert.NotNull(ac.AsMessageActivity().Attachments);
                }
            })
            .StartTestAsync();
        }
 public InstallAppDialog(BotAccessors accessors)
     : base(nameof(InstallAppDialog))
 {
     _accessors = accessors;
 }
 public BotSample(ITranslateHandler translateHandler, IDialogFactory dialogFactory, ILuisRecognizer recognizer, ITextConverter textConverter, BotAccessors botAccessors) :
     base(translateHandler, null, dialogFactory, recognizer, textConverter)
 {
     Dialogs = dialogFactory.UseDialogAccessor(botAccessors.DialogStateAccessor)
               .Create <StockDialog>()
               .Create <TextPrompt>("prompt")
               .Build();
 }
示例#30
0
 public MainDialog(BotAccessors botAccessors)
 {
     _accessors = botAccessors;
 }