Esempio n. 1
0
 public Player(HeroCard hero, Texture2D[] textures)
 {
     Hand = new List<Card>();
     TreasureCards = new List<TreasureCard>();
     Health = 20;
     Hero = hero;
     CardTextures = textures;
     Dead = false;
 }
Esempio n. 2
0
        /// <summary>
        /// Get all messages from DirectLine and reply back to Line
        /// </summary>
        private async Task GetAndReplyMessages(string replyToken, string userId)
        {
            dl.ActivitySet result = string.IsNullOrEmpty(watermark) ?
                                    await dlClient.Conversations.GetActivitiesAsync(conversationId) :
                                    await dlClient.Conversations.GetActivitiesAsync(conversationId, watermark);

            userParams["Watermark"] = (Int64.Parse(result.Watermark)).ToString();

            foreach (var activity in result.Activities)
            {
                if (activity.From.Id == userId)
                {
                    continue;
                }

                List <ISendMessage> messages = new List <ISendMessage>();

                if (activity.Attachments != null && activity.Attachments.Count != 0 && (activity.AttachmentLayout == null || activity.AttachmentLayout == "list"))
                {
                    foreach (var attachment in activity.Attachments)
                    {
                        if (attachment.ContentType.Contains("card.animation"))
                        {
                            // https://docs.botframework.com/en-us/core-concepts/reference/#animationcard
                            // Use TextMessage for title and use Image message for image. Not really an animation though.
                            AnimationCard card = JsonConvert.DeserializeObject <AnimationCard>(attachment.Content.ToString());
                            messages.Add(new TextMessage($"{card.Title}\r\n{card.Subtitle}\r\n{card.Text}"));
                            foreach (var media in card.Media)
                            {
                                var originalContentUrl = media.Url?.Replace("http://", "https://");
                                var previewImageUrl    = card.Image?.Url?.Replace("http://", "https://");
                                messages.Add(new ImageMessage(originalContentUrl, previewImageUrl));
                            }
                        }
                        else if (attachment.ContentType.Contains("card.audio"))
                        {
                            // https://docs.botframework.com/en-us/core-concepts/reference/#audiocard
                            // Use TextMessage for title and use Audio message for image.
                            AudioCard card = JsonConvert.DeserializeObject <AudioCard>(attachment.Content.ToString());
                            messages.Add(new TextMessage($"{card.Title}\r\n{card.Subtitle}\r\n{card.Text}"));

                            foreach (var media in card.Media)
                            {
                                var originalContentUrl     = media.Url?.Replace("http://", "https://");
                                var durationInMilliseconds = 1;

                                messages.Add(new AudioMessage(originalContentUrl, (long)durationInMilliseconds));
                            }
                        }
                        else if (attachment.ContentType.Contains("card.hero") || attachment.ContentType.Contains("card.thumbnail"))
                        {
                            // https://docs.botframework.com/en-us/core-concepts/reference/#herocard
                            // https://docs.botframework.com/en-us/core-concepts/reference/#thumbnailcard
                            HeroCard hcard = null;

                            if (attachment.ContentType.Contains("card.hero"))
                            {
                                hcard = JsonConvert.DeserializeObject <HeroCard>(attachment.Content.ToString());
                            }
                            else if (attachment.ContentType.Contains("card.thumbnail"))
                            {
                                ThumbnailCard tCard = JsonConvert.DeserializeObject <ThumbnailCard>(attachment.Content.ToString());
                                hcard = new HeroCard(tCard.Title, tCard.Subtitle, tCard.Text, tCard.Images, tCard.Buttons, null);
                            }

                            // Get four buttons per template.
                            for (int i = 0; i < (double)hcard.Buttons.Count / 4; i++)
                            {
                                ButtonsTemplate buttonsTemplate = new ButtonsTemplate(
                                    title: string.IsNullOrEmpty(hcard.Title) ? hcard.Text : hcard.Title,
                                    thumbnailImageUrl: hcard.Images?.FirstOrDefault()?.Url?.Replace("http://", "https://"),
                                    text: hcard.Subtitle ?? hcard.Text
                                    );

                                if (hcard.Buttons != null)
                                {
                                    foreach (var button in hcard.Buttons.Skip(i * 4).Take(4))
                                    {
                                        buttonsTemplate.Actions.Add(GetAction(button));
                                    }
                                }
                                else
                                {
                                    // Action is mandatory, so create from title/subtitle.
                                    var actionLabel = hcard.Title?.Length < hcard.Subtitle?.Length ? hcard.Title : hcard.Subtitle;
                                    actionLabel = actionLabel.Substring(0, Math.Min(actionLabel.Length, 20));
                                    buttonsTemplate.Actions.Add(new PostbackTemplateAction(actionLabel, actionLabel, actionLabel));
                                }

                                messages.Add(new TemplateMessage("Buttons template", buttonsTemplate));
                            }
                        }
                        else if (attachment.ContentType.Contains("receipt"))
                        {
                            // https://docs.botframework.com/en-us/core-concepts/reference/#receiptcard
                            // Use TextMessage and Buttons. As LINE doesn't support thumbnail type yet.

                            ReceiptCard card = JsonConvert.DeserializeObject <ReceiptCard>(attachment.Content.ToString());
                            var         text = card.Title + "\r\n\r\n";
                            foreach (var fact in card.Facts)
                            {
                                text += $"{fact.Key}:{fact.Value}\r\n";
                            }
                            text += "\r\n";
                            foreach (var item in card.Items)
                            {
                                text += $"{item.Title}\r\nprice:{item.Price},quantity:{item.Quantity}";
                            }

                            messages.Add(new TextMessage(text));

                            ButtonsTemplate buttonsTemplate = new ButtonsTemplate(
                                text: $"total:{card.Total}", title: $"tax:{card.Tax}");

                            foreach (var button in card.Buttons)
                            {
                                buttonsTemplate.Actions.Add(GetAction(button));
                            }

                            messages.Add(new TemplateMessage("Buttons template", buttonsTemplate));
                        }
                        else if (attachment.ContentType.Contains("card.signin"))
                        {
                            // https://docs.botframework.com/en-us/core-concepts/reference/#signincard
                            // Line doesn't support auth button yet, so simply represent link.
                            SigninCard card = JsonConvert.DeserializeObject <SigninCard>(attachment.Content.ToString());

                            ButtonsTemplate buttonsTemplate = new ButtonsTemplate(text: card.Text);

                            foreach (var button in card.Buttons)
                            {
                                buttonsTemplate.Actions.Add(GetAction(button));
                            }

                            messages.Add(new TemplateMessage("Buttons template", buttonsTemplate));
                        }
                        else if (attachment.ContentType.Contains("card.video"))
                        {
                            // https://docs.botframework.com/en-us/core-concepts/reference/#videocard
                            // Use Video message for video and buttons for action.

                            VideoCard card = JsonConvert.DeserializeObject <VideoCard>(attachment.Content.ToString());

                            foreach (var media in card.Media)
                            {
                                var originalContentUrl = media?.Url?.Replace("http://", "https://");
                                var previewImageUrl    = card.Image?.Url?.Replace("http://", "https://");

                                messages.Add(new VideoMessage(originalContentUrl, previewImageUrl));
                            }

                            ButtonsTemplate buttonsTemplate = new ButtonsTemplate(
                                title: card.Title, text: $"{card.Subtitle}\r\n{card.Text}");
                            foreach (var button in card.Buttons)

                            {
                                buttonsTemplate.Actions.Add(GetAction(button));
                            }
                            messages.Add(new TemplateMessage("Buttons template", buttonsTemplate));
                        }
                        else if (attachment.ContentType.Contains("image"))
                        {
                            var originalContentUrl = attachment.ContentUrl?.Replace("http://", "https://");
                            var previewImageUrl    = string.IsNullOrEmpty(attachment.ThumbnailUrl) ? attachment.ContentUrl?.Replace("http://", "https://") : attachment.ThumbnailUrl?.Replace("http://", "https://");

                            messages.Add(new ImageMessage(originalContentUrl, previewImageUrl));
                        }
                        else if (attachment.ContentType.Contains("audio"))
                        {
                            var originalContentUrl     = attachment.ContentUrl?.Replace("http://", "https://");
                            var durationInMilliseconds = 0;

                            messages.Add(new AudioMessage(originalContentUrl, durationInMilliseconds));
                        }
                        else if (attachment.ContentType.Contains("video"))
                        {
                            var originalContentUrl = attachment.ContentUrl?.Replace("http://", "https://");
                            var previewImageUrl    = attachment.ThumbnailUrl?.Replace("http://", "https://");

                            messages.Add(new VideoMessage(originalContentUrl, previewImageUrl));
                        }
                    }
                }
                else if (activity.Attachments != null && activity.Attachments.Count != 0 && activity.AttachmentLayout != null)
                {
                    CarouselTemplate carouselTemplate = new CarouselTemplate();

                    foreach (var attachment in activity.Attachments)
                    {
                        HeroCard hcard = null;

                        if (attachment.ContentType == "application/vnd.microsoft.card.hero")
                        {
                            hcard = JsonConvert.DeserializeObject <HeroCard>(attachment.Content.ToString());
                        }
                        else if (attachment.ContentType == "application/vnd.microsoft.card.thumbnail")
                        {
                            ThumbnailCard tCard = JsonConvert.DeserializeObject <ThumbnailCard>(attachment.Content.ToString());
                            hcard = new HeroCard(tCard.Title, tCard.Subtitle, tCard.Text, tCard.Images, tCard.Buttons, null);
                        }
                        else
                        {
                            continue;
                        }

                        CarouselColumn tColumn = new CarouselColumn(
                            title: hcard.Title,
                            thumbnailImageUrl: hcard.Images.FirstOrDefault()?.Url?.Replace("http://", "https://"),
                            text: string.IsNullOrEmpty(hcard.Subtitle) ?
                            hcard.Text : hcard.Subtitle);

                        if (hcard.Buttons != null)
                        {
                            foreach (var button in hcard.Buttons.Take(3))
                            {
                                tColumn.Actions.Add(GetAction(button));
                            }
                        }
                        else
                        {
                            // Action is mandatory, so create from title/subtitle.
                            var actionLabel = hcard.Title?.Length < hcard.Subtitle?.Length ? hcard.Title : hcard.Subtitle;
                            actionLabel = actionLabel.Substring(0, Math.Min(actionLabel.Length, 20));
                            tColumn.Actions.Add(new PostbackTemplateAction(actionLabel, actionLabel, actionLabel));
                        }

                        carouselTemplate.Columns.Add(tColumn);
                    }

                    messages.Add(new TemplateMessage("Carousel template", carouselTemplate));
                }
                else if (activity.Entities != null && activity.Entities.Count != 0)
                {
                    foreach (var entity in activity.Entities)
                    {
                        switch (entity.Type)
                        {
                        case "Place":
                            Place          place = entity.Properties.ToObject <Place>();
                            GeoCoordinates geo   = JsonConvert.DeserializeObject <GeoCoordinates>(place.Geo.ToString());
                            messages.Add(new LocationMessage(place.Name, place.Address.ToString(), (decimal)geo.Latitude, (decimal)geo.Longitude));
                            break;

                        case "GeoCoordinates":
                            GeoCoordinates geoCoordinates = entity.Properties.ToObject <GeoCoordinates>();
                            messages.Add(new LocationMessage(activity.Text, geoCoordinates.Name, (decimal)geoCoordinates.Latitude, (decimal)geoCoordinates.Longitude));
                            break;
                        }
                    }
                }
                else if (activity.ChannelData != null)
                {
                }
                else if (!string.IsNullOrEmpty(activity.Text))
                {
                    if (activity.Text.Contains("\n\n*"))
                    {
                        var             lines           = activity.Text.Split(new[] { "\n\n" }, StringSplitOptions.RemoveEmptyEntries);
                        ButtonsTemplate buttonsTemplate = new ButtonsTemplate(text: lines[0]);

                        foreach (var line in lines.Skip(1))
                        {
                            buttonsTemplate.Actions.Add(new PostbackTemplateAction(line, line.Replace("* ", ""), line.Replace("* ", "")));
                        }

                        messages.Add(new TemplateMessage("Buttons template", buttonsTemplate));
                    }
                    else
                    {
                        messages.Add(new TextMessage(activity.Text));
                    }
                }

                try
                {
                    // If messages contain more than 5 items, then do reply for first 5, then push the rest.
                    for (int i = 0; i < (double)messages.Count / 5; i++)
                    {
                        if (i == 0)
                        {
                            await messagingClient.ReplyMessageAsync(replyToken, messages.Take(5).ToList());
                        }
                        else
                        {
                            await messagingClient.PushMessageAsync(replyToken, messages.Skip(i * 5).Take(5).ToList());
                        }
                    }
                }
                catch (LineResponseException ex)
                {
                    if (ex.Message == "Invalid reply token")
                    {
                        try
                        {
                            for (int i = 0; i < (double)messages.Count / 5; i++)
                            {
                                await messagingClient.PushMessageAsync(userId, messages.Skip(i * 5).Take(5).ToList());
                            }
                        }
                        catch (LineResponseException innerEx)
                        {
                            await messagingClient.PushMessageAsync(userId, innerEx.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    await messagingClient.PushMessageAsync(userId, ex.Message);
                }
            }
        }
Esempio n. 3
0
        public async Task Help(IDialogContext context, LuisResult result)
        {
            await context.PostAsync("Hi! I'm MUCY. Give me your flightnumber for information. " +
                                    "I can also navigate you to our homepage for booking a parking place or for career information. Or you can try asking me something else. :)");


            var resultMessage = context.MakeMessage();

            resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            resultMessage.Attachments      = new List <Attachment>();

            HeroCard heroCardFlight = new HeroCard()
            {
                Title  = "Flight",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000309917bb582f0564/besucherterrasse-3.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Details for my flight",
                        Type  = "imBack",
                        Value = "Details for my flight"
                    },
                    new CardAction()
                    {
                        Title = "Next departure flights",
                        Type  = "imBack",
                        Value = "Next departure flights"
                    },
                    new CardAction()
                    {
                        Title = "Next flight to...",
                        Type  = "imBack",
                        Value = "Next flight to..."
                    }
                }
            };

            HeroCard heroCardService = new HeroCard()
            {
                Title  = "Services",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000300370bb582dbbae/gastro-dallmayr-t2-kellner.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Recommended services",
                        Type  = "imBack",
                        Value = "Recommended services"
                    },
                    new CardAction()
                    {
                        Title = "Search service for ...",
                        Type  = "imBack",
                        Value = "Search service for ..."
                    },
                    new CardAction()
                    {
                        Title = "Events",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.com/events-1455138"
                    },
                }
            };

            HeroCard heroCardCareer = new HeroCard()
            {
                Title  = "Career at Munich Airport",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000293718bb582da737/it-mitarbeiter-computer.jpg"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Career starter/experienced",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/berufseinsteiger-erfahrene-94612"
                    },
                    new CardAction()
                    {
                        Title = "University graduate",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/trainee-94642"
                    },
                    new CardAction()
                    {
                        Title = "Student",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/studenten-94672"
                    },
                    new CardAction()
                    {
                        Title = "Pupil",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/schuler-94701"
                    }
                }
            };

            HeroCard heroCardNavigation = new HeroCard()
            {
                Title  = "Navigation",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.com/_b/0000000000000000416174bb58413a89/anreise-mit-transferdienst.jpg?t=eyJoZWlnaHQiOjgwMCwid2lkdGgiOjE0MDAsInF1YWxpdHkiOjc1fQ==--10cc77c47a7474cc6d92316be562f49e0d955ef7"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Parking place",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/parken-89995"
                    },
                    new CardAction()
                    {
                        Title = "Navigate me from ...",
                        Type  = "imBack",
                        Value = "Navigate me from ..."
                    },
                    new CardAction()
                    {
                        Title = "Travel by train/bus",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/offentliche-verkehrsmittel-90215"
                    },
                }
            };

            resultMessage.Attachments.Add(heroCardFlight.ToAttachment());
            resultMessage.Attachments.Add(heroCardService.ToAttachment());
            resultMessage.Attachments.Add(heroCardNavigation.ToAttachment());
            resultMessage.Attachments.Add(heroCardCareer.ToAttachment());
            await context.PostAsync(resultMessage);

            context.Wait(this.MessageReceived);
        }
