async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token)
        {
            try
            {
                await inner.PostAsync(activity, token);
            }
            catch (Exception ex)
            {
                trace.WriteLine(ex.Message);
                var messageActivity = activity.AsMessageActivity();
                if (messageActivity != null)
                {
                    await botToUser.PostAsync(messageProvider.GetMessage("ExceptionMessage"), cancellationToken : token);

                    await botToUser.PostAsync(messageProvider.GetMessage("WhatMoreCanIDo"), cancellationToken : token);

                    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, messageActivity))
                    {
                        var botData = scope.Resolve <IBotData>();
                        await botData.LoadAsync(default(CancellationToken));

                        var stack = scope.Resolve <IDialogStack>();
                        stack.Reset();
                        botData.ConversationData.Clear();
                        await botData.FlushAsync(default(CancellationToken));
                    }
                }
            }
        }
    public async Task PostAsync(IMessageActivity message,
                                CancellationToken cancellationToken = default(CancellationToken))
    {
        if (message.Text == "I’m Sorry, I don’t have an answer for you. Please try and rephrase your question")
        {
            //save to permanant storage here
            //if you would like to use a database
            //I have a very simple database bot example here
            //https://github.com/JasonSowers/DatabaseBotExample
        }
        //user is the recipient
        var userId = message.Recipient.Id;

        //remove entry from dictionary
        Utils.MessageDictionary.Remove(userId);
        //this is just for testing purposes and can be removed
        try
        {
            await inner.PostAsync($"{userId} - {Utils.MessageDictionary[userId]}");
        }
        catch (Exception e)
        {
            await inner.PostAsync($"No entry found for {userId}");
        }
        await inner.PostAsync((Activity)message, cancellationToken);
    }
Exemple #3
0
        async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token)
        {
            try
            {
                await _inner.PostAsync(activity, token);
            }
            catch (Exception error)
            {
                try
                {
                    if (Debugger.IsAttached)
                    {
                        var message = _botToUser.MakeMessage();
                        message.Text        = $"Exception: { error.Message}";
                        message.Attachments = new[]
                        {
                            new Attachment(MediaTypeNames.Text.Plain, content: error.StackTrace)
                        };

                        await _botToUser.PostAsync(message, token);
                    }
                    else
                    {
                        await _botToUser.PostAsync("Ops! I'm still handle the previous message...", cancellationToken : token);
                    }
                }
                catch (Exception e)
                {
                    _trace.WriteLine(e);
                }

                throw;
            }
        }
        private static async Task EvaluateAndRespondToSentimentAsync(IBotToUser context, Sentiment sentiment, string languageCode)
        {
            // If there's no Sentiment object or score value, quit now.
            if (sentiment?.Score == null)
            {
                return;
            }

            var sentimentResponse = string.Empty;

            try
            {
                // Score ranges from 0.0 to 1, with 4 decimals of precision
                if (sentiment.Score <= 0.1)
                {
                    // If the sentiment is lower than 3%, respond with apologies and recommend to reach out to support
                    sentimentResponse = "I'm sorry you're having problems. If you'd like to talk to a person, please email [email protected] and they will be able to assist further.";
                }
                else if (sentiment.Score >= 0.95)
                {
                    // if the sentiment is in the top 97%, respond with a reminder to leave a review for the app.
                    sentimentResponse = "I'm happy to see you're enjoying our services. Please consider leaving an app review after you're done today!";
                }

                // If there's no response needed, quit now.
                if (string.IsNullOrEmpty(sentimentResponse))
                {
                    return;
                }

                // Check to see if we need to translate the response.
                if (languageCode != "en")
                {
                    using (var translationClient = new TextTranslationServiceClient(SubscriptionKeys.TextTranslationServiceKey))
                    {
                        if (!string.IsNullOrEmpty(sentimentResponse))
                        {
                            var translationResult = await translationClient.TranslateAsync(sentimentResponse, languageCode);

                            var translatedSentimentResponse = translationResult.Translations.FirstOrDefault()?.Text;

                            if (!string.IsNullOrEmpty(translatedSentimentResponse))
                            {
                                // If we were able to translate the message, update the message we're sending.
                                sentimentResponse = translatedSentimentResponse;
                            }
                        }
                    }
                }

                // Reply with the sentiment response.
                await context.PostAsync(sentimentResponse);
            }
            catch (Exception ex)
            {
                await context.PostAsync($"EvaluateAndRespondToSentimentAsync Exception: {ex.Message}");
            }
        }
