コード例 #1
0
        private async Task HandleDeleteActivitiesAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            foreach (var activityId in _activityIds)
            {
                await turnContext.DeleteActivityAsync(activityId, cancellationToken);
            }

            this._activityIds.Clear();
        }
コード例 #2
0
        public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
        {
            //Examine outgoing activity for SuggestedActions and convert it to card with messageBack Actions
            //All messageBack actions are tagged with "AddedBy"
            turnContext.OnSendActivities(async(newContext, activities, nextSend) =>
            {
                var suggestedActionCardActivities = new List <Activity>();
                foreach (var activity in activities.Where(act => (act.ChannelId == TeamsChannelId && act.SuggestedActions != null)))
                {
                    var newActivity         = newContext.Activity.CreateReply();
                    newActivity.Attachments = new List <Attachment>();
                    //Create a new card having suggested action buttons
                    var suggestedActionCard = new HeroCard()
                    {
                        Buttons = activity.SuggestedActions.ToMessageBackActions()
                    };
                    newActivity.Attachments.Add(suggestedActionCard.ToAttachment());
                    suggestedActionCardActivities.Add(newActivity);
                    activity.SuggestedActions = null;
                }

                activities.AddRange(suggestedActionCardActivities);
                return(await nextSend());
            });

            //Examine incoming activity for messageBack actions
            if (turnContext.Activity.ChannelId == TeamsChannelId &&
                turnContext.Activity.Value != null)
            {
                var obj = (JObject)turnContext.Activity.Value;
                if (obj != null &&
                    obj.ContainsKey(Constants.AddedBy) &&
                    obj[Constants.AddedBy].ToString() == Constants.SuggestedActionsMiddleware)
                {
                    // In case the suggestedAction was a MessageBack
                    switch (obj["type"].ToString())
                    {
                    case ActionTypes.MessageBack:
                    {
                        try
                        {
                            turnContext.Activity.Value = JObject.Parse(obj["Value"].ToString());
                        }
                        catch (JsonReaderException ex)
                        {
                            turnContext.Activity.Value = obj["Value"].ToString();
                        }
                    }
                    break;
                    }
                    //delete the original suggested actions card in which this button was clicked.
                    _ = turnContext.DeleteActivityAsync(turnContext.Activity.ReplyToId);
                }
            }

            await next(cancellationToken).ConfigureAwait(false);
        }
コード例 #3
0
        private async Task DeleteCardActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            await turnContext.DeleteActivityAsync(turnContext.Activity.ReplyToId, cancellationToken);

            // Send EoC when the card is deleted
            var eocActivity = Activity.CreateEndOfConversationActivity();

            eocActivity.Code = EndOfConversationCodes.CompletedSuccessfully;
            await turnContext.SendActivityAsync(eocActivity, cancellationToken);
        }
コード例 #4
0
        public async Task <InvokeResponse> HandleFileConsentDeclineResponse(ITurnContext <IInvokeActivity> turnContext, FileConsentCardResponse fileConsentCardResponse, CancellationToken cancellationToken = default)
        {
            if (!string.IsNullOrEmpty(turnContext.Activity.ReplyToId))
            {
                await turnContext.DeleteActivityAsync(turnContext.Activity.ReplyToId, cancellationToken);
            }

            return(new InvokeResponse {
                Status = (int)HttpStatusCode.OK
            });
        }
        /// <summary>
        /// Clean up the data such as file, consent card, record.
        /// </summary>
        /// <param name="turnContext">The context object for this turn.</param>
        /// <param name="fileName">The file name.</param>
        /// <param name="notificationId">The notification id.</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 representing asynchronous operation.</returns>
        public async Task CleanUp(
            ITurnContext turnContext,
            string fileName,
            string notificationId,
            CancellationToken cancellationToken)
        {
            var exportData = await this.exportDataRepository.GetAsync(
                turnContext.Activity.From?.AadObjectId,
                notificationId);

            // Clean up activity such as deleting consent card, file from blob storage and table record.
            await turnContext.DeleteActivityAsync(exportData.FileConsentId, cancellationToken);

            await this.DeleteFileAsync(fileName);

            await this.exportDataRepository.DeleteAsync(exportData);
        }
