예제 #1
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            if (message.Text.Equals("確認"))
            {
                await context.PostAsync("將進行修改 [ AD ] 密碼");

                context.Done($"");
            }
            else if (message.Text.Equals("回上一步驟"))
            {
                context.Done($"goback");
            }
            //else if (message.Text.Equals("不知道"))
            //{
            //    await context.PostAsync("密碼登入相關頁面如下");
            //    context.Done(context);
            //}
            else if (RootDialog.GetBack2home()) //回首頁
            {
                context.Done("");
            }
            else
            {
                await context.PostAsync("請選擇表單中選項");
            }
        }
예제 #2
0
        /// <summary>
        ///     POST: api/Messages
        ///     Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            new Thread(() =>
            {
                if (activity.ChannelId == ChannelIds.Facebook)
                {
                    Thread.CurrentThread.IsBackground = true;
                    FacebookClient fbClient           = new FacebookClient();
                    fbClient.SendTyping(activity.From.Id);
                }
            }).Start();

            if (activity.Type == ActivityTypes.Message)
            {
                //Reset conversation on facebook start
                //if(activity.Text == "STARTED_CON")
                //    activity.GetStateClient().BotState.DeleteStateForUser(activity.ChannelId, activity.From.Id);

                await Conversation.SendAsync(activity, () => RootDialog.StartWithHelloChain());
            }
            else
            {
                await HandleSystemMessage(activity);
            }

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

            return(response);
        }
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            if (result != null && TextCheck(message.Text))
            {
                ProdSearch_KeywordDialog.setKeyword(message.Text);
                context.Done(context);
            }
            else if (RootDialog.GetBack2home()) //回首頁
            {
                context.Done(context);
            }
            else
            {
                await context.PostAsync("無法辨識指令,請再次選擇您要的種類...");

                //呼叫ThumbnailCard
                var reply = context.MakeMessage();
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments      = GetMenu();
                await context.PostAsync(reply);

                context.Wait(MessageReceivedAsync);
            }

            // TODO: Put logic for handling user message here
        }
예제 #4
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            if (message.Text.Equals("確認 (AD)"))
            {
                PwdSetting.Dialogs.PwdResetDialog.setpwd("AD");
                await context.PostAsync("這是 [ AD ] 密碼,將為您進行修改 ");

                context.Done($"");
            }
            else if (message.Text.Equals("確認 (內網)"))
            {
                PwdSetting.Dialogs.PwdResetDialog.setpwd("內網");
                await context.PostAsync("這是 [ 內 網 ] 密碼,將為您進行修改 ");

                context.Done($"");
            }
            else if (RootDialog.GetBack2home()) //回首頁
            {
                context.Done(context);
            }
            else
            {
                var reply = context.MakeMessage();
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments      = GetCardsAttachmentsInweb();
                await context.PostAsync(reply);

                await context.PostAsync("以上有您要修改密碼之頁面嗎 ? (如有請選擇確認鍵)");
            }
        }
예제 #5
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            if (message != null && (message.Text.Equals("險種分類") || message.Text.Equals("關鍵字")))
            {
                ProdSearch_Selc = message.Text;
                context.Done(context);
            }
            else if (RootDialog.GetBack2home()) //回首頁
            {
                context.Done(context);
            }
            else
            {
                await context.PostAsync("無法辨識指令,請再次選擇您要進行的搜尋方式...");

                var reply = context.MakeMessage();
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments      = GetMenu();
                await context.PostAsync(reply);

                context.Wait(MessageReceivedAsync);
            }

            // TODO: Put logic for handling user message here
        }
예제 #6
0
        public async Task ShouldReturnNoAppointmentToday()
        {
            Initialize();
            // Replace Dialog class to your own class
            IDialog <object> rootDialog = new RootDialog();
            var d365Mock = new Mock <ID365Service>();

            d365Mock.Setup(m => m.GetAppointmentsForToday()).Returns(Task.FromResult(new List <Appointment>()));

            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterInstance(d365Mock.Object).As <ID365Service>();
            WebApiApplication.Container = builder.Build();

            var toBot = DialogTestBase.MakeTestMessage();

            toBot.From.Id = Guid.NewGuid().ToString();
            toBot.Text    = Resource.Menu_Appointment_For_Today;
            Func <IDialog <object> > MakeRoot = () => rootDialog;

            using (new FiberTestBase.ResolveMoqAssembly(rootDialog))
                using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, rootDialog))
                {
                    // act: sending the message
                    IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot);

                    // assert: check if the dialog returned the right response
                    Assert.IsTrue(toUser.Text.Equals(Resource.No_Appointment_Today));
                }
        }