Esempio n. 4
0
        public async Task GetRecommendedServices(IDialogContext context, LuisResult result)
        {
            var    restURL      = "https://a2textpaid.azurewebsites.net/";
            var    url          = restURL + "GetRecommendedServices?language=en-US";
            string responseBody = GET(url);

            GetRecommendedServices.RootObject serviceDetails = JsonConvert.DeserializeObject <GetRecommendedServices.RootObject>(responseBody);

            var resultMessage = context.MakeMessage();

            resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            resultMessage.Attachments      = new List <Attachment>();

            List <CardAction> cards = new List <CardAction>();

            foreach (GetRecommendedServices.Content c in serviceDetails.content)
            {
                cards.Add(new CardAction()
                {
                    Title = c.title
                });
                if (c.descriptionImage_horizontal.low != null)
                {
                    HeroCard heroCard = new HeroCard()
                    {
                        Title  = c.title,
                        Text   = c.description,
                        Images = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = c.descriptionImage_horizontal.low
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"https://www.munich-airport.de/suchergebnisseite-75217?utf8=%E2%9C%93&search_form_presenter[commit]=1&search_form_presenter[profile]=site_search&search_form_presenter[search_term]=" + c.title
                            }
                        }
                    };
                    resultMessage.Attachments.Add(heroCard.ToAttachment());
                }
                else
                {
                    HeroCard heroCard = new HeroCard()
                    {
                        Title  = c.title,
                        Text   = c.description,
                        Images = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = c.titleImage.low
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"https://www.munich-airport.de/suchergebnisseite-75217?utf8=%E2%9C%93&search_form_presenter[commit]=1&search_form_presenter[profile]=site_search&search_form_presenter[search_term]=" + c.title
                            }
                        }
                    };
                    resultMessage.Attachments.Add(heroCard.ToAttachment());
                }
            }
            await context.PostAsync(resultMessage);

            context.Wait(this.MessageReceived);
        }
