/// <inheritdoc />
        public async Task SendMessageAsync(ScheduledMessage scheduledMessage, CancellationToken cancellationToken)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                MicrosoftAppCredentials credentials = BuildMicrosoftAppCredentials();

                string   serviceUrl = GetLastServiceUrl(scheduledMessage.Details);
                Uri      serviceUri = new Uri(serviceUrl);
                Activity activity   = CreateBotMessageActivity(scheduledMessage);

                if (!MicrosoftAppCredentials.IsTrustedServiceUrl(serviceUrl))
                {
                    MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
                }

                using (ConnectorClient connector = new ConnectorClient(serviceUri, credentials))
                {
                    logger.LogInformation($"Sending message to conversation RecipientId: ${activity.Recipient.Id}.");
                    await connector.Conversations.SendToConversationAsync(activity, cancellationToken);
                }
            }
            else
            {
                logger.LogInformation("CancellationToken is in CancellationRequested state.");
            }
        }
예제 #2
0
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        public static async Task <ResourceResponse> SendMessage(MessagePayload data, MicrosoftAppCredentials credentials)
        {
            var botAccount  = new ChannelAccount(data.FromId, data.FromName ?? "ExpressBot");
            var userAccount = new ChannelAccount(data.ToId, data.ToName);

            // trust the service url if it is not already trusted
            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(data.ServiceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(data.ServiceUrl);
            }

            var connector = new ConnectorClient(new Uri(data.ServiceUrl), credentials);

            var conversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);

            IMessageActivity message = Activity.CreateMessageActivity();

            message.From         = botAccount;
            message.Recipient    = userAccount;
            message.Conversation = new ConversationAccount(false, conversation.Id);
            message.Text         = data.Text;
            message.Locale       = data.ToName ?? "en-US";
            message.ChannelData  = data.ChannelData;
            return(await connector.Conversations.SendToConversationAsync((Activity)message));
        }
예제 #3
0
        public async Task <string> FindLocale(IActivity activity, CancellationToken token)
        {
            if (string.IsNullOrEmpty(this.locale))
            {
                var resumptionData = await this.resumptionContext.LoadDataAsync(token);

                if (resumptionData != null && resumptionData.IsTrustedServiceUrl)
                {
                    MicrosoftAppCredentials.TrustServiceUrl(this.conversationReference.ServiceUrl);
                }

                this.locale = (activity as IMessageActivity)?.Locale;

                // if locale is null or whitespace in the incoming request,
                // try to set it from the ResumptionContext
                if (string.IsNullOrWhiteSpace(this.locale))
                {
                    this.locale = resumptionData?.Locale;
                }

                // persist resumptionData with updated information
                var data = new ResumptionData
                {
                    Locale = this.locale,
                    IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(this.conversationReference.ServiceUrl)
                };
                await this.resumptionContext.SaveDataAsync(data, token);
            }
            return(this.locale);
        }
        /// <summary>
        /// Send a preview of a draft notification.
        /// </summary>
        /// <param name="draftNotificationEntity">Draft notification entity.</param>
        /// <param name="teamDataEntity">The team data entity.</param>
        /// <param name="teamsChannelId">The Teams channel id.</param>
        /// <returns>It returns HttpStatusCode.OK, if this method triggers the bot service to send the adaptive card successfully.
        /// It returns HttpStatusCode.TooManyRequests, if the bot service throttled the request to send the adaptive card.</returns>
        public async Task <HttpStatusCode> SendPreview(NotificationDataEntity draftNotificationEntity, TeamDataEntity teamDataEntity, string teamsChannelId)
        {
            if (draftNotificationEntity == null)
            {
                throw new ArgumentException("Null draft notification entity.");
            }

            if (teamDataEntity == null)
            {
                throw new ArgumentException("Null team data entity.");
            }

            if (string.IsNullOrWhiteSpace(teamsChannelId))
            {
                throw new ArgumentException("Null channel id.");
            }

            // Create bot conversation reference.
            var conversationReference = this.PrepareConversationReferenceAsync(teamDataEntity, teamsChannelId);

            // Ensure the bot service URL is trusted.
            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(conversationReference.ServiceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(conversationReference.ServiceUrl);
            }

            // Trigger bot to send the adaptive card.
            try
            {
                var previewQueueMessageContent = new SendQueueMessageContent
                {
                    NotificationId = draftNotificationEntity.Id,
                    ActivtiyId     = null,
                    RecipientData  = null,
                    NotificationUpdatePreviewEntity = new NotificationUpdatePreviewEntity
                    {
                        ActionType             = "PreviewNotification",
                        NotificationDataEntity = null,
                        ConversationReferance  = conversationReference,
                        MessageActivity        = await this.GetPreviewMessageActivity(draftNotificationEntity),
                        ServiceUrl             = conversationReference.ServiceUrl,
                        AppID = this.botAppId,
                    },
                };
                await this.sendQueue.SendAsync(previewQueueMessageContent);

                return(HttpStatusCode.OK);
            }
            catch (ErrorResponseException e)
            {
                var errorResponse = (ErrorResponse)e.Body;
                if (errorResponse != null &&
                    errorResponse.Error.Code.Equals(DraftNotificationPreviewService.ThrottledErrorResponse, StringComparison.OrdinalIgnoreCase))
                {
                    return(HttpStatusCode.TooManyRequests);
                }

                throw;
            }
        }
