Example #1
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var replyText            = new StringBuilder();
            var inputText            = turnContext.Activity.Text.Trim();
            SearchIndexClient client = GetSearchClient();
            var typingActivity       = new Activity[] { new Activity {
                                                            Type = ActivityTypes.Typing
                                                        }, new Activity {
                                                            Type = "delay", Value = 1000
                                                        } };
            await turnContext.SendActivitiesAsync(typingActivity);

            Microsoft.Azure.Search.Models.DocumentSearchResult <Microsoft.Azure.Search.Models.Document> results = await client.Documents.SearchAsync(inputText);

            if (results?.Results != null && results.Results.Any())
            {
                foreach (SearchResult <Document> item in results.Results.Take(5))
                {
                    replyText.AppendLine($"{item.Document["Path"].ToString()}");
                }
            }
            else
            {
                replyText.AppendLine("No results found!");
            }

            await turnContext.SendActivityAsync(MessageFactory.Text(replyText.ToString(), replyText.ToString()), cancellationToken);
        }
Example #2
0
        /// <summary>
        /// This bot runs Dialogs that send message Activites in a way that can be scaled out with a multi-machine deployment.
        /// The bot logic makes use of the standard HTTP ETag/If-Match mechanism for optimistic locking. This mechanism
        /// is commonly supported on cloud storage technologies from multiple vendors including teh Azure Blob Storage
        /// service. A full implementation against Azure Blob Storage is included in this sample.
        /// </summary>
        /// <param name="turnContext">The ITurnContext object created by the integration layer.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Create the storage key for this conversation.
            string key = $"{turnContext.Activity.ChannelId}/conversations/{turnContext.Activity.Conversation?.Id}";

            // The execution sits in a loop because there might be a retry if the save operation fails.
            while (true)
            {
                // Load any existing state associated with this key
                var(oldState, etag) = await _store.LoadAsync(key);

                // Run the dialog system with the old state and inbound activity, the result is a new state and outbound activities.
                var(activities, newState) = await DialogHost.RunAsync(_rootDialog, turnContext.Activity, oldState);

                // Save the updated state associated with this key.
                bool success = await _store.SaveAsync(key, newState, etag);

                // Following a successful save, send any outbound Activities, otherwise retry everything.
                if (success)
                {
                    if (activities.Any())
                    {
                        // This is an actual send on the TurnContext we were given and so will actual do a send this time.
                        await turnContext.SendActivitiesAsync(activities);
                    }

                    break;
                }
            }
        }
Example #3
0
        public async Task AttachPhoneCard(ITurnContext turnContext, List <PhoneNum> list, string searchName, CancellationToken cancellationToken)
        {
            var reply = new List <IMessageActivity>();

            reply.Add(MessageFactory.Text($"{searchName}으로 검색한 결과는 다음과 같습니다.\n\n전화를 거시려면 버튼을 눌러주세요"));

            var cardActions = new List <CardAction>();

            foreach (PhoneNum phoneNum in list)
            {
                cardActions.Add(new CardAction()
                {
                    Title = phoneNum.Department + " - " + phoneNum.Name,
                    Type  = ActionTypes.Call,
                    Value = phoneNum.PhoneNumber
                });
            }
            var attachments = new List <Attachment>();

            attachments.Add(new HeroCard
            {
                Buttons = cardActions
            }.ToAttachment());
            reply.Add(MessageFactory.Attachment(attachments));


            await turnContext.SendActivitiesAsync(reply.ToArray(), cancellationToken);
        }
Example #4
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            if (activity.Type == ActivityTypes.Message)
            {
                if (activity.Attachments != null && activity.Attachments.Any())
                {
                    // We know the user is sending an attachment as there is at least one item
                    // in the Attachments list.
                    await HandleIncomingAttachmentAsync(turnContext, activity);

                    return;
                }

                if (activity.Text?.Trim()?.ToLowerInvariant() == "hi")
                {
                    await turnContext.SendActivitiesAsync(
                        new IActivity[]
                    {
                        new Activity(type: ActivityTypes.Message, text: "Hi! 🙋‍"),
                        new Activity(type: ActivityTypes.Message, text: "Send me a picture of a handwritten digit and I'll tell you what the number is!"),
                        new Activity(type: ActivityTypes.Message, text: "Yeah, I'm that smart! 😎"),
                    },
                        cancellationToken);
                }
            }
        }
        protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            foreach (var member in membersAdded)
            {
                // Greet anyone that was not the target (recipient) of this message.
                // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    //var welcomeCard = CreateAdaptiveCardAttachment();
                    var response = MessageFactory.Text("Welcome \n مرحبا");
                    await turnContext.SendActivitiesAsync(
                        new Activity[] {
                        new Activity {
                            Type = "delay", Value = 3000
                        },
                        response,
                        new Activity {
                            Type = ActivityTypes.Typing
                        },
                        new Activity {
                            Type = "delay", Value = 3000
                        }
                    }, cancellationToken);

                    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>("DialogState"), cancellationToken);
                }
            }
        }