예제 #7
0
        public async Task TestHello()
        {
            // Instantiate dialog to test
            IDialog <object> rootDialog = new RootDialog();

            // Create in-memory bot environment
            Func <IDialog <object> > MakeRoot = () => rootDialog;

            using (new FiberTestBase.ResolveMoqAssembly(rootDialog))
                using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, rootDialog))
                {
                    // Create a message to send to bot
                    var toBot = DialogTestBase.MakeTestMessage();
                    toBot.From.Id = Guid.NewGuid().ToString();

                    // Act
                    toBot.Text = "hello";
                    IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    Assert.AreEqual("請輸入你的名字", toUser.Text);

                    // Act
                    toBot.Text = "Puck";
                    toUser     = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    Assert.AreEqual("設定名稱為 Puck", toUser.Text);
                }
        }
예제 #8
0
        public IActionResult Callback([FromBody] Updates updates)
        {
            // TODO
            // реализовать проверку security-key

            // Тип события
            switch (updates.Type)
            {
            // Ключ-подтверждение
            case "confirmation":

                //return new OkObjectResult(_configuration["Config:Confirmation"]);
                return(new OkObjectResult("dcf06e03"));

            // Новое сообщение
            case "message_new":

                var api = new VkApi();

                api.Authorize(new ApiAuthParams()
                {
                    AccessToken = MyAppToken
                });

                var dialog = new RootDialog(JsonConvert.DeserializeObject <Message>(updates.Object.ToString()));

                api.Messages.Send(dialog.Response());

                return(new OkObjectResult("ok"));

                //// Десериализация
                //var msg = JsonConvert.DeserializeObject<Message>(updates.Object.ToString());

                //var api = new VkApi();

                //api.Authorize(new ApiAuthParams() { AccessToken = MyAppToken });


                ////var keyboard = new KeyboardBuilder(/*"text", false*/).AddButton("Расписание", "расписание", KeyboardButtonColor.Positive);
                ////keyboard.AddButton("Расписание", "расписание", KeyboardButtonColor.Negative);
                ////keyboard.AddLine();
                ////keyboard.AddButton("Расписание", "расписание", KeyboardButtonColor.Primary);
                ////keyboard.AddButton("Расписание", "расписание");

                //api.Messages.Send(new MessagesSendParams()
                //{
                //    PeerId = -(long)(MyGroupId),
                //    ChatId = msg.ChatId,
                //    UserId = msg.FromId,
                //    //StickerId = a.Message.
                //    Message = msg.Text,
                //    RandomId = (int)msg.Id + 1,
                //    //StickerId = msg.
                //    //Keyboard = keyboard.Build()
                //});
            }

            return(new OkObjectResult("ok"));
        }