Esempio n. 5
0
        private async Task ResumeAfterHotelsFormDialog(IDialogContext context, IAwaitable <HotelsQuery> result)
        {
            try
            {
                var searchQuery = await result;

                var hotels = await this.GetHotelsAsync(searchQuery);

                await context.PostAsync($"I found in total {hotels.Count()} hotels for your dates:");

                var resultMessage = context.MakeMessage();
                resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                resultMessage.Attachments      = new List <Attachment>();

                foreach (var hotel in hotels)
                {
                    HeroCard heroCard = new HeroCard()
                    {
                        Title    = hotel.Name,
                        Subtitle = $"{hotel.Rating} starts. {hotel.NumberOfReviews} reviews. From ${hotel.PriceStarting} per night.",
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = hotel.Image
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"https://www.bing.com/search?q=hotels+in+" + HttpUtility.UrlEncode(hotel.Location)
                            }
                        }
                    };

                    resultMessage.Attachments.Add(heroCard.ToAttachment());
                }

                await context.PostAsync(resultMessage);
            }
            catch (FormCanceledException ex)
            {
                string reply;

                if (ex.InnerException == null)
                {
                    reply = "You have canceled the operation. Quitting from the HotelsDialog";
                }
                else
                {
                    reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
                }

                await context.PostAsync(reply);
            }
            finally
            {
                context.Done <object>(null);
            }
        }
 protected override async Task OnMembersRemovedAsync(IList <ChannelAccount> membersRemoved, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
 {
     var heroCard = new HeroCard(text: $"{string.Join(' ', membersRemoved.Select(member => member.Id))} removed from {turnContext.Activity.Conversation.ConversationType}");
     await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
 }
 protected override async Task OnTeamsTeamRenamedAsync(TeamInfo teamInfo, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
 {
     var heroCard = new HeroCard(text: $"{teamInfo.Name} is the new Team name");
     await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
 }
Esempio n. 8
0
    private async Task <Activity> CreateReplyFromAzureSearchMappingAsync(ITurnContext turnContext, MessageMapping messageMapping, string azureSearchResultJson)
    {
        try
        {
            // Parse Json into AzureSearchResult structure
            JObject azureSearchResult = JObject.Parse(azureSearchResultJson);

            // select all returned values of the AzureSearchResult
            JArray searchResultArray = (JArray)azureSearchResult.SelectToken("value");

            var reply = turnContext.Activity.CreateReply();

            // Send default message, if there are no results
            if (searchResultArray?.Count == 0)
            {
                reply = await CreateMessageFromDialogStructureMessageAsync(turnContext, _dialogModel.DefaultMessage);

                return(reply);
            }

            reply.Attachments      = new List <Attachment>();
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Text             = messageMapping.Text;

            // Go through all search results
            foreach (JObject searchResult in searchResultArray.Children <JObject>())
            {
                // Create Image List
                var imageList = new List <CardImage>();

                // Get the value for the imageUrlPlaceholder from the mapping
                var imageUrlPlaceholder = messageMapping.Card.ImageUrl;

                // If the value exists, replace it with the value from the AzureSearchResult
                if (!String.IsNullOrEmpty(imageUrlPlaceholder))
                {
                    // Replace all occurences of searchResult properties with their respective values
                    var imageUrl = MapSearchResultsToString(imageUrlPlaceholder, searchResult);

                    // Add the image to the list
                    imageList.Add(
                        new CardImage {
                        Url = imageUrl
                    }
                        );
                }

                // Create Button List
                var buttonList = new List <CardAction>();

                if (messageMapping.Card.Options != null)
                {
                    foreach (var button in messageMapping.Card.Options)
                    {
                        buttonList.Add(new CardAction(
                                           Microsoft.Bot.Schema.ActionTypes.ImBack,
                                           title: button,
                                           value: button
                                           ));
                    }
                }


                var card = new HeroCard
                {
                    Images   = imageList,
                    Text     = MapSearchResultsToString(messageMapping.Card.Text, searchResult),
                    Title    = MapSearchResultsToString(messageMapping.Card.Title, searchResult),
                    Subtitle = MapSearchResultsToString(messageMapping.Card.Subtitle, searchResult),
                    Buttons  = buttonList
                };

                // Add the card to our reply.
                reply.Attachments.Add(card.ToAttachment());
            }

            return(reply);
        }
        catch (Exception e)
        {
            throw new Exception("[DialogMessageHandler] Error while mapping AzureSearchResult to Message format.", e);
        }
    }
Esempio n. 9
0
        /// <summary>
        /// Handles compose extension queries.
        /// </summary>
        /// <param name="activity">Incoming request from Bot Framework.</param>
        /// <param name="connectorClient">Connector client instance for posting to Bot Framework.</param>
        /// <returns>Task tracking operation.</returns>
        private static HttpResponseMessage HandleComposeExtensionQuery(Activity activity, ConnectorClient connectorClient)
        {
            // Get Compose extension query data.
            ComposeExtensionQuery composeExtensionQuery = activity.GetComposeExtensionQueryData();

            var searchTerm = composeExtensionQuery.Parameters.Single(p => p.Name == "Location").Value.ToString();

            var catalog = Products.Instance;
            var results = catalog.ProductCatalog.Where(p => p.SKU.StartsWith(searchTerm)).ToList();
            ComposeExtensionResponse response;

            if (results.Count > 0)
            {
                var attachments = new List <ComposeExtensionAttachment>();
                int i           = 1;
                foreach (var item in results)
                {
                    var result = new HeroCard
                    {
                        Buttons = new List <CardAction>
                        {
                            new CardAction
                            {
                                Type  = ActionTypes.OpenUrl,
                                Title = "Show in CMS",
                                Value = "https://www.bing.com"
                            },
                        },
                        Title    = $"{item.Name} - {item.SKU}",
                        Subtitle = "Item #" + item.SKU,
                        Text     = item.NumberInStock + " in stock.",
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = "https://placekitten.com/420/320?image=" + i
                            }
                        }
                    };
                    attachments.Add(result.ToAttachment().ToComposeExtensionAttachment());
                    i++;
                }



                response = new ComposeExtensionResponse
                {
                    ComposeExtension = new ComposeExtensionResult
                    {
                        Attachments      = attachments,
                        Type             = "result",
                        AttachmentLayout = "list"
                    }
                };
            }
            else
            {
                // Process data and return the response.
                response = new ComposeExtensionResponse
                {
                    ComposeExtension = new ComposeExtensionResult
                    {
                        Attachments = new List <ComposeExtensionAttachment>
                        {
                            new HeroCard
                            {
                                Title = "No results..."
                            }.ToAttachment().ToComposeExtensionAttachment()
                        },
                        Type             = "result",
                        AttachmentLayout = "list"
                    }
                };
            }


            StringContent       stringContent       = new StringContent(JsonConvert.SerializeObject(response));
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);

            httpResponseMessage.Content = stringContent;
            return(httpResponseMessage);
        }
Esempio n. 10
0
        private async Task ResumeAfterHotelsFormDialog(IDialogContext context, IAwaitable <HotelsQuery> result)
        {
            try
            {
                var searchQuery = await result;

                var hotels = await this.GetHotelsAsync(searchQuery);

                await context.PostAsync($"{AppConstant.FoundHotelMessage} {hotels.Count()} {AppConstant.HotelTextMessageNotification}");

                var resultMessage = context.MakeMessage();
                resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                resultMessage.Attachments      = new List <Attachment>();

                foreach (var hotel in hotels)
                {
                    HeroCard heroCard = new HeroCard()
                    {
                        Title    = hotel.Name,
                        Subtitle = $"Ratings:{hotel.Rating}",
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = hotel.Image
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,

                                Value = $"https://www.bing.com/search?q=hotels+in+" + HttpUtility.UrlEncode(hotel.Location)
                            }
                        }
                    };


                    resultMessage.Attachments.Add(heroCard.ToAttachment());
                }

                await context.PostAsync(resultMessage);
            }
            catch (FormCanceledException ex)
            {
                string reply;

                if (ex.InnerException == null)
                {
                    reply = AppConstant.CancelOperationMessage;
                }
                else
                {
                    reply = $"{AppConstant.OpsssTextMessage} {ex.InnerException.Message}";
                }

                await context.PostAsync(reply);
            }
            finally
            {
                context.Done <object>(null);
            }
        }
Esempio n. 11
0
        public FindFoodDialog() : base("Start")
        {
            _googleKey = "[YourGoogleKey]";

            _foodChoice = new List <Choice>()
            {
                new Choice {
                    Value = "餐廳"
                },
                new Choice {
                    Value = "中式"
                },
                new Choice {
                    Value = "日式"
                },
            };

            Dialogs.Add("Start",
                        new WaterfallStep[]
            {
                async(dc, args, next) =>
                {
                    await dc.Prompt(
                        "choicePrompt", "請選擇您想要的食物類型:",
                        new ChoicePromptOptions()
                    {
                        Choices           = _foodChoice,
                        RetryPromptString = "您輸入的資料不正確"
                    });
                },
                // 評分
                async(dc, args, next) =>
                {
                    var state = dc.Context.GetConversationState <Dictionary <string, object> >();
                    state.Add("FoodType", ((ChoiceResult)args).Value.Value);

                    await dc.Prompt(
                        "ratingPrompt", "請選擇您想要的最低評分: ( 1 ~ 5 )",
                        new PromptOptions()
                    {
                        RetryPromptString = "您輸入的資料不正確"
                    });
                },
                // 完成
                async(dc, args, next) =>
                {
                    var state = dc.Context.GetConversationState <Dictionary <string, object> >();

                    var rating = ((NumberResult <int>)args).Value;

                    var client = new HttpClient();
                    var res    = await client.GetAsync($"https://maps.googleapis.com/maps/api/place/nearbysearch/json?" +
                                                       $"location=25.040585,121.5648247&radius=1000&query={state["FoodType"]}&" +
                                                       $"language=zh-tw&key={_googleKey}");
                    res.EnsureSuccessStatusCode();

                    string json          = await res.Content.ReadAsStringAsync();
                    var restaurantResult = JsonConvert.DeserializeObject <RestaurantResult>(json);

                    await dc.Context.SendActivity($"我找到了 {restaurantResult.Results.Count()} 家餐廳:");
                    var activity = MessageFactory.Carousel(new List <Attachment>());

                    foreach (var restaurant in restaurantResult.Results)
                    {
                        if (restaurant.Rating > rating)
                        {
                            HeroCard heroCard = new HeroCard()
                            {
                                Title    = restaurant.Name,
                                Subtitle = $"{restaurant.Rating} starts.",
                                Images   = new List <CardImage>()
                                {
                                    new CardImage()
                                    {
                                        Url =
                                            $"https://maps.googleapis.com/maps/api/place/photo?maxwidth=200&photoreference=" +
                                            $"{restaurant.Photos[0].PhotoReference}&key={_googleKey}"
                                    }
                                },
                                Buttons = new List <CardAction>()
                                {
                                    new CardAction()
                                    {
                                        Title = "更多詳情",
                                        Type  = ActionTypes.OpenUrl,
                                        Value = $"https://www.bing.com/search?q={restaurant.Name}"
                                    }
                                }
                            };

                            activity.Attachments.Add(heroCard.ToAttachment());
                        }
                    }

                    await dc.Context.SendActivity(activity);
                    await dc.End();
                }
            }
                        );

            Dialogs.Add("choicePrompt", new Microsoft.Bot.Builder.Dialogs.ChoicePrompt(
                            Culture.English, async(context, result) =>
            {
                if (!_foodChoice.Select(m => m.Value).Contains(result.Value.Value))
                {
                    await context.SendActivity("輸入不正確,請重新輸入");
                    result.Status = PromptStatus.NotRecognized;
                }
            })
            {
                Style = ListStyle.Auto
            });

            Dialogs.Add("ratingPrompt", new Microsoft.Bot.Builder.Dialogs.NumberPrompt <int>(
                            Culture.English, async(context, result) =>
            {
                if (result.Value < 0)
                {
                    await context.SendActivity("輸入錯誤");
                    result.Status = PromptStatus.TooSmall;
                }

                if (result.Value > 5)
                {
                    await context.SendActivity("輸入錯誤");
                    result.Status = PromptStatus.TooBig;
                }
            }));
        }