Example #6
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var dialogContext = await _dialogs.CreateContextAsync(turnContext, cancellationToken);

            if (turnContext.Activity.Text.ToLowerInvariant() == "end conversation")
            {
                await turnContext.SendActivitiesAsync(
                    new Activity[]
                {
                    MessageFactory.Text("Alright ending conversation..."),
                }, cancellationToken
                    );

                await _botAccessors.UserProfile.SetAsync(turnContext, new CustomerModel(), cancellationToken);

                await _botAccessors.QuoteBasket.SetAsync(turnContext, new QuoteBasketModel(), cancellationToken);

                await dialogContext.BeginDialogAsync("IntroDialog");
            }
            else if (turnContext.Activity.Text.ToLowerInvariant() == "create quote")
            {
                await dialogContext.BeginDialogAsync("CustomerProfileDialog", null, cancellationToken);
            }


            else
            {
                await dialogContext.ContinueDialogAsync(cancellationToken);
            }
        }
        private async Task SendToPowerVA(string conversationId, string text, ITurnContext turnContext, DirectLineClient directLineClient)
        {
            _logger.LogInformation($"{turnContext.Activity?.Id} Sending, conversationId={conversationId}, text={text}");

            // Send to Power VA
            var response = await directLineClient.Conversations.PostActivityAsync(conversationId, new Activity()
            {
                Type = ActivityTypes.Message,
                From = new ChannelAccount {
                    Id = "userId", Name = "userName"
                },
                Text        = text,
                ChannelData = _channelData,
                TextFormat  = "plain",
                Locale      = "en-US"
            });

            if (_enableYouSaid)
            {
                var youSaid = turnContext.Activity.CreateReply();
                youSaid.Text  = $"You said: {text}.";
                youSaid.Speak = SimpleConvertToSSML(youSaid.Text);
                _logger.LogInformation($"{turnContext.Activity?.Id} Speaking: {youSaid.Speak}");

                await turnContext.SendActivitiesAsync(new[] { youSaid });
            }
        }
Example #8
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            //var replyText = $"Echo: {turnContext.Activity.Text}";
            //await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);

            var          replyText      = new StringBuilder();
            var          inputText      = turnContext.Activity.Text.Trim();
            SearchClient client         = GetSearchClient();
            var          typingActivity = new Activity[] { new Activity {
                                                               Type = ActivityTypes.Typing
                                                           }, new Activity {
                                                               Type = "delay", Value = 1000
                                                           } };
            await turnContext.SendActivitiesAsync(typingActivity);

            SearchResults <SearchDocument> response = await client.SearchAsync <SearchDocument>(inputText);

            await foreach (var result in response.GetResultsAsync())
            {
                replyText.AppendLine($"{result.Document["Path"].ToString()}");
            }

            string searchResult = replyText.ToString();

            if (string.IsNullOrWhiteSpace(searchResult))
            {
                searchResult = $"No match found";
            }

            await turnContext.SendActivityAsync(MessageFactory.Text(searchResult), cancellationToken);
        }
Example #9
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            await turnContext.SendActivityAsync(MessageFactory.Text("parent: before child"), cancellationToken);

            var activity = MessageFactory.Text("parent to child");

            activity.ApplyConversationReference(turnContext.Activity.GetConversationReference(), true);
            activity.DeliveryMode = DeliveryModes.BufferedReplies;

            var response = await _client.PostActivityAsync <Activity[]>(
                null,
                "toBotId",
                new Uri("http://localhost:3979/api/messages"),
                new Uri("http://tempuri.org/whatever"),
                Guid.NewGuid().ToString(),
                activity,
                cancellationToken);

            if (response.Status == (int)HttpStatusCode.OK)
            {
                await turnContext.SendActivitiesAsync(response.Body, cancellationToken);
            }

            await turnContext.SendActivityAsync(MessageFactory.Text("parent: after child"), cancellationToken);
        }
Example #10
0
        private static async Task HandleInfographicInvocation(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Regex typeLookupRegex = new Regex($"^!\\w+ \"?([^\"]+)\"?$", RegexOptions.IgnoreCase);
            Match typeLookupMatch = typeLookupRegex.Match(turnContext.Activity.Text);
            var   searchTerm      = ((typeLookupMatch.Success && typeLookupMatch.Groups.Count >= 2) ? typeLookupMatch.Groups[1].Value : "").ToLowerInvariant();

            var raids = await PokeBattlerApi.GetRaids();

            var results = raids.Where(raid =>
                                      !string.IsNullOrEmpty(raid.Article?.InfographicURL) &&
                                      !searchTerm.Replace("-", " ").Split(" ").Except(raid.Pokemon.ToLowerInvariant().Replace("_", " ").Split(" ")).Any()
                                      );

            TextInfo ti = new CultureInfo("en-US", false).TextInfo;

            if (results.Any())
            {
                bool pluralize = results.Count() > 1;

                await turnContext.SendActivityAsync(MessageFactory.Text($"Here's {(pluralize ? "infographics" : " an infographic")} with details about {ti.ToTitleCase(searchTerm)}, courtesy of Pokebattler."));

                await turnContext.SendActivitiesAsync(
                    results
                    .Select(result =>
                            MessageFactory.Attachment(new Attachment("image/png", result.Article.InfographicURL)) as IActivity
                            )
                    .ToArray()
                    );
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"Sorry, but Pokebattler doesn't currently appear to have an infographic for {ti.ToTitleCase(searchTerm)}"), cancellationToken);
            }
        }
Example #11
0
        private async Task RespondPowerVirtualAgentsBotReplyAsync(DirectLineClient client, RelayConversation currentConversation, ITurnContext <IMessageActivity> turnContext)
        {
            var retryMax = WaitForBotResponseMaxMilSec / PollForBotResponseIntervalMilSec;

            for (int retry = 0; retry < retryMax; retry++)
            {
                // Get bot response using directlineClient,
                // response contains whole conversation history including user & bot's message
                ActivitySet response = await client.Conversations.GetActivitiesAsync(currentConversation.ConversationtId, currentConversation.WaterMark);

                // Filter bot's reply message from response
                List <DirectLineActivity> botResponses = response?.Activities?.Where(x =>
                                                                                     x.Type == DirectLineActivityTypes.Message &&
                                                                                     string.Equals(x.From.Name, _botService.GetBotName(), StringComparison.Ordinal)).ToList();

                if (botResponses?.Count() > 0)
                {
                    if (int.Parse(response?.Watermark ?? "0") <= int.Parse(currentConversation.WaterMark ?? "0"))
                    {
                        // means user sends new message, should break previous response poll
                        return;
                    }

                    currentConversation.WaterMark = response.Watermark;
                    await turnContext.SendActivitiesAsync(_responseConverter.ConvertToBotSchemaActivities(botResponses).ToArray());
                }

                Thread.Sleep(PollForBotResponseIntervalMilSec);
            }
        }
Example #12
0
        /// <summary>
        /// Users expect a timely response to their messages.
        /// </summary>
        /// <param name="turnContext"> turn context</param>
        /// <param name="cancellationToken">cancellation token</param>
        /// <returns>
        /// async response
        /// 1. Typing activity
        /// 2. wait 3000 m/s
        /// 3. text message.
        /// </returns>
        protected override async Task OnMessageActivityAsync(
            ITurnContext <IMessageActivity> turnContext,
            CancellationToken cancellationToken)
        {
            if (string.Equals(
                    turnContext.Activity.Text,
                    "wait",
                    System.StringComparison.InvariantCultureIgnoreCase))
            {
                await turnContext.SendActivitiesAsync(
                    new IActivity[]
                {
                    new Activity {
                        Type = ActivityTypes.Typing
                    },
                    new Activity {
                        Type = "delay", Value = 3000
                    },
                    MessageFactory.Text("Finished typing", "Finished typing")
                },
                    cancellationToken);
            }
            else
            {
                var replyText = $"Echo: {turnContext.Activity.Text}. Say 'wait' to watch me type.";

                // return async activity
                await turnContext.SendActivityAsync(
                    MessageFactory.Text(
                        replyText,
                        replyText),
                    cancellationToken);
            }
        }
Example #13
0
        private async Task ProcessVABotAsync(ITurnContext <Microsoft.Bot.Schema.IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var token = await _botServices.VABotService.GetTokenAsync();

            using (var directLineClient = new DirectLineClient(token))
            {
                var conversation = await directLineClient.Conversations.StartConversationAsync();

                var conversationtId = conversation.ConversationId;

                var response = await directLineClient.Conversations.PostActivityAsync(conversationtId, new Microsoft.Bot.Connector.DirectLine.Activity()
                {
                    Type = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Message,
                    From = new Microsoft.Bot.Connector.DirectLine.ChannelAccount {
                        Id = "userId", Name = "userName"
                    },
                    Text        = turnContext.Activity.Text,
                    ChannelData = JObject.FromObject(_botServices.VABotService.ChannelData),
                    TextFormat  = "plain",
                    Locale      = "en-Us",
                });

                Thread.Sleep(4000);

                var activities = await GetActivitiesAsync(directLineClient, conversationtId, _botServices.VABotService.BotName);

                var activity = turnContext.Activity as Microsoft.Bot.Schema.Activity;

                await turnContext.SendActivitiesAsync(
                    activities
                    .Select(message =>
                {
                    var reply = activity.CreateReply(message.Text);
                    reply.Attachments = message?.Attachments?.Select(a => new Microsoft.Bot.Schema.Attachment()
                    {
                        Content = a.Content,
                        ContentType = a.ContentType,
                        ContentUrl = a.ContentUrl
                    }).ToList();

                    reply.SuggestedActions = new Microsoft.Bot.Schema.SuggestedActions()
                    {
                        Actions = message?.SuggestedActions?.Actions?.Select(a => new Microsoft.Bot.Schema.CardAction()
                        {
                            Title = a.Title,
                            Value = a.Value,
                            Type = a.Type,
                            Image = a.Image
                        }).ToList(),
                    };

                    return(reply);
                })
                    .ToArray());
            }
        }
Example #14
0
 public static async Task SendWelcomeBackMessage(ChannelAccount member, ITurnContext turnContext, CancellationToken cancellationToken)
 {
     if (member.Id != turnContext.Activity.Recipient.Id)
     {
         await turnContext.SendActivitiesAsync(new[] {
             MessageFactory.Text($"Welcome back to the group, {member.Name}! I'm glad to see you again."),
             MessageFactory.Text(Constants.WelcomeMessages.WelcomeBackReminderMessage)
         }, cancellationToken);
     }
 }
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var recognizer = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
                var topIntent  = recognizer?.GetTopScoringIntent();

                if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                {
                    var location = LuisParser.GetEntityValue(recognizer);

                    if (location.ToString() != string.Empty)
                    {
                        var ro = await WeatherService.GetWeather(location);

                        var weather = $"{ro.weather.First().main} ({ro.main.temp.ToString("N2")} °C)";

                        var typing = Activity.CreateTypingActivity();
                        var delay  = new Activity {
                            Type = "delay", Value = 5000
                        };

                        var activities = new IActivity[] {
                            typing,
                            delay,
                            MessageFactory.Text($"Weather of {location} is: {weather}"),
                            MessageFactory.Text("Thanks for using our service!")
                        };

                        await turnContext.SendActivitiesAsync(activities);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"==>Can't understand you, sorry!");
                    }
                }
                else
                {
                    var msg = @"No LUIS intents were found.
                    This sample is about identifying a city and an intent:
                    'Find the current weather in a city'
                    Try typing 'What's the weather in Prague'";

                    await turnContext.SendActivityAsync(msg);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken);
            }
        }
Example #16
0
 public static async Task SendWelcomeMessage(ChannelAccount member, ITurnContext turnContext, CancellationToken cancellationToken)
 {
     if (member.Id != turnContext.Activity.Recipient.Id)
     {
         await turnContext.SendActivitiesAsync(new[] {
             MessageFactory.Text($"Welcome, {member.Name}! We're always excited to have a new trainer join our community! Our group guidelines and FAQs can be found here: {VariableResources.WelcomePacketUrl}"),
             MessageFactory.Text(Constants.WelcomeMessages.FirstTimeNameFormatMessage),
             MessageFactory.Text(string.Format(Constants.WelcomeMessages.ParameterizedFirstTimeBotTutorialMessage, VariableResources.GymNameExamples.First()))
         }, cancellationToken);
     }
 }
        private async Task <(string, string)> ProcessTurnAsync(ITurnContext turnContext, string token, string conversationId, string watermark, Func <string, Task> saveConversationId)
        {
            using (var directLineClient = new DirectLineClient(token))
            {
                if (string.IsNullOrEmpty(conversationId))
                {
                    _logger.LogInformation($"{turnContext.Activity?.Id} Starting conversation");

                    var conversation = await directLineClient.Conversations.StartConversationAsync();

                    conversationId = conversation.ConversationId;

                    // Save state, so if there are later exceptions, we don't repeat the message below.
                    await saveConversationId(conversationId);

                    if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
                    {
                        var activity = turnContext.Activity.CreateReply();
                        if (_enableStartWithOk)
                        {
                            activity.Text = "For this demo, start your sentences with the word OK.";
                        }
                        else
                        {
                            activity.Text = "Hello, thanks for calling the Voice Power Virtual Agent demo.";
                        }

                        activity.Speak = SimpleConvertToSSML(activity.Text);

                        await turnContext.SendActivitiesAsync(new[] { activity });
                    }
                }

                if (turnContext.Activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(turnContext.Activity.Text))
                {
                    if (!_enableStartWithOk || (turnContext.Activity.Text.StartsWith("OK", true, CultureInfo.InvariantCulture)))
                    {
                        var text = _enableStartWithOk ? turnContext.Activity.Text.Substring(turnContext.Activity.Text.IndexOf(' ') + 1) : turnContext.Activity.Text;

                        await SendToPowerVA(conversationId, text, turnContext, directLineClient);

                        watermark = await ReceiveFromPowerVA(conversationId, watermark, turnContext, directLineClient);
                    }
                    else
                    {
                        _logger.LogInformation($"{turnContext.Activity?.Id} Discarding, conversationId={conversationId}, text={turnContext.Activity.Text}");
                    }
                }
            }

            return(conversationId, watermark);
        }
Example #18
0
 // simula la scrittura in real time di un array di activity
 public async void typeAnswers(List <Activity> activities, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     foreach (Activity activity in activities)
     {
         await turnContext.SendActivitiesAsync(
             new Activity[] {
             new Activity {
                 Type = ActivityTypes.Typing
             },
             new Activity {
                 Type = "delay", Value = 1200
             },
             activity,
         },
             cancellationToken);
     }
 }
        //private string SimpleConvertToSSML(string Message)
        //{
        //    string Lang = "en-US";
        //    string VoiceName = "Microsoft Server Speech Text to Speech Voice (en-US, JessaNeural)";
        //    string ExpressionType = "cheerful";

        //    return $@"<speak version=""1.0"" xmlns=""https://www.w3.org/2001/10/synthesis"" xmlns:mstts=""https://www.w3.org/2001/mstts"" xml:lang=""{Lang}"">
        //        <voice name=""{VoiceName}"">
        //            <mstts:express-as type=""{ExpressionType}"">
        //                {Message}
        //            </mstts:express-as>
        //        </voice>
        //    </speak>";
        //}

        private async Task <string> ReceiveFromPowerVA(string conversationId, string watermark, ITurnContext turnContext, DirectLineClient directLineClient)
        {
            _logger.LogInformation($"{turnContext.Activity?.Id} Receiving, conversationId={conversationId}, watermark={watermark}");

            // Receive from Power VA
            var startReceive = DateTime.UtcNow;

            do
            {
                await Task.Delay(_pollingDelay);

                var activitySet = await directLineClient.Conversations.GetActivitiesAsync(conversationId, watermark);

                var responseActivities = activitySet?.Activities?
                                         .Where(x => x.Type == ActivityTypes.Message && x.From.Name == _dynamicsBotName)
                                         .Select(m =>
                {
                    _logger.LogInformation($"{turnContext.Activity?.Id} Received, {m.Text}");

                    var activity       = turnContext.Activity.CreateReply(m.Text);
                    activity.Speak     = SimpleConvertToSSML(activity.Text);
                    activity.InputHint = InputHints.ExpectingInput;
                    return(activity);
                })
                                         .Cast <Bot.Schema.IActivity>()
                                         .ToArray();

                if (activitySet != null)
                {
                    if (responseActivities != null && responseActivities.Length > 0)
                    {
                        _logger.LogInformation($"{turnContext.Activity?.Id} Received, count={responseActivities.Length}");
                        await turnContext.SendActivitiesAsync(responseActivities);

                        // Reset the clock, sliding the window
                        startReceive = DateTime.UtcNow;
                    }

                    watermark = activitySet.Watermark;
                }
            } while ((DateTime.UtcNow - startReceive) < _receiveWindow);

            return(watermark);
        }
Example #20
0
            protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
            {
                // touch every
                var activity  = turnContext.Activity;
                var adapter   = turnContext.Adapter;
                var turnState = turnContext.TurnState;
                var responsed = turnContext.Responded;

                turnContext.OnDeleteActivity((t, a, n) => Task.CompletedTask);
                turnContext.OnSendActivities((t, a, n) => Task.FromResult(new ResourceResponse[] { new ResourceResponse() }));
                turnContext.OnUpdateActivity((t, a, n) => Task.FromResult(new ResourceResponse()));
                await turnContext.DeleteActivityAsync(activity.GetConversationReference());

                await turnContext.SendActivityAsync(new Activity());

                await turnContext.SendActivitiesAsync(new IActivity[] { new Activity() });

                await turnContext.UpdateActivityAsync(new Activity());
            }
        public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            string token;
            string conversationId = null;
            string watermark      = null;

            _logger.LogInformation($"{turnContext.Activity?.Id} Entering OnMessageActivityAsync, conversationId: {turnContext.Activity?.Conversation?.Id}, activityType: {turnContext.Activity.Type}");

            // Read state
            var props = await _storage.ReadAsync(new[] { turnContext.Activity.Conversation.Id });

            if (props.Count == 0)
            {
                _logger.LogInformation($"{turnContext.Activity?.Id} Getting token for a new conversation....");
                token = await GetTokenAsync();
            }
            else
            {
                props          = (IDictionary <string, object>)props[turnContext.Activity.Conversation.Id];
                token          = (string)props["token"];
                conversationId = (string)props["conversationId"];
                watermark      = (string)props["watermark"];
            }

            _logger.LogInformation($"{turnContext.Activity?.Id} Got token, {token.Substring(0, 6)}, conversationId: {conversationId}, watermark: {watermark}");

            try
            {
                Func <string, Task> saveConversationId = (c) => WriteState(turnContext, c, token, watermark);
                (conversationId, watermark) = await ProcessTurnAsync(turnContext, token, conversationId, watermark, saveConversationId);
            }
            catch (Exception ex)
            {
                _telemetryClient.TrackException(ex);
                var activity = turnContext.Activity.CreateReply();
                activity.Text = activity.Speak = ex.Message;
                await turnContext.SendActivitiesAsync(new[] { activity });
            }

            await WriteState(turnContext, conversationId, token, watermark);

            _logger.LogInformation($"{turnContext.Activity?.Id} Exiting OnMessageActivityAsync, conversationId: {turnContext.Activity?.Conversation?.Id}");
        }
Example #22
0
        /// <summary>
        /// Send the welcome message.
        /// </summary>
        /// <param name="turnContext">Provides the <see cref="ITurnContext"/> for the turn of the bot.</param>
        /// <param name="cancellationToken" >(Optional) A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the operation result of the Turn operation.</returns>
        private async Task SendWelcomeMessageAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var profileState = await _accessors.UserProfileAccessor.GetAsync(turnContext, () => new UserProfile(), cancellationToken);

            if (profileState.IsWelcomeMessageSent)
            {
                return;
            }
            profileState.IsWelcomeMessageSent = true;
            await _accessors.UserProfileAccessor.SetAsync(turnContext, profileState);

            var greeting = turnContext.Activity.From?.Name == null ? "Hi!" : $"Hi {turnContext.Activity.From.Name}!";
            await turnContext.SendActivitiesAsync(
                new IActivity[]
            {
                new Activity(type: ActivityTypes.Message, text: greeting),
                new Activity(type: ActivityTypes.Message, text: "My name is C.I.C.A. (Cool and Intelligent Carwash Assistant) and I'm your bot 🤖 who will help you reserve car washing services and answer your questions."),
                new Activity(type: ActivityTypes.Message, text: "Ask me questions like 'How to use the app?' or 'What does interior cleaning cost?'."),
                new Activity
                {
                    Type             = ActivityTypes.Message,
                    InputHint        = InputHints.AcceptingInput,
                    Text             = "Or I can make reservations for you. But before that you need to log in by typing 'login'.",
                    SuggestedActions = new SuggestedActions
                    {
                        Actions = new List <CardAction>
                        {
                            new CardAction {
                                Title = "login", Type = ActionTypes.ImBack, Value = "login"
                            },
                            new CardAction {
                                Title = "How to use the app?", Type = ActionTypes.ImBack, Value = "How to use the app?"
                            },
                            new CardAction {
                                Title = "What does interior cleaning cost?", Type = ActionTypes.ImBack, Value = "What does interior cleaning cost?"
                            },
                        },
                    },
                },
            },
                cancellationToken);
        }
        protected async override Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var conversationStateAccessors = _conversationState.CreateProperty <ConversationData>(nameof(ConversationData));
            var conversationData           = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationData());

            var userStateAccessors = _userState.CreateProperty <UserProfile>(nameof(UserProfile));
            var userProfile        = await userStateAccessors.GetAsync(turnContext, () => new UserProfile());

            var replyText = $"كسمك يا {turnContext.Activity.Text}";
            await turnContext.SendActivitiesAsync(
                new Activity[] {
                new Activity {
                    Type = ActivityTypes.Typing
                },
                new Activity {
                    Type = "delay", Value = 3000
                },
                MessageFactory.Text(replyText, replyText),
            },
                cancellationToken);
        }
Example #24
0
        private static async Task HandleRaidBossesInvocation(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            await turnContext.SendActivityAsync(MessageFactory.Text(Constants.RaidBossesMessage), cancellationToken);

            var tierFiveRaids = await PokeBattlerApi.GetRaids(tier : 5);

            if (tierFiveRaids.All(raid => !string.IsNullOrEmpty(raid.Article?.InfographicURL)))
            {
                bool pluralize = tierFiveRaids.Count() > 1;

                await turnContext.SendActivityAsync(MessageFactory.Text($"Here's {(pluralize ? "infographics" : " an infographic")} with details about the current tier-five raid {(pluralize ? "bosses" : "boss")}, courtesy of Pokebattler."));

                await turnContext.SendActivitiesAsync(
                    tierFiveRaids
                    .Select(raid =>
                            MessageFactory.Attachment(new Attachment("image/png", raid.Article.InfographicURL)) as IActivity
                            )
                    .ToArray()
                    );
            }
        }
        /// <summary>
        /// When OnTurn method receives a submit invoke activity on bot turn, it calls this method.
        /// </summary>
        /// <param name="turnContext">Provides context for a turn of a bot.</param>
        /// <param name="taskModuleRequestData">Task module invoke request value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents a task module response.</returns>
        protected override async Task<TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext<IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequestData, CancellationToken cancellationToken)
        {
            var valuesFromTaskModule = JsonConvert.DeserializeObject<SearchSubmitAction>(taskModuleRequestData.Data?.ToString());
            try
            {
                if (valuesFromTaskModule == null)
                {
                    this.logger.LogInformation($"Request data obtained on task module submit action is null.");
                    await turnContext.SendActivityAsync(Strings.ErrorMessage).ConfigureAwait(false);
                    return default;
                }

                switch (valuesFromTaskModule.Command.ToUpperInvariant().Trim())
                {
                    case Constants.MyProfile:
                        this.logger.LogInformation("Activity type is invoke submit from my profile command");
                        await this.dialog.RunAsync(turnContext, this.conversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken).ConfigureAwait(false);
                        break;
                    case Constants.Search:
                        this.logger.LogInformation("Activity type is invoke submit from search command");
                        List<IActivity> selectedUserActivities = new List<IActivity>();
                        valuesFromTaskModule.UserProfiles.ForEach(userProfile => selectedUserActivities.Add(MessageFactory.Attachment(SearchCard.GetUserCard(userProfile))));

                        // Bot is expected to send multiple user profile cards which may cross the threshold limit of bot messages/sec, hence adding the retry logic.
                        await RetryPolicy.ExecuteAsync(async () =>
                        {
                            await turnContext.SendActivitiesAsync(selectedUserActivities.ToArray(), cancellationToken).ConfigureAwait(false);
                        }).ConfigureAwait(false);
                        break;
                }

                return default;
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error in submit action of task module.");
                return default;
            }
        }
Example #26
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var cards = new List <IMessageActivity>();

            // Search for knowledge articles in CDS org
            var kbCards = await kBSearchOperation.SearchKBArticles(turnContext.Activity.Text);

            if (kbCards != null && kbCards.Count > 0)
            {
                cards.AddRange(kbCards);
            }

            // Check if the message has appointment intent
            var appointmentCard = await appointmentDetectionOperation.GetAppointmentDetectionCard(turnContext, cancellationToken);

            if (appointmentCard != null)
            {
                cards.Add(appointmentCard);
            }

            if (cards.Count > 0)
            {
                // IMPORTANT!
                // This tag MUST be present in all responses going from the bot
                // Any response without this tag will cause unintended UX errors
                cards.ForEach((card) =>
                {
                    Dictionary <string, object> channelinfo = new Dictionary <string, object>
                    {
                        { "tags", "smartbot" }
                    };
                    card.ChannelData = channelinfo;
                });

                // Send the card(s) as response
                await turnContext.SendActivitiesAsync(cards.ToArray(), cancellationToken);
            }
        }
Example #27
0
        public async Task AttachProfessorsCard(ITurnContext turnContext, List <ProfessorsNum> list, string searchName, CancellationToken cancellationToken)
        {
            var reply = new List <IMessageActivity>();

            foreach (ProfessorsNum professorsNum in list)
            {
                reply.Add(MessageFactory.Text
                              ($"{searchName}교수님으로 검색한 결과는 다음과 같습니다\n\n" +
                              $"대학 : {professorsNum.College}\n\n" +
                              $"학부 : {professorsNum.Department}\n\n" +
                              $"트랙 : {professorsNum.Track}\n\n" +
                              $"연구실 : {professorsNum.Lab}\n\n" +
                              $"이메일 : {professorsNum.Email}"));
            }

            var cardActions = new List <CardAction>();

            foreach (ProfessorsNum professorsNum in list)
            {
                cardActions.Add(new CardAction()
                {
                    Title = professorsNum.Name + "교수님께 전화걸기",
                    Type  = ActionTypes.Call,
                    Value = professorsNum.Adress
                });
            }
            var attachments = new List <Attachment>();

            attachments.Add(new HeroCard
            {
                Buttons = cardActions
            }.ToAttachment());
            reply.Add(MessageFactory.Attachment(attachments));


            await turnContext.SendActivitiesAsync(reply.ToArray(), cancellationToken);
        }
Example #28
0
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     // This first if statement is a temporary hack to work around the fact that GroupMe doesn't correctly route add/join messages through OnMembersAddedAsync.
     // Once https://github.com/microsoft/BotFramework-Services/issues/97 is resolved, welcome messages need only be handled by OnMembersAddedAsync
     foreach (var member in turnContext.Activity.NewMembers())
     {
         await WelcomeHelper.SendWelcomeMessage(member, turnContext, cancellationToken);
     }
     foreach (var member in turnContext.Activity.ReturningMembers())
     {
         await WelcomeHelper.SendWelcomeBackMessage(member, turnContext, cancellationToken);
     }
     if (turnContext.Activity.Text.StartsWith("!", StringComparison.Ordinal))
     {
         await InvocationHelper.HandleInvocationActivity(turnContext, cancellationToken);
     }
     if (turnContext.Activity.Polls().Any())
     {
         await turnContext.SendActivitiesAsync(new[] {
             MessageFactory.Text(Constants.VoteAndLikeReminder),
             MessageFactory.Text(Constants.MaskReminder)
         }, cancellationToken);
     }
 }
 public async Task <ResourceResponse[]> SendActivitiesAsync(IActivity[] activities, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await _adapter.SendActivitiesAsync(activities, cancellationToken));
 }
Example #30
0
 public Task <ResourceResponse[]> SendActivitiesAsync(IActivity[] activities, CancellationToken cancellationToken = default(CancellationToken))
 => _innerTurnContext.SendActivitiesAsync(activities, cancellationToken);