예제 #9
0
        public async Task TestCards()
        {
            // Instantiate dialog to test
            IDialog <object> rootDialog = new RootDialog();

            // Create in-memory bot environment
            Func <IDialog <object> > MakeRoot = () => rootDialog;

            using (new FiberTestBase.ResolveMoqAssembly(rootDialog))
                using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, rootDialog))
                {
                    // Create a message to send to bot
                    var toBot = DialogTestBase.MakeTestMessage();
                    toBot.From.Id = Guid.NewGuid().ToString();

                    // Act
                    toBot.Text = "cards";
                    IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    HeroCard heroCard = (HeroCard)toUser.Attachments[0].Content;
                    Assert.AreEqual("請選擇卡片類型?", heroCard.Text);
                    Assert.AreEqual("HeroCard", heroCard.Buttons[0].Value);
                    Assert.AreEqual("ReceiptCard", heroCard.Buttons[1].Value);
                    Assert.AreEqual("ThumbnailCard", heroCard.Buttons[2].Value);
                    Assert.AreEqual("SigninCard", heroCard.Buttons[3].Value);
                    Assert.AreEqual("AnimationCard", heroCard.Buttons[4].Value);
                    Assert.AreEqual("AudioCard", heroCard.Buttons[5].Value);
                    Assert.AreEqual("VideoCard", heroCard.Buttons[6].Value);

                    // Act
                    toBot.Text = "HeroCard";
                    toUser     = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    HeroCard heroCard2 = (HeroCard)toUser.Attachments[0].Content;
                    Assert.AreEqual("請選擇排版類型?", heroCard2.Text);
                    Assert.AreEqual("single", heroCard2.Buttons[0].Value);
                    Assert.AreEqual("list", heroCard2.Buttons[1].Value);
                    Assert.AreEqual("carousel", heroCard2.Buttons[2].Value);

                    // Act
                    toBot.Text = "carousel";
                    toUser     = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    HeroCard heroCard3 = (HeroCard)toUser.Attachments[0].Content;
                    Assert.AreEqual("carousel", toUser.AttachmentLayout);
                    Assert.AreEqual("Splatoon 2", heroCard3.Title);
                    Assert.AreEqual("Happy New Year.  by Puck", heroCard3.Text);
                    Assert.AreEqual(1, heroCard3.Images.Count);
                    Assert.AreEqual("https://imgur.com/hwylGzp.jpg", heroCard3.Images[0].Url);
                    Assert.AreEqual("https://imgur.com/hwylGzp.jpg", heroCard3.Buttons[0].Value);
                    Assert.AreEqual(1, heroCard3.Buttons.Count);
                    Assert.AreEqual("Open", heroCard3.Buttons[0].Title);
                    Assert.AreEqual(ActionTypes.OpenUrl, heroCard3.Buttons[0].Type);
                }
        }
예제 #10
0
        public async Task Prueba_deberia_devolver_respuestaAsync()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                var waitCalled      = false;
                var message         = string.Empty;
                var postAsyncCalled = false;

                var target = new RootDialog();

                var activity = new Activity(ActivityTypes.Message)
                {
                    Text = "Hello World"
                };

                var awaiter = new Microsoft.Bot.Builder.Internals.Fibers.Fakes.StubIAwaiter <IMessageActivity>()
                {
                    IsCompletedGet = () => true,
                    GetResult      = () => activity
                };

                var awaitable = new Microsoft.Bot.Builder.Dialogs.Fakes.StubIAwaitable <IMessageActivity>()
                {
                    GetAwaiter = () => awaiter
                };

                var context = new Microsoft.Bot.Builder.Dialogs.Fakes.StubIDialogContext();

                Microsoft.Bot.Builder.Dialogs.Fakes.ShimExtensions.PostAsyncIBotToUserStringStringCancellationToken = (user, s1, s2, token) =>
                {
                    message         = s1;
                    postAsyncCalled = true;
                    return(Task.CompletedTask);
                };

                Microsoft.Bot.Builder.Dialogs.Fakes.ShimExtensions.WaitIDialogStackResumeAfterOfIMessageActivity = (stack, callback) =>
                {
                    if (waitCalled)
                    {
                        return;
                    }

                    waitCalled = true;

                    // The callback is what is being tested.
                    callback(context, awaitable);
                };

                // Act
                await target.StartAsync(context);

                // Assert
                Assert.AreEqual("You sent Hello World which was 11 characters", message, "Message is wrong");
                Assert.IsTrue(postAsyncCalled, "PostAsync was not called");
            }
        }