Esempio n. 12
0
        /// <summary>
        /// 刷新商城的英雄显示信息
        /// </summary>
        /// <param name="goodsId"></param>
        private void RefreshMarketHeroList(int goodsId)
        {
            HeroCard card = GetCardByGoodsId(goodsId);

            this.DeltCardInfo(goodsId, card);
        }
Esempio n. 13
0
        private async Task <Activity> GetAvaialableAgentOptionsCard(Activity activity)
        {
            Activity messageActivity = activity.CreateReply();
            string   commandKeyword  = $"{Commands.CommandKeyword}/@{activity.Recipient.Name}";
            string   acceptCommand   = $"{Commands.CommandKeyword} {Commands.CommandAcceptRequest} *requestId*";
            string   rejectCommand   = $"{Commands.CommandKeyword} {Commands.CommandRejectRequest} *requestId*";

            HeroCard thumbnailCard = new HeroCard()
            {
                Title    = "Agent menu",
                Subtitle = "Agent/supervisor options for controlling end user bot conversations",
                Text     = $"Select from the buttons below.\n\nOr type \"{commandKeyword}\" followed by the keyword, eg. \"{acceptCommand}\"",
                Buttons  = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Watch",
                        Type  = ActionTypes.PostBack,
                        Value = Commands.CommandAddAggregationChannel
                    },
                    new CardAction()
                    {
                        Title = "Connect",
                        Type  = ActionTypes.PostBack,
                        Value = acceptCommand
                    },
                    new CardAction()
                    {
                        Title = "Disconnect",
                        Type  = ActionTypes.PostBack,
                        Value = Commands.CommandEndEngagement
                    },
                    //new CardAction()
                    //{
                    //    Title = "Reject",
                    //    Type = ActionTypes.PostBack,
                    //    Value = rejectCommand
                    //},
                    new CardAction()
                    {
                        Title = "List active",
                        Type  = ActionTypes.PostBack,
                        Value = $"{Commands.CommandKeyword} {Commands.CommandListEngagements}"
                    },
                    new CardAction()
                    {
                        Title = "List waiting",
                        Type  = ActionTypes.PostBack,
                        Value = $"{Commands.CommandKeyword} {Commands.CommandListPendingRequests}"
                    },
                    new CardAction()
                    {
                        Title = "List all",
                        Type  = ActionTypes.PostBack,
                        Value = $"{Commands.CommandKeyword} {Commands.CommandListAllParties}"
                    },

                    new CardAction()
                    {
                        Title = "Reset",
                        Type  = ActionTypes.PostBack,
                        Value = Commands.CommandDeleteAllRoutingData
                    }
                }
            };

            messageActivity.Attachments = new List <Attachment>()
            {
                thumbnailCard.ToAttachment()
            };
            return(messageActivity);
        }
Esempio n. 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)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient   connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                Luis.LuisTemplate res       = await Luis.GetIntent.FetchTemplateAsync(activity.Text);

                string Intent = res.intents[0].intent;

                Activity reply;

                if (activity.Text.Contains("@email:"))
                {
                    string[] result = await GetFromEmail.get(activity.Text.Substring(7));

                    reply = activity.CreateReply(result[0]);
                    connector.Conversations.ReplyToActivity(reply);
                    reply = activity.CreateReply(result[1]);
                    connector.Conversations.ReplyToActivity(reply);
                    reply = activity.CreateReply(result[2]);
                }

                else if (Intent.Equals("FindFriend"))
                {
                    if (res.entities.Length > 0)
                    {
                        List <string> emails = await GetFromName.get(res.entities[0].entity);

                        reply                  = activity.CreateReply("Here are the users with the name : " + res.entities[0].entity);
                        reply.Recipient        = activity.From;
                        reply.Type             = "message";
                        reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                        reply.Attachments      = new List <Attachment>();

                        foreach (var x in emails)
                        {
                            List <CardImage> images = new List <CardImage>();
                            images.Add(new CardImage("http://nulm.gov.in/images/user.png"));

                            List <CardAction> actions = new List <CardAction>();
                            CardAction        action  = new CardAction()
                            {
                                Value = "@email:" + x,
                                Type  = ActionTypes.PostBack,
                                Title = "FIND"
                            };
                            actions.Add(action);

                            HeroCard card = new HeroCard()
                            {
                                Images   = images,
                                Buttons  = actions,
                                Title    = "Email",
                                Subtitle = x
                            };

                            Attachment a = card.ToAttachment();
                            reply.Attachments.Add(a);
                        }
                        reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    }
                    else
                    {
                        reply = activity.CreateReply("Sorry, I did not understand that");
                    }
                }

                else
                {
                    reply = activity.CreateReply("Sorry, I did not understand that");
                }
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Esempio n. 15
0
        /// <summary>
        ///     This will get called after returning from the QnA
        /// </summary>
        /// <param name="context">The current chat context</param>
        /// <param name="result">The IAwaitable result</param>
        /// <returns></returns>
        private async Task AfterQnA(IDialogContext context, IAwaitable <object> result)
        {
            string message = null;

            try
            {
                message = (string)await result;
            }
            catch (Exception e)
            {
                await context.PostAsync($"QnAMaker: {e.Message}");

                // Wait for the next message
                context.Wait(MessageReceivedAsync);
            }

            // Display the answer from QnA Maker Service
            var answer = message;

            if (((IMessageActivity)context.Activity).Text.ToLowerInvariant().Contains("trivia"))
            {
                // Since we are not needing to pass any message to start trivia, we can use call instead of forward
                context.Call(new TriviaDialog(), AfterTrivia);
            }
            else if (!string.IsNullOrEmpty(answer))
            {
                Activity reply = ((Activity)context.Activity).CreateReply();

                string[] qnaAnswerData = answer.Split('|');
                string   title         = qnaAnswerData[0];
                string   description   = qnaAnswerData[1];
                string   url           = qnaAnswerData[2];
                string   imageURL      = qnaAnswerData[3];

                if (title == "")
                {
                    char charsToTrim = '|';
                    await context.PostAsync(answer.Trim(charsToTrim));
                }

                else
                {
                    HeroCard card = new HeroCard
                    {
                        Title    = title,
                        Subtitle = description,
                    };
                    card.Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.OpenUrl, "Learn More", value: url)
                    };
                    card.Images = new List <CardImage>
                    {
                        new CardImage(url = imageURL)
                    };
                    reply.Attachments.Add(card.ToAttachment());
                    await context.PostAsync(reply);
                }
                context.Wait(MessageReceivedAsync);
            }
            else
            {
                await context.PostAsync("No good match found in KB.");

                int length = (((IMessageActivity)context.Activity).Text ?? string.Empty).Length;
                await context.PostAsync($"You sent {((IMessageActivity)context.Activity).Text} which was {length} characters");

                context.Wait(MessageReceivedAsync);
            }
        }
Esempio n. 16
0
        private async Task SelectAnwendung(IDialogContext context, IAwaitable <Anwendung> anwendung)
        {
            IMessageActivity msg = context.MakeMessage();

            msg.Type        = "message";
            msg.Attachments = new List <Attachment>();
            List <CardImage>  cardImages  = new List <CardImage>();
            List <CardAction> cardButtons = new List <CardAction>();
            CardAction        plButton    = null;
            HeroCard          plCard      = null;

            switch (await anwendung)
            {
            case Anwendung.Office:
                context.ConversationData.SetValue <string>("anwendung", "office");

                cardImages.Add(new CardImage(url: "https://uqzqqq-bn1305.files.1drv.com/y3pR8K3P3Qdr7gkcPmrE_rSyVHYuOQ4-Azt_4fEA4fp4K8pSclujdIV4JGrbRtj-zMY9ADPJikimo7xQqam6ZYFQkurm-wVd-eCUUo2-baqNt-WcAu5HXusFrSmUFGCh94wsJbkLNGSHSXmTW2tzS1rIQ/Drucken%20MS%20Office.jpg?psid=1"));

                plButton = new CardAction()
                {
                    Value = "https://1drv.ms/b/s!AsBP--kaOJEKgfBlOHEU36x3VwMG8A",
                    Type  = "openUrl",
                    Title = "Zur Anleitung"
                };

                plCard = new HeroCard()
                {
                    Title    = "Office Beidseitigdrucken",
                    Subtitle = "Beschreibung wie man im Office das Beidseitigdrucken einstellt.",
                    Images   = cardImages,
                    Buttons  = cardButtons
                };
                break;

            case Anwendung.Windows:
                context.ConversationData.SetValue <string>("anwendung", "windows");

                cardImages.Add(new CardImage(url: "https://uqzqqq-bn1305.files.1drv.com/y3pR8K3P3Qdr7gkcPmrE_rSyVHYuOQ4-Azt_4fEA4fp4K8pSclujdIV4JGrbRtj-zMY9ADPJikimo7xQqam6ZYFQkurm-wVd-eCUUo2-baqNt-WcAu5HXusFrSmUFGCh94wsJbkLNGSHSXmTW2tzS1rIQ/Drucken%20MS%20Office.jpg?psid=1"));

                plButton = new CardAction()
                {
                    Value = "https://1drv.ms/b/s!AsBP--kaOJEKgfBlOHEU36x3VwMG8A",
                    Type  = "openUrl",
                    Title = "Zur Anleitung"
                };

                plCard = new HeroCard()
                {
                    Title    = "Windows-Anwendungen Beidseitigdrucken",
                    Subtitle = "Beschreibung wie man in Windows-Anwendungen das Beidseitigdrucken einstellt.",
                    Images   = cardImages,
                    Buttons  = cardButtons
                };
                break;

            default:
                break;
            }
            cardButtons.Add(plButton);

            Attachment plAttachment = plCard.ToAttachment();

            msg.Attachments.Add(plAttachment);

            await context.PostAsync(msg);

            context.Wait(MessageReceived);
        }