コード例 #6
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());
            }
コード例 #7
0
        private async Task DeleteActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            var ignoreDelete = turnContext.TurnState.Get <CardManagerTurnState>()?.MiddlewareIgnoreDelete;

            ignoreDelete?.Add(activity.Id);

            try
            {
                await turnContext.DeleteActivityAsync(activity.Id, cancellationToken).ConfigureAwait(false);
            }
            catch
            {
                // TODO: Find out what exceptions I need to handle
                throw;
            }
            finally
            {
                ignoreDelete?.Remove(activity.Id);
            }

            await RemoveActivityAsync(turnContext, activity, cancellationToken).ConfigureAwait(false);
        }
コード例 #8
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            turnContext.Activity.RemoveRecipientMention();
            if (turnContext.Activity.Text == "delete")
            {
                foreach (var activityId in _list)
                {
                    await turnContext.DeleteActivityAsync(activityId, cancellationToken);
                }
                _list.Clear();
            }
            else
            {
                await SendMessageAndLogActivityId(turnContext, $"{turnContext.Activity.Text}", cancellationToken);

                foreach (var activityId in _list)
                {
                    var newActivity = MessageFactory.Text(turnContext.Activity.Text);
                    newActivity.Id = activityId;
                    await turnContext.UpdateActivityAsync(newActivity, cancellationToken);
                }
            }
        }
コード例 #9
0
 public async Task DeleteActivityAsync(string activityId, CancellationToken cancellationToken = default(CancellationToken))
 {
     await _adapter.DeleteActivityAsync(activityId, cancellationToken);
 }
コード例 #10
0
 public Task DeleteActivityAsync(string activityId, CancellationToken cancellationToken = default(CancellationToken))
 => _innerTurnContext.DeleteActivityAsync(activityId, cancellationToken);
コード例 #11
0
 private async Task DeleteCardActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     await turnContext.DeleteActivityAsync(turnContext.Activity.ReplyToId, cancellationToken);
 }
コード例 #12
0
        public SkillCallingRequestHandler(ITurnContext turnContext, Action <Activity> tokenRequestHandler = null, Action <Activity> handoffActivityHandler = null)
        {
            _turnContext            = turnContext ?? throw new ArgumentNullException(nameof(turnContext));
            _tokenRequestHandler    = tokenRequestHandler;
            _handoffActivityHandler = handoffActivityHandler;

            var routes = new RouteTemplate[]
            {
                new RouteTemplate()
                {
                    Method = "POST",
                    Path   = "/activities/{activityId}",
                    Action = new RouteAction()
                    {
                        Action =
                            async(request, routeData) =>
                        {
                            var activity = await request.ReadBodyAsJson <Activity>().ConfigureAwait(false);

                            if (activity != null)
                            {
                                if (activity.Type == ActivityTypes.Event && activity.Name == TokenEvents.TokenRequestEventName)
                                {
                                    if (_tokenRequestHandler != null)
                                    {
                                        _tokenRequestHandler(activity);

                                        return(new ResourceResponse());
                                    }
                                    else
                                    {
                                        throw new ArgumentNullException("TokenRequestHandler", "Skill is requesting for token but there's no handler on the calling side!");
                                    }
                                }
                                else if (activity.Type == ActivityTypes.EndOfConversation)
                                {
                                    if (_handoffActivityHandler != null)
                                    {
                                        _handoffActivityHandler(activity);

                                        return(new ResourceResponse());
                                    }
                                    else
                                    {
                                        throw new ArgumentNullException("HandoffActivityHandler", "Skill is sending handoff activity but there's no handler on the calling side!");
                                    }
                                }
                                else
                                {
                                    var result = await _turnContext.SendActivityAsync(activity).ConfigureAwait(false);

                                    return(result);
                                }
                            }
                            else
                            {
                                throw new Exception("Error deserializing activity response!");
                            }
                        },
                    },
                },
                new RouteTemplate()
                {
                    Method = "PUT",
                    Path   = "/activities/{activityId}",
                    Action = new RouteAction()
                    {
                        Action =
                            async(request, routeData) =>
                        {
                            var activity = await request.ReadBodyAsJson <Activity>().ConfigureAwait(false);

                            var result = _turnContext.UpdateActivityAsync(activity).ConfigureAwait(false);
                            return(result);
                        },
                    },
                },
                new RouteTemplate()
                {
                    Method = "DELETE",
                    Path   = "/activities/{activityId}",
                    Action = new RouteAction()
                    {
                        Action =
                            async(request, routeData) =>
                        {
                            var result = await _turnContext.DeleteActivityAsync(routeData.activityId);

                            return(result);
                        },
                    },
                },
            };

            _router = new Router(routes);
        }