예제 #11
0
        public async Task Bot_Test_Attachments()
        {
            foreach (var item in RootDialog.dataAtt)
            {
                var preg = item.Key;
                var att  = item.Value;

                using (ShimsContext.Create())
                {
                    var waitCalled           = false;
                    IMessageActivity message = null;

                    var target = new RootDialog();

                    var activity = new Activity(ActivityTypes.Message)
                    {
                        Text         = preg,
                        From         = new ChannelAccount("id", "name"),
                        Recipient    = new ChannelAccount("recipid", "recipname"),
                        Conversation = new ConversationAccount(false, "id", "name")
                    };

                    var awaiter = new Microsoft.Bot.Builder.Internals.Fibers.Fakes.StubIAwaiter <IMessageActivity>()
                    {
                        IsCompletedGet = () => true,
                        GetResult      = () => activity
                    };

                    var awaitable = new Microsoft.Bot.Builder.Dialogs.Fakes.StubIAwaitable <IMessageActivity>()
                    {
                        GetAwaiter = () => awaiter
                    };

                    var context = new Microsoft.Bot.Builder.Dialogs.Fakes.StubIDialogContext();

                    context.PostAsyncIMessageActivityCancellationToken = (messageActivity, token) => {
                        message = messageActivity;
                        return(Task.CompletedTask);
                    };

                    Microsoft.Bot.Builder.Dialogs.Fakes.ShimExtensions.WaitIDialogStackResumeAfterOfIMessageActivity = (stack, callback) =>
                    {
                        if (waitCalled)
                        {
                            return;
                        }
                        waitCalled = true;
                        callback(context, awaitable);
                    };
                    await target.MessageReceivedWithTextAsync(context, awaitable);


                    Assert.AreEqual(att, message.Attachments[0]);
                }
            }
        }
        private async Task <HttpResponseMessage> HandleO365ConnectorCardActionQuery(Activity activity)
        {
            var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));

            var userInfo = UserInfoRepository.GetUserInfo(activity.From.Id);

            // Validate for Sing In
            if (userInfo == null || userInfo.ExpiryTime < DateTime.Now)
            {
                var        reply  = activity.CreateReply();
                SigninCard plCard = RootDialog.GetSignInCard();
                reply.Attachments.Add(plCard.ToAttachment());
                await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(reply);

                return(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
            }

            var email  = string.Empty;
            var member = connectorClient.Conversations.GetConversationMembersAsync(activity.Conversation.Id).Result.AsTeamsChannelAccounts().FirstOrDefault();

            if (member != null)
            {
                email = member.Email;
            }


            // Get O365 connector card query data.
            Task <Task> task = new Task <Task>(async() =>
            {
                O365ConnectorCardActionQuery o365CardQuery = activity.GetO365ConnectorCardActionQueryData();
                Activity replyActivity = activity.CreateReply();
                switch (o365CardQuery.ActionId)
                {
                case "Custom":
                    // Get Passenger List & Name
                    var teamDetails = Newtonsoft.Json.JsonConvert.DeserializeObject <CustomTeamData>(o365CardQuery.Body);
                    await CreateTeam(connectorClient, activity, userInfo, teamDetails.TeamName, teamDetails.Members.Split(';').ToList());
                    break;

                case "Flight":
                    var flightDetails = Newtonsoft.Json.JsonConvert.DeserializeObject <O365BodyValue>(o365CardQuery.Body);


                    await CreateTeam(connectorClient, activity, userInfo, "Flight-" + flightDetails.Value, GetMemberList(email));
                    // await AttachClassWisePassengerList(classInfo.Value, replyActivity, $"Passengers with {classInfo.Value} tickets");
                    break;

                default:
                    break;
                }
            });

            task.Start();

            return(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
        }
        public async Task ShouldReturnEvents()
        {
            // Instantiate ShimsContext to use Fakes
            using (ShimsContext.Create())
            {
                // Return "dummyToken" when calling GetAccessToken method
                AuthBot.Fakes.ShimContextExtensions.GetAccessTokenIBotContextString =
                    async(a, e) => { return("dummyToken"); };

                var mockEventService = new Mock <IEventService>();
                mockEventService.Setup(x => x.GetEvents()).ReturnsAsync(new List <Event>()
                {
                    new Event
                    {
                        Subject = "dummy event",
                        Start   = new DateTimeTimeZone()
                        {
                            DateTime = "2017-05-31 12:00",
                            TimeZone = "Standard Tokyo Time"
                        },
                        End = new DateTimeTimeZone()
                        {
                            DateTime = "2017-05-31 13:00",
                            TimeZone = "Standard Tokyo Time"
                        }
                    }
                });
                var builder = new ContainerBuilder();
                builder.RegisterInstance(mockEventService.Object).As <IEventService>();
                WebApiApplication.Container = builder.Build();

                // Instantiate dialog to test
                IDialog <object> rootDialog = new RootDialog();

                // Create in-memory bot environment
                Func <IDialog <object> > MakeRoot = () => rootDialog;
                using (new FiberTestBase.ResolveMoqAssembly(rootDialog))
                    using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, rootDialog))
                    {
                        // Register global message handler
                        RegisterBotModules(container);

                        // Create a message to send to bot
                        var toBot = DialogTestBase.MakeTestMessage();
                        toBot.From.Id = Guid.NewGuid().ToString();
                        toBot.Text    = "get events";

                        // Send message and check the answer.
                        IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot);

                        // Verify the result
                        Assert.IsTrue(toUser.Text.Equals("2017-05-31 12:00-2017-05-31 13:00: dummy event"));
                    }
            }
        }