예제 #5
0
        public static void SendForUser(User user, string message)
        {
            if (user == null)
            {
                return;
            }
            try
            {
                var client = new ConnectorClient(new Uri(user.ServiceUrl), Configurator.BotCredentials);

                var userAccount = new ChannelAccount(user.UserId, user.UserName);
                var botAccount  = new ChannelAccount(user.FromId, user.FromName);

                var activity = new Activity
                {
                    Conversation = new ConversationAccount(id: user.UserId),
                    ChannelId    = user.ChannelId,
                    From         = userAccount,
                    Recipient    = botAccount,
                    Text         = message,
                    Id           = user.Conversation
                };

                var reply = activity.CreateReply(message);
                if (String.IsNullOrEmpty(activity.ServiceUrl))
                {
                    MicrosoftAppCredentials.IsTrustedServiceUrl(activity.ServiceUrl);
                }
                MicrosoftAppCredentials.IsTrustedServiceUrl(user.ServiceUrl);
                client.Conversations.ReplyToActivity(reply);
            }
            catch (Exception) { /*nope*/ }
        }
예제 #6
0
 /// <summary>
 /// Creates an instance of the resumption cookie.
 /// </summary>
 /// <param name="userId"> The user Id.</param>
 /// <param name="botId"> The bot Id.</param>
 /// <param name="conversationId"> The conversation Id.</param>
 /// <param name="channelId"> The channel Id of the conversation.</param>
 /// <param name="serviceUrl"> The service url of the conversation.</param>
 /// <param name="locale"> The locale of the message.</param>
 public ResumptionCookie(string userId, string botId, string conversationId, string channelId, string serviceUrl, string locale = "en")
 {
     // purposefully using named arguments because these all have the same type
     this.Address = new Address(botId: botId, channelId: channelId, userId: userId, conversationId: conversationId, serviceUrl: serviceUrl);
     SetField.CheckNull(nameof(locale), locale);
     this.IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(serviceUrl);
     this.Locale = locale;
 }
 public ResumptionCookie(Address address, string userName, bool isGroup, string locale)
 {
     this.Address             = address;
     this.UserName            = userName;
     this.IsGroup             = isGroup;
     this.Locale              = locale;
     this.IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(address.ServiceUrl);
 }