Exemple #5
0
        /// <inheritdoc/>
        protected override async Task PostAsync(IActivity item, bool state, CancellationToken token)
        {
            await _botToUser.PostAsync($"Your conversation Id is:{item.Conversation.Id}.", cancellationToken : token);

            await _botToUser.PostAsync($"Your dialog stack is:", cancellationToken : token);

            foreach (var task in _task.Frames)
            {
                await _botToUser.PostAsync($"Task {task.Target.GetType()}.", cancellationToken : token);
            }
        }
        /// <summary>執行階段:主要的對話處理程序,會從所有全域處理程序中執行最高分的項目</summary>
        protected override async Task PostAsync(IActivity item, bool state, CancellationToken token)
        {
            if (await _agentService.IsInExistingConversationAsync(item, token))
            {
                await _agentToUser.SendToUserAsync(item as Activity, token);
            }
            else
            {
                await _botToUser.PostAsync(ConversationText.NotTalkingWithAnyUser);

                await _botToUser.PostAsync(ConversationText.NotTalkingWithBot);
            }
        }
        protected override async Task PostAsync(IActivity item, bool state, CancellationToken token)
        {
            if (await _agentService.IsInExistingConversationAsync(item, token))
            {
                await _agentToUser.SendToUserAsync(item as Activity, token);
            }
            else
            {
                await _botToUser.PostAsync("You are not talking with any user.");

                await _botToUser.PostAsync("And sadly, you can't talk to me either. :(");
            }
        }
        async Task IMessageQueue.DrainQueueAsync(IBotToUser botToUser, CancellationToken token)
        {
            while (this.queue.Count > 0)
            {
                var toUser = this.queue.Dequeue();
                // last message in the queue will be treated specially for channels that need input hints
                if (this.queue.Count == 0)
                {
                    var stack = this.makeStack();
                    if (this.channelCapability.ShouldSetInputHint(toUser) && stack.Frames.Count > 0)
                    {
                        var topOfStack = stack.Frames[0].Target;
                        // if there is a prompt dialog on top of stack, the InputHint will be set to Expecting
                        if (topOfStack != null && topOfStack.GetType().DeclaringType == typeof(PromptDialog))
                        {
                            toUser.InputHint = InputHints.ExpectingInput;
                        }
                        else
                        {
                            toUser.InputHint = InputHints.AcceptingInput;
                        }
                    }
                }
                else
                {
                    if (this.channelCapability.ShouldSetInputHint(toUser))
                    {
                        toUser.InputHint = InputHints.IgnoringInput;
                    }
                }

                await botToUser.PostAsync(toUser, token);
            }
        }
Exemple #9
0
        async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token)
        {
            try
            {
                await this.inner.PostAsync(activity, token);
            }
            catch (Exception error)
            {
                this.trace.WriteLine(error);

                Log.Fatal(error, "Impossible to reply to the user because of an {Type} exception: '{Message}'", error.GetType(), error.Message);

                try
                {
                    var message = this.botToUser.MakeMessage();
                    message.Text = Resources.UnhandledException_Message;

                    AddExceptionToMessageAtDebug(message, error);

                    await botToUser.PostAsync(message, cancellationToken : token);
                }
                catch (Exception inner)
                {
                    this.trace.WriteLine(inner);

                    Log.Fatal(inner, "Impossible to notify the user because of an {Type} exception: '{Message}'", inner.GetType(), inner.Message);
                }

                throw;
            }
        }
        /// <summary>
        /// Posts a typing (e.g. "...") message to user.
        /// </summary>
        public static Task PostTyping(this IBotToUser context)
        {
            var reply = context.MakeMessage();

            reply.Type = ActivityTypes.Typing;
            return(context.PostAsync(reply));
        }
        private static async Task SendMessageAsync(IBotToUser context, Attachment attachment)
        {
            var message = context.MakeMessage();

            message.Attachments.Add(attachment);
            await context.PostAsync(message);
        }
        private static async Task SendMessageAsync(IBotToUser context, string text)
        {
            var message = context.MakeMessage();

            message.Text = text;
            await context.PostAsync(message);
        }
Exemple #13
0
        /// <summary>
        /// Post a message to be sent to the bot, using previous messages to establish a conversation context.
        /// </summary>
        /// <param name="text">The message text.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task that represents the post operation.</returns>
        public static async Task PostAsync(this IBotToUser botToUser, string text, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = botToUser.MakeMessage();

            message.Text = text;
            await botToUser.PostAsync(message, cancellationToken);
        }