예제 #14
0
        protected async override Task PostAsync(Activity item, string state, CancellationToken token)
        {
            var message = item as IMessageActivity;

            if (message != null)
            {
                var root = new RootDialog();

                await task.PollAsync(CancellationToken.None);
            }
        }
예제 #15
0
        public async Task ShouldReturnProducts()
        {
            Initialize();
            // Replace Dialog class to your own class
            IDialog <object> rootDialog = new RootDialog();
            var d365Mock = new Mock <ID365Service>();

            d365Mock.Setup(m => m.GetProducts("dummy query")).Returns(
                Task.FromResult(
                    new List <Product>()
            {
                new Product()
                {
                    Name        = "Dummy Product",
                    Description = "Dummy Desc"
                }
            }));

            var azureBlobMock = new Mock <IAzureBlobService>();

            azureBlobMock.Setup(m => m.Upload("", "")).Returns("");

            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterInstance(d365Mock.Object).As <ID365Service>();
            builder.RegisterInstance(azureBlobMock.Object).As <IAzureBlobService>();
            WebApiApplication.Container = builder.Build();

            var toBot = DialogTestBase.MakeTestMessage();

            toBot.From.Id = Guid.NewGuid().ToString();
            toBot.Text    = Resource.Menu_SearchProduct;
            Func <IDialog <object> > MakeRoot = () => rootDialog;

            using (new FiberTestBase.ResolveMoqAssembly(rootDialog))
                using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, rootDialog))
                {
                    // act: sending the message
                    IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot);

                    Assert.IsTrue(toUser.Text.Equals(Resource.Enter_ProductName));

                    toBot.Text = "dummy query";

                    toUser = await GetResponse(container, MakeRoot, toBot);

                    ThumbnailCard card = (ThumbnailCard)toUser.Attachments.First().Content;
                    // assert: check if the dialog returned the right response
                    Assert.IsTrue(card.Title.Equals("Dummy Product"));
                    Assert.IsTrue(card.Buttons.First().Title.Equals(Resource.Detail));
                }
        }
        /// <summary>
        /// Handle an invoke activity.
        /// </summary>
        private async Task <HttpResponseMessage> HandleInvokeActivity(Activity activity)
        {
            var activityValue = activity.Value.ToString();

            switch (activity.Name)
            {
            case "signin/verifyState":
                await Conversation.SendAsync(activity, () => new RootDialog());

                break;

            case "composeExtension/query":
                // Handle fetching task module content
                using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    var channelData = activity.GetChannelData <TeamsChannelData>();
                    var tid         = channelData.Tenant.Id;

                    string emailId = await RootDialog.GetUserEmailId(activity);

                    if (emailId == null)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                    var response = await MessageExtension.HandleMessageExtensionQuery(connector, activity, tid, emailId);

                    return(response != null
                            ? Request.CreateResponse(response)
                            : new HttpResponseMessage(HttpStatusCode.OK));
                }

            case "task/fetch":
                // Handle fetching task module content
                return(await HandleTaskModuleFetchRequest(activity, activityValue));

            case "task/submit":
                // Handle submission of task module info
                // Run this on a task so that
                new Task(async() =>
                {
                    var action    = JsonConvert.DeserializeObject <TaskModule.BotFrameworkCardValue <ActionDetails> >(activityValue);
                    activity.Name = action.Data.ActionType;
                    await Conversation.SendAsync(activity, () => new RootDialog());
                }).Start();

                await Task.Delay(TimeSpan.FromSeconds(2));    // Give it some time to start showing output.

                break;
            }
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var activity = await result;

            if (result != null)
            {
                setnonLuisKeyword(activity.Text);
                context.Done(context);
            }
            else if (RootDialog.GetBack2home()) //回首頁
            {
                context.Done(context);
            }
        }