Esempio n. 17
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var      reply2 = await argument as Activity;
            Activity reply  = reply2.CreateReply();
            string   base64String;
            string   image64;

            try
            {
                using (Image image = Image.FromFile(HttpContext.Current.Server.MapPath("~/bomb300.png")))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        image.Save(m, image.RawFormat);
                        byte[] imageBytes = m.ToArray();

                        // Convert byte[] to Base64 String
                        base64String = Convert.ToBase64String(imageBytes);
                    }
                }
                image64 = "data:image/png;base64," + base64String;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

//            var reply2 = await argument as Activity;
//            Activity reply = reply2.CreateReply();
//            string base64String;
//            string image64;
//            Attachment pdf;
//            try
//            {
//                //This was written for images, so you can display something else here if you would like
//                Byte[] bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/bomb300.png"));
//                base64String = Convert.ToBase64String(bytes);
//                image64 = "data:image/png;base64," + base64String;
//                reply.Attachments = new List<Attachment>();
//                pdf = new Attachment(contentType: "image/png", content: image64);
//                reply.Attachments.Add(pdf);
//            }
//            catch (Exception e)
//            {
//                Console.WriteLine(e);
//                throw;
//            }
//            await context.PostAsync(reply);
//
//
            var      absolute         = System.Web.VirtualPathUtility.ToAbsolute("~/bomb300.png");
            Uri      resourceFullPath = new Uri(_baseUri, absolute);
            HeroCard heroCard         = new HeroCard()
            {
                Images = new List <CardImage>
                {
                    new CardImage(
                        url: image64)
                },
                Tap = new CardAction()
                {
                    Value = resourceFullPath,
                    Type  = "openUrl",
                }
            };

            reply.Attachments = new List <Attachment>
            {
                heroCard.ToAttachment()
            };
            await context.PostAsync(reply);

            context.Wait(MessageReceivedAsync);
        }
Esempio n. 18
0
        public async Task Events(IDialogContext context, LuisResult result)
        {
            var resultMessage = context.MakeMessage();

            resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            resultMessage.Attachments      = new List <Attachment>();

            HeroCard card1 = new HeroCard()
            {
                Title  = "Aussichtsterrasse",
                Text   = "Im Terminal 2 gibt es eine kostenlose Aussichtsterrasse mit Blick auf das Vorfeld und das neue Satellitengebäude.",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000968171bb587df491/ATF9913.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                }
            };
            HeroCard card2 = new HeroCard()
            {
                Title  = "Besucherpark",
                Text   = "Besucherhügel - Tante Ju - Erlebnisspielplatz. Der nächste Familienausflug kann kommen! Für Souveniers ist auch gesorgt.",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000308893bb582ef909/besucherpark-luftbild.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                }
            };
            HeroCard card3 = new HeroCard()
            {
                Title  = "Airport-Touren",
                Text   = "Wie kommt der Koffer in den Flieger? Wie wird getankt? Woher kommt das Frischwasser? Bei den Airport-Touren bist du mittendrin!",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000001562517bb58c7c9b5/airporttour-bus1.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Touren",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/airport-touren-90392"
                    }
                }
            };
            HeroCard card4 = new HeroCard()
            {
                Title  = "Events",
                Text   = "Wintermarkt, Surf & Style, Public Viewing... Auf dem Campus gibt es das ganze Jahr tolle Attraktionen!",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000966385bb587de620/2013-08-10-surf-style-02-flo-hagena.jpg"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Events",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/events-90512"
                    }
                }
            };

            resultMessage.Attachments.Add(card1.ToAttachment());
            resultMessage.Attachments.Add(card2.ToAttachment());
            resultMessage.Attachments.Add(card3.ToAttachment());
            resultMessage.Attachments.Add(card4.ToAttachment());
            await context.PostAsync(resultMessage);

            context.Wait(MessageReceived);
        }
 protected override async Task OnTeamsChannelDeletedAsync(ChannelInfo channelInfo, TeamInfo teamInfo, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
 {
     var heroCard = new HeroCard(text: $"{channelInfo.Name} is the Channel deleted");
     await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
 }
Esempio n. 20
0
        public async Task Service(IDialogContext context, LuisResult result)
        {
            await context.PostAsync("Dir ist langweilig?");

            Thread.Sleep(2000);
            await context.PostAsync("Da weiß ich einiges!");

            Thread.Sleep(1000);

            var resultMessage = context.MakeMessage();

            resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            resultMessage.Attachments      = new List <Attachment>();

            HeroCard card1 = new HeroCard()
            {
                Title  = "Shopping",
                Text   = "Egal ob Souvenirs, Fashion oder Duty Free Schnäppchen - unsere rund 170 Shops lassen keine Wünsche offen!",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000398383bb583d7ba6/shopping-assistant.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Shops",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/shops-90739"
                    }
                }
            };
            HeroCard card2 = new HeroCard()
            {
                Title  = "Essen & Trinken",
                Text   = "Ca. 50 Restaurants, Cafés und Bistros bieten eine große Auswahl an Speisen. Von bayerisch bis asiatisch ist für jeden was dabei.",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000276318bb582c2405/gastronomie_flughafen1.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Restaurants",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/restaurants-90769"
                    }
                }
            };
            HeroCard card3 = new HeroCard()
            {
                Title  = "Events",
                Text   = "Ein Ausflug zum Besucherpark oder doch lieber eine Tour durch den Flughafen? Hier sind alle Möglichkeiten im Überblick.",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000760907bb585d0e23/familie-auf-besucherhuegel.jpg?t=eyJoZWlnaHQiOjM0Mywid2lkdGgiOjYwMCwicXVhbGl0eSI6NzV9--386e466d2d6748ab82a85b7bb62f54d37c93007b"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Events",
                        Type  = "imBack",
                        Value = "Events"
                    }
                }
            };

            resultMessage.Attachments.Add(card1.ToAttachment());
            resultMessage.Attachments.Add(card2.ToAttachment());
            resultMessage.Attachments.Add(card3.ToAttachment());
            await context.PostAsync(resultMessage);

            context.Wait(MessageReceived);
        }
 protected override async Task OnTeamsMembersAddedAsync(IList <ChannelAccount> membersAdded, TeamInfo teamInfo, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
 {
     var heroCard = new HeroCard(text: $"{string.Join(' ', membersAdded.Select(member => member.Id))} joined {teamInfo.Name}");
     await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
 }
Esempio n. 22
0
        public async Task Hilfe(IDialogContext context, LuisResult result)
        {
            await context.PostAsync("Hier habe ich Vorschläge für dich, welche Fragen du mir stellen kannst. Du kannst auch etwas anderes versuchen.");


            var resultMessage = context.MakeMessage();

            resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            resultMessage.Attachments      = new List <Attachment>();

            HeroCard heroCardFlight = new HeroCard()
            {
                Title  = "Flug",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000309917bb582f0564/besucherterrasse-3.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Flugdetails",
                        Type  = "imBack",
                        Value = "Details zu meinem Flug"
                    },
                    new CardAction()
                    {
                        Title = "Nächste Ablüge",
                        Type  = "imBack",
                        Value = "Was sind die nächsten Abflüge?"
                    },
                    new CardAction()
                    {
                        Title = "Nächster Flug nach...",
                        Type  = "imBack",
                        Value = "Nächster Flug nach..."
                    }
                }
            };

            HeroCard heroCardService = new HeroCard()
            {
                Title  = "Services",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000300370bb582dbbae/gastro-dallmayr-t2-kellner.jpg?t=eyJoZWlnaHQiOjU5NCwid2lkdGgiOjEwNDAsInF1YWxpdHkiOjc1fQ==--8bc9b0db14da84b92a0700825434d855749ba85f"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Service Empfehlungen",
                        Type  = "imBack",
                        Value = "Service Empfehlungen"
                    },
                    new CardAction()
                    {
                        Title = "Servicesuche",
                        Type  = "imBack",
                        Value = "Suche nach..."
                    },
                    new CardAction()
                    {
                        Title = "Events",
                        Type  = "imBack",
                        Value = "Events"
                    },
                }
            };

            HeroCard heroCardKarriere = new HeroCard()
            {
                Title  = "Karriere am Flughafen",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.de/_b/0000000000000000293718bb582da737/it-mitarbeiter-computer.jpg"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Einsteiger/Erfahrene",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/berufseinsteiger-erfahrene-94612"
                    },
                    new CardAction()
                    {
                        Title = "Trainee",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/trainee-94642"
                    },
                    new CardAction()
                    {
                        Title = "Student",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/studenten-94672"
                    },
                    new CardAction()
                    {
                        Title = "Schüler",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/schuler-94701"
                    },
                    new CardAction()
                    {
                        Title = "Stellenangebote",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/stellenangebote-94732"
                    }
                }
            };

            HeroCard heroCardNavigation = new HeroCard()
            {
                Title  = "Navigation",
                Images = new List <CardImage>()
                {
                    new CardImage()
                    {
                        Url = "https://www.munich-airport.com/_b/0000000000000000416174bb58413a89/anreise-mit-transferdienst.jpg?t=eyJoZWlnaHQiOjgwMCwid2lkdGgiOjE0MDAsInF1YWxpdHkiOjc1fQ==--10cc77c47a7474cc6d92316be562f49e0d955ef7"
                    }
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Parkplatz",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/parken-89995"
                    },
                    new CardAction()
                    {
                        Title = "Auto Route",
                        Type  = "imBack",
                        Value = "Navigiere mich von..."
                    },
                    new CardAction()
                    {
                        Title = "Bahn/Bus",
                        Type  = ActionTypes.OpenUrl,
                        Value = $"https://www.munich-airport.de/offentliche-verkehrsmittel-90215"
                    },
                }
            };

            resultMessage.Attachments.Add(heroCardFlight.ToAttachment());
            resultMessage.Attachments.Add(heroCardService.ToAttachment());
            resultMessage.Attachments.Add(heroCardNavigation.ToAttachment());
            resultMessage.Attachments.Add(heroCardKarriere.ToAttachment());
            await context.PostAsync(resultMessage);

            context.Wait(MessageReceived);
        }