예제 #8
0
        /// <summary>
        /// Creates an instance of resumption cookie form a <see cref="Connector.IMessageActivity"/>
        /// </summary>
        /// <param name="msg"> The message.</param>
        public ResumptionCookie(IMessageActivity msg)
        {
            this.Address        = new Address(msg);
            UserName            = msg.From?.Name;
            IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(msg.ServiceUrl);
            var isGroup = msg.Conversation?.IsGroup;

            IsGroup = isGroup.HasValue && isGroup.Value;
            Locale  = msg.Locale;
        }
        public async void Channel_MsaHeader_Valid_ServiceUrlShouldBeTrusted()
        {
            string header      = $"Bearer {await new MicrosoftAppCredentials("2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F").GetTokenAsync()}";
            var    credentials = new SimpleCredentialProvider("2cd87869-38a0-4182-9251-d056e8f0ac24", "");

            await JwtTokenValidation.AuthenticateRequest(
                new Activity { ServiceUrl = "https://smba.trafficmanager.net/amer-client-ss.msg/" },
                header,
                credentials,
                emptyClient);

            Assert.True(MicrosoftAppCredentials.IsTrustedServiceUrl("https://smba.trafficmanager.net/amer-client-ss.msg/"));
        }
        public async void Channel_AuthenticationDisabled_ServiceUrlShouldNotBeTrusted()
        {
            var header      = "";
            var credentials = new SimpleCredentialProvider();

            var claimsPrincipal = await JwtTokenValidation.AuthenticateRequest(
                new Activity { ServiceUrl = "https://webchat.botframework.com/" },
                header,
                credentials,
                emptyClient);

            Assert.False(MicrosoftAppCredentials.IsTrustedServiceUrl("https://webchat.botframework.com/"));
        }
        public async void Channel_MsaHeader_Valid_ServiceUrlShouldBeTrusted()
        {
            var header      = "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImI0eXNPV0l0RDEzaVFmTExlQkZYOWxSUER0ayIsInR5cCI6IkpXVCIsIng1dCI6ImI0eXNPV0l0RDEzaVFmTExlQkZYOWxSUER0ayJ9.eyJzZXJ2aWNldXJsIjoiaHR0cHM6Ly9zbWJhLnRyYWZmaWNtYW5hZ2VyLm5ldC9hbWVyLWNsaWVudC1zcy5tc2cvIiwibmJmIjoxNTE5Njk3OTQ0LCJleHAiOjE1MTk3MDE1NDQsImlzcyI6Imh0dHBzOi8vYXBpLmJvdGZyYW1ld29yay5jb20iLCJhdWQiOiI3Zjc0NTEzZS02Zjk2LTRkYmMtYmU5ZC05YTgxZmVhMjJiODgifQ.wjApM-MBhEIHSRHJGmivfpyFg0-SrTFh6Xta2RrKlZT4urACPX7kdZAb6oGOeDIm0NU16BPcpEqtCm9nBPmwoKKRbLCQ4Q3DGcB_LY15VCYfiiAnaevNNcvq7j_Hu-oyTmKOqpjfzu8qMIsjySClf1qZFucUrqzccePtlb63DAVfv-nF3bp-sm-zFG7RBX32cCygBMvpVENBroAq3ANfUQCmixkExcGr5npV3dFihSE0H9ntLMGseBdW7dRe5xOXDIgCtcCJPid-A6Vz-DxWGabyy2mVXLwYYuDxP4L5aruGwJIl_Z2-_MjhrWVszoeCRoOlx9-LNtbdSYGWmXWSbg";
            var credentials = new SimpleCredentialProvider("7f74513e-6f96-4dbc-be9d-9a81fea22b88", "");

            await JwtTokenValidation.AuthenticateRequest(
                new Activity { ServiceUrl = "https://smba.trafficmanager.net/amer-client-ss.msg/" },
                header,
                credentials,
                emptyClient);

            Assert.True(MicrosoftAppCredentials.IsTrustedServiceUrl("https://smba.trafficmanager.net/amer-client-ss.msg/"));
        }