예제 #18
0
        public async Task TestOperation()
        {
            // Instantiate dialog to test
            IDialog <object> rootDialog = new RootDialog();

            // Create in-memory bot environment
            Func <IDialog <object> > MakeRoot = () => rootDialog;

            using (new FiberTestBase.ResolveMoqAssembly(rootDialog))
                using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, rootDialog))
                {
                    // Create a message to send to bot
                    var toBot = DialogTestBase.MakeTestMessage();
                    toBot.From.Id = Guid.NewGuid().ToString();

                    // Act
                    toBot.Text = "operation";
                    IMessageActivity toUser = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    Assert.AreEqual("請輸入第一個數字: ", toUser.Text);

                    // Act
                    toBot.Text = "123";
                    toUser     = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    HeroCard heroCard = (HeroCard)toUser.Attachments[0].Content;
                    Assert.AreEqual("請輸入運算子: ", heroCard.Text);
                    Assert.AreEqual("Add", heroCard.Buttons[0].Value);
                    Assert.AreEqual("Sub", heroCard.Buttons[1].Value);
                    Assert.AreEqual("Mul", heroCard.Buttons[2].Value);
                    Assert.AreEqual("Div", heroCard.Buttons[3].Value);

                    // Act
                    toBot.Text = "Add";
                    toUser     = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    Assert.AreEqual("請輸入第二個數字: ", toUser.Text);

                    // Act
                    toBot.Text = "456";
                    toUser     = await GetResponse(container, MakeRoot, toBot);

                    // Assert
                    Assert.AreEqual("123 + 456 = 579", toUser.Text);
                }
        }
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            // check if activity is of type message
            if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
            {
                await Conversation.SendAsync(activity, () => new RootDialog());
            }
            else if (activity.IsO365ConnectorCardActionQuery())
            {
                // this will handle the request coming any action on Actionable messages
                return(await HandleO365ConnectorCardActionQuery(activity));
            }
            else if (activity != null && activity.GetActivityType() == ActivityTypes.Invoke && activity.Name == "signin/verifyState")
            {
                var stateInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <SateValue>(activity.Value.ToString());

                // var userInfo =
                // userData.SetProperty<string>("AccessToken", activity.Value.ToString());
                UserInfoRepository.AddUserInfo(new UserInfo()
                {
                    userId = activity.From.Id, accessToken = stateInfo.state, ExpiryTime = DateTime.Now.AddSeconds(3450)
                });                                                                                                                                                      //3450

                var reply = activity.CreateReply();
                reply.Text = "You are successfully signed in. Now, you can use the 'create team' command.";


                // Get Email Id.
                var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));
                var email           = string.Empty;
                var member          = connectorClient.Conversations.GetConversationMembersAsync(activity.Conversation.Id).Result.AsTeamsChannelAccounts().FirstOrDefault();
                if (member != null)
                {
                    email = member.Email;
                }


                var card = RootDialog.GetFilter(email);
                reply.Attachments.Add(card);


                await connectorClient.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
        protected override async Task PostAsync(IActivity item, string state, CancellationToken token)
        {
            var message = item as IMessageActivity;

            if (message != null)
            {
                this.stack.Reset();

                var rootDialog = new RootDialog();

                await this.stack.Forward(rootDialog, null, message, CancellationToken.None);

                await this.task.PollAsync(CancellationToken.None);
            }
        }