Esempio n. 23
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                StateClient stateClient = activity.GetStateClient();
                BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                var    userMessage = activity.Text;
                string endOutput   = "Hello";
                int    isCRRequest = 1;


                // get appointment function, interact with database
                if (userMessage.ToLower().Equals("get appointments"))
                {
                    List <TimeTable> timerecord = await AzureManager.AzureManagerInstance.GetTimerecords();

                    endOutput = "";
                    foreach (TimeTable t in timerecord)
                    {
                        endOutput += t.Ticketnum + "------------------" + t.Meettime + "\n\n";
                    }

                    isCRRequest = 2;
                }



                // create a card with login and call button
                if (userMessage.ToLower().Equals("contoso"))
                {
                    Activity replyToConversation = activity.CreateReply("Contoso Bank--Fluent in finance");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();
                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://cdn5.f-cdn.com/contestentries/699966/15508968/57a8d7ac18e0b_thumb900.jpg"));
                    List <CardAction> cardButtons = new List <CardAction>();



                    CardAction plButton1 = new CardAction()
                    {
                        Value = "https://bancocontoso.azurewebsites.net/",
                        Type  = "openUrl",
                        Title = "Login"
                    };
                    cardButtons.Add(plButton1);

                    CardAction plButton6 = new CardAction()
                    {
                        Value = "Make an appointment",
                        Type  = "imBack",
                        Title = "Make an appointment"
                    };
                    cardButtons.Add(plButton6);

                    CardAction plButton2 = new CardAction()
                    {
                        Value = "0640211227149",
                        Type  = "call",
                        Title = "Contact us"
                    };
                    cardButtons.Add(plButton2);

                    HeroCard plCard = new HeroCard()
                    {
                        Title   = "Address:",
                        Text    = "301-G050, Science building, University of Auckland",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }


                // if receive hello, a card is pop up, this card has a button to call the other card
                if (userMessage.ToLower().Equals("hello"))
                {
                    Activity replyToConversation = activity.CreateReply("Hello, now is " + System.DateTime.Now);
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();
                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://cdn5.f-cdn.com/contestentries/699966/15508968/57a8d7ac18e0b_thumb900.jpg"));
                    List <CardAction> cardButtons = new List <CardAction>();

                    CardAction plButton3 = new CardAction()
                    {
                        Value = "https://www.microsoft.com/en-nz/",
                        Type  = "openUrl",
                        Title = "Go to website"
                    };
                    cardButtons.Add(plButton3);

                    CardAction plButton4 = new CardAction()
                    {
                        Value = "contoso",
                        Type  = "imBack",
                        Title = "More function"
                    };
                    cardButtons.Add(plButton4);



                    HeroCard plCard = new HeroCard()
                    {
                        Text    = "Please reply the name of currency to check the currency rate, or you can click the button for services.",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }



                // how to reply
                if (isCRRequest == 2)
                {
                    // return our reply to the user
                    Activity infoReply = activity.CreateReply(endOutput);

                    await connector.Conversations.ReplyToActivityAsync(infoReply);
                }

                else
                {
                    // calculate the currency rate to return
                    CurRateObjects.RootObject rootObject;
                    HttpClient client = new HttpClient();
                    string     x      = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + activity.Text));

                    rootObject = JsonConvert.DeserializeObject <CurRateObjects.RootObject>(x);
                    double currentRate = 1 / rootObject.rates.NZD;
                    string money       = activity.Text;

                    // return our reply to the user
                    Activity reply = activity.CreateReply($"Currently, 1 NZD = {currentRate} {money}");
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }



            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Esempio n. 24
0
        //SEARCH
        public static async Task Search(IDialogContext context, OptionsSearch OS, DocumentSearchResult <object> searchResults)
        {
            int nResults = 0;
            SearchResult <object> searchResult;


            int i     = 0;
            int Total = 0;

            while (i < searchResults.Results.Count)
            {
                if (searchResults.Results[i].Score > 0.25)
                {
                    Total++;
                }
                i++;
            }
            string sMsg = "Found ";

            if (Total > 1)
            {
                sMsg += Total + " entries ";
            }
            else
            {
                if (Total == 0)
                {
                    sMsg += " no entries ";
                }
                else
                {
                    sMsg += "one entry ";
                }
            }
            //sMsg += "with score > 0.25";
            if (Total > int.Parse(OS.MaxResults))
            {
                sMsg += " Showing the first " + OS.MaxResults + ".";
            }
            await context.PostAsync(sMsg);


            var replyMessage0    = context.MakeMessage();
            List <Attachment> LA = new List <Attachment>();

            if (searchResults.Results.Count > 0)
            {
                var item = searchResults.Results[0].Highlights;
                var s    = item["content"];
                foreach (var item2 in s)
                {
                    string     item3 = item2.Replace("<em>", "**").Replace("</em>", "**");
                    Attachment A1    = new HeroCard()
                    {
                        Text = item3
                               //Buttons = new List<CardAction>() { CA }
                    }
                    .ToAttachment();
                    LA.Add(A1);
                }
                replyMessage0.Attachments = LA;
                await context.PostAsync(replyMessage0);
            }

            LA = new List <Attachment>();
            var replyMessage = context.MakeMessage();

            while (nResults < int.Parse(OS.MaxResults) && nResults < searchResults.Results.Count)
            {
                searchResult = searchResults.Results[nResults];
                if (searchResult.Score > 0.25)
                {
                    Dictionary <string, object> LC = JsonConvert.DeserializeObject <Dictionary <string, object> >(searchResult.Document.ToString());

                    CardAction CA = new CardAction(ActionTypes.ImBack, searchResult.Score.ToString(), null, "value");
                    //replyMessage.Text = "**" + LC[OS.FieldQ] + "**";
                    int mT = LC[OS.FieldA].ToString().Length;
                    int mC = LC[OS.FieldQ].ToString().Length;
                    if (mT > 200)
                    {
                        mT = 200;
                    }
                    if (mC > 200)
                    {
                        mC = 200;
                    }
                    Attachment A = new HeroCard()
                    {
                        Text     = "**" + LC[OS.FieldA].ToString().Substring(0, mT) + "**",
                        Subtitle = LC[OS.FieldQ].ToString().Substring(0, mC),
                        //Buttons = new List<CardAction>() { CA }
                    }
                    .ToAttachment();
                    //LA.Add(A);
                    //await context.PostAsync("Score:" + searchResult.Score);
                }
                nResults++;
            }
            if (LA.Count > 0)
            {
                replyMessage.Attachments = LA;
                await context.PostAsync(replyMessage);
            }
        }
Esempio n. 25
0
        private static async Task <DialogTurnResult> FindShopStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            string Input = (string)stepContext.Result;

            string     site    = Startup.KakaoAPI;
            string     query   = string.Format("{0}?query={1}", site, Input + " 서브웨이");
            WebRequest request = WebRequest.Create(query);
            string     rkey    = Startup.KakaoKey;

            string header = "KakaoAK " + rkey;

            request.Headers.Add("Authorization", header);

            WebResponse  response = request.GetResponse();
            Stream       stream   = response.GetResponseStream();
            StreamReader reader   = new StreamReader(stream, Encoding.UTF8);

            string json = reader.ReadToEnd();

            stream.Close();

            JObject jtemp = JObject.Parse(json);
            JArray  array = JArray.Parse(jtemp["documents"].ToString());

            var attachments = new List <Attachment>();
            var reply       = MessageFactory.Attachment(attachments);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            List <string> places = new List <string>();

            places.Add("다시 검색하기");
            if (array.Count < 1)
            {
                await stepContext.Context.SendActivityAsync("검색 결과가 없습니다.");

                return(await stepContext.ReplaceDialogAsync(nameof(LocationDialog)));
            }
            foreach (JObject jobj in array)
            {
                string place_name   = jobj["place_name"].ToString();
                string phone        = jobj["phone"].ToString();
                string address_name = jobj["address_name"].ToString();
                places.Add(place_name);

                string id       = jobj["id"].ToString();
                string kakaoUrl = "https://map.kakao.com/link/to/" + id;

                var heroCard = new HeroCard
                {
                    Title    = place_name,
                    Subtitle = phone,
                    Text     = address_name,
                    Buttons  = new List <CardAction>
                    {
                        new CardAction(ActionTypes.OpenUrl, value: kakaoUrl, title: "카카오맵에서 확인하기"),
                        new CardAction(ActionTypes.PostBack, "여기서 주문하기", value: place_name)
                    },
                };
                reply.Attachments.Add(heroCard.ToAttachment());
            }
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("주문할 서브웨이 지점을 선택하세요"), cancellationToken);

            await stepContext.Context.SendActivityAsync(reply, cancellationToken);

            return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                 new PromptOptions
            {
                Choices = ChoiceFactory.ToChoices(places),
            }, cancellationToken));
        }
Esempio n. 26
0
        private IMessageActivity BuildMessage(IDialogContext context, BrickItem retbrick)
        {
            var reply = context.MakeMessage();

            if ((retbrick.BrickService == ServiceProvider.Bricklink) || (retbrick.BrickService == ServiceProvider.Brickset) ||
                (retbrick.BrickService == ServiceProvider.Rebrickable) || (retbrick.BrickService == ServiceProvider.Peeron))
            {
                reply.Attachments = new List <Attachment>();
                List <CardAction> cardButtons = new List <CardAction>();
                if (retbrick.Instructions != null)
                {
                    foreach (var inst in retbrick.Instructions)
                    {
                        cardButtons.Add(new CardAction()
                        {
                            Title = inst.Name, Value = inst.URL, Type = "openUrl"
                        });
                    }
                }
                HeroCard plCard = new HeroCard()
                {
                    Title = $"# {retbrick.Number} - {retbrick.Name}"
                };
                if (retbrick.ThumbnailUrl != null)
                {
                    if (retbrick.ThumbnailUrl != "")
                    {
                        List <CardImage> cardImages = new List <CardImage>();
                        cardImages.Add(new CardImage(url: retbrick.ThumbnailUrl));
                        plCard.Images = cardImages;
                    }
                }
                if (retbrick.BrickURL != null)
                {
                    if (retbrick.BrickURL != "")
                    {
                        cardButtons.Add(new CardAction()
                        {
                            Title = $"{retbrick.BrickService.ToString()} page", Value = retbrick.BrickURL, Type = "openUrl"
                        });
                    }
                }
                plCard.Buttons  = cardButtons;
                plCard.Subtitle = $"Theme: {retbrick.Theme}";
                if (retbrick.YearReleased != 0)
                {
                    plCard.Subtitle += $" - Year: {retbrick.YearReleased}";
                }
                else
                {
                    plCard.Subtitle += " - Year unknown";
                }
                if (retbrick.Color != null)
                {
                    if (retbrick.Color != "")
                    {
                        plCard.Subtitle += $" - Color: {retbrick.Color}";
                    }
                }
                //string setcurrency;
                //need to implement a way to check the currncy.
                //context.PrivateConversationData.TryGetValue(BrickBotRes.CurrencyValue, out setcurrency);
                if (retbrick.BrickService == ServiceProvider.Bricklink)
                {
                    if (retbrick.New.Average != 0)
                    {
                        plCard.Text += $"New min {retbrick.New.Min.ToString("0.00")}; max {retbrick.New.Max.ToString("0.00")}; avg {retbrick.New.Average.ToString("0.00")} {retbrick.New.Currency}. ";
                    }
                    if (retbrick.Used.Average != 0)
                    {
                        plCard.Text += $"Used min {retbrick.Used.Min.ToString("0.00")}; max {retbrick.Used.Max.ToString("0.00")}; avg {retbrick.Used.Average.ToString("0.00")} {retbrick.Used.Currency}. ";
                    }
                }
                else
                if (retbrick.New?.Average != null)
                {
                    if (retbrick.New.Average != 0)
                    {
                        plCard.Text += $"Price {retbrick.New.Average} {retbrick.New.Currency}";
                    }
                }

                reply.Attachments.Add(plCard.ToAttachment());
            }
            return(reply);
        }
Esempio n. 27
0
        public async Task GetMyFlight(IDialogContext context, LuisResult result)
        {
            var entities = new List <EntityRecommendation>(result.Entities);

            if (entities.Any((entity) => entity.Type == "Flightnumber"))
            {
                var flugnummer = entities.Where((entity) => entity.Type == "Flightnumber").First();
                flightNoStr = flugnummer.Entity ?? null;

                airlineStr = flightNoStr.Substring(0, 2);
                numberStr  = flightNoStr.Substring(2, flightNoStr.Length - 2);

                var    restURL      = "https://a2textpaid.azurewebsites.net/";
                var    url          = restURL + "GetMyFlight?airline=" + airlineStr + "&flightnumber=" + numberStr + "&language=en-US";
                string responseBody = GET(url);

                GetMyFlight.RootObject flightDetails = JsonConvert.DeserializeObject <GetMyFlight.RootObject>(responseBody);

                await context.PostAsync(flightDetails.text);

                var resultMessage = context.MakeMessage();
                resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                resultMessage.Attachments      = new List <Attachment>();

                HeroCard heroCard = new HeroCard()
                {
                    Title    = flightNoStr.ToUpper(),
                    Subtitle = "From " + flightDetails.content.departureAirport + " to " + flightDetails.content.arrivalAirport,
                    Images   = new List <CardImage>()
                    {
                        new CardImage()
                        {
                            Url = "http://bilder.t-online.de/b/77/27/34/42/id_77273442/610/tid_da/auftrieb-und-geschwindigkeit-sorgen-dafuer-dass-das-flugzeug-in-der-luft-bleibt-.jpg"
                        }
                    },
                    Buttons = new List <CardAction>()
                    {
                        new CardAction()
                        {
                            Title = "More details",
                            Type  = ActionTypes.OpenUrl,
                            Value = $"https://www.bing.com/search?q=" + HttpUtility.UrlEncode(flightNoStr)
                        }
                    }
                };
                resultMessage.Attachments.Add(heroCard.ToAttachment());
                await context.PostAsync(resultMessage);
            }

            if (entities.Any((entity) => entity.Type == "Airline"))
            {
                var airline = entities.Where((entity) => entity.Type == "Airline").First();
                airlineStr = airline.Entity ?? null;

                if (entities.Any((entity) => entity.Type == "builtin.number"))
                {
                    var number = entities.Where((entity) => entity.Type == "builtin.number").First();
                    numberStr = number.Entity ?? null;

                    var    restURL      = "https://a2textpaid.azurewebsites.net/";
                    var    url          = restURL + "GetMyFlight?airline=" + airlineStr + "&flightnumber=" + numberStr + "&language=en-US";
                    string responseBody = GET(url);

                    GetMyFlight.RootObject flightDetails = JsonConvert.DeserializeObject <GetMyFlight.RootObject>(responseBody);

                    await context.PostAsync(flightDetails.text);

                    var resultMessage = context.MakeMessage();
                    resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    resultMessage.Attachments      = new List <Attachment>();

                    HeroCard heroCard = new HeroCard()
                    {
                        Title    = airlineStr + numberStr,
                        Subtitle = "From " + flightDetails.content.departureAirport + " to " + flightDetails.content.arrivalAirport,
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = "http://bilder.t-online.de/b/77/27/34/42/id_77273442/610/tid_da/auftrieb-und-geschwindigkeit-sorgen-dafuer-dass-das-flugzeug-in-der-luft-bleibt-.jpg"
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"https://www.bing.com/search?q=" + HttpUtility.UrlEncode(airlineStr + numberStr)
                            }
                        }
                    };
                    resultMessage.Attachments.Add(heroCard.ToAttachment());
                    await context.PostAsync(resultMessage);
                }
            }

            else if (flightNoStr == null || airlineStr == null)
            {
                await context.PostAsync("Please tell me your flightnumber.");
            }
            context.Wait(this.MessageReceived);
            flightNoStr = null;
            airlineStr  = null;
            numberStr   = null;
        }
Esempio n. 28
0
        private static Activity CreateCarousel()
        {
            var cardImpuestoAlcabala = new HeroCard
            {
                Title    = "Impuesto Alcabala",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/01_ImpuestoAlcabala.png") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Realizar Trámite", Value = "Realizar Trámite", Type = ActionTypes.ImBack
                    },
                    new CardAction()
                    {
                        Title = "Consultar Trámite", Value = "", Type = ActionTypes.ImBack
                    }
                }
            };

            var cardLicenciaFuncionamiento = new HeroCard
            {
                Title    = "Licencia de Funcionamiento",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/02_LicenciaFuncionamiento.png") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Realizar Trámite", Value = "", Type = ActionTypes.ImBack
                    },
                    new CardAction()
                    {
                        Title = "Consultar Trámite", Value = "", Type = ActionTypes.ImBack
                    }
                }
            };

            var cardImpuestoVehicular = new HeroCard
            {
                Title    = "Impuesto Vehicular",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/03_ImpuestoVehicular.png") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Realizar Trámite", Value = "", Type = ActionTypes.ImBack
                    },
                    new CardAction()
                    {
                        Title = "Consultar Trámite", Value = "", Type = ActionTypes.ImBack
                    }
                }
            };

            var cardEstadoCuenta = new HeroCard
            {
                Title    = "Estado de Cuenta",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/04_EstadoCuenta.png") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Consultar", Value = "", Type = ActionTypes.ImBack
                    },
                }
            };

            var cardCentroContacto = new HeroCard
            {
                Title    = "Centro de Contactos",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/05_CentroContactos.png") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Consultar", Value = "Centro de Contactos", Type = ActionTypes.ImBack
                    },
                    new CardAction()
                    {
                        Title = "Sitio Web", Value = "http://www.municallao.gob.pe/index.php/locales-municipales", Type = ActionTypes.OpenUrl
                    }
                }
            };

            var cardCalificarBot = new HeroCard
            {
                Title    = "Calificación",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/06_Calificar.jpg") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Calificar Bot", Value = "Calificar Bot", Type = ActionTypes.ImBack
                    }
                }
            };

            var cardRegistrarCiudadano = new HeroCard
            {
                Title    = "Registrar Ciudadano",
                Subtitle = "Opciones",
                //Images = new List<CardImage> { new CardImage("https://munibotstorage.blob.core.windows.net/images/07_RegistrarUsuario.png") },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Registrar Ciudadano", Value = "Registrar Ciudadano", Type = ActionTypes.ImBack
                    }
                }
            };

            var optionAttachments = new List <Attachment>()
            {
                cardImpuestoAlcabala.ToAttachment(),
                cardLicenciaFuncionamiento.ToAttachment(),
                cardImpuestoVehicular.ToAttachment(),
                cardEstadoCuenta.ToAttachment(),
                cardCentroContacto.ToAttachment(),
                cardCalificarBot.ToAttachment(),
                cardRegistrarCiudadano.ToAttachment()
            };
            var reply = MessageFactory.Attachment(optionAttachments);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            return(reply as Activity);
        }
Esempio n. 29
0
        //private async Task<DialogTurnResult> QuestionsStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        //{
        //    return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
        //    {
        //        Prompt = MessageFactory.Text("Please enter your programming question.")
        //    }, cancellationToken);
        //}
        private async Task <DialogTurnResult> CallGenerateAnswerAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            //stepContext.Values["Question1"] = (string)stepContext.Result;
            //stepContext.Values["question"] = (string)stepContext.Result;

            var qnaMakerOptions = new QnAMakerOptions
            {
                ScoreThreshold = DefaultThreshold,
                Top            = DefaultTopN,
            };
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Humm... Searching...😊"), cancellationToken);

            await stepContext.Context.SendActivitiesAsync(
                new Activity[] {
                new Activity {
                    Type = ActivityTypes.Typing
                },
                new Activity {
                    Type = "delay", Value = 7000
                },
            },
                cancellationToken);

            //stepContext.Values["Question"] = (string)stepContext.Result;
            var response = await _services.QnAMakerService.GetAnswersAsync(stepContext.Context, qnaMakerOptions);

            //if ( i < 0.5)
            //{
            //    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry 😞,No QnAMaker answers found for your programming question."), cancellationToken);
            //}

            if (response != null && response.Length > 0)
            {
                float i = response[0].Score;
                //await stepContext.Context.SendActivityAsync(MessageFactory.Text("No QnAMaker answers found for your programming question."), cancellationToken);
                if (response.Length >= 1 && i >= 0.9)
                {
                    //for (int j = 0; j < response.Length; j++)
                    //{
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("I found the following results from your question"), cancellationToken);

                    await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = MessageFactory.Text(response[0].Answer),
                    }, cancellationToken);

                    // }
                }
                if (response.Length == 1 && i <= 0.9 && i >= 0.5)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("I found the following results from your question"), cancellationToken);

                    await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = MessageFactory.Text(response[0].Answer),
                    }, cancellationToken);
                }
                if (response.Length > 1 && i > 0.5)
                {
                    var options  = response.Select(r => r.Questions[0]).ToList();
                    var herocard = new HeroCard();
                    herocard.Text = "Did you mean:";
                    List <CardAction> buttons = new List <CardAction>();

                    foreach (var item in options)
                    {
                        buttons.Add(new CardAction()
                        {
                            Type  = ActionTypes.ImBack,
                            Title = item.ToString(),
                            Value = item.ToString()
                        });
                    }
                    buttons.Add(new CardAction()
                    {
                        Type  = ActionTypes.ImBack,
                        Title = "None of the above.",
                        Value = "Cancel."
                    });

                    herocard.Buttons = buttons;
                    var response1 = stepContext.Context.Activity.CreateReply();
                    response1.Attachments = new List <Attachment>()
                    {
                        herocard.ToAttachment()
                    };
                    await stepContext.Context.SendActivityAsync(response1);
                }

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else
            {
                //await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry 😞,No QnAMaker answers found for your programming question."), cancellationToken);
                await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = MessageFactory.Text("Sorry 😞,No QnAMaker answers found for your programming question."),
                }, cancellationToken);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }



            //switch (response.Length)
            //{
            //    case 0:
            //        await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //        {
            //            Prompt = MessageFactory.Text("No QnAMaker answers found."),
            //        }, cancellationToken);
            //        break;
            //    case 1:
            //            await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //            {
            //                Prompt = MessageFactory.Text(response[0].Answer),
            //            }, cancellationToken);
            //        break;
            //    //case 2:
            //    //    for (int i = 0; i < response.Length; i++)
            //    //    {
            //    //        await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //    //        {
            //    //            Prompt = MessageFactory.Text(response[i].Answer),
            //    //        }, cancellationToken);
            //    //    }
            //    //    break;
            //    default:
            //        var options = response.Select(r => r.Questions[0]).ToList();
            //        var herocard = new HeroCard();
            //        herocard.Text = "Did you mean:";
            //        List<CardAction> buttons = new List<CardAction>();

            //        foreach (var item in options)
            //        {
            //            buttons.Add(new CardAction()
            //            {
            //                Type = ActionTypes.ImBack,
            //                Title = item.ToString(),
            //                Value = item.ToString()
            //            });
            //        }
            //        buttons.Add(new CardAction()
            //        {
            //            Type = ActionTypes.ImBack,
            //            Title = "None of the above.",
            //            Value = "None of the above."
            //        });

            //        herocard.Buttons = buttons;
            //        var response1 = stepContext.Context.Activity.CreateReply();
            //        response1.Attachments = new List<Attachment>() { herocard.ToAttachment() };
            //        await stepContext.Context.SendActivityAsync(response1);
            //        break;
            //}


            //return await qnaMaker.GetAnswersAsync(stepContext.Context, qnaMakerOptions);
            // var response = await _services.GetAnswersRawAsync(stepContext.Context, qnaMakerOptions).ConfigureAwait(false);
            //if (response != null && response.Length > 0)
            //{
            //int i = 0;
            //int id = response[0].Id;
            //ID.QuestionID = id;
            //do
            //{
            //        await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //    {
            //        Prompt = MessageFactory.Text(response[i].Answer),
            //    }, cancellationToken);
            //    //i=i+1;

            //        i++;

            //} while (i < response.Length);

            //await QuestionConfirmStepAsync(stepContext, cancellationToken);

            //await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { }, cancellationToken);
            //return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { }, cancellationToken);
            //QuestionConfirmStepAsync(stepContext, cancellationToken);
            //QuestionConfirmStepAsync(stepContext,cancellationToken);
            //}
            //else
            //{
            //    //return await stepContext.Context.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
            //     await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //    {
            //        Prompt = MessageFactory.Text("I could not find an answer to your question. Please rephrase your question, so that I can better understand it."),
            //    }, cancellationToken);

            //    //return await stepContext.ContinueDialogAsync();
            //    return await stepContext.EndDialogAsync(null, cancellationToken);

            //}
        }
Esempio n. 30
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
                var client = new ConnectorClient(new Uri(message.ServiceUrl));
                IConversationUpdateActivity update = message;
                if (update.MembersAdded.Any())
                {
                    var reply      = message.CreateReply();
                    var newMembers = update.MembersAdded?.Where(t => t.Id != message.Recipient.Id);
                    foreach (var newMember in newMembers)
                    {
                        // Hero card way
                        //var reply = message.CreateReply();
                        List <CardImage> cardImages = new List <CardImage>();
                        cardImages.Add(new CardImage(url: "https://docsearch.blob.core.windows.net/files/fin-advisor.jpg"));

                        List <CardAction> cardButtons = new List <CardAction>();

                        CardAction plButtonLoan = new CardAction()
                        {
                            Value = "Finanzierung",
                            Type  = "imBack",
                            Title = "Persönlichisierte Finanzierung"
                        };
                        cardButtons.Add(plButtonLoan);

                        CardAction plButtonCredit = new CardAction()
                        {
                            Value = "Dispotkredit Erhöhen",
                            Type  = "imBack",
                            Title = "Dispotkrediterhöhung"
                        };
                        cardButtons.Add(plButtonCredit);

                        CardAction plCloseCreditButton = new CardAction()
                        {
                            Value = "Ablösesumme",
                            Type  = "imBack",
                            Title = "Kreditablösesumme Anfragen"
                        };
                        cardButtons.Add(plCloseCreditButton);

                        HeroCard plCard = new HeroCard()
                        {
                            Title    = $"Hallo, ich bin Pia!",
                            Subtitle = $"Ich kann Fragen zu Deinen Konten und Finanzierungen beantworten, zum Beispiel:",
                            Images   = cardImages,
                            Buttons  = cardButtons
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        reply.Attachments.Add(plAttachment);


                        // User suggestions way
                        //reply.Type = ActivityTypes.Message;
                        //reply.TextFormat = TextFormatTypes.Plain;

                        //reply.SuggestedActions = new SuggestedActions()
                        //{
                        //    Actions = new List<CardAction>()
                        //    {
                        //        new CardAction(){ Title = "Blue", Type=ActionTypes.ImBack, Value="Blue" },
                        //        new CardAction(){ Title = "Red", Type=ActionTypes.ImBack, Value="Red" },
                        //        new CardAction(){ Title = "Green", Type=ActionTypes.ImBack, Value="Green" }
                        //    }
                        //};

                        client.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);
        }
Esempio n. 31
0
        public static HeroCard CreateCommandOptionsCard(string botName)
        {
            HeroCard card = new HeroCard()
            {
                Title    = Strings.CommandMenuTitle,
                Subtitle = Strings.CommandMenuDescription,

                Text = string.Format(
                    Strings.CommandMenuInstructions,
                    Command.CommandKeyword,
                    botName,
                    new Command(
                        Commands.AcceptRequest,
                        new string[] { "(user ID)", "(user conversation ID)" },
                        botName).ToString()),

                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.Watch),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.Watch, null, botName).ToString()
                    },
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.Unwatch),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.Unwatch, null, botName).ToString()
                    },
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.GetRequests),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.GetRequests, null, botName).ToString()
                    },
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.AcceptRequest),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.AcceptRequest, null, botName).ToString()
                    },
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.RejectRequest),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.RejectRequest, null, botName).ToString()
                    },
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.GetHistory),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.GetHistory, null, botName).ToString()
                    },
                    new CardAction()
                    {
                        Title = Command.CommandToString(Commands.Disconnect),
                        Type  = ActionTypes.ImBack,
                        Value = new Command(Commands.Disconnect, null, botName).ToString()
                    }
                }
            };

            return(card);
        }
Esempio n. 32
0
 public OtherPlayer(HeroCard heroCard, Texture2D[] textures, string name, int health, int numOfCards) : base(heroCard, textures) 
 {
     Name = name;
     Health = health;
     numberOfCards = numOfCards;
 }