public static async Task ListMe(ITurnContext context, TokenResponse tokenResponse)
        {
            var token  = tokenResponse;
            var client = new SimpleGraphClient(token.Token);

            var me = await client.GetMe();

            var manager = await client.GetManager();

            var reply         = context.Activity.CreateReply();
            var photoResponse = await client.GetPhoto();

            var photoText = string.Empty;

            if (photoResponse != null)
            {
                var replyAttachment = new Attachment(photoResponse.ContentType, photoResponse.Base64string);
                reply.Attachments.Add(replyAttachment);
            }
            else
            {
                photoText = "You should really add an image to your Outlook profile :)";
            }
            reply.Text = $"You are {me.DisplayName} and you report to {manager.DisplayName}.  {photoText}";
            await context.SendActivityAsync(reply);
        }
        public static async Task GetUserAsync(ITurnContext turnContext, TokenResponse tokenResponse, string upn)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client = new SimpleGraphClient(tokenResponse.Token);
            var user   = await client.GetUserAsync(upn);

            var fileRead = System.IO.File.ReadAllText(@".\Resources\GetUserCard.json");
            var item     = (JObject)JsonConvert.DeserializeObject(fileRead);

            string classData = JsonConvert.SerializeObject(user, Formatting.Indented);

            AdaptiveTransformer transformer = new AdaptiveTransformer();
            string cardJson = transformer.Transform(fileRead, classData);

            Attachment attachment = new Attachment();

            attachment.ContentType = "application/vnd.microsoft.card.adaptive";
            attachment.Content     = JsonConvert.DeserializeObject(cardJson);

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

            reply.Attachments.Add(attachment);

            await turnContext.SendActivityAsync(reply);
        }
Пример #3
0
        private InvokeResponse GetStatusCard(string cardType)
        {
            if (!string.IsNullOrEmpty(cardType))
            {
                Microsoft.Bot.Schema.Attachment card2 = CardHelper.CreateAdaptiveCardAttachment(cardType, configuration);

                InvokeResponseBody response2 = new InvokeResponseBody();
                response2.statusCode = 200;
                response2.type       = "application/vnd.microsoft.card.adaptive";
                response2.value      = card2.Content;
                InvokeResponse invokeResponse2 = new InvokeResponse();
                invokeResponse2.Body   = response2;
                invokeResponse2.Status = 200;
                return(invokeResponse2);
            }
            else
            {
                InvokeResponseBody response2 = new InvokeResponseBody();
                response2.statusCode = 200;
                response2.type       = "application/vnd.microsoft.activity.message";
                response2.value      = "message";
                InvokeResponse invokeResponse2 = new InvokeResponse();
                invokeResponse2.Body   = response2;
                invokeResponse2.Status = 200;
                return(invokeResponse2);
            }
        }
Пример #4
0
        // Send consent card to user.
        private static Activity SendFileCardAsync(ITurnContext turnContext, string filename, long filesize)
        {
            var consentContext = new Dictionary <string, string>
            {
                { "filename", filename },
            };

            var fileCard = new FileConsentCard
            {
                Description    = "This is the archive chat file I want to send you",
                SizeInBytes    = filesize,
                AcceptContext  = consentContext,
                DeclineContext = consentContext,
            };

            var asAttachment = new Microsoft.Bot.Schema.Attachment
            {
                Content     = fileCard,
                ContentType = FileConsentCard.ContentType,
                Name        = filename,
            };

            var replyActivity = turnContext.Activity.CreateReply();

            replyActivity.Attachments = new List <Microsoft.Bot.Schema.Attachment>()
            {
                asAttachment
            };
            return(replyActivity);
        }
Пример #5
0
        private IMessageActivity GetEntertainCard()
        {
            var attachment = new Microsoft.Bot.Schema.Attachment(contentType: "video/mp4",
                                                                 name: "5 minutes Meditation",
                                                                 thumbnailUrl: "https://www.yogajournal.com/.image/t_share/MTQ2MTgwNzM5MDQ5OTg5NjY0/sunset-meditation-mudra.jpg",
                                                                 contentUrl: "https://www.youtube.com/watch?v=inpok4MKVLM&t=14s");

            return(MessageFactory.Attachment(attachment));
        }
Пример #6
0
        /// <summary>
        ///     Creates an <see cref="Attachment" /> that contains an <see cref="AdaptiveCard" />.
        /// </summary>
        /// <param name="filePath">The path to the <see cref="AdaptiveCard" /> json file.</param>
        /// <returns>An <see cref="Attachment" /> that contains an adaptive card.</returns>
        private static Attachment CreateAdaptiveCardAttachment(string filePath)
        {
            var adaptiveCardJson       = File.ReadAllText(filePath);
            var adaptiveCardAttachment = new Attachment
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(adaptiveCardJson)
            };

            return(adaptiveCardAttachment);
        }
Пример #7
0
        private static Attachment CreateInteractiveMessage(string filePath)
        {
            var interactiveMsgJson     = System.IO.File.ReadAllText(filePath);
            var adaptiveCardAttachment = JsonConvert.DeserializeObject <Block[]>(interactiveMsgJson);
            var blockList  = adaptiveCardAttachment.ToList();
            var attachment = new Attachment
            {
                Content     = blockList,
                ContentType = "application/json",
                Name        = "blocks",
            };

            return(attachment);
        }
Пример #8
0
        public static Attachment ImageChosen(string imageUrl)
        {
            var heroCard = new HeroCard
            {
                Title    = "The image has been chosen",
                Subtitle = $"Time to get your guesses in",
                Text     = $"Reply with @WhereOnEarthBot and your guess. Results will come in when everyone has added a guess or at 16:00. Good luck!",
                Images   = new List <CardImage> {
                    new CardImage(imageUrl)
                }
            };
            IMessageActivity reply = MessageFactory.Attachment(new List <Attachment>());

            Microsoft.Bot.Schema.Attachment attachment = heroCard.ToAttachment();
            return(attachment);
        }
Пример #9
0
        public static Attachment Reminder(string imageUrl)
        {
            var heroCard = new HeroCard
            {
                Title  = $"Don't forget to get your guess in",
                Text   = $"There's just 3 1/2 hours remaining (depending on my maths!)",
                Images = new List <CardImage> {
                    new CardImage(imageUrl)
                }
            };

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

            Microsoft.Bot.Schema.Attachment attachment = heroCard.ToAttachment();
            return(attachment);
        }
Пример #10
0
        public static Attachment AwaitingGuesses(int userCount, string imageUrl, int usersWithEntryCount, string userName, string guessLocation)
        {
            var heroCard = new HeroCard
            {
                Title    = $"Thanks {userName}",
                Subtitle = $"I'm saving your guess as {guessLocation}",
                Text     = $"Still more results from users to come - {usersWithEntryCount} users have entered out of the {userCount} in this channel.",
                Images   = new List <CardImage> {
                    new CardImage(imageUrl)
                }
            };

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

            Microsoft.Bot.Schema.Attachment attachment = heroCard.ToAttachment();
            return(attachment);
        }
Пример #11
0
        public static Attachment ResultCardAttachment(string winningUserName, string imageUrl, string winningEntry, string winningDistance, string actualAnswer, string originalText)
        {
            var heroCard = new HeroCard
            {
                Title    = "We have a winner!",
                Subtitle = $"Congratulations {winningUserName}",
                Text     = $"The winning guess was {winningEntry} which was {winningDistance} km from the real answer of {actualAnswer} ({originalText})",
                Images   = new List <CardImage> {
                    new CardImage(imageUrl)
                }
            };

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

            Microsoft.Bot.Schema.Attachment attachment = heroCard.ToAttachment();
            return(attachment);
        }
Пример #12
0
        public async Task <string> StartAsync([FromBody] MatchStartPayload payload)
        {
            // HACK HACK HACK
            string content = gameStartTemplate
                             .Replace("${Title}", payload.Title)
                             .Replace("${Score}", payload.Score);
            //var cardJson = this.transformer.Transform(this.customerProfileTemplate, JsonConvert.SerializeObject(jsonData));

            var attachment = new Attachment
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(content),
            };

            var conversationParameters = new ConversationParameters
            {
                IsGroup     = true,
                ChannelData = new TeamsChannelData
                {
                    Channel = new ChannelInfo("19:[email protected]"),
                },
                Activity = (Activity)MessageFactory.Attachment(attachment)
            };

            // Post game start card
            var result = await client.Conversations.CreateConversationAsync(conversationParameters);

            convos[result.Id] = result.ActivityId;

            // Post follow up message
            var message = Activity.CreateMessageActivity();

            message.Text = payload.Message;
            await client.Conversations.ReplyToActivityAsync(result.Id, convos[result.Id], (Activity)message);

            // Return the thread id
            return(await Task.FromResult(result.Id));
        }
Пример #13
0
        // Displays information about the user in the bot.
        public static async Task ListMeAsync(ITurnContext turnContext, TokenResponse tokenResponse)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            // Pull in the data from the Microsoft Graph.
            var client = new SimpleGraphClient(tokenResponse.Token);
            var me     = await client.GetMeAsync();

            var manager = await client.GetManagerAsync();

            var photoResponse = await client.GetPhotoAsync();

            // Generate the reply activity.
            var reply     = turnContext.Activity.CreateReply();
            var photoText = string.Empty;

            if (photoResponse != null)
            {
                var replyAttachment = new Attachment(photoResponse.ContentType, photoResponse.Base64String);
                reply.Attachments.Add(replyAttachment);
            }
            else
            {
                photoText = "Consider adding an image to your Outlook profile.";
            }

            reply.Text = $"You are {me.DisplayName} and you report to {manager.DisplayName}. {photoText}";
            await turnContext.SendActivityAsync(reply);
        }
Пример #14
0
        /// <summary>
        /// Send channel data
        /// </summary>
        /// <param name="card"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static async Task SendChannelData(Attachment card, IConfiguration configuration)
        {
            //Teams channel id in which to create the post.
            string teamsChannelId = configuration["ChannelId"];

            //The Bot Service Url needs to be dynamically fetched (and stored) from the Team. Recommendation is to capture the serviceUrl from the bot Payload and later re-use it to send proactive messages.
            string serviceUrl = configuration["BotServiceUrl"];

            //From the Bot Channel Registration
            string botClientID     = configuration["MicrosoftAppId"];
            string botClientSecret = configuration["MicrosoftAppPassword"];

            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            var connectorClient         = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
            var topLevelMessageActivity = MessageFactory.Attachment(card);
            var conversationParameters  = new ConversationParameters
            {
                IsGroup     = true,
                ChannelData = new TeamsChannelData
                {
                    Channel = new ChannelInfo(teamsChannelId),
                },
                Activity = (Activity)topLevelMessageActivity
            };

            var conversationResource = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

            var replyMessage = Activity.CreateMessageActivity();

            replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());

            //get and store the user details in temp file
            var tempFilePath = @"Temp/ConversationFile.txt";

            System.IO.File.WriteAllText(tempFilePath, replyMessage.Conversation.Id.ToString());
        }
Пример #15
0
        private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (stepContext.Result != null)
            {
                // We do not need to store the token in the bot. When we need the token we can
                // send another prompt. If the token is valid the user will not need to log back in.
                // The token will be available in the Result property of the task.
                var tokenResponse = stepContext.Result as TokenResponse;

                // If we have the token use the user is authenticated so we may use it to make API calls.
                if (tokenResponse?.Token != null)
                {
                    string           data      = String.Empty;
                    IList <TeamsApp> teamsApps = null;
                    Microsoft.Bot.Schema.Attachment attachData = null;
                    string logintext = "User is not login.Type 'login' to proceed";
                    var    command   = ((string)stepContext.Values["command"] ?? string.Empty).ToLowerInvariant();
                    var    client    = new AppCatalogHelper(tokenResponse.Token);

                    switch (command)
                    {
                    case "listapp":
                        teamsApps = await client.GetAllapp();

                        if (teamsApps != null && teamsApps.Count > 0)
                        {
                            taskInfoData = client.ParseData(teamsApps);
                            attachData   = client.AgendaAdaptiveList("listapp", taskInfoData);
                            taskInfoData.Clear();
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        else
                        {
                            //login if not authenticated
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }

                        break;

                    case "app":
                        teamsApps = await client.AppCatalogById();

                        if (teamsApps != null && teamsApps.Count > 0)
                        {
                            taskInfoData = client.ParseData(teamsApps);
                            attachData   = client.AgendaAdaptiveList("App", taskInfoData);
                            taskInfoData.Clear();
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        else
                        {
                            //login if not authenticated
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }

                        break;

                    case "findapp":
                        teamsApps = await client.FindApplicationByTeamsId();

                        if (teamsApps != null && teamsApps.Count > 0)
                        {
                            taskInfoData = client.ParseData(teamsApps);
                            attachData   = client.AgendaAdaptiveList("findapp", taskInfoData);
                            taskInfoData.Clear();
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        else
                        {
                            //login if not authenticated
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }


                        break;

                    case "status":
                        teamsApps = await client.AppStatus();

                        if (teamsApps != null && teamsApps.Count > 0)
                        {
                            taskInfoData = client.ParseData(teamsApps);
                            attachData   = client.AgendaAdaptiveList("status", taskInfoData);
                            taskInfoData.Clear();
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        else
                        {
                            //login if not authenticated
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }

                        break;

                    case "bot":
                        teamsApps = await client.ListAppHavingBot();

                        if (teamsApps != null && teamsApps.Count > 0)
                        {
                            taskInfoData = client.ParseData(teamsApps);
                            attachData   = client.AgendaAdaptiveList("bot", taskInfoData);
                            taskInfoData.Clear();
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        else
                        {
                            //login if not authenticated
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }

                        break;

                    case "update":
                        var upData = await client.UpdateFileAsync();

                        if (upData == "require login")
                        {
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }
                        else
                        {
                            attachData = client.AdaptivCardList("Update", upData);
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        break;

                    case "publish":
                        var pubData = await client.UploadFileAsync();

                        if (pubData == "require login")
                        {
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }
                        else
                        {
                            attachData = client.AdaptivCardList("publish", pubData);
                            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachData), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        break;

                    case "delete":
                        var delData = await client.DeleteApp();

                        if (delData != "Deleted")
                        {
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text(logintext, logintext), cancellationToken);
                        }
                        else
                        {
                            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Delete app successfully"), cancellationToken);

                            await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);
                        }
                        break;

                    case "list":
                        await client.SendContinueMessageAsync(stepContext.Context, cancellationToken);

                        break;

                    default:
                        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Your token is: {tokenResponse.Token}"), cancellationToken);

                        break;
                    }
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("We couldn't log you in. Please try again later."), cancellationToken);
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("We couldn't log you in. Please try again later."), cancellationToken);
            }

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Пример #16
0
        protected override async Task <InvokeResponse> OnInvokeActivityAsync(ITurnContext <IInvokeActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.Name == "composeExtension/fetchTask")
            {
                MessagingExtensionAction action = new MessagingExtensionAction();
                var task = await this.OnTeamsMessagingExtensionFetchTaskAsync(turnContext, action, cancellationToken);

                return(CreateInvokeResponse(task));
            }
            if (turnContext.Activity.Name == "composeExtension/query")
            {
                var quer = JsonConvert.DeserializeObject <MESearch>(turnContext.Activity.Value.ToString());
                MessagingExtensionQuery query = new MessagingExtensionQuery();
                query.Parameters = quer.Parameters;
                query.CommandId  = quer.commandId;
                var result = await this.OnTeamsMessagingExtensionQueryAsync(turnContext, query, cancellationToken);

                return(CreateInvokeResponse(result));
            }
            else if (turnContext.Activity.Name == "adaptiveCard/action")
            {
                var data = JsonConvert.DeserializeObject <ActionType>(turnContext.Activity.Value.ToString());

                string        cases   = data.action.verb.ToString();
                SPFileHandler handler = new SPFileHandler();

                switch (cases.ToString())
                {
                case "approveRequest":
                    //Approve the request
                    await handler.ApproveFileAsync(configuration);

                    Microsoft.Bot.Schema.Attachment card = CardHelper.CreateAdaptiveCardAttachment(MessageExtension_SP.Helpers.Constants.ApprovedCard, configuration);
                    var activity = MessageFactory.Attachment(card);
                    activity.Id = turnContext.Activity.ReplyToId;
                    await turnContext.UpdateActivityAsync(activity, cancellationToken);

                    break;

                case "rejectRequest":
                    // reject the request
                    await handler.RejectFileAsync(configuration);

                    Microsoft.Bot.Schema.Attachment card1 = CardHelper.CreateAdaptiveCardAttachment(MessageExtension_SP.Helpers.Constants.RejectedCard, configuration);
                    var activities = MessageFactory.Attachment(card1);
                    activities.Id = turnContext.Activity.ReplyToId;
                    await turnContext.UpdateActivityAsync(activities, cancellationToken);

                    break;

                case "cardRefresh":
                    //read conversation id from text file
                    string conversationId = System.IO.File.ReadAllText(@"Temp/ConversationFile.txt");
                    if (turnContext.Activity.Conversation.Id == conversationId)
                    {
                        string userId      = turnContext.Activity.From.AadObjectId;
                        string teamOwnerId = await Common.GetManagerId(configuration);

                        //based on owner id show the approver card
                        if (userId == teamOwnerId)
                        {
                            return(GetStatusCard(MessageExtension_SP.Helpers.Constants.OwnerCard));
                        }
                    }
                    return(GetStatusCard(null));
                }
            }

            return(GetStatusCard(null));
        }
Пример #17
0
        // Forward message to Slack
        private async Task <bool> SendTeamsMessageAsync(User recipient, object messageContent)
        {
            if (recipient == null || messageContent == null)
            {
                return(false);
            }

            var isSuccess = false;

            try
            {
                var toId        = recipient.Id;
                var toName      = recipient.Name;
                var fromId      = recipient.BotId;
                var fromName    = recipient.BotName;
                var serviceUrl  = recipient.ServiceUrl;
                var tenantId    = recipient.TenantId; // Required for Microsoft Teams
                var userAccount = new ChannelAccount(toId, toName);
                var botAccount  = new ChannelAccount(fromId, fromName);

                var attachment = new Attachment
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content     = messageContent,
                };

                var message = Activity.CreateMessageActivity();
                message.From        = botAccount;
                message.Recipient   = userAccount;
                message.Attachments = new List <Attachment>()
                {
                    attachment
                };

                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
                var account = new MicrosoftAppCredentials(_appId, _password);
                var client  = new ConnectorClient(new Uri(serviceUrl), account);

                // Reuse existing conversation if recipient is a channel
                string conversationId;
                ConversationResourceResponse conversation = null;
                if (recipient.IsGroupChannel)
                {
                    var conversationParameters = new ConversationParameters
                    {
                        IsGroup     = true,
                        ChannelData = new TeamsChannelData
                        {
                            Channel = new ChannelInfo(recipient.Id),
                        },
                        Activity = (Activity)message,
                    };
                    conversation = await client.Conversations.CreateConversationAsync(conversationParameters);
                }
                else
                {
                    conversation         = client.Conversations.CreateOrGetDirectConversation(botAccount, userAccount, tenantId);
                    conversationId       = conversation.Id;
                    message.Conversation = new ConversationAccount(id: conversationId);
                    var response = await client.Conversations.SendToConversationAsync((Activity)message);

                    _logger.LogInformation($"Response id: {response.Id}");
                }

                isSuccess = true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

            return(isSuccess);
        }
Пример #18
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);
        }
Пример #19
0
        protected Microsoft.Bot.Schema.Attachment ToAdaptiveCardAttachmentForOtherFlows(
            List <TaskItem> todos,
            int allTaskCount,
            string taskContent,
            BotResponse botResponse1,
            BotResponse botResponse2)
        {
            var toDoCard = new AdaptiveCard();
            var showText = Format(botResponse2.Reply.Text, new StringDictionary()
            {
                { "taskCount", allTaskCount.ToString() }
            });
            var speakText = Format(botResponse1.Reply.Speak, new StringDictionary()
            {
                { "taskContent", taskContent }
            })
                            + Format(botResponse2.Reply.Speak, new StringDictionary()
            {
                { "taskCount", allTaskCount.ToString() }
            });

            toDoCard.Speak = speakText;

            var body      = new List <AdaptiveElement>();
            var textBlock = new AdaptiveTextBlock
            {
                Text = showText,
            };

            body.Add(textBlock);
            var choiceSet = new AdaptiveChoiceSetInput
            {
                IsMultiSelect = true,
            };
            var value = Guid.NewGuid().ToString() + ",";

            foreach (var todo in todos)
            {
                var choice = new AdaptiveChoice
                {
                    Title = todo.Topic,
                    Value = todo.Id,
                };
                choiceSet.Choices.Add(choice);
                if (todo.IsCompleted)
                {
                    value += todo.Id + ",";
                }
            }

            value           = value.Remove(value.Length - 1);
            choiceSet.Value = value;
            body.Add(choiceSet);
            toDoCard.Body = body;

            var attachment = new Microsoft.Bot.Schema.Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = toDoCard,
            };

            return(attachment);
        }
Пример #20
0
        private async Task <MessagingExtensionActionResponse> CreateCalendarEvent(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 == "CalendarEvent")
                    {
                        //var username = turnContext.Activity.From.AadObjectId;
                        var eventTitle        = ((JObject)action.Data)["Title"]?.ToString();
                        var eventDetails      = ((JObject)action.Data)["Details"]?.ToString();
                        var eventStartDt      = ((JObject)action.Data)["StartDt"]?.ToString();
                        var eventStartTime    = ((JObject)action.Data)["StartTime"]?.ToString();
                        var eventDurationMins = ((JObject)action.Data)["EventDuration"]?.ToString();

                        eventStartDt = eventStartDt + "T" + eventStartTime + ":00";

                        CultureInfo culture        = new CultureInfo("en-US");
                        DateTime    tempDate       = Convert.ToDateTime(eventStartDt, culture);
                        DateTime    eventDateStart = DateTime.Now;
                        DateTime    eventDateEnd   = tempDate.AddMinutes(Int16.Parse(eventDurationMins));
                        var         eventEndDate   = eventDateEnd.ToString();

                        var eventResponse = await client.CreateOutlookEventAsync(eventTitle, eventStartDt, eventEndDate, eventDetails);

                        var eventUrl = eventResponse.WebLink;

                        eventUrl = "https://teams.microsoft.com/_?culture=en-us&country=US&lm=deeplink&lmsrc=homePageWeb&cmpid=WebSignIn#/scheduling-form/?isBroadcast=false&eventId=" + eventResponse.Id + "&opener=1&providerType=0&navCtx=event-card-peek&calendarType=User";

                        string ackCalendarCardPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "AckCardCalendarEvents.json");
                        string ackCalendarCardJson = System.IO.File.ReadAllText(ackCalendarCardPath, Encoding.UTF8);

                        ackCalendarCardJson = ackCalendarCardJson.Replace("replaceUrl", eventUrl ?? "", true,
                                                                          culture: CultureInfo.InvariantCulture);
                        ackCalendarCardJson = ackCalendarCardJson.Replace("ReplaceTitel", eventResponse.Subject.ToString() ?? "", true,
                                                                          culture: CultureInfo.InvariantCulture);

                        var card = AdaptiveCard.FromJson(ackCalendarCardJson);
                        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 = "Event Creation",
                                },
                            },
                        }));
                    }
                    return(null);
                }

                catch (Exception ex)
                { throw ex; }
            }
            return(null);
        }