コード例 #1
0
        //    Rootobject rootobject = new Rootobject();

        /// <summary>
        /// In This Method We are going To Display Rich card For The User To Select issue category
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task StartAsync(IDialogContext context)
        {
            try
            {
                var replymessage = context.MakeMessage();
                var herocard     = new HeroCard()
                {
                    Text   = "Please Choose issue category",
                    Images = new List <CardImage> {
                        new CardImage(MessagesController.chartUrl)
                    }
                    // Buttons = new List<CardAction> { new CardAction(ActionTypes.ImBack, "Software", value: "Software Issue"), new CardAction(ActionTypes.ImBack, "Hardware", value: "HardWare Issue") }
                };
                replymessage.AttachmentLayout = AttachmentLayoutTypes.List;
                replymessage.Attachments      = new List <Microsoft.Bot.Connector.Attachment>();
                Microsoft.Bot.Connector.Attachment plAttachment = herocard.ToAttachment();
                replymessage.Attachments.Add(plAttachment);
                Logging.ConversationLogg(context.Activity.From.Name, RootDialog.ActivityValue, replymessage.ToString(), DateTime.Now, context.Activity.ChannelId);
                context.PostAsync(replymessage);
                PromptDialog.Text(context, MessageReceivedAsync, "Choose Issue");
                //context.Wait(MessageReceivedAsync);
                return(Task.CompletedTask);
            }
            catch (Exception ex)
            {
                Logging.errorloginfo(ex.Message, DateTime.Now);
                return(null);
            }
        }
コード例 #2
0
        private void RequestLogin(Microsoft.Bot.Connector.Activity message)
        {
            var resumptionCookie        = new ResumptionCookie(message);
            var encodedResumptionCookie = UrlToken.Encode <ResumptionCookie>(resumptionCookie);

            Microsoft.Bot.Connector.Activity oriMessage = resumptionCookie.GetMessage();


            var reply = oriMessage.CreateReply(Messages.BOT_PLEASE_LOGIN);

            reply.Recipient   = oriMessage.From;
            reply.Type        = Microsoft.Bot.Connector.ActivityTypes.Message;
            reply.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
            List <Microsoft.Bot.Connector.CardAction> cardButtons = new List <Microsoft.Bot.Connector.CardAction>();
            var encodedCookie = UrlToken.Encode(resumptionCookie);

            Microsoft.Bot.Connector.CardAction button = new Microsoft.Bot.Connector.CardAction()
            {
                Value = $"{ConfigurationHelper.GetString("AgentLogin_URL")}?cookie={encodedCookie}",
                Type  = "signin",
                Title = Messages.BOT_SIGNIN_BUTTON_TEXT,
                Image = "https://michistorageea.blob.core.windows.net/cdn/login.png"
            };
            cardButtons.Add(button);
            Microsoft.Bot.Connector.SigninCard plCard = new Microsoft.Bot.Connector.SigninCard(
                text: $"{Messages.BOT_PLEASE_LOGIN}",
                buttons: cardButtons);
            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
            reply.Attachments.Add(plAttachment);
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
            var             response  = connector.Conversations.SendToConversation(reply);
        }
コード例 #3
0
        private async Task LogIn(IDialogContext context)
        {
            string token;

            if (!context.PrivateConversationData.TryGetValue(AuthTokenKey, out token))
            {
                var conversationReference = context.Activity.ToConversationReference();

                context.PrivateConversationData.SetValue("persistedCookie", conversationReference);

                var reply = context.MakeMessage();
                reply.Type = "message";

                if (context.Activity.ChannelId == ChannelIds.Skype.ToString())
                {
                    Microsoft.Bot.Connector.Attachment plAttachment = GetSkypeSigninCard(conversationReference);
                    reply.Attachments.Add(plAttachment);
                }
                else
                {
                    Microsoft.Bot.Connector.Attachment plAttachment = GetSigninCard(conversationReference);
                    reply.Attachments.Add(plAttachment);
                }

                await context.PostAsync(reply);

                context.Wait(MessageReceivedAsync);
            }
            else
            {
                await context.PostAsync($"Your are already logged in.");

                context.Done(token);
            }
        }
コード例 #4
0
        private async Task AfterSubsidiarySelected(IDialogContext context, IAwaitable <string> result)
        {
            try
            {
                var selectedSubsidiary = await result;

                this.SFRequest.Subsidiary = selectedSubsidiary;

                var adaptivecardtest = new AdaptiveCard()
                {
                    Body = new List <CardElement>()
                    {
                        new TextBlock()
                        {
                            Text = "When do you want to meet?"
                        },
                        new DateInput()
                        {
                            Id    = "StartTime",
                            Speak = "<s>When do you want to meet with the team?</s>"
                        }
                    },
                    Actions = new List <ActionBase>()
                    {
                        new SubmitAction()
                        {
                            Title = "Pick!",
                            Speak = "<s>Pick</s>"
                        }
                    }
                };

                Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = adaptivecardtest
                };
                var reply = context.MakeMessage();
                reply.Attachments.Add(attachment);

                await context.PostAsync(reply, CancellationToken.None);

                context.Wait(MessageReceivedAsync);

                //var requestForm = new FormDialog<Models.SFRequest>(this.SFRequest, Models.SFRequest.BuildRequestForm, FormOptions.PromptInStart);
                //context.Call(requestForm, this.AfterRequestForm);
                //context.Forward()
            }
            catch (TooManyAttemptsException)
            {
                await this.StartOverTextAsync(context, Resources.RootDialog_TooManyAttempts);
            }
        }