예제 #21
0
        public Program()
        {
            var regDlg = new RegistrationDialog(this);
            var fbDlg = new FeedbackDialog(this);
            var tüDlg = new TrainingsübersichtDialog(this);
            var trDlg = new TrainingDialog(this);
            var rDlg = new RootDialog(this);

            regDlg.OnShowRequest += regDlg.Show;
            regDlg.OnRegistrationRequest += (tid, name, email) => {
                if (name == "x")
                    regDlg.Retry("someMatchcode", name, email, string.Format("Received: {0}, {1}, {2}", tid, name, email));
                else
                    regDlg.Ack("someMatchcode", name, email);
            };

            fbDlg.OnShowRequest += fbDlg.Show;
            fbDlg.OnFeedbackRequest += (tmatchcode, email, score, suggestions) =>
            {
                if (email == "x")
                    fbDlg.Retry(tmatchcode, email, score, suggestions, string.Format("Received: {0}, {1}, {2}, {3}", tmatchcode, email, score, suggestions));
                else
                    fbDlg.Ack(tmatchcode);
            };

            tüDlg.OnShowRequest += trainerMatchcode => tüDlg.Show(trainerMatchcode,
                new[] { new Tuple<string, string>("1", "training1"), new Tuple<string, string>("2", "training2") }, 
                "");
            tüDlg.OnTrainingCreationRequest += (trainerMatchcode, newTrainingMatchcode) => tüDlg.Show(trainerMatchcode, new[] { new Tuple<string, string>("1", "training1"), new Tuple<string, string>("2", "training2"), new Tuple<string, string>("3", newTrainingMatchcode), },
                                                                                                                    newTrainingMatchcode == "x" ? "Training matchcode already existent." : "");

            trDlg.OnShowRequest += trainingId =>
                {
                    var ti = new TrainingInfo {
                        Matchcode = "someTraining",
                        Votes = new[]
                            {
                                new VoteInfo {Name = "n1", Email = "e1@", Score = 6, Suggestions = "s1"},
                                new VoteInfo {Name = "n2", Email = "e2@", Score = 7, Suggestions = "s2"},
                            },
                        AverageScore = 6.5
                    };
                    trDlg.Show(ti);
                };

            Get["/hello"] = _ => "Hello from instavote.dialogs.tests, " + DateTime.Now;
        }
예제 #22
0
        private void ExecuteMainDialog(IStatePropertyAccessor <DialogState> dlgstate)
        {
            var waterFallSteps = new WaterfallStep[]
            {
                RunMainDialog,
                EndMainDlg
            };

            _dialogSet = new DialogSet(dlgstate);
            _dialogSet.Add(new TextPrompt("text"));
            _dialogSet.Add(new NumberPrompt <int>("number"));
            _dialogSet.Add(new ChoicePrompt("choice"));
            _dialogSet.Add(new ExecuteChildDialog(nameof(UserForm), UserForm.PromptProperties()));
            _dialogSet.Add(new ExecuteChildDialog(nameof(PizzaOrder), PizzaOrder.PromptProperties()));
            _dialogSet.Add(new ExecuteChildDialog(nameof(RootDialog), RootDialog.PromptProperties()));
            _dialogSet.Add(new WaterfallDialog("main", waterFallSteps));
        }
        private async Task <Activity> 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)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels

                for (int i = 0; i < message.MembersAdded.Count; i++)
                {
                    if (message.MembersAdded[i].Id == message.Recipient.Id)
                    {
                        // Bot is added. Let's send welcome message.
                        var           connectorClient = new ConnectorClient(new Uri(message.ServiceUrl));
                        ThumbnailCard card            = RootDialog.GetHelpMessage();

                        var reply = message.CreateReply();
                        reply.TextFormat = TextFormatTypes.Xml;
                        reply.Attachments.Add(card.ToAttachment());

                        await connectorClient.Conversations.ReplyToActivityAsync(reply);

                        break;
                    }
                }
            }
            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 that the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
        protected override async Task PostAsync(IActivity item, string state, CancellationToken token)
        {
            var message = item as IMessageActivity;

            if (message != null)
            {
                //var ticketForm = new FormDialog<TokenModel>(new TokenModel(), TokenModel.BuildForm, FormOptions.PromptInStart);

                var ticketForm = new RootDialog();

                var interruption = ticketForm.Void <object, IMessageActivity>();

                task.Call(interruption, null);

                await task.PollAsync(token);
            }
        }
예제 #25
0
        private void OpenProfileWindow(Profile profile)
        {
            void ShowAction()
            {
                var win = new ProfileWindow(Context, profile);

                ProfileWindows.Add(win.ProfileGuid, win);
                win.Closed += OnProfileWindowClosed;
                win.Focus();
                win.Show();
                var restoreFocusDialogClose = RootDialog.GetType().GetField("_restoreFocusDialogClose", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

                restoreFocusDialogClose?.SetValue(RootDialog, null);
            }

            Dispatcher.BeginInvoke((Action)ShowAction);
        }
예제 #26
0
        public DialogsProvider(Config.RawData.DialogsContainer root)
        {
            Dialogs      = new List <Dialog>();
            DialogsTable = new Dictionary <string, Dialogs.Dialog>();

            // fill support buttons
            SupportButtons = new Dictionary <string, Button>();
            foreach (var btn in root.SupportButtons)
            {
                try
                {
                    var    type   = Type.GetType(btn.Type);
                    Button button = Activator.CreateInstance(type, btn) as Button;
                    SupportButtons.Add(btn.Id, button);
                }
                catch (Exception e)
                {
                    BotManager.Core?.LogController?.LogWarning(new DebugMessage($"Couldn't convert support button '{btn.Id}'", "DialogsProvider()", e));
                }
            }

            // create root dialog
            try
            {
                RootDialog = new RootDialog(root as Config.RawData.Dialog);
                RootDialog.GetEditable().SupportButtons = GetButtons(root.Buttons);

                RegistrationDialog = new RegistrationDialog(root.RegistrationDialog, null);
                RegistrationDialog.GetEditable().SupportButtons = GetButtons(root.RegistrationDialog.Buttons);

                DialogsTable.Add(RootDialog.Id, RootDialog);
                Dialogs.Add(RootDialog);
                DialogsTable.Add(RegistrationDialog.Id, RegistrationDialog);
                Dialogs.Add(RegistrationDialog);
            }
            catch (Exception e)
            {
                BotManager.Core?.LogController?.LogCritical(new DebugMessage($"Couldn't initialize root dialog!", "DialogsProvider()", e));
                throw e;
            }

            // fill other dialogs and bind supportButtons
            RootDialog.GetEditable().Dialogs         = DialogInitializer(root, RootDialog);
            RegistrationDialog.GetEditable().Dialogs = DialogInitializer(root.RegistrationDialog, RegistrationDialog);
        }
예제 #27
0
        private Activity 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)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels

                IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity;
                if (iConversationUpdated != null)
                {
                    ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl));

                    foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty <ChannelAccount>())
                    {
                        // if the bot is added, then
                        if (member.Id == iConversationUpdated.Recipient.Id)
                        {
                            RootDialog.SetBack2home(true);
                            var reply = ((Activity)iConversationUpdated).CreateReply($"您好~ 我是小光機器人");
                            connector.Conversations.ReplyToActivity(reply);
                        }
                    }
                }
            }
            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)
            {
            }

            return(null);
        }
        protected override async Task PostAsync(IActivity item, string state, CancellationToken token)
        {
            var message = item as IMessageActivity;

            // If the message is not null, the message was returned from PrepareAsync because it matched a navigation command.
            if (message != null)
            {
                // To navigate to another dialog/conversation flow, reset the dialog stack so the stack is in a pristine state.
                this.stack.Reset();

                var rootDialog = new RootDialog();

                // Forward the navigation command to the RootDialog so it can add the correct dialog to the stack to handle the change in conversation flow.
                await this.stack.Forward(rootDialog, null, message, CancellationToken.None);

                await this.task.PollAsync(CancellationToken.None);
            }
        }
        private async Task <Activity> HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.GetActivityType() == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity;
                if (iConversationUpdated != null)
                {
                    ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl));

                    foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty <ChannelAccount>())
                    {
                        if (member.Id == iConversationUpdated.Recipient.Id)
                        {
                            var cardText = await ScubaCardService.GetCardText("0-Welcome");

                            var reply = RootDialog.GetCardReply(message, cardText);
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            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)
            {
            }

            return(null);
        }
        private async Task <Activity> 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)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels

                IConversationUpdateActivity update = message;
                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    var client = scope.Resolve <IConnectorClient>();
                    if (update.MembersAdded.Any())
                    {
                        foreach (var newMember in update.MembersAdded)
                        {
                            if (newMember.Id == message.Recipient.Id)
                            {
                                await RootDialog.SendWelcomeMessage(message);
                            }
                        }
                    }
                }
            }
            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)
            {
            }

            return(null);
        }
예제 #31
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            if (1 != 1)     //此員編第一次登入
            {
            }
            else if (RootDialog.GetBack2home()) //回首頁
            {
                context.Done(context);
            }
            else
            {
                Id = message.Text;


                context.Done(context);
            }
        }