コード例 #13
0
        /// <summary>
        /// On Teams Messaging Extension Submit Action Async.
        /// </summary>
        /// <param name="turnContext">turnContext.</param>
        /// <param name="action">action.</param>
        /// <param name="cancellationToken">cancellationToken.</param>
        /// <returns>.</returns>
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            _telemetry.TrackEvent("OnTeamsMessagingExtensionSubmitActionAsync");
            ReflectionDataRepository reflectionDataRepository = new ReflectionDataRepository(_configuration, _telemetry);

            try
            {
                TaskInfo taskInfo = JsonConvert.DeserializeObject <TaskInfo>(action.Data.ToString());
                switch (taskInfo.action)
                {
                case "reflection":
                    return(await OnTeamsMessagingExtensionFetchTaskAsync(turnContext, action, cancellationToken));

                case "sendAdaptiveCard":
                    try
                    {
                        var name = (turnContext.Activity.From.Name).Split();
                        taskInfo.postCreateBy       = name[0] + ' ' + name[1];
                        taskInfo.postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                        taskInfo.channelID        = turnContext.Activity.TeamsGetChannelId();
                        taskInfo.postSendNowFlag  = (taskInfo.executionTime == "Send now") ? true : false;
                        taskInfo.IsActive         = true;
                        taskInfo.questionRowKey   = Guid.NewGuid().ToString();
                        taskInfo.recurrsionRowKey = Guid.NewGuid().ToString();
                        taskInfo.reflectionRowKey = Guid.NewGuid().ToString();
                        taskInfo.serviceUrl       = turnContext.Activity.ServiceUrl;
                        taskInfo.teantId          = turnContext.Activity.Conversation.TenantId;
                        taskInfo.scheduleId       = Guid.NewGuid().ToString();
                        await _dbHelper.SaveReflectionDataAsync(taskInfo);

                        if (taskInfo.postSendNowFlag == true)
                        {
                            var typingActivity = MessageFactory.Text(string.Empty);
                            typingActivity.Type = ActivityTypes.Typing;
                            await turnContext.SendActivityAsync(typingActivity);

                            var adaptiveCard = _cardHelper.CreateNewReflect(taskInfo);
                            var message      = MessageFactory.Attachment(new Attachment {
                                ContentType = AdaptiveCard.ContentType, Content = adaptiveCard
                            });
                            var resultid = await turnContext.SendActivityAsync(message, cancellationToken);

                            ReflectionDataEntity reflectData = await reflectionDataRepository.GetReflectionData(taskInfo.reflectionID);

                            reflectData.ReflectMessageId = resultid.Id;
                            await reflectionDataRepository.InsertOrMergeAsync(reflectData);

                            try
                            {
                                var feedbackCard = _cardHelper.FeedBackCard(new Dictionary <int, List <FeedbackDataEntity> >(), taskInfo.reflectionID, taskInfo.question);

                                Attachment attachmentfeedback = new Attachment()
                                {
                                    ContentType = AdaptiveCard.ContentType,
                                    Content     = feedbackCard,
                                };
                                using var connector = new ConnectorClient(new Uri(reflectData.ServiceUrl), _configuration["MicrosoftAppId"], _configuration["MicrosoftAppPassword"]);

                                var conversationId = $"{reflectData.ChannelID};messageid={reflectData.ReflectMessageId}";
                                var replyActivity  = MessageFactory.Attachment(new Attachment {
                                    ContentType = AdaptiveCard.ContentType, Content = feedbackCard
                                });
                                replyActivity.Conversation = new ConversationAccount(id: conversationId);
                                var resultfeedback = await connector.Conversations.SendToConversationAsync((Activity)replyActivity, cancellationToken);

                                reflectData.MessageID = resultfeedback.Id;
                                // update messageid in reflection table
                                await reflectionDataRepository.InsertOrMergeAsync(reflectData);
                            }
                            catch (System.Exception e)
                            {
                                _telemetry.TrackException(e);
                                Console.WriteLine(e.Message.ToString());
                            }
                        }
                        return(null);
                    }
                    catch (Exception ex)
                    {
                        _telemetry.TrackException(ex);
                        return(null);
                    }

                case "ManageRecurringPosts":
                    var postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                    var response = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 600,
                                Width  = 780,
                                Title  = "Track how you're feeling every day.",
                                Url    = this._configuration["BaseUri"] + "/ManageRecurringPosts/" + postCreatedByEmail + "?pathfromindex=true"
                            },
                        },
                    };
                    return(response);

                case "OpenDetailfeedback":
                    var responsefeedback = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 600,
                                Width  = 780,
                                Title  = "Track how you're feeling every day.",
                                Url    = this._configuration["BaseUri"] + "/openReflectionFeedback/" + taskInfo.reflectionID + "/" + taskInfo.feedback,
                            },
                        },
                    };
                    return(responsefeedback);

                case "removeposts":
                    try
                    {
                        var activity = Activity.CreateMessageActivity();
                        if (taskInfo.isDelete)
                        {
                            var messageId = await _dbHelper.RemoveReflectionId(taskInfo.messageID);

                            if (messageId != null)
                            {
                                await turnContext.DeleteActivityAsync(messageId);
                            }
                            await turnContext.DeleteActivityAsync(taskInfo.messageID);

                            activity.Text = "This post has been removed";
                            await turnContext.SendActivityAsync(activity);

                            return(null);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        _telemetry.TrackException(ex);
                        return(null);
                    }

                default:
                    return(null);
                }
                ;
            }
            catch (Exception ex)
            {
                _telemetry.TrackException(ex);
                return(null);
            }
        }