コード例 #5
0
        protected static IMessageActivity ProcessResultAndCreateMessageActivity(IDialogContext context, ref QnAMakerResult result)
        {
            var message = context.MakeMessage();

            //var attachmentsItemRegex = new Regex("((&lt;attachment){1}((?:\\s+)|(?:(contentType=&quot;[\\w\\/]+&quot;))(?:\\s+)|(?:(contentUrl=&quot;[\\w:/.]+&quot;))(?:\\s+)|(?:(name=&quot;[\\w\\s]+&quot;))(?:\\s+)|(?:(thumbnailUrl=&quot;[\\w:/.]+&quot;))(?:\\s+))+(/&gt;))", RegexOptions.IgnoreCase);
            var attachmentsItemRegex = new Regex("((&lt;attachment){1}((?:\\s+)|(?:(contentType=&quot;[\\w\\/-]+&quot;))(?:\\s+)|(?:(contentUrl=&quot;[\\w:/.=?-]+&quot;))(?:\\s+)|(?:(name=&quot;[\\w\\s&?\\-.@%$!£\\(\\)]+&quot;))(?:\\s+)|(?:(thumbnailUrl=&quot;[\\w:/.=?-]+&quot;))(?:\\s+))+(/&gt;))", RegexOptions.IgnoreCase);
            var matches = attachmentsItemRegex.Matches(result.Answer);

            foreach (var attachmentMatch in matches)
            {
                result.Answer = result.Answer.Replace(attachmentMatch.ToString(), string.Empty);

                var    match        = attachmentsItemRegex.Match(attachmentMatch.ToString());
                string contentType  = string.Empty;
                string name         = string.Empty;
                string contentUrl   = string.Empty;
                string thumbnailUrl = string.Empty;

                foreach (var group in match.Groups)
                {
                    if (group.ToString().ToLower().Contains("contenttype="))
                    {
                        contentType = group.ToString().ToLower().Replace(@"contenttype=&quot;", string.Empty).Replace("&quot;", string.Empty);
                    }
                    if (group.ToString().ToLower().Contains("contenturl="))
                    {
                        contentUrl = group.ToString().ToLower().Replace(@"contenturl=&quot;", string.Empty).Replace("&quot;", string.Empty);
                    }
                    if (group.ToString().ToLower().Contains("name="))
                    {
                        name = group.ToString().ToLower().Replace(@"name=&quot;", string.Empty).Replace("&quot;", string.Empty);
                    }
                    if (group.ToString().ToLower().Contains("thumbnailurl="))
                    {
                        thumbnailUrl = group.ToString().ToLower().Replace(@"thumbnailurl=&quot;", string.Empty).Replace("&quot;", string.Empty);
                    }
                }

                var attachment = new Attachment(contentType, contentUrl, name: !string.IsNullOrEmpty(name) ? name : null, thumbnailUrl: !string.IsNullOrEmpty(thumbnailUrl) ? thumbnailUrl : null);
                message.Attachments.Add(attachment);
            }

            return(message);
        }
コード例 #6
0
        /// <summary>
        /// Display card with weather info on it
        /// </summary>
        /// <param name="context"></param>
        /// <param name="card"></param>
        /// <param name="cardName"></param>
        /// <returns></returns>
        private IMessageActivity GetWeatherMessage(IDialogContext context, AdaptiveCard card, string cardName)
        {
            var message = context.MakeMessage();

            if (message.Attachments == null)
            {
                message.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
            }
            var attachment = new Microsoft.Bot.Connector.Attachment()
            {
                Content     = card,
                ContentType = AdaptiveCard.ContentType,
                Name        = cardName
            };

            message.Attachments.Add(attachment);

            return(message);
        }
コード例 #7
0
        private async Task MessageReceivedStartQuestions(IDialogContext context, IAwaitable <object> result)
        {
            var message         = await result;
            var questionMessage = context.MakeMessage();

            if (i < quiz.Count)
            {
                var questionNumber = (i + 1) + " of " + quiz.Count + ". ";
                if (quiz[i].Option3 == null)
                {
                    var heroCard = new HeroCard
                    {
                        Subtitle = questionNumber + quiz[i].Question,
                        Buttons  = new List <CardAction>()
                        {
                            new CardAction {
                                Title = quiz[i].Option1, Type = "imBack", Value = quiz[i].Option1
                            },
                            new CardAction {
                                Title = quiz[i].Option2, Type = "imBack", Value = quiz[i].Option2
                            },
                        }
                    };
                    questionMessage.Attachments.Add(heroCard.ToAttachment());
                }
                else
                {
                    var heroCard = new HeroCard
                    {
                        Subtitle = questionNumber + quiz[i].Question,
                        Buttons  = new List <CardAction>()
                        {
                            new CardAction {
                                Title = quiz[i].Option1, Type = "imBack", Value = quiz[i].Option1
                            },
                            new CardAction {
                                Title = quiz[i].Option2, Type = "imBack", Value = quiz[i].Option2
                            },
                            new CardAction {
                                Title = quiz[i].Option3, Type = "imBack", Value = quiz[i].Option3
                            },
                            new CardAction {
                                Title = quiz[i].Option4, Type = "imBack", Value = quiz[i].Option4
                            }
                        }
                    };
                    questionMessage.Attachments.Add(heroCard.ToAttachment());
                }

                await context.PostAsync(questionMessage);

                context.Wait(MessageReceivedCorrection);
            }
            else
            {
                List <CardAction> cardButtons = new List <CardAction>();
                cardButtons.Add(new CardAction
                {
                    Title = "Main Menu",
                    Value = "Home",
                    Type  = "imBack"
                });

                var heroCard = new ThumbnailCard
                {
                    Title    = "JQuery Quiz is completed",
                    Subtitle = "Total number of Wrong Answers: " + Convert.ToString(quiz.Count - correctAnswers),
                    Text     = "Total number of Correct Answers: " + correctAnswers.ToString() + " Out of " + quiz.Count.ToString(),
                    Images   = new List <CardImage> {
                        new CardImage("https://techquizbot.azurewebsites.net/images/JqueryICon.png")
                    },
                    Buttons = cardButtons
                };

                var replyMessage = context.MakeMessage();

                Microsoft.Bot.Connector.Attachment plAttachment = heroCard.ToAttachment();
                replyMessage.Attachments.Add(plAttachment);
                var activity = await result as Activity;
                Utility.UpdateResults(activity, "JQuery", correctAnswers, quiz.Count);

                await context.PostAsync(replyMessage);

                quiz           = new List <QuizEntity>();
                i              = 0;
                correctAnswers = 0;
                context.Wait(MessageReceivedAsync);
            }
        }
コード例 #8
0
        public static IForm <QuoteGenerate> BuildQuoteForm()
        {
            return(new FormBuilder <QuoteGenerate>().Message("I can help you generate quotes Kindly Provide your details!").Field(nameof(FirstName)).Field(nameof(LastName)).Field(nameof(frequency))
                   .AddRemainingFields().OnCompletion(async(context, profileForm) =>
            {
                try
                {
                    var smtpClient = new SmtpClient
                    {
                        Host = "smtp-mail.outlook.com", // set your SMTP server name here
                        Port = 25,                      // Port
                        EnableSsl = true,
                        Credentials = new NetworkCredential("*****@*****.**", "ImpressiveDude@1")
                    };


                    using (var message = new MailMessage("*****@*****.**", "*****@*****.**")
                    {
                        Subject = "Hello",
                        Body = " Dear "
                    })
                        await smtpClient.SendMailAsync(message);
                }
                catch (Exception e) {
                    await context.PostAsync($"{e.Message}");
                }

                await context.PostAsync("generating your quote");

                Activity replyToConversation = (Activity)context.MakeMessage();

                replyToConversation.Attachments = new List <Attachment>();
                AdaptiveCard card = new AdaptiveCard()
                {
                    Body = new List <CardElement>()
                    {
                        new Container()
                        {
                            Speak = "<s>Hello!</s>",
                            Items = new List <CardElement>()
                            {
                                new ColumnSet()
                                {
                                    Columns = new List <Column>()
                                    {
                                        new Column()
                                        {
                                            Size = ColumnSize.Auto,
                                            Items = new List <CardElement>()
                                            {
                                                //new Image()
                                                //{
                                                //     Url = "https://image.ibb.co/chDkEy/1gov101.png",
                                                //     Size = ImageSize.Large,
                                                //     Style = ImageStyle.Normal
                                                //}
                                            }
                                        },
                                        new Column()
                                        {
                                            Size = "300",
                                            Items = new List <CardElement>()
                                            {
                                                new TextBlock()
                                                {
                                                    Text = $"Quote for {profileForm.FirstName}",
                                                    Weight = TextWeight.Bolder,
                                                    //IsSubtle = true
                                                },
                                                new TextBlock()
                                                {
                                                    Text = "Maximum Sum Assured 10,000",
                                                    Weight = TextWeight.Bolder,
                                                    IsSubtle = true
                                                },

                                                new TextBlock()
                                                {
                                                    Text = "Age at inception | 29",
                                                    Weight = TextWeight.Bolder,
                                                    IsSubtle = true
                                                },

                                                new TextBlock()
                                                {
                                                    Text = "Treasury Bill |10,000",
                                                    Weight = TextWeight.Bolder,
                                                    IsSubtle = true
                                                },

                                                new TextBlock()
                                                {
                                                    Text = "Anual Contribution |120,000",
                                                    Weight = TextWeight.Bolder,
                                                    IsSubtle = true
                                                },
                                                new TextBlock()
                                                {
                                                    Text = $"Frequency | {profileForm.frequency}",
                                                    Weight = TextWeight.Bolder,
                                                    IsSubtle = true
                                                },
                                                new TextBlock()
                                                {
                                                    Text = $"Duration | {profileForm.Duration}",
                                                    Weight = TextWeight.Bolder,
                                                    IsSubtle = true
                                                },
                                            }
                                        }
                                    }
                                },
                                new ColumnSet()
                                {
                                    Columns = new List <Column>()
                                    {
                                        new Column()
                                        {
                                            Size = ColumnSize.Auto,
                                            Separation = SeparationStyle.Strong,
                                            Items = new List <CardElement>()
                                            {
                                                new TextBlock()
                                                {
                                                    Text = "A copy of this quotes has been sen to your mail.",
                                                    Wrap = true
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    Actions = new List <ActionBase>()
                    {
                        new SubmitAction()
                        {
                            Title = "Buy Now",
                            Speak = "<s>Buy</s>",
                        }
                    }
                };
                Microsoft.Bot.Connector.Attachment attachment = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content = card
                };
                replyToConversation.Attachments.Add(attachment);

                await context.PostAsync(replyToConversation);
            }).Build());
        }
コード例 #9
0
        public async Task ShowOptionQuantidade(IDialogContext context)
        {
            AdaptiveCard card = new AdaptiveCard()
                                //AdaptiveCard card = new AdaptiveCard()
            {
                Body = new List <AdaptiveElement>()
                {
                    new AdaptiveTextBlock()
                    {
                        Text = "Qual email para contato?"
                    },
                    new AdaptiveTextInput()
                    {
                        Id          = "email",
                        Placeholder = "Exemplo: [email protected]",
                        Style       = AdaptiveTextInputStyle.Email,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Qual telefone para contato?"
                    },
                    new AdaptiveTextInput()
                    {
                        Id          = "telefone",
                        Placeholder = "Exemplo: 3100000000",
                        Style       = AdaptiveTextInputStyle.Tel,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Qual é o nome da sua empresa?"
                    },
                    new AdaptiveTextInput()
                    {
                        Id          = "nomeEmpresa",
                        Placeholder = "Exemplo: Arktetur",
                        Style       = AdaptiveTextInputStyle.Text,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Qual é o nome do seu assistente virtual?"
                    },
                    new AdaptiveTextInput()
                    {
                        Id          = "nomeBot",
                        Placeholder = "Exemplo: Ark",
                        Style       = AdaptiveTextInputStyle.Text,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Me conte sobre sua empresa:"
                    },
                    new AdaptiveTextInput()
                    {
                        Id          = "sobre",
                        Placeholder = "Exemplo: Somos uma empresa criada em 2010 com intuito de fornecer serviços especializados.",
                        Style       = AdaptiveTextInputStyle.Text,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Quantos serviços vocês fornecem?"
                    },
                    new AdaptiveNumberInput()
                    {
                        Id  = "servicos",
                        Min = 1,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Para quantos clientes vocês prestam serviço?"
                    },
                    new AdaptiveNumberInput()
                    {
                        Id  = "clientes",
                        Min = 0,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "São quantos fundadores?"
                    },
                    new AdaptiveNumberInput()
                    {
                        Id  = "fundadores",
                        Min = 1,
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Quantos parceiros?"
                    },
                    new AdaptiveNumberInput()
                    {
                        Id  = "parceiros",
                        Min = 0,
                    },
                },
                Actions = new List <AdaptiveAction>()
                {
                    new AdaptiveSubmitAction()
                    {
                        Title    = "Enviar",
                        DataJson = "{ \"Type\": \"FormularioInicial\" }"
                    }
                }
            };
            var attachment = new Microsoft.Bot.Connector.Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card
            };

            var reply = context.MakeMessage();

            reply.Attachments.Add(attachment);

            await context.PostAsync(reply);

            context.Wait(RecebeFormularioInicial);
        }
コード例 #10
0
        private async Task RecebeFormularioInicial(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            //if (message.Value != null)

            var value      = message.Value.ToString().Replace("{{", "{").Replace("}}", "}");
            var formulario = JsonConvert.DeserializeObject <FormularioInicial>(value);

            var servicos = new List <AdaptiveTextInput>();

            for (var i = 0; i < Convert.ToInt32(formulario.servicos); i++)
            {
                servicos.Add(new AdaptiveTextInput
                {
                    Id    = "servico" + i,
                    Style = AdaptiveTextInputStyle.Text,
                });
            }

            var clientes = new List <AdaptiveTextInput>();

            for (var i = 0; i < Convert.ToInt32(formulario.clientes); i++)
            {
                clientes.Add(new AdaptiveTextInput
                {
                    Id    = "clientes" + i,
                    Style = AdaptiveTextInputStyle.Text,
                });
            }

            var fundadores = new List <AdaptiveTextInput>();

            for (var i = 0; i < Convert.ToInt32(formulario.fundadores); i++)
            {
                fundadores.Add(new AdaptiveTextInput
                {
                    Id    = "fundadores" + i,
                    Style = AdaptiveTextInputStyle.Text,
                });
            }

            var parceiros = new List <AdaptiveTextInput>();

            for (var i = 0; i < Convert.ToInt32(formulario.parceiros); i++)
            {
                parceiros.Add(new AdaptiveTextInput
                {
                    Id    = "parceiros" + i,
                    Style = AdaptiveTextInputStyle.Text,
                });
            }

            List <AdaptiveElement> elementosForm = new List <AdaptiveElement>();

            if (parceiros.Count > 0)
            {
                elementosForm.Add(new AdaptiveTextBlock(text: "Quais serviços sua empresa presta?"));
                foreach (var item in servicos)
                {
                    elementosForm.Add(item);
                }
            }

            if (clientes.Count > 0)
            {
                elementosForm.Add(new AdaptiveTextBlock(text: "Quais clientes sua empresa presta?"));
                foreach (var item in clientes)
                {
                    elementosForm.Add(item);
                }
            }

            if (fundadores.Count > 0)
            {
                elementosForm.Add(new AdaptiveTextBlock(text: "Quais fundadores sua empresa presta?"));
                foreach (var item in fundadores)
                {
                    elementosForm.Add(item);
                }
            }

            if (parceiros.Count > 0)
            {
                elementosForm.Add(new AdaptiveTextBlock(text: "Quais parceiros sua empresa presta?"));
                foreach (var item in parceiros)
                {
                    elementosForm.Add(item);
                }
            }

            AdaptiveCard card = new AdaptiveCard()
                                //AdaptiveCard card = new AdaptiveCard()
            {
                Body    = elementosForm,
                Actions = new List <AdaptiveAction>()
                {
                    new AdaptiveSubmitAction()
                    {
                        Title    = "Enviar",
                        DataJson = "{ \"Type\": \"FormularioFinal\" }"
                    }
                }
            };

            Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card
            };

            var reply = context.MakeMessage();

            reply.Attachments.Add(attachment);

            await context.PostAsync(reply);

            context.Wait(RecebeFormularioFinal);
        }
コード例 #11
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            string   miralLuisoutput     = "empty";
            Activity replyToConversation = activity.CreateReply();

            replyToConversation.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            try
            {
                if (activity.Type == ActivityTypes.Message)
                {
                    int       length = (activity.Text ?? string.Empty).Length;
                    MiralLUIS StLUIS = await GetEntityFromLUIS(activity.Text);

                    if (StLUIS.topScoringIntent != null && !string.IsNullOrEmpty(StLUIS.topScoringIntent.intent))
                    {
                        switch (StLUIS.topScoringIntent.intent)
                        {
                        case "findrides":
                            //miralLuisoutput = $"Folowing ride are available (every 30 mins): Splash, RollerCoaster, Dragon, MiralEye, Transformers and RoundRobin";
                            miralLuisoutput = "";
                            CardAction Splash = new CardAction()
                            {
                                Type  = "imBack",
                                Title = "Splash",
                                Value = "Show Splash timings"
                            };
                            CardAction RollerCoaster = new CardAction()
                            {
                                Type  = "imBack",
                                Title = "RollerCoaster",
                                Value = "Show RollerCoaster timings"
                            };
                            CardAction Dragon = new CardAction()
                            {
                                Type  = "imBack",
                                Title = "Dragon",
                                Value = "Show Dragon timings"
                            };
                            CardAction Transformers = new CardAction()
                            {
                                Type  = "imBack",
                                Title = "Transformers",
                                Value = "Show Transformers timings"
                            };

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(Splash);
                            cardButtons.Add(RollerCoaster);
                            cardButtons.Add(Dragon);
                            cardButtons.Add(Transformers);
                            HeroCard plCard = new HeroCard()
                            {
                                Title    = "Folowing ride are available:",
                                Subtitle = " (every 30 mins)",
                                Buttons  = cardButtons
                            };
                            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttachment);
                            break;

                        case "None":
                            miralLuisoutput = "None Intent";
                            break;

                        case "greeting":
                            miralLuisoutput = "Hello, Welcome to Miral Theme Park, Have a Good Day :)";
                            Microsoft.Bot.Connector.Attachment att = new Microsoft.Bot.Connector.Attachment()
                            {
                                ContentUrl  = "https://1a7ae9d8.ngrok.io/miral/miralthemepark.jpg",
                                ContentType = "image/jpg",
                            };
                            replyToConversation.Attachments.Add(att);

                            break;

                        case "ridetimes":
                            if (StLUIS.entities != null && StLUIS.entities.Count() > 0 && !string.IsNullOrEmpty(StLUIS.entities[0].entity))
                            {
                                Random r = new Random();
                                int    x = r.Next(10, 20); //Max range
                                miralLuisoutput = $"Next ride time for {StLUIS.entities[0].entity} is at {x}:00  PM, enjoy your ride :)";
                                Microsoft.Bot.Connector.Attachment att1 = new Microsoft.Bot.Connector.Attachment()
                                {
                                    ContentUrl  = $"https://1a7ae9d8.ngrok.io/miral/" + StLUIS.entities[0].entity + ".jpg",
                                    ContentType = "image/jpg",
                                };
                                replyToConversation.Attachments.Add(att1);
                            }
                            break;

                        case "weather":
                            HttpClient client   = new HttpClient();
                            var        rsult    = client.GetAsync("http://api.openweathermap.org/data/2.5/weather?q=Delhi,india&appid=eac3f002d569916e04d2ed17c3f457d0").Result;
                            var        contents = rsult.Content.ReadAsStringAsync().Result;
                            var        res      = new JavaScriptSerializer().Deserialize <WeatherObjectRoot>(contents);

                            miralLuisoutput = $"Temprature in Delhi is : {(res.main.temp - 273)} °C";
                            break;

                        default:
                            miralLuisoutput = "Sorry, I am not getting you...";
                            break;
                        }
                    }
                }
                else
                {
                    HandleSystemMessage(activity);
                }
            }
            catch (Exception ex)
            {
                miralLuisoutput = $"Exception = {ex.Message}";
            }
            replyToConversation.Text = miralLuisoutput;
            await connector.Conversations.SendToConversationAsync(replyToConversation);

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

            return(response);
        }
コード例 #12
0
        public async Task StartAsync(IDialogContext context)
        {
            var reply = context.MakeMessage();
            List <AdaptiveChoice> choice = new List <AdaptiveChoice>();

            choice.Add(new AdaptiveChoice()
            {
                Title = "--Select option--", Value = "--Select option--"
            });
            var query = @"query  {
                    viewer{
                        name
                      repositories(first: 100)
                      {
                         nodes
                        {
                         name
                        }
                      }
                    }
                }";

            var           client = new GraphQLClient();
            string        data   = client.Query(query, null);
            AllRepository obj    = Newtonsoft.Json.JsonConvert.DeserializeObject <AllRepository>(data);

            foreach (Node1 rep in obj.data.viewer.repositories.nodes)
            {
                choice.Add(new AdaptiveChoice()
                {
                    Title = rep.name, Value = rep.name
                });
            }
            AdaptiveCard card = new AdaptiveCard()
            {
                Body = new List <AdaptiveElement>()
                {
                    new AdaptiveTextBlock()
                    {
                        Text = "Search Issue", Weight = AdaptiveTextWeight.Bolder, Size = AdaptiveTextSize.Large, Wrap = true, HorizontalAlignment = AdaptiveHorizontalAlignment.Center
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Select Repository"
                    },
                    new AdaptiveChoiceSetInput()
                    {
                        Id = "Repository", Style = AdaptiveChoiceInputStyle.Compact, Choices = choice
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Select Issue State"
                    },
                    new AdaptiveChoiceSetInput()
                    {
                        Id      = "State", Value = "--ALL--", IsMultiSelect = false, Style = AdaptiveChoiceInputStyle.Compact,
                        Choices = new List <AdaptiveChoice>()
                        {
                            new AdaptiveChoice()
                            {
                                Title = "--ALL--", Value = "--ALL--"
                            },
                            new AdaptiveChoice()
                            {
                                Title = "OPEN",
                                Value = "OPEN"
                            },
                            new AdaptiveChoice()
                            {
                                Title = "CLOSED",
                                Value = "CLOSED"
                            }
                        }
                    }
                },
                Actions = new List <AdaptiveAction>()
                {
                    new AdaptiveSubmitAction()
                    {
                        Title    = "Submit",
                        Id       = "IssueDetail",
                        DataJson = @"{""Action"":""GetIssueDetail""}"
                    }
                }
            };

            Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card,
                //  Name = "ABCD"
            };

            reply.Attachments.Add(attachment);
            await context.PostAsync(reply);

            context.Done <object>(new object());
        }
コード例 #13
0
        private async Task ResumeArticleSearchDialog(IDialogContext context, IAwaitable <ArticleSearchQuery> result)
        {
            try
            {
                var    resultFromArticleSearch = await result;
                string _strhelpArticle         = Convert.ToString(resultFromArticleSearch.HelpArticle);
                int    _iLearningMaterial      = Convert.ToInt32(resultFromArticleSearch.LearningMaterial);

                try
                {
                    SharePointPrimary             obj          = new SharePointPrimary();
                    Dictionary <ListItem, string> searchedDocs = new Dictionary <ListItem, string>();

                    if (_iLearningMaterial == 2)
                    {
                        searchedDocs = obj.SearchLearningVideoByTopic(_strhelpArticle);
                        if (searchedDocs.Count > 0)
                        {
                            if (searchedDocs.Count == 1)
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} video on your search topic \U0001F44D ");
                            }
                            else
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} videos on your search topic \U0001F44D ");
                            }

                            foreach (var eachDoc in searchedDocs)
                            {
                                try
                                {
                                    var videoCard = new VideoCard();
                                    videoCard.Title    = eachDoc.Key.FieldValuesAsHtml["Title"];
                                    videoCard.Subtitle = eachDoc.Key.FieldValuesAsHtml["SubTitle"];
                                    videoCard.Text     = eachDoc.Key.FieldValuesAsHtml["VideoSetDescription"];

                                    string _previewImageBase64 = obj.GetImage(eachDoc.Key.FieldValuesAsText["AlternateThumbnailUrl"].Split(',')[0].ToString(), _iLearningMaterial);


                                    if (!string.IsNullOrEmpty(_previewImageBase64))
                                    {
                                        videoCard.Image = new ThumbnailUrl(
                                            url: _previewImageBase64,
                                            alt: "Learning Video");
                                    }

                                    //string _videoBase64 = obj.GetVideo("https://avaindcollabsl.sharepoint.com/sites/SOHA_HelpRepository/VideoRepository/Build%20a%20Chat%20Bot%20with%20Azure%20Bot%20Service/buildachatbotwithazurebotservice_high.mp4");

                                    //string _videoBase64 = obj.GetVideo(eachDoc.Value);


                                    if (!string.IsNullOrEmpty(eachDoc.Value))
                                    {
                                        videoCard.Media = new List <MediaUrl> {
                                            new MediaUrl("https://sec.ch9.ms/ch9/a7a4/10df13cf-a7ac-40a2-b713-6fcc935ba7a4/buildachatbotwithazurebotservice.mp4")
                                        };

                                        videoCard.Buttons = new List <CardAction> {
                                            new CardAction(
                                                type: ActionTypes.OpenUrl,
                                                title: "Learn more",
                                                value: "https://channel9.msdn.com/Blogs/MVP-Azure/build-a-chatbot-with-azure-bot-service")
                                        };
                                    }


                                    //if (!string.IsNullOrEmpty(/*eachDoc.Value*/_videoBase64))
                                    //{
                                    //    videoCard.Media = new List<MediaUrl> { new MediaUrl(_videoBase64) };

                                    //    videoCard.Buttons = new List<CardAction> { new CardAction(
                                    //    type  : ActionTypes.OpenUrl,
                                    //    title : "Learn more",
                                    //    value : eachDoc.Value) };
                                    //}

                                    Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment();
                                    var replyMessage = context.MakeMessage();
                                    attachment = videoCard.ToAttachment();
                                    replyMessage.Attachments.Add(attachment);

                                    await context.PostAsync(replyMessage);
                                }
                                catch (Exception ex)
                                {
                                    await context.PostAsync(ex.Message);
                                }
                            }

                            await context.PostAsync("Hope you have found the result informative. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                        else
                        {
                            await context.PostAsync($"No video found. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                    }
                    else if (_iLearningMaterial == 1)
                    {
                        searchedDocs = obj.SearchHelpArticleonTopic(_strhelpArticle);
                        if (searchedDocs.Count > 0)
                        {
                            if (searchedDocs.Count == 1)
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} article on your search topic \U0001F44D ");
                            }
                            else
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} articles on your search topic \U0001F44D ");
                            }

                            foreach (var eachDoc in searchedDocs)
                            {
                                Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment();

                                var replyMessage = context.MakeMessage();

                                var heroCard = new HeroCard();

                                string _previewImageBase64 = obj.GetImage(eachDoc.Value.ToString(), _iLearningMaterial);

                                heroCard.Title    = eachDoc.Key.DisplayName;
                                heroCard.Subtitle = "by Avanade Collab SL Capability";
                                heroCard.Text     = eachDoc.Key.FieldValuesAsHtml["KpiDescription"];
                                heroCard.Buttons  = new List <CardAction> {
                                    new CardAction(ActionTypes.OpenUrl, "Read more", value: Constants.RootSiteCollectionURL + eachDoc.Key.File.ServerRelativeUrl)
                                };

                                if (!string.IsNullOrEmpty(_previewImageBase64))
                                {
                                    heroCard.Images = new List <CardImage> {
                                        new CardImage(_previewImageBase64)
                                    }
                                }
                                ;


                                attachment = heroCard.ToAttachment();
                                replyMessage.Attachments.Add(attachment);

                                await context.PostAsync(replyMessage);
                            }

                            await context.PostAsync("Hope you have found the result informative. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                        else
                        {
                            await context.PostAsync($"No document found. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                    }
                }
                catch (TooManyAttemptsException)
                {
                    context.Fail(new TooManyAttemptsException("Unable to find any help document."));
                }
            }
            catch (TooManyAttemptsException)
            {
                await context.PostAsync("Sorry \U0001F641 , I am unable to understand you. Let us try again.");
            }
        }
コード例 #14
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            bool   boolAskedForUserName = false;
            string strUserName          = "";

            #region Set CurrentBaseURL and ChannelAccount
            // Get the base URL that this service is running at
            // This is used to show images
            string CurrentBaseURL =
                this.Url.Request.RequestUri.AbsoluteUri.Replace(@"api/messages", "");

            // Create an instance of BotData to store data
            BotData objBotData = new BotData();

            // Instantiate a StateClient to save BotData
            StateClient stateClient = activity.GetStateClient();

            // Use stateClient to get current userData
            BotData userData = await stateClient.BotState.GetUserDataAsync(
                activity.ChannelId, activity.From.Id);

            // Update userData by setting CurrentBaseURL and Recipient
            userData.SetProperty <string>("CurrentBaseURL", CurrentBaseURL);

            // Save changes to userData
            await stateClient.BotState.SetUserDataAsync(
                activity.ChannelId, activity.From.Id, userData);

            #endregion

            if (activity.Type == ActivityTypes.Message)
            {
                BotData leadData = stateClient.BotState.GetPrivateConversationData(
                    activity.ChannelId, activity.Conversation.Id, activity.From.Id);

                Models.BotDataEntities DB     = new Models.BotDataEntities();
                User          user            = DB.Users.FirstOrDefault(x => x.UserID == activity.From.Id);
                StringBuilder strReplyMessage = new StringBuilder();
                if (user == null)
                {
                    boolAskedForUserName = leadData.GetProperty <bool>("AskedForUserName");
                    strUserName          = leadData.GetProperty <string>("Email") ?? "";
                    // Create text for a reply message

                    if (boolAskedForUserName == false) // Never asked for email
                    {
                        strReplyMessage.Append(SR.Hello);
                        strReplyMessage.Append($"\n\n");
                        strReplyMessage.Append(SR.WhatEmail);

                        // Set BotUserData
                        leadData.SetProperty <bool>("AskedForUserName", true);
                    }
                    else // Have asked for email
                    {
                        string[] emailDomain = { "@pycogroup.com", "@pyramid-consulting", "@pyco.be", "@pyco-group.com" };
                        if (!emailDomain.Any(x => activity.Text.Contains(x))) // Name was never provided
                        {
                            // If we have asked for a username but it has not been set
                            // the current response is the user name
                            strReplyMessage.Append(SR.PycoEmailWrong);
                        }
                        else // Name was provided
                        {
                            string email = new EmailHelper().ExtractEmails(activity.Text);
                            leadData.SetProperty <string>("Email", email);
                            strReplyMessage.Append(string.Format(SR.OTPSend, email));
                            string newpass = SendOTP(activity, email);
                            user = new User()
                            {
                                Channel    = activity.ChannelId,
                                UserID     = activity.From.Id,
                                UserName   = activity.From.Name,
                                ExpiredOTP = DateTime.UtcNow.AddHours(1),
                                IsVerified = false,
                                Email      = email,
                                OTP        = newpass,
                                JoinDate   = DateTime.UtcNow
                            };
                            DB.Users.Add(user);
                            DB.SaveChanges();
                        }
                    }

                    // Save BotUserData
                    stateClient.BotState.SetPrivateConversationData(
                        activity.ChannelId, activity.Conversation.Id, activity.From.Id, leadData);

                    // Create a reply message
                    ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                    Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                    await connector.Conversations.ReplyToActivityAsync(replyMessage);
                }
                else //check OTP is ok or user already authorize
                {
                    if (user.IsVerified)
                    {
                        await Conversation.SendAsync(activity, () => new ResourceDialog());
                    }
                    else
                    {
                        if (user.OTP == activity.Text && user.ExpiredOTP > DateTime.UtcNow)
                        {
                            //Update Database
                            user.IsVerified = true;
                            DB.Users.Attach(user);
                            DB.Entry(user).State = EntityState.Modified;
                            // other changed properties
                            DB.SaveChanges();
                            strReplyMessage.Append(SR.OTPValid);
                            strReplyMessage.Append(string.Format(SR.Welcome, activity.From.Name));
                            ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                            Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());

                            // Call the CreateButtons utility method
                            // that will create 5 buttons to put on the Here Card
                            List <CardAction> cardButtons = UIControl.CreateButtons();

                            // Create a Hero Card and add the buttons
                            HeroCard plCard = new HeroCard()
                            {
                                Buttons = cardButtons
                            };

                            // Create an Attachment
                            // set the AttachmentLayout as 'list'
                            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
                            replyMessage.Attachments.Add(plAttachment);
                            replyMessage.AttachmentLayout = "list";


                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }
                        else if (user.OTP != activity.Text && user.ExpiredOTP > DateTime.UtcNow)
                        {
                            strReplyMessage.Append(SR.OTPWrong);
                            ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                            Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }
                        else // OTP is wrong and expired
                        {
                            strReplyMessage.Append(SR.OTPInvalid);
                            DB.Users.Remove(user);
                            ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                            Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
コード例 #15
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
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Construct a base URL for Image
                // To allow it to be found wherever the application is deployed
                string strCurrentURL =
                    this.Url.Request.RequestUri.AbsoluteUri.Replace(@"api/messages", "");

                // Create a reply message
                Activity replyToConversation = message.CreateReply();
                replyToConversation.Recipient   = message.From;
                replyToConversation.Type        = "message";
                replyToConversation.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
                // AttachmentLayout options are list or carousel
                replyToConversation.AttachmentLayout = "carousel";

                #region Card One
                // Full URL to the image
                string strNumberGuesserOpeningCard =
                    String.Format(@"{0}/{1}",
                                  strCurrentURL,
                                  "Images/Pyco.png");

                // Create a CardImage and add our image
                List <CardImage> cardImages1 = new List <CardImage>();
                cardImages1.Add(new CardImage(url: strNumberGuesserOpeningCard));

                // Create a CardAction to make the HeroCard clickable
                // Note this does not work in some Skype clients
                CardAction btnAiHelpWebsite = new CardAction()
                {
                    Type  = "openUrl",
                    Title = "PycoGroup.com",
                    Value = "http://www.pycogroup.com"
                };

                // Finally create the Hero Card
                // adding the image and the CardAction
                HeroCard plCard1 = new HeroCard()
                {
                    Title    = SR.WelcomeTilte,
                    Subtitle = SR.PycoTerm,
                    Images   = cardImages1,
                    Tap      = btnAiHelpWebsite
                };

                // Create an Attachment by calling the
                // ToAttachment() method of the Hero Card
                Microsoft.Bot.Connector.Attachment plAttachment1 = plCard1.ToAttachment();

                // Add the Attachment to the reply message
                replyToConversation.Attachments.Add(plAttachment1);
                #endregion


                // Create a ConnectorClient and use it to send the reply message
                var connector =
                    new ConnectorClient(new Uri(message.ServiceUrl));
                var reply =
                    connector.Conversations.SendToConversationAsync(replyToConversation);
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing that the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
        public static async Task <string> SendNotification(IDialogContext context, string userOrChannelId, string messageText, Microsoft.Bot.Connector.Attachment attachment, string updateMessageId, bool isChannelMessage)

        {
            var userId = userOrChannelId.Trim();

            var botId = context.Activity.Recipient.Id;

            var botName = context.Activity.Recipient.Name;

            var channelData = context.Activity.GetChannelData <TeamsChannelData>();

            var connectorClient = new ConnectorClient(new Uri(context.Activity.ServiceUrl));

            var parameters = new ConversationParameters

            {
                Bot = new ChannelAccount(botId, botName),

                Members = !isChannelMessage ? new ChannelAccount[] { new ChannelAccount(userId) } : null,

                ChannelData = new TeamsChannelData

                {
                    Tenant = channelData.Tenant,

                    Channel = isChannelMessage ? new ChannelInfo(userId) : null,

                    Notification = new NotificationInfo()
                    {
                        Alert = true
                    }
                },

                IsGroup = isChannelMessage
            };

            try

            {
                var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);

                var replyMessage = Activity.CreateMessageActivity();

                replyMessage.From = new ChannelAccount(botId, botName);

                replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());

                replyMessage.ChannelData = new TeamsChannelData()
                {
                    Notification = new NotificationInfo(true)
                };

                replyMessage.Text = messageText;

                if (attachment != null)
                {
                    replyMessage.Attachments.Add(attachment);//  EchoBot.ManagerViewCard(employee, leaveDetails));
                }
                if (string.IsNullOrEmpty(updateMessageId))

                {
                    var resourceResponse = await connectorClient.Conversations.SendToConversationAsync(conversationResource.Id, (Activity)replyMessage);

                    return(resourceResponse.Id);
                }
                else

                {
                    await connectorClient.Conversations.UpdateActivityAsync(conversationResource.Id, updateMessageId, (Activity)replyMessage);

                    return(updateMessageId); // Just return the same Id.
                }
            }
            catch (Exception ex)

            {
                // Handle the error.

                ErrorLogService.LogError(ex);

                var msg = context.MakeMessage();

                msg.Text = ex.Message;

                await context.PostAsync(msg);

                return(null);
            }
        }
        private static async Task <string> SendChannelNotification(IDialogContext context, string channelId, string messageText, Microsoft.Bot.Connector.Attachment attachment, Employee employee, string updateMessageId, string channleConversationId, bool addAtMention)

        {
            var connectorClient = new ConnectorClient(new Uri(context.Activity.ServiceUrl));

            try

            {
                var replyMessage = Activity.CreateMessageActivity();

                replyMessage.Conversation = new ConversationAccount(id: channelId);

                replyMessage.ChannelData = new TeamsChannelData()
                {
                    Notification = new NotificationInfo(true)
                };

                replyMessage.Text = messageText;

                if (addAtMention)

                {
                    replyMessage.AddMentionToText(new ChannelAccount(employee.UserUniqueId, employee.DisplayName), MentionTextLocation.PrependText);
                }

                if (attachment != null)
                {
                    replyMessage.Attachments.Add(attachment);//  EchoBot.ManagerViewCard(employee, leaveDetails));
                }
                if (string.IsNullOrEmpty(updateMessageId))

                {
                    var resourceResponse = await connectorClient.Conversations.SendToConversationAsync(channleConversationId, (Activity)replyMessage);

                    return(resourceResponse.Id);
                }
                else

                {
                    await connectorClient.Conversations.UpdateActivityAsync(channleConversationId, updateMessageId, (Activity)replyMessage);

                    return(updateMessageId); // Just return the same Id.
                }
            }
            catch (Exception ex)

            {
                ErrorLogService.LogError(ex);

                // Handle the error.

                var msg = context.MakeMessage();

                msg.Text = ex.Message;

                await context.PostAsync(msg);

                return(null);
            }
        }
コード例 #18
0
        private async Task MessageReceivedNextQuestions(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            sb.Append(i + ". " + message.Text + "## ");


            var questionMessage = context.MakeMessage();

            if (i < feedback.Count)
            {
                var questionNumber = (i + 1) + " of " + feedback.Count + ". ";

                if (feedback[i].TypeOfQuestion == "ChooseOne")
                {
                    var heroCard1 = new HeroCard
                    {
                        Subtitle = questionNumber + feedback[i].Question,
                        Buttons  = new List <CardAction>()
                        {
                            new CardAction {
                                Title = feedback[i].Option1, Type = "imBack", Value = feedback[i].Option1
                            },
                            new CardAction {
                                Title = feedback[i].Option2, Type = "imBack", Value = feedback[i].Option2
                            },
                            new CardAction {
                                Title = feedback[i].Option3, Type = "imBack", Value = feedback[i].Option3
                            },
                            new CardAction {
                                Title = feedback[i].Option4, Type = "imBack", Value = feedback[i].Option4
                            }
                        }
                    };
                    questionMessage.Attachments.Add(heroCard1.ToAttachment());
                    await context.PostAsync(questionMessage);
                }
                else if (feedback[i].TypeOfQuestion == "FreeText")
                {
                    await context.PostAsync(questionNumber + feedback[i].Question);
                }
                i = i + 1;

                context.Wait(MessageReceivedNextQuestions);
            }
            else
            {
                //await context.PostAsync(sb.ToString());
                var activity = await result as Activity;
                Utility.UpdateResults(activity, "FeedbackQBot", sb);
                List <CardAction> cardButtons = new List <CardAction>();
                cardButtons.Add(new CardAction
                {
                    Title = "Main Menu",
                    Value = "Home",
                    Type  = "imBack"
                });

                var heroCard = new ThumbnailCard
                {
                    Title    = "Feedback",
                    Subtitle = "",
                    Text     = "Thank you for your Valuable feedback.",
                    Images   = new List <CardImage> {
                        new CardImage("https://techquizbot.azurewebsites.net/images/feedback.png")
                    },
                    Buttons = cardButtons
                };

                var replyMessage = context.MakeMessage();

                Microsoft.Bot.Connector.Attachment plAttachment = heroCard.ToAttachment();
                replyMessage.Attachments.Add(plAttachment);

                await context.PostAsync(replyMessage);



                sb       = new StringBuilder();
                feedback = new List <SurveyEntity>();
                i        = 0;
                //context.Call(new Dialogs.RootDialog(), this.ResumeAfterOptionDialog);
                context.Wait(MessageReceivedAsync);
            }
        }