Exemple #14
0
        public async Task RenderAsync(List <ISesamError> errors)
        {
            var message = botToUser.MakeMessage();

            message = BuildMessageFromErrors(errors, message);
            await botToUser.PostAsync(message);
        }
        async Task IAlarmRenderer.RenderAsync(IBotToUser botToUser, string title, DateTime now)
        {
            Alarm alarm;

            if (this.scheduler.TryFindAlarm(title, out alarm))
            {
                var card = new HeroCard();
                card.Title    = alarm.Title ?? "Default Alarm";
                card.Subtitle = alarm.State
                    ? (alarm.When.HasValue ? $"{alarm.When}" : "not set")
                    : "disabled";

                IAlarmable query = alarm;
                DateTime   next;
                if (query.TryFindNext(now, out next))
                {
                    var  remaining = next.Subtract(now);
                    bool today     = now.Date == next.Date;
                    card.Text = $"There is {remaining:dd\\.hh\\:mm\\:ss} remaining before this alarm rings.";
                }

                var buttons = this.actions.ActionsFor(alarm);
                card.Buttons = buttons.ToArray();

                var message = botToUser.MakeMessage();
                message.Attachments = new[] { card.ToAttachment() };

                await botToUser.PostAsync(message);
            }
            else
            {
                throw new AlarmNotFoundException();
            }
        }
 private static async Task ShowHelp(IBotToUser context)
 {
     await context.PostAsync("You can ask me about talks, rooms and speakers.\n\n" +
                             "Try asking: When is Tatham's talk?\n\n" +
                             "or\n\n" +
                             "What's happening on Red room?\n\n" +
                             "or\n\n" +
                             "What's going on at 3PM?");
 }
Exemple #17
0
        protected override async Task PostAsync(IActivity item, string state, CancellationToken token)
        {
            this.stack.Reset();
            botData.UserData.Clear();
            botData.PrivateConversationData.Clear();
            await botData.FlushAsync(token);

            await botToUser.PostAsync(Resources.UserProfileDeleted);
        }
        async Task IScorable <IActivity, double> .PostAsync(IActivity message, object state, CancellationToken token)
        {
            this.stack.Reset();
            botData.UserData.Clear();
            botData.PrivateConversationData.Clear();
            await botData.FlushAsync(token);

            await botToUser.PostAsync(Resources.UserProfileDeleted);
        }
        private static async Task SendMessageAsync(IBotToUser context, List <HeroCard> cards, string title)
        {
            var message = context.MakeMessage();

            message.Text             = title;
            message.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            message.Attachments      = cards.Select(card => card.ToAttachment()).ToList();
            await context.PostAsync(message);
        }
        /// <inheritdoc/>
        protected override async Task PostAsync(IActivity item, bool state, CancellationToken token)
        {
            _stack.Reset();
            _botData.UserData.Clear();
            _botData.PrivateConversationData.Clear();
            _botData.ConversationData.Clear();
            await _botData.FlushAsync(token);

            await _botToUser.PostAsync("Profile Reset", cancellationToken : token);
        }
        async Task IScorable <double> .PostAsync <Item>(IPostToBot inner, Item item, object state, CancellationToken token)
        {
            var message = (IMessageActivity)(object)item;

            this.stack.Reset();
            botData.UserData.Clear();
            botData.PrivateConversationData.Clear();
            await botData.FlushAsync(token);

            await botToUser.PostAsync(Resources.UserProfileDeleted);
        }
 async Task IMessageQueue.QueueMessageAsync(IBotToUser botToUser, IMessageActivity message, CancellationToken token)
 {
     // This assumes that if InputHint is set on message, it is the right value that channel expects
     // and will NOT queue the message
     if (this.channelCapability.ShouldSetInputHint(message))
     {
         // drain the queue
         while (this.queue.Count > 0)
         {
             var toUser = this.queue.Dequeue();
             toUser.InputHint = InputHints.IgnoringInput;
             await botToUser.PostAsync(toUser, token);
         }
         queue.Enqueue(message);
     }
     else
     {
         await botToUser.PostAsync(message, token);
     }
 }