예제 #12
0
        /// <summary>
        /// Creates an instance of resumption cookie form a <see cref="Connector.IMessageActivity"/>
        /// </summary>
        /// <param name="msg"> The message.</param>
        public ResumptionCookie(IMessageActivity msg)
        {
            UserId              = msg.From?.Id;
            UserName            = msg.From?.Name;
            ChannelId           = msg.ChannelId;
            ServiceUrl          = msg.ServiceUrl;
            IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(msg.ServiceUrl);
            BotId          = msg.Recipient?.Id;
            ConversationId = msg.Conversation?.Id;
            var isGroup = msg.Conversation?.IsGroup;

            IsGroup = isGroup.HasValue && isGroup.Value;
            Locale  = msg.Locale;
        }
        /// <summary>
        /// Send a preview of a draft notification.
        /// </summary>
        /// <param name="draftNotificationEntity">Draft notification entity.</param>
        /// <param name="teamDataEntity">The team data entity.</param>
        /// <param name="teamsChannelId">The Teams channel id.</param>
        /// <returns>It returns HttpStatusCode.OK, if this method triggers the bot service to send the adaptive card successfully.
        /// It returns HttpStatusCode.TooManyRequests, if the bot service throttled the request to send the adaptive card.</returns>
        public async Task <HttpStatusCode> SendPreview(NotificationDataEntity draftNotificationEntity, TeamDataEntity teamDataEntity, string teamsChannelId)
        {
            if (draftNotificationEntity == null)
            {
                throw new ArgumentException("Null draft notification entity.");
            }

            if (teamDataEntity == null)
            {
                throw new ArgumentException("Null team data entity.");
            }

            if (string.IsNullOrWhiteSpace(teamsChannelId))
            {
                throw new ArgumentException("Null channel id.");
            }

            // Create bot conversation reference.
            var conversationReference = this.PrepareConversationReferenceAsync(teamDataEntity, teamsChannelId);

            // Ensure the bot service URL is trusted.
            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(conversationReference.ServiceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(conversationReference.ServiceUrl);
            }

            // Trigger bot to send the adaptive card.
            try
            {
                await this.diConnectBotAdapter.ContinueConversationAsync(
                    this.botAppId,
                    conversationReference,
                    async (turnContext, cancellationToken) => await this.SendAdaptiveCardAsync(turnContext, draftNotificationEntity),
                    CancellationToken.None);

                return(HttpStatusCode.OK);
            }
            catch (ErrorResponseException e)
            {
                var errorResponse = (ErrorResponse)e.Body;
                if (errorResponse != null &&
                    errorResponse.Error.Code.Equals(DraftNotificationPreviewService.ThrottledErrorResponse, StringComparison.OrdinalIgnoreCase))
                {
                    return(HttpStatusCode.TooManyRequests);
                }

                throw;
            }
        }
        // This will send an adhoc message to the user
        public static async Task Resume(
            string toId,
            string toName,
            string fromId,
            string fromName,
            string conversationId,
            string message,
            string serviceUrl = "https://smba.trafficmanager.net/apis/",
            string channelId  = "skype")
        {
            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(serviceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            }

            try
            {
                var userAccount = new ChannelAccount(toId, toName);
                var botAccount  = new ChannelAccount(fromId, fromName);
                var connector   = new ConnectorClient(new Uri(serviceUrl));

                var activity = Activity.CreateMessageActivity();
                // var activity = Activity.CreateConversationUpdateActivity();

                if (!string.IsNullOrEmpty(conversationId) && !string.IsNullOrEmpty(channelId))
                {
                    activity.ChannelId = channelId;
                }
                else
                {
                    conversationId = (await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount)).Id;
                }

                activity.From         = botAccount;
                activity.Recipient    = userAccount;
                activity.Conversation = new ConversationAccount(id: conversationId);
                activity.Text         = message;
                activity.Locale       = "en-Us";
                //activity.ReplyToId = "Reply told";

                await connector.Conversations.SendToConversationAsync((Activity)activity);

                //await connector.Conversations.SendToConversationAsync((Activity)activity2);
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp);
            }
        }
예제 #15
0
 /// <summary>
 /// Creates an instance of the resumption cookie.
 /// </summary>
 /// <param name="userId"> The user Id.</param>
 /// <param name="botId"> The bot Id.</param>
 /// <param name="conversationId"> The conversation Id.</param>
 /// <param name="channelId"> The channel Id of the conversation.</param>
 /// <param name="serviceUrl"> The service url of the conversation.</param>
 /// <param name="locale"> The locale of the message.</param>
 public ResumptionCookie(string userId, string botId, string conversationId, string channelId, string serviceUrl, string locale = "en")
 {
     SetField.CheckNull(nameof(userId), userId);
     SetField.CheckNull(nameof(botId), botId);
     SetField.CheckNull(nameof(conversationId), conversationId);
     SetField.CheckNull(nameof(channelId), channelId);
     SetField.CheckNull(nameof(serviceUrl), serviceUrl);
     SetField.CheckNull(nameof(locale), locale);
     this.UserId              = userId;
     this.BotId               = botId;
     this.ConversationId      = conversationId;
     this.ChannelId           = channelId;
     this.ServiceUrl          = serviceUrl;
     this.IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(serviceUrl);
     this.Locale              = locale;
 }
        public async void Channel_MsaHeader_Invalid_ServiceUrlShouldNotBeTrusted()
        {
            string header      = $"Bearer {await new MicrosoftAppCredentials("2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F").GetTokenAsync()}";
            var    credentials = new SimpleCredentialProvider("7f74513e-6f96-4dbc-be9d-9a81fea22b88", "");

            await Assert.ThrowsAsync <UnauthorizedAccessException>(
                async() => await JwtTokenValidation.AuthenticateRequest(
                    new Activity {
                ServiceUrl = "https://webchat.botframework.com/"
            },
                    header,
                    credentials,
                    emptyClient));

            Assert.False(MicrosoftAppCredentials.IsTrustedServiceUrl("https://webchat.botframework.com/"));
        }
예제 #17
0
        // This will send an adhoc message to the user
        public static async Task Resume(
            string toId,
            string toName,
            string fromId,
            string fromName,
            string conversationId,
            string message,
            string serviceUrl = "https://smba.trafficmanager.net/apis/",
            string channelId  = "skype")
        {
            //System.Diagnostics.Trace.TraceWarning("Geen idee wat we nu doen, maar we proberen het");
            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(serviceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            }

            try
            {
                var userAccount = new ChannelAccount(toId, toName);
                var botAccount  = new ChannelAccount(fromId, fromName);
                var connector   = new ConnectorClient(new Uri(serviceUrl));

                IMessageActivity activity = Activity.CreateMessageActivity();

                if (!string.IsNullOrEmpty(conversationId) && !string.IsNullOrEmpty(channelId))
                {
                    activity.ChannelId = channelId;
                }
                else
                {
                    conversationId = (await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount)).Id;
                }

                activity.From         = botAccount;
                activity.Recipient    = userAccount;
                activity.Conversation = new ConversationAccount(id: conversationId);
                activity.Text         = message;
                activity.Locale       = "en-Us";
                await connector.Conversations.SendToConversationAsync((Activity)activity);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Trace.TraceWarning("We hebben een error 2");
                Debug.WriteLine(exp);
            }
        }
예제 #18
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;
            // Create a queue Message
            var queueMessage = new Message
            {
                RelatesTo           = context.Activity.ToConversationReference(),
                Text                = message.Text,
                IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(message.ServiceUrl)
            };

            // write the queue Message to the queue
            await AddMessageToQueueAsync(JsonConvert.SerializeObject(queueMessage));

            await context.PostAsync($"You said {queueMessage.Text}. Your message has been added to a queue, and it will be sent back to you via a Function shortly.");

            context.Wait(MessageReceivedAsync);
        }
예제 #19
0
        private ConversationReference PrepareConversationReferenceAsync(
            string serviceUrl,
            string tenantId,
            string teamId)
        {
            var user = new ChannelAccount
            {
                Id = teamId,
            };

            var bot = new ChannelAccount
            {
                Id = $"28:{this.botId}",
            };

            var conversationAccount = new ConversationAccount
            {
                ConversationType = BotMetadataConstants.ChannelConversationType,
                Id       = teamId,
                TenantId = tenantId,
            };

            var conversationReference = new ConversationReference
            {
                Bot          = bot,
                User         = user,
                ChannelId    = BotMetadataConstants.MsTeamsChannelId,
                Conversation = conversationAccount,
                ServiceUrl   = serviceUrl,
            };

            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(conversationReference.ServiceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(conversationReference.ServiceUrl);
            }

            return(conversationReference);
        }
예제 #20
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            // check if activity is of type message
            try
            {
                if (activity.GetActivityType() == ActivityTypes.Message)
                {
                    string appdId      = "*APP ID HERE*";
                    string appPassword = "******";


                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl), appdId, appPassword);

                    MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);

                    MicrosoftAppCredentials.IsTrustedServiceUrl(activity.ServiceUrl);
                    var channelId = activity.ChannelId;

                    await Conversation.SendAsync(activity, () => new BasicQnAMakerDialog(channelId, _getMeals, _siteConfigService, _externalService));

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    await HandleSystemMessageAsync(activity);
                }
                ;
            }
            catch (Exception e)
            {
                String s = e.ToString();
                throw;
            }



            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
예제 #21
0
 public ResumptionCookie(Address address)
 {
     this.Address        = address;
     IsTrustedServiceUrl = MicrosoftAppCredentials.IsTrustedServiceUrl(address.ServiceUrl);
 }