示例#1
0
        // Will be called after OnTeamsMessagingExtensionFetchTaskAsync when user has entered all data in the Messaging Extension Adaptive Card
        private async Task <MessagingExtensionActionResponse> CreateToDoTaskModule(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            //TeamChannelDetails objChannelDetails = new TeamChannelDetails();
            //if (turnContext.Activity.TeamsGetChannelId() != null)
            //{
            //    objChannelDetails = SimpleTeamsOperations.GetTeamChannelDetails(turnContext, cancellationToken).Result;
            //}

            var magicCode = string.Empty;
            var state     = (turnContext.Activity.Value as Newtonsoft.Json.Linq.JObject).Value <string>("state");

            if (!string.IsNullOrEmpty(state))
            {
                int parsed = 0;
                if (int.TryParse(state, out parsed))
                {
                    magicCode = parsed.ToString();
                }
            }

            var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, _connectionName, magicCode, cancellationToken: cancellationToken);

            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
            {
                // There is no token, so the user has not signed in yet.
                // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);
                return(new MessagingExtensionActionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "auth",
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = "Bot Service OAuth",
                                },
                            },
                        },
                    },
                });
            }
            var accessToken = tokenResponse.Token;

            if (accessToken != null || !string.IsNullOrEmpty(accessToken))
            {
                try
                {
                    var client = new SimpleGraphClient(accessToken);
                    var type   = ((JObject)action.Data)["Type"]?.ToString();
                    //var url = turnContext.Activity.Value.ToString();
                    //JObject jsonUrl = JObject.Parse(url);
                    //var link = jsonUrl["messagePayload"]["linkToMessage"];
                    if (type == "ToDoTask")
                    {
                        var username      = turnContext.Activity.From.AadObjectId;
                        var taskTitle     = ((JObject)action.Data)["Title"]?.ToString();
                        var taskStartDate = ((JObject)action.Data)["StartDate"]?.ToString();
                        var taskDueDate   = ((JObject)action.Data)["DueDate"]?.ToString();

                        var itemBody     = new Beta.ItemBody();
                        var ToDoResponse = await client.CreateOutlookTaskAsync(taskTitle, taskStartDate, taskDueDate, itemBody);

                        var taskUrl = "https://to-do.office.com/tasks/id/" + ToDoResponse.Id.ToString() + "/details";

                        string taskCardPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "todoCardTeams.json");
                        string taskCardJson = System.IO.File.ReadAllText(taskCardPath, Encoding.UTF8);

                        taskCardJson = taskCardJson.Replace("replaceUrl", taskUrl ?? "", true,
                                                            culture: CultureInfo.InvariantCulture);
                        taskCardJson = taskCardJson.Replace("ReplaceTitel", ToDoResponse.Subject.ToString() ?? "", true,
                                                            culture: CultureInfo.InvariantCulture);

                        var card = AdaptiveCard.FromJson(taskCardJson);
                        Microsoft.Bot.Schema.Attachment attachment = new Microsoft.Bot.Schema.Attachment()
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = card.Card
                        };

                        IMessageActivity cardMsg = MessageFactory.Attachment(attachment);
                        await turnContext.SendActivityAsync(cardMsg, cancellationToken);

                        return(await Task.FromResult(new MessagingExtensionActionResponse
                        {
                            Task = new TaskModuleContinueResponse
                            {
                                Value = new TaskModuleTaskInfo
                                {
                                    Card = attachment,
                                    Height = 180,
                                    Width = 480,
                                    Title = "Task Creation",
                                },
                            },
                        }));
                    }
                    return(null);
                }

                catch (Exception ex)
                { throw ex; }
            }
            return(null);
        }
        public async Task <Beta.OutlookTask> CreateOutlookTaskAsync(string subject, string dueDate, string startTime, Beta.ItemBody body)
        {
            var graphClient = GetAuthenticatedClient();
            var outlookTask = new Beta.OutlookTask
            {
                Subject       = subject,
                StartDateTime = new Beta.DateTimeTimeZone
                {
                    DateTime = startTime,
                    TimeZone = "Eastern Standard Time"
                },
                DueDateTime = new Beta.DateTimeTimeZone
                {
                    DateTime = dueDate,
                    TimeZone = "Eastern Standard Time"
                },
                Body = body
            };

            var res = await graphClient.Me.Outlook.Tasks.Request().Header("Prefer", "outlook.timezone=\"Pacific Standard Time\"").AddAsync(outlookTask);

            return(res);
        }