Exemple #23
0
        /// <summary>
        /// Post a message to be sent to the bot, using previous messages to establish a conversation context.
        /// </summary>
        /// <remarks>
        /// If the locale parameter is not set, locale of the incoming message will be used for reply.
        /// </remarks>
        /// <param name="botToUser">Communication channel to use.</param>
        /// <param name="text">The message text.</param>
        /// <param name="locale">The locale of the text.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task that represents the post operation.</returns>
        public static async Task PostAsync(this IBotToUser botToUser, string text, string locale = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = botToUser.MakeMessage();
            message.Text = text;

            if (!string.IsNullOrEmpty(locale))
            {
                message.Locale = locale;
            }

            await botToUser.PostAsync(message, cancellationToken);
        }
        /// <summary>
        /// Replay activity to IBotToUser.
        /// </summary>
        /// <param name="activity">Activity.</param>
        /// <returns>Task.</returns>
        public async Task Replay(IActivity activity)
        {
            if (activity is IMessageActivity)
            {
                var msg = _botToUser.MakeMessage();
                msg.Text = _header(activity);
                await _botToUser.PostAsync(msg);

                var act = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(activity));
                if (act.ChannelId != msg.ChannelId)
                {
                    act.ChannelData = null;
                }
                act.From         = msg.From;
                act.Recipient    = msg.Recipient;
                act.ReplyToId    = msg.ReplyToId;
                act.ChannelId    = msg.ChannelId;
                act.Conversation = msg.Conversation;
                await _botToUser.PostAsync(act);
            }
        }
Exemple #25
0
        async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token)
        {
            try
            {
                await _inner.PostAsync(activity, token);
            }
            catch (Exception error)
            {
                var logger = LogManager.GetCurrentClassLogger();
                logger.LogError("Unhandled exception during dialog.", error.Message, error.ToString(), activity.Conversation.Id);

                try
                {
                    if (Debugger.IsAttached)
                    {
                        var message = _botToUser.MakeMessage();
                        message.Text        = $"Exception: { error }";
                        message.Attachments = new[]
                        {
                            new Attachment(MediaTypeNames.Text.Plain, content: error.StackTrace)
                        };

                        await _botToUser.PostAsync(message, token);
                    }
                    else
                    {
                        var message = _botToUser.MakeMessage();
                        message.Text = "Chatboten har støtt på et uventet problem. Vennligst prøv igjen senere eller ring oss";
                        await _botToUser.PostAsync(message, token);
                    }
                }
                catch (Exception inner)
                {
                    _trace.WriteLine(inner);
                    logger.LogError("Unhandled exception during handling an error.", inner.Message, inner.ToString(), activity.Conversation.Id);
                }

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

            if (message != null)
            {
                var reply = _botToUser.MakeMessage();

                reply.Text = answers.SelectRandomdly();

                await _botToUser.PostAsync(reply);
            }
        }
Exemple #27
0
        public static async Task PostWithTranslationAsync(this IBotToUser context, string message, string messageLocale, string userLocale)
        {
            if (messageLocale == null)
            {
                throw new ArgumentNullException(nameof(messageLocale));
            }
            if (userLocale == null)
            {
                throw new ArgumentNullException(nameof(userLocale));
            }

            try
            {
                var bingTranslatorClient = new BingTranslatorClient("Test187871", "dAnT3r/eIc8KedBRUgRCV+juxpf4Wl312jn1Bd2SXzk=");
                var translatedMessage    = await bingTranslatorClient.Translate(message, messageLocale, userLocale);

                await context.PostAsync(translatedMessage, userLocale);
            }
            catch (Exception e)
            {
                await context.PostAsync("Translator service problems, please try again later", "en-US");
            }
        }
 public async Task PostAsync(IActivity activity, CancellationToken token)
 {
     try
     {
         await inner.PostAsync(activity, token);
     }
     catch (Exception ex)
     {
         try
         {
             await botToUser.PostAsync("Sorry that I'm unable to answer you in current context. Please try again later...", cancellationToken : token);
         }
         catch (Exception innerex)
         {
             trace.WriteLine(inner);
         }
         throw;
     }
 }
        public async Task PostAsync(IActivity activity, CancellationToken token)
        {
            try
            {
                await inner.PostAsync(activity, token);
            }
            catch (Exception)
            {
                try
                {
                    await botToUser.PostAsync("An Error Has Occurred.....", cancellationToken : token);
                }
                catch (Exception inner)
                {
                    trace.WriteLine(inner);
                }

                throw;
            }
        }
        /// <summary>執行階段:主要的對話處理程序,會從所有全域處理程序中執行最高分的項目</summary>
        protected override async Task PostAsync(IActivity item, bool state, CancellationToken token)
        {
            if (await _humanService.IsInExistingConversationAsync(item, token))
            {
                var message      = item as Activity;
                var agentAddress = new Agent(message).GetAddress();
                var botData      = await Utility.GetBotDataAsync(agentAddress, _botDataStore, token);

                botData.PrivateConversationData.TryGetValue(Constants.USER_ROUTE_KEY, out Agent agent);

                var reference = agent.ConversationReference;
                var reply     = reference.GetPostToUserMessage();
                reply.Text = message?.Text;

                await Utility.SendToConversationAsync(reply);
            }
            else
            {
                await _botToUser.PostAsync("您沒有與任何使用者對話", null, token);
            }
        }