コード例 #14
0
        private async Task ProcessSkillActivityAsync(ITurnContext turnContext, NextDelegate next, ChannelApiArgs invokeArgs, CancellationToken cancellationToken)
        {
            try
            {
                // TODO: this cast won't work for custom adapters
                var adapter = turnContext.Adapter as BotFrameworkAdapter;

                switch (invokeArgs.Method)
                {
                // Send activity(activity)
                case ChannelApiMethods.SendToConversation:
                {
                    var activityPayload = (Activity)invokeArgs.Args[0];
                    if (activityPayload.Type == ActivityTypes.EndOfConversation)
                    {
                        await ProcessEndOfConversationAsync(turnContext, next, activityPayload, cancellationToken).ConfigureAwait(false);

                        invokeArgs.Result = new ResourceResponse(id: Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
                        return;
                    }

                    invokeArgs.Result = await turnContext.SendActivityAsync(activityPayload, cancellationToken).ConfigureAwait(false);

                    return;
                }

                // Send activity(replyToId, activity)
                case ChannelApiMethods.ReplyToActivity:
                {
                    var activityPayload = (Activity)invokeArgs.Args[1];
                    activityPayload.ReplyToId = (string)invokeArgs.Args[0];

                    if (activityPayload.Type == ActivityTypes.EndOfConversation)
                    {
                        await ProcessEndOfConversationAsync(turnContext, next, activityPayload, cancellationToken).ConfigureAwait(false);

                        invokeArgs.Result = new ResourceResponse(id: Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
                        return;
                    }

                    invokeArgs.Result = await turnContext.SendActivityAsync(activityPayload, cancellationToken).ConfigureAwait(false);

                    return;
                }

                // UpdateActivity(activity)
                case ChannelApiMethods.UpdateActivity:
                    invokeArgs.Result = await turnContext.UpdateActivityAsync((Activity)invokeArgs.Args[0], cancellationToken).ConfigureAwait(false);

                    return;

                // DeleteActivity(activityId)
                case ChannelApiMethods.DeleteActivity:
                    await turnContext.DeleteActivityAsync((string)invokeArgs.Args[0], cancellationToken).ConfigureAwait(false);

                    break;

                // SendConversationHistory(history)
                case ChannelApiMethods.SendConversationHistory:
                    throw new NotImplementedException($"{ChannelApiMethods.SendConversationHistory} is not supported");

                // GetConversationMembers()
                case ChannelApiMethods.GetConversationMembers:
                    if (adapter != null)
                    {
                        invokeArgs.Result = await adapter.GetConversationMembersAsync(turnContext, cancellationToken).ConfigureAwait(false);
                    }

                    break;

                // GetConversationPageMembers((int)pageSize, continuationToken)
                case ChannelApiMethods.GetConversationPagedMembers:
                    throw new NotImplementedException($"{ChannelApiMethods.SendConversationHistory} is not supported");

                //if (adapter != null)
                //{
                //    invokeArgs.Result = await adapter.OnGetConversationsAsync((int)invokeArgs.Args[0], (string)invokeArgs.Args[1], cancellationToken).ConfigureAwait(false);
                //}

                // DeleteConversationMember(memberId)
                case ChannelApiMethods.DeleteConversationMember:
                    if (adapter != null)
                    {
                        await adapter.DeleteConversationMemberAsync(turnContext, (string)invokeArgs.Args[0], cancellationToken).ConfigureAwait(false);
                    }

                    break;

                // GetActivityMembers(activityId)
                case ChannelApiMethods.GetActivityMembers:
                    if (adapter != null)
                    {
                        invokeArgs.Result = await adapter.GetActivityMembersAsync(turnContext, (string)invokeArgs.Args[0], cancellationToken).ConfigureAwait(false);
                    }

                    break;

                case ChannelApiMethods.UploadAttachment:
                    throw new NotImplementedException($"{ChannelApiMethods.UploadAttachment} is not supported");
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types (excluding, we use the general exception to store it in the inokeArgs).
            catch (Exception ex)
            {
                invokeArgs.Exception = ex;
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }
コード例 #15
0
        public async Task <InvokeResponse> HandleFileConsentAcceptResponse(ITurnContext <IInvokeActivity> turnContext, FileConsentCardResponse fileConsentCardResponse, CancellationToken cancellationToken = default)
        {
            var consentAcceptResponse = new InvokeResponse {
                Status = (int)HttpStatusCode.OK
            };

            var responseContext = JsonConvert.DeserializeObject <FileConsentContext>(fileConsentCardResponse.Context?.ToString());

            if (responseContext is null)
            {
                return(consentAcceptResponse);
            }

            var candidate = await _candidateService.GetById(responseContext.CandidateId, cancellationToken);

            if (candidate is null)
            {
                return(consentAcceptResponse);
            }

            IMessageActivity reply;

            try
            {
                // Upload the file contents to the upload session we got from the invoke value
                // See https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession#upload-bytes-to-the-upload-session
                var bytes = Encoding.UTF8.GetBytes(candidate.Summary);
                using (var stream = new MemoryStream(bytes))
                {
                    using (var content = new StreamContent(stream))
                    {
                        content.Headers.ContentRange = new ContentRangeHeaderValue(0, bytes.LongLength - 1, bytes.LongLength);
                        content.Headers.ContentType  = new MediaTypeHeaderValue(MediaTypeNames.Application.Octet);
                        var client   = _clientFactory.CreateClient();
                        var response = await client.PutAsync(fileConsentCardResponse.UploadInfo.UploadUrl, content, cancellationToken);

                        response.EnsureSuccessStatusCode();
                    }
                }

                if (!string.IsNullOrEmpty(turnContext.Activity.ReplyToId))
                {
                    await turnContext.DeleteActivityAsync(turnContext.Activity.ReplyToId, cancellationToken);
                }

                // Send the user a link to the uploaded file
                var fileInfoCard = new FileInfoCard
                {
                    FileType = fileConsentCardResponse.UploadInfo.FileType,
                    UniqueId = fileConsentCardResponse.UploadInfo.UniqueId
                };

                reply = MessageFactory.Attachment(fileInfoCard.ToAttachment(fileConsentCardResponse.UploadInfo.Name, fileConsentCardResponse.UploadInfo.ContentUrl));
            }
            catch (Exception ex)
            {
                reply = MessageFactory.Text($"There was an error uploading the file: {ex.Message}");
            }

            await turnContext.SendActivityAsync(reply, cancellationToken);

            return(consentAcceptResponse);
        }
コード例 #16
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            AddConversationReference(turnContext.Activity as Activity);
            if (turnContext.Activity.Value != null)
            {
                JObject jObject     = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(turnContext.Activity.Value));
                bool    isCommented = false;
                var     json        = JsonConvert.SerializeObject(turnContext.Activity.Value);
                var     desc        = 0;

                var key = jObject["Key"].ToString();

                ThirdMessageType message = new ThirdMessageType();
                message.Type = jObject["Type"].ToString();


                var approve = jObject["Approved"].ToString();
                message.IDCard      = jObject["IDCard"].ToString();
                message.IDTask      = jObject["IDTask"].ToString();
                message.TaskType    = jObject["TaskType"].ToString();
                message.Key         = jObject["Key"].ToString();
                message.AssignedTo  = jObject["AssignedTo"].ToString();
                message.MessageType = jObject["MessageType"].ToString();

                message.LibDispName = jObject["LibDispName"].ToString();
                message.TitleTask   = jObject["TitleTask"].ToString();
                message.Link        = jObject["Link"].ToString();
                message.Comment     = "";

                message.TaskType = jObject["TitleTask"].ToString();
                if (approve == "Rejected")
                {
                    message.Comment = jObject["Comment"].ToString();
                }
                else
                {
                    message.Comment = jObject["ApproveComment"].ToString();
                }
                message.CardType = "submitted";
                var myUpdatedCard = AdaptiveCardFactory.CreateAdaptiveCardAfterSubmitAttachment(message, approve, message.Comment);
                if (approve == "Rejected" && string.IsNullOrEmpty(message.Comment.Trim()))
                {
                    desc             = 1;
                    message.CardType = "comment";
                    isCommented      = true;
                    myUpdatedCard    = AdaptiveCardFactory.CreateAdaptiveCardCommentRequiredAttachment(message);
                }

                else
                {
                    var data = new StringContent(json, Encoding.UTF8, "application/json");

                    var url = "https://prod-67.westeurope.logic.azure.com:443/workflows/5ac4ad090e0e442887e67aa2319ae3ea/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=q1Uz83atZhsoR5aR3eb742pv9tqrhWmAsL5Gj2q2Lv8";
                    myUpdatedCard = AdaptiveCardFactory.CreateAdaptiveCardWaitingAttachment(message);
                    var newActivityForWait = MessageFactory.Attachment(myUpdatedCard);
                    newActivityForWait.Id = key;
                    switch (message.Type)
                    {
                    case "message":
                    {
                        UpdateMessage(turnContext, cancellationToken, newActivityForWait);
                        break;
                    }

                    case "carousel":
                    {
                        message.CardType = "wait";
                        await UpdateCarousel(turnContext, cancellationToken, myUpdatedCard, message, 1);

                        break;
                    }
                    }

                    var response = await client.PostAsync(url, data);

                    var contents = await response.Content.ReadAsStringAsync();

                    JObject jObjectResponse = JObject.Parse(contents);

                    var succesfullApprove = jObjectResponse["Approved"].ToString();
                    var status            = jObjectResponse["Status"].ToString().Trim();
                    status           = status == "Done" ? "Approved" : status == "Back" ? "Rejected" : "Error";
                    message.Approved = status;

                    switch (succesfullApprove)
                    {
                    case "0":
                    {
                        myUpdatedCard = AdaptiveCardFactory.CreateAdaptiveCardAfterSubmitAttachment(message, status, message.Comment);
                        break;
                    }

                    case "1":
                    {
                        myUpdatedCard = AdaptiveCardFactory.CreateAdaptiveCardAlreadySubmitAttachment(message, status);
                        break;
                    }
                    }
                }

                var newActivity = MessageFactory.Attachment(myUpdatedCard);
                newActivity.Id = key;

                // var connector = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl));
                //await connector.Conversations.DeleteActivityAsync(turnContext.Activity.Conversation.Id, key, cancellationToken);
                switch (message.Type)
                {
                case "message":
                {
                    UpdateMessage(turnContext, cancellationToken, newActivity);
                    break;
                }

                case "carousel":
                {
                    if (!isCommented)
                    {
                        message.CardType = "submitted";
                    }
                    await UpdateCarousel(turnContext, cancellationToken, myUpdatedCard, message, 1);

                    break;
                }
                }
                await Task.Delay(500);

                switch (message.Type)
                {
                case "message":
                {
                    UpdateMessage(turnContext, cancellationToken, newActivity);
                    break;
                }

                case "carousel":
                {
                    if (!isCommented)
                    {
                        message.CardType = "submitted";
                    }
                    await UpdateCarousel(turnContext, cancellationToken, myUpdatedCard, message, desc);

                    break;
                }
                }
                //string approved = jObject["approved"].ToString();
            }
            else
            {
                var userStateAccessors = _userState.CreateProperty <UserProfile>(nameof(UserProfile));
                var userProfile        = await userStateAccessors.GetAsync(turnContext, () => new UserProfile());

                if (userProfile.IsSend == true)
                {
                    turnContext.Activity.RemoveRecipientMention();
                    switch (turnContext.Activity.Text.Trim())
                    {
                    case "Help":

                        await turnContext.SendActivityAsync(MessageFactory.Text($"Я бот для роботи з LSDocs. Мої основні функції: \n\n" +
                                                                                $"- отримання 10 останніх завдань, які можна затвердити (просто напишіть мені 'TopTen'); \n\n " +
                                                                                $"- можливість виконання завдань безпосередньо у боті (Lazy approvals); \n\n" +
                                                                                $"- сповіщення про призначення нової задачі; \n\n" +
                                                                                $"- щоденні сповіщення про поточний статус особистих задач; \n\n" +
                                                                                $"- сповіщення за 24 години про протермінування задач. \n\n" +
                                                                                $"А також я постійно навчаюсь, тому можливостей буде більше.🙂  \n\n" +
                                                                                $" \n\n " +
                                                                                $"Якщо у Вас є питання чи пропозиції щодо моєї роботи зв'яжіться з моєю службою підтримки почтою [email protected] чи за телефоном +38 044 232 95 09. "), cancellationToken);

                        break;

                    case "TopTen":
                    {
                        userProfile.IsSend = false;

                        var credentials                = new MicrosoftAppCredentials("4e2e9e85-b2ba-4557-9082-706d081a64e0", "f+#o^wOr%9SPfaJXrow26^]{");
                        var connector                  = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl), credentials);
                        var conversationId             = turnContext.Activity.Conversation.Id;
                        var conversationStateAccessors = _conversationState.CreateProperty <ConversationData>(nameof(ConversationData));
                        var conversationData           = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationData());

                        IEnumerable <TeamsChannelAccount> members = TeamsInfo.GetMembersAsync(turnContext, cancellationToken).Result;
                        var user = new RequestBody();
                        foreach (var member in members)
                        {
                            user = new RequestBody()
                            {
                                AssignedTo = member.UserPrincipalName
                            };
                            if (string.IsNullOrEmpty(user.AssignedTo))
                            {
                                throw new Exception("no user");
                            }
                            if (!string.IsNullOrEmpty(userProfile.CarouselId) && userProfile.Count == 1)
                            {
                                userProfile.Count--;
                                await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);

                                await _userState.SaveChangesAsync(turnContext, false, cancellationToken);

                                await turnContext.DeleteActivityAsync(userProfile.CarouselId, cancellationToken);

                                conversationData.PromptedUserCarousel = false;
                                userProfile.CarouselId = "";
                                userProfile.messagesCarousel.Clear();
                            }

                            List <Attachment>       attachments = new List <Attachment>();
                            IMessageActivity        carousel    = MessageFactory.Carousel(attachments);
                            List <ThirdMessageType> messages    = new List <ThirdMessageType>();

                            var json    = JsonConvert.SerializeObject(user);
                            var waitReq = await turnContext.SendActivityAsync(MessageFactory.Text($"Зачекайте! Вигружаємо задачі з LSDOCS..."), cancellationToken);

                            const string link = "https://prod-10.westeurope.logic.azure.com/workflows/87b2e250b3624ef79777ecfdb37ea0bb/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=jSY4t__HFAn16knFTcmEEqWJl2HZYH4rLHu6rDzdf8U";
                            var          data = new StringContent(json, Encoding.UTF8, "application/json");

                            var response = await client.PostAsync(link, data);



                            var contents = await response.Content.ReadAsStringAsync();

                            JArray  array;
                            JObject jObjectResponse = JObject.Parse(contents);

                            try
                            {
                                array = JArray.Parse(jObjectResponse["messages"].ToString());
                            }
                            catch (Exception ex)
                            {
                                throw (new Exception("Flow return bad top ten"));
                            }
                            if (array.Count == 0)
                            {
                                await turnContext.SendActivityAsync(MessageFactory.Text($"Всі задачі виконані 🙂"), cancellationToken);

                                await turnContext.DeleteActivityAsync(waitReq.Id, cancellationToken);

                                return;
                            }


                            //if (messages.Count != 0)
                            //{
                            //    await turnContext.DeleteActivityAsync(carousel.Id, cancellationToken);
                            //    carousel.Attachments.Clear();
                            //    attachments.Clear();

                            //    messages.Clear();
                            //}

                            foreach (JObject cards in array.Children <JObject>())
                            {
                                var parameters = new Dictionary <string, string>();
                                foreach (JProperty prop in cards.Properties())
                                {
                                    parameters.Add(prop.Name, prop.Value.ToString());
                                }

                                ThirdMessageType message = new ThirdMessageType();
                                message.AssignedTo  = parameters["AssignedTo"].ToString();
                                message.MessageType = parameters["MessageType"].ToString();
                                message.IDCard      = parameters["IDCard"].ToString();
                                message.IDTask      = parameters["IDTask"].ToString();
                                message.LibDispName = parameters["LibDispName"].ToString();
                                //message.TaskType = parameters["TaskType"].ToString();
                                message.TaskType = "";

                                message.TitleTask = parameters["TitleTask"].ToString();
                                message.Link      = parameters["Link"].ToString();
                                message.Approved  = "";

                                message.Key = "carousel";

                                messages.Add(message);

                                var adaptiveCardAttachment = AdaptiveCardFactory.CreateAdaptiveCardForSubmitAttachment(message);
                                carousel.Attachments.Add(adaptiveCardAttachment);
                            }
                            await turnContext.DeleteActivityAsync(waitReq.Id, cancellationToken);

                            if (string.IsNullOrEmpty(userProfile.CarouselId) && userProfile.Count < 1)
                            {
                                userProfile.Count++;
                                await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);

                                await _userState.SaveChangesAsync(turnContext, false, cancellationToken);

                                var req = await turnContext.SendActivityAsync(carousel, cancellationToken);

                                var newAttachments = new List <Attachment>();
                                newAttachments.AddRange(carousel.Attachments);
                                carousel.Attachments.Clear();
                                attachments.Clear();

                                var newCarousel = MessageFactory.Carousel(attachments);
                                foreach (var message in messages)
                                {
                                    message.Key  = req.Id;
                                    message.Type = "carousel";


                                    var adaptiveCardAttachment = AdaptiveCardFactory.CreateAdaptiveCardForSubmitAttachment(message);
                                    newCarousel.Attachments.Add(adaptiveCardAttachment);
                                }


                                newCarousel.Id = req.Id;

                                userProfile.messagesCarousel = messages;

                                userProfile.CarouselId = req.Id;
                                conversationData.PromptedUserCarousel = true;


                                await turnContext.UpdateActivityAsync(newCarousel, cancellationToken);

                                userProfile.IsSend = true;

                                await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);

                                await _userState.SaveChangesAsync(turnContext, false, cancellationToken);

                                return;
                            }
                            break;
                        }
                        break;
                    }

                    default:
                        // Echo back what the user said
                        await turnContext.SendActivityAsync(MessageFactory.Text($"Ви ввели комманду, якої я ще не знаю. Спробуйте написати 'Help'"), cancellationToken);

                        break;
                    }
                }
                else
                {
                    return;
                }
            }
        }