示例#3
0
        // 2. Will be called after OnTeamsMessagingExtensionFetchTaskAsync when user has entered all data in the Messaging Extension Adaptive Card
        private async Task <MessagingExtensionActionResponse> CreateTaskModuleCommand(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var msg     = action.MessagePayload.Body.Content;
            var data    = action.Data;
            var channel = turnContext.Activity.TeamsGetChannelId();
            var groupId = "";

            if (channel != null)
            {
                TeamDetails teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, turnContext.Activity.TeamsGetTeamInfo().Id, cancellationToken);

                groupId = teamDetails.AadGroupId;
            }
            var     subject   = ((JObject)action.Data)["Title"]?.ToString();
            var     dueDate   = ((JObject)action.Data)["DueDate"]?.ToString();
            var     startDate = ((JObject)action.Data)["StartDate"]?.ToString();
            var     type      = ((JObject)action.Data)["Type"]?.ToString();
            var     url       = turnContext.Activity.Value.ToString();
            JObject jsonUrl   = JObject.Parse(url);
            var     link      = jsonUrl["messagePayload"]["linkToMessage"];
            var     magicCode = string.Empty;
            var     state     = (turnContext.Activity.Value as Newtonsoft.Json.Linq.JObject).Value <string>("state");

            if (!string.IsNullOrEmpty(state))
            {
                int parsed = 0;
                if (int.TryParse(state, out parsed))
                {
                    magicCode = parsed.ToString();
                }
            }
            var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, _connectionName, magicCode, cancellationToken: cancellationToken);

            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
            {
                // There is no token, so the user has not signed in yet.
                // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);
                return(new MessagingExtensionActionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "auth",
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = "Bot Service OAuth",
                                },
                            },
                        },
                    },
                });
            }
            var accessToken = tokenResponse.Token;

            if (accessToken != null || !string.IsNullOrEmpty(accessToken))
            {
                var client = new SimpleGraphClient(accessToken);
                if (type == "todo")
                {
                    var body = new Beta.ItemBody
                    {
                        Content = msg + " - " + link
                    };
                    var taskResult = await client.CreateTaskAsync(subject, dueDate, startDate, body);

                    var todoUrl = "https://to-do.office.com/tasks/id/" + taskResult.Id + "/details";
                    List <ChannelAccount> participants = new List <ChannelAccount>();
                    participants.Add(new ChannelAccount(turnContext.Activity.From.Id, turnContext.Activity.From.Name));
                    var connectorClient        = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
                    var conversationParameters = new ConversationParameters()
                    {
                        ChannelData = new TeamsChannelData
                        {
                            Tenant = new TenantInfo
                            {
                                Id = tenantId,
                            }
                        },
                        Members = new List <ChannelAccount>()
                        {
                            participants[0]
                        }
                    };
                    var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

                    string taskCardPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "todoCardTeams.json");
                    var    r            = File.ReadAllText(taskCardPath, Encoding.UTF8);
                    string taskCardJson = r;
                    taskCardJson = taskCardJson.Replace("replaceUrl", todoUrl ?? "", true, culture: CultureInfo.InvariantCulture);
                    taskCardJson = taskCardJson.Replace("ReplaceTitel", taskResult.Subject.ToString() ?? "", true, culture: CultureInfo.InvariantCulture);
                    var        card       = AdaptiveCard.FromJson(taskCardJson);
                    Attachment attachment = new Attachment()
                    {
                        ContentType = AdaptiveCard.ContentType,
                        Content     = card.Card
                    };
                    IMessageActivity cardMsg = MessageFactory.Attachment(attachment);
                    await connectorClient.Conversations.SendToConversationAsync(response.Id, (Activity)cardMsg, cancellationToken);
                }
                if (type == "planner")
                {
                    var username      = turnContext.Activity.From.AadObjectId;
                    var taskTitle     = ((JObject)action.Data)["Title"]?.ToString();
                    var taskStartDate = ((JObject)action.Data)["StartDate"]?.ToString();
                    var taskDueDate   = ((JObject)action.Data)["DueDate"]?.ToString();
                    var taskSPlanId   = ((JObject)action.Data)["Choices"]?.ToString();
                    var planResult    = await client.CreatePlannerTaskAsync(taskSPlanId, taskTitle, taskDueDate, taskStartDate, username);

                    if (!string.IsNullOrEmpty(groupId))
                    {
                        var taskUrl = "https://tasks.office.com/solviondemo.net/en-US/Home/Planner/#/plantaskboard?groupId=" + groupId + "&planId=" + planResult.PlanId + "&taskId=" + planResult.Id;
                        List <ChannelAccount> participants = new List <ChannelAccount>();
                        participants.Add(new ChannelAccount(turnContext.Activity.From.Id, turnContext.Activity.From.Name));
                        var connectorClient        = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
                        var conversationParameters = new ConversationParameters()
                        {
                            ChannelData = new TeamsChannelData
                            {
                                Tenant = new TenantInfo
                                {
                                    Id = tenantId,
                                }
                            },
                            Members = new List <ChannelAccount>()
                            {
                                participants[0]
                            }
                        };
                        var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

                        string taskCardPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "plannerCardTeams.json");
                        var    r            = File.ReadAllText(taskCardPath, Encoding.UTF8);
                        string taskCardJson = r;
                        taskCardJson = taskCardJson.Replace("replaceUrl", taskUrl ?? "", true, culture: CultureInfo.InvariantCulture);
                        taskCardJson = taskCardJson.Replace("ReplaceTitel", planResult.Title.ToString() ?? "", true, culture: CultureInfo.InvariantCulture);
                        var        card       = AdaptiveCard.FromJson(taskCardJson);
                        Attachment attachment = new Attachment()
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = card.Card
                        };
                        IMessageActivity cardMsg = MessageFactory.Attachment(attachment);
                        await connectorClient.Conversations.SendToConversationAsync(response.Id, (Activity)cardMsg, cancellationToken);
                    }
                    else
                    {
                        List <ChannelAccount> participants = new List <ChannelAccount>();
                        participants.Add(new ChannelAccount(turnContext.Activity.From.Id, turnContext.Activity.From.Name));
                        var connectorClient        = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
                        var conversationParameters = new ConversationParameters()
                        {
                            ChannelData = new TeamsChannelData
                            {
                                Tenant = new TenantInfo
                                {
                                    Id = tenantId,
                                }
                            },
                            Members = new List <ChannelAccount>()
                            {
                                participants[0]
                            }
                        };
                        var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

                        var personalMessageActivity = MessageFactory.Text($"I've created a new Planner task with the title **" + planResult.Title.ToString() + "** in the Plan you have chosen");
                        await connectorClient.Conversations.SendToConversationAsync(response.Id, personalMessageActivity);
                    }
                }
            }
            return(null);
        }