Example #1
0
        /// <summary>
        /// Get the state api endpoint from settings.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>The state api endpoint from settings.</returns>
        private static string GetSettingsStateApiUrl(string key = "BotStateEndpoint")
        {
            var url = SettingsUtils.GetAppSettings(key);

            if (!string.IsNullOrEmpty(url))
            {
                MicrosoftAppCredentials.TrustServiceUrl(url, DateTime.MaxValue);
            }
            return(url);
        }
Example #2
0
        static void Main(string[] args)
        {
            var appId       = "<Microsoft App ID>";
            var appPassword = "******";

            //Emulator
            var fromId         = "default - user";
            var recipientId    = "95i2nkda1dd4";
            var serviceUrl     = "http://*****:*****@dTuM__gWAS0";
            //var serviceUrl = "https://webchat.botframework.com/";
            //var conversationId = "fd8a04848c4744ddbbcce046f6086967";

            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            var connector   = new ConnectorClient(new Uri(serviceUrl), appId, appPassword);
            var botAccount  = new ChannelAccount(id: recipientId);
            var userAccount = new ChannelAccount(id: fromId);

            IMessageActivity message = Activity.CreateMessageActivity();

            message.Conversation = new ConversationAccount(id: conversationId);
            message.From         = botAccount;
            message.Recipient    = userAccount;
            message.Locale       = "ja-jp";
            message.Text         = $@"Chatbotからのお知らせです。

本日のおすすめは、季節のフルーツとれたてのあまーいいちごです。";
            var cardImage = new CardImage {
                Url = "https://chatbot201707.azurewebsites.net/img/strawberry.jpg"
            };
            var heroCard = new HeroCard {
                Title = "季節のフルーツ", Images = new List <CardImage> {
                    cardImage
                }
            };

            message.Attachments.Add(heroCard.ToAttachment());
            connector.Conversations.SendToConversation((Activity)message);
        }
Example #3
0
        /// <summary>
        /// Method ends the existing scrum if running and then sends the start scrum card.
        /// </summary>
        /// <param name="scrumConfiguration">Scrum configuration details obtained from storage.</param>
        /// <returns>A task that ends the existing scrum and sends the start scrum card .</returns>
        public async Task ScrumStartActivityAsync(ScrumConfiguration scrumConfiguration)
        {
            try
            {
                string serviceUrl = scrumConfiguration.ServiceUrl;
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

                var conversationReference = new ConversationReference()
                {
                    ChannelId = TeamsBotFrameworkChannelId,
                    Bot       = new ChannelAccount()
                    {
                        Id = $"28:{this.microsoftAppCredentials.MicrosoftAppId}"
                    },
                    ServiceUrl   = serviceUrl,
                    Conversation = new ConversationAccount()
                    {
                        ConversationType = Constants.ChannelConversationType, IsGroup = true, Id = scrumConfiguration.ChannelId, TenantId = this.options.Value.TenantId
                    },
                };

                this.logger.LogInformation($"Sending start scrum card to channelId: {scrumConfiguration.ChannelId}");

                await RetryPolicy.ExecuteAsync(async() =>
                {
                    try
                    {
                        await((BotFrameworkAdapter)this.adapter).ContinueConversationAsync(
                            this.microsoftAppCredentials.MicrosoftAppId,
                            conversationReference,
                            async(conversationTurnContext, conversationCancellationToken) =>
                        {
                            bool isValidScrum = await this.EndExistingScrumAsync(conversationTurnContext, scrumConfiguration, conversationCancellationToken);
                            if (!isValidScrum)
                            {
                                this.logger.LogInformation("Error while ending the existing scrum.");
                                await conversationTurnContext.SendActivityAsync(this.localizer.GetString(this.localizer.GetString("ErrorMessage")));
                            }

                            await this.SendScrumStartCardAsync(conversationTurnContext, scrumConfiguration, conversationCancellationToken);
                        },
                            CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, "Error while performing retry logic to send scrum start card.");
                        throw;
                    }
                });
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error while sending start scrum to channel from background service.");
            }
        }
Example #4
0
 public static async Task NotifyUser(this IDialogContext context, string messageText)
 {
     if (!string.IsNullOrEmpty(messageText))
     {
         string serviceUrl = context.PrivateConversationData.Get <string>("ServiceUrl");
         var    connector  = new ConnectorClient(new Uri(serviceUrl));
         var    reply      = context.MakeMessage();
         reply.Text = messageText;
         MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
         await connector.Conversations.ReplyToActivityAsync((Activity)reply);
     }
 }
Example #5
0
        // TODO: Pending review
        // Forward message to Slack
        private async Task <bool> SendSlackMessageAsync(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 userAccount = new ChannelAccount(toId, toName);
                var botAccount  = new ChannelAccount(fromId, fromName);

                var message = Activity.CreateMessageActivity();
                message.From        = botAccount;
                message.Recipient   = userAccount;
                message.ChannelData = messageContent;

                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;
                if (recipient.IsGroupChannel)
                {
                    conversationId = recipient.SlackConversationId;
                }
                else
                {
                    var conversation = client.Conversations.CreateDirectConversation(botAccount, userAccount);
                    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);
        }
Example #6
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            var builder = new ContainerBuilder();

            builder.RegisterModule(new LessonPlanModule());
            builder.RegisterModule(new BasicDialogModule());

            builder
            .RegisterType <AzureTableLogger>()
            .Keyed <ILogger>(FiberModule.Key_DoNotSerialize)
            .AsSelf()
            .As <ILogger>()
            .SingleInstance();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));

            var store = new TableBotDataStore(ConfigurationManager.AppSettings["StorageConnectionString"]);
            var cache = new CachingBotDataStore(store,
                                                CachingBotDataStoreConsistencyPolicy
                                                .ETagBasedConsistency);

            MicrosoftAppCredentials.TrustServiceUrl("directline.botframework.com");

            builder.RegisterType <AzureActivityLogger>().As <IActivityLogger>().InstancePerDependency();

            Conversation.UpdateContainer(
                coversation =>
            {
                coversation.Register(c => store)
                .Keyed <IBotDataStore <BotData> >(AzureModule.Key_DataStore)
                .AsSelf()
                .SingleInstance();

                coversation.Register(c => cache)
                .As <IBotDataStore <BotData> >()
                .AsSelf()
                .InstancePerLifetimeScope();
            });



            var config = GlobalConfiguration.Configuration;

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Server.MapPath("translation.json"));
        }
Example #7
0
        static ConnectorClient GetConnectorClient(string serviceUrl, string botClientId, string botSecret)
        {
            MicrosoftAppCredentials appCredentials =
                new MicrosoftAppCredentials(botClientId, botSecret);

            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

            Uri             uri             = new Uri(serviceUrl);
            ConnectorClient connectorClient =
                new ConnectorClient(uri, appCredentials);

            return(connectorClient);
        }
        /// <summary>
        /// Method to update team goal, personal goal and note details in storage when team goal is ended.
        /// </summary>
        /// <param name="teamGoalDetail">Holds team goal detail entity data sent from background service.</param>
        /// <returns>A task that represents team goal, personal goal and personal goal note details data is saved or updated.</returns>
        public async Task UpdateGoalDetailsAsync(TeamGoalDetail teamGoalDetail)
        {
            teamGoalDetail = teamGoalDetail ?? throw new ArgumentNullException(nameof(teamGoalDetail));

            try
            {
                var    teamId     = teamGoalDetail.TeamId;
                string serviceUrl = teamGoalDetail.ServiceUrl;
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

                var conversationReference = new ConversationReference()
                {
                    ChannelId = Constants.TeamsBotFrameworkChannelId,
                    Bot       = new ChannelAccount()
                    {
                        Id = $"28:{this.microsoftAppCredentials.MicrosoftAppId}"
                    },
                    ServiceUrl   = serviceUrl,
                    Conversation = new ConversationAccount()
                    {
                        ConversationType = Constants.ChannelConversationType, IsGroup = true, Id = teamId, TenantId = this.options.Value.TenantId
                    },
                };

                await this.retryPolicy.ExecuteAsync(async() =>
                {
                    try
                    {
                        await((BotFrameworkAdapter)this.adapter).ContinueConversationAsync(
                            this.microsoftAppCredentials.MicrosoftAppId,
                            conversationReference,
                            async(turnContext, cancellationToken) =>
                        {
                            await this.UpdateGoalEntitiesAsync(turnContext, teamGoalDetail, cancellationToken);
                        },
                            CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, $"Error while performing retry logic to send goal reminder card for : {teamGoalDetail.TeamGoalId}.");
                        throw;
                    }
                });
            }
            #pragma warning disable CA1031 // Catching general exceptions to log exception details in telemetry client.
            catch (Exception ex)
            #pragma warning restore CA1031 // Catching general exceptions to log exception details in telemetry client.
            {
                this.logger.LogError(ex, $"Error while updating personal goal, team goal and personal goal note detail from background service for : {teamGoalDetail.TeamGoalId} at {nameof(this.UpdateGoalDetailsAsync)}");
            }
        }
Example #9
0
        private static async Task NotifyUser(string serviceUrl, string cardToSend, ChannelAccount user, string tenantId)
        {
            var me = new ChannelAccount()
            {
                Id   = CloudConfigurationManager.GetSetting("MicrosoftAppId"),
                Name = "MeetupBot"
            };

            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

            // Create 1:1 with user
            using (var connectorClient = new ConnectorClient(new Uri(serviceUrl)))
            {
                // ensure conversation exists
                var response = connectorClient.Conversations.CreateOrGetDirectConversation(me, user, tenantId);

                // construct the activity we want to post
                var activity = new Activity()
                {
                    Type         = ActivityTypes.Message,
                    Conversation = new ConversationAccount()
                    {
                        Id = response.Id,
                    },
                    Attachments = new List <Attachment>()
                    {
                        new Attachment()
                        {
                            ContentType = "application/vnd.microsoft.card.adaptive",
                            Content     = JsonConvert.DeserializeObject(cardToSend),
                        }
                    }
                };

                var isTesting = Boolean.Parse(CloudConfigurationManager.GetSetting("Testing"));

                if (!isTesting)
                {
                    // shoot the activity over
                    // added try catch because if user has set "Block conversations with bots"
                    try
                    {
                        await connectorClient.Conversations.SendToConversationAsync(activity, response.Id);
                    }
                    catch (UnauthorizedAccessException uae)
                    {
                        System.Diagnostics.Trace.TraceError($"Failed to notify user due to error {uae.ToString()}");
                    }
                }
            }
        }
        /// <summary>
        /// Get a team's roster.
        /// </summary>
        /// <param name="serviceUrl">The service URL.</param>
        /// <param name="teamId">Team id, e.g. "19:[email protected]".</param>
        /// <param name="tenantId">Tenant id for the team and user.</param>
        /// <returns>Roster of the team with the passed in id.</returns>
        private async Task <IEnumerable <UserDataEntity> > GetTeamRosterRecipientDataEntityListAsync(
            string serviceUrl,
            string teamId,
            string tenantId)
        {
            // Set the service URL in the trusted list to ensure the SDK includes the token in the request.
            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

            var conversationReference = new ConversationReference
            {
                ServiceUrl   = serviceUrl,
                Conversation = new ConversationAccount
                {
                    Id = teamId,
                },
            };

            IEnumerable <UserDataEntity> userDataEntitiesResult = null;

            await this.botAdapter.ContinueConversationAsync(
                this.microsoftAppId,
                conversationReference,
                async (turnContext, cancellationToken) =>
            {
                var members = await this.GetMembersAsync(turnContext, cancellationToken);

                userDataEntitiesResult = members.Select(member =>
                {
                    var userDataEntity = new UserDataEntity
                    {
                        UserId = member.Id,
                        Name   = member.Name,

                        // Set the conversation ID to null because it is not known at this time and
                        // may not have been created yet.
                        ConversationId = null,
                        ServiceUrl     = serviceUrl,
                        Email          = member.Email,
                        Upn            = member.UserPrincipalName,
                        AadId          = member.AadObjectId,
                        TenantId       = tenantId,
                    };

                    return(userDataEntity);
                });
            },
                CancellationToken.None);

            return(userDataEntitiesResult);
        }
Example #11
0
        private static async Task <TeamsChannelAccount[]> GetTeamMembers(string serviceUrl, string teamId, string tenantId)
        {
            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

            using (var connector = new ConnectorClient(new Uri(serviceUrl)))
            {
                // Pull the roster of specified team and then remove everyone who has opted out explicitly
#pragma warning disable CS0618 // Type or member is obsolete
                var members = await connector.Conversations.GetTeamsConversationMembersAsync(teamId, tenantId);

#pragma warning restore CS0618 // Type or member is obsolete
                return(members);
            }
        }
Example #12
0
        public async Task <string> SendToChannel(IActivity activity)
        {
            MicrosoftAppCredentials.TrustServiceUrl(ServiceUrl, DateTime.MaxValue);
            var connector = new ConnectorClient(new Uri(ServiceUrl));

            activity.ChannelId    = ChannelId;
            activity.From         = new ChannelAccount(id: BotId, name: BotName);
            activity.Conversation = new ConversationAccount(id: ConversationId);


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

            return(ConversationId);
        }
Example #13
0
        public async Task <IActionResult> Post([FromBody] Activity activity)
        {
            try
            {
                if (activity.Type == ActivityTypes.Message)
                {
                    MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);

                    var appCredentials = new MicrosoftAppCredentials(this.configuration);
                    var connector      = new ConnectorClient(new Uri(activity.ServiceUrl), appCredentials);

                    var arguments = new ArguementsHandler(activity.Text);
                    if (arguments.CanAction())
                    {
                        var command     = arguments.GetCommand();
                        var userHandler = new UserIntractionHandler(connector, activity);
                        switch (command)
                        {
                        case CommandHandler.Commands.Download:
                            await new CommandHandler(this.download, this.videoConverter).DownloadCommand(arguments, userHandler);
                            break;

                        default:
                            var message = $"Usage: bot download [Optional Commands] [Youtube URL] {Environment.NewLine}";
                            message += $"Where [Commands] is one of: {Environment.NewLine}";
                            message += $"--start HH:MM:SS {Environment.NewLine}";
                            message += $"--end HH:MM:SS {Environment.NewLine}";
                            await userHandler.SendHeroCard("Bot Help", message);

                            break;
                        }
                    }

                    // return our reply to the user
                    // var reply = activity.CreateReply("HelloWorld");
                    // await connector.Conversations.ReplyToActivityAsync(reply);
                }
                else
                {
                    // HandleSystemMessage(activity);
                }

                return(this.Ok());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message} ");
                throw;
            }
        }
Example #14
0
        /// <summary>
        /// Sends notification to the user.
        /// </summary>
        /// <param name="user">The user to which notification need to send</param>
        /// <param name="card">The notification card that to be send</param>
        /// <returns>A <see cref="Tasks.Task"/> representing the asynchronous operation.</returns>
        public async Tasks.Task SendNotificationToUserAsync(Conversation user, Attachment card)
        {
            if (user == null || string.IsNullOrEmpty(user.ConversationId) ||
                string.IsNullOrEmpty(Convert.ToString(user.UserId, CultureInfo.InvariantCulture)) ||
                string.IsNullOrEmpty(user.ServiceUrl) ||
                card == null)
            {
                return;
            }

            try
            {
                MicrosoftAppCredentials.TrustServiceUrl(user.ServiceUrl);

                var conversationReference = new ConversationReference()
                {
                    Bot = new ChannelAccount()
                    {
                        Id = $"28:{this.microsoftAppCredentials.MicrosoftAppId}"
                    },
                    ChannelId    = TeamsBotChannelId,
                    Conversation = new ConversationAccount()
                    {
                        Id = user.ConversationId
                    },
                    ServiceUrl = user.ServiceUrl,
                };

                var botFrameworkAdapter           = this.botFrameworkHttpAdapter as BotFrameworkAdapter;
                ResourceResponse resourceResponse = null;

                await this.retryPolicy.ExecuteAsync(async() =>
                {
                    await botFrameworkAdapter.ContinueConversationAsync(
                        this.microsoftAppCredentials.MicrosoftAppId,
                        conversationReference,
                        async(turnContext, cancellationToken) =>
                    {
                        resourceResponse = await turnContext.SendActivityAsync(MessageFactory.Attachment(card), cancellationToken);
                    },
                        CancellationToken.None);
                });
            }
#pragma warning disable CA1031 // Caching general exception to log exception and user Id
            catch (Exception ex)
#pragma warning restore CA1031 // Caching general exception to log exception and user Id
            {
                this.logger.LogError(ex, $"Unable to send notification to user {user.UserId}");
            }
        }
        // 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);
            }
        }
        /// <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;
            }
        }
        public async Task <bool> SignOutUserAsync(string userId, string connectionName, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (connectionName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "connectionName");
            }
            if (userId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "userId");
            }

            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/usertoken/SignOut?&userId={userId}&connectionName={connectionName}").ToString();

            _url = _url.Replace("{connectionName}", System.Uri.EscapeDataString(connectionName));
            _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId));

            MicrosoftAppCredentials.TrustServiceUrl(_url);

            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);

            // Set Credentials
            if (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            if (_statusCode == HttpStatusCode.OK)
            {
                return(true);
            }
            else
            {
                // TODO: some error situation should be logged
                return(false);
            }
        }
Example #18
0
        public static async Task <bool> AuthenticateBotRequest(HttpRequestMessage req, Activity activity, CancellationToken token)
        {
            var credProvider = new SettingsCredentialProvider();

            var authenticator = new BotAuthenticator(credProvider, JwtConfig.ToBotFromChannelOpenIdMetadataUrl, disableEmulatorTokens: false);


            var authenticated = await authenticator.TryAuthenticateAsync(req, new[] { activity }, token);

            if (authenticated)
            {
                MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);
            }
            return(authenticated);
        }
        /// <summary>
        ///  Send a reply to a specific message that was previously sent.
        /// </summary>
        /// <param name="text">The text to send.</param>
        /// <param name="serviceUrl">ServiceUrl for the tenant.</param>
        /// <param name="conversationId">The conversation ID of the previously sent message.</param>
        /// <param name="activityId">The activity ID of the previously sent message.</param>
        /// <param name="botSettings">Bot configuration settings.</param>
        /// <returns>Async task.</returns>
        public static async Task <ResourceResponse> ReplyToChannelMessageAsync(string text, string serviceUrl, string conversationId, string activityId, BotSettings botSettings)
        {
            var message = Activity.CreateMessageActivity();

            message.Text = text;

            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl, DateTime.MaxValue);
            using (var connectorClient = new ConnectorClient(new Uri(serviceUrl), botSettings.Id, botSettings.Password))
            {
                var resourceResponse = await connectorClient.Conversations.ReplyToActivityAsync(conversationId, activityId, (Activity)message);

                // Returns resource response containing message ID
                return(resourceResponse);
            }
        }
Example #20
0
        private async Task SendToConversation(
            string text,
            IList <Attachment> attachments,
            ConversationData conversationData,
            CancellationToken cancellationToken)
        {
            MicrosoftAppCredentials.TrustServiceUrl(conversationData.ServiceUrl);
            using (var client = new ConnectorClient(
                       new Uri(conversationData.ServiceUrl),
                       new MicrosoftAppCredentials(_appSettings.MicrosoftAppId, _appSettings.MicrosoftAppPassword)))
            {
                var conversationParameters = new ConversationParameters
                {
                    Bot         = new ChannelAccount(_appSettings.MicrosoftAppId),
                    ChannelData = new TeamsChannelData
                    {
                        Tenant = new TenantInfo
                        {
                            Id = conversationData.TenantId
                        }
                    },
                    Members = new List <ChannelAccount> {
                        new ChannelAccount(conversationData.AccountId)
                    }
                };

                var conversation = await client.Conversations.CreateConversationAsync(conversationParameters, cancellationToken);

                var activity = MessageFactory.Text(text);
                activity.Conversation = new ConversationAccount {
                    Id = conversation.Id
                };
                activity.ChannelData = new TeamsChannelData
                {
                    Notification = new NotificationInfo
                    {
                        Alert = true
                    }
                };

                if (attachments != null && attachments.Count > 0)
                {
                    activity.Attachments = attachments;
                }

                await client.Conversations.SendToConversationAsync(activity, cancellationToken);
            }
        }
Example #21
0
        static async Task Main(string[] args)
        {
            //The Bot Service Url needs to be dynamically stored and fetched from the Team.
            //This Url is present in every payload which Teams sends to the Bot after the Bot is added to the Team.
            //Recommendation is to store the serviceUrl from the bot payload and later re-use it to send proactive messages.
            string serviceUrl = "https://smba.trafficmanager.net/emea/";

            //From the Bot Channel Registration
            string botClientID     = "<client-id>";
            string botClientSecret = "<client-secret>";

            //Teams channel id in which to create the post.
            string teamsChannelId = "19:[email protected]";


            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            var connectorClient = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));


            string adaptiveCardJsonFilePath = @"AdaptiveCard.json";

            string json = File.ReadAllText(adaptiveCardJsonFilePath);

            AdaptiveCardParseResult result = AdaptiveCard.FromJson(json);

            // Get card from result
            AdaptiveCard adaptiveCard = result.Card;

            var cardAttachment = new Attachment
            {
                Content     = adaptiveCard,
                ContentType = AdaptiveCard.ContentType,
            };

            var messageActivity = MessageFactory.Attachment(cardAttachment);

            //Send the activity to Teams.
            var conversationParameters = new ConversationParameters
            {
                IsGroup     = true,
                ChannelData = new TeamsChannelData
                {
                    Channel = new ChannelInfo(teamsChannelId),
                },
                Activity = (Activity)messageActivity
            };
            await connectorClient.Conversations.CreateConversationAsync(conversationParameters);
        }
        public async Task SendMessageToChannel(string title, BotSubscription subscription)
        {
            var subscriptionFacade = new SubscriptionFacade();
            var channelData        = new TeamsChannelData
            {
                Channel = new ChannelInfo(subscription.ChannelId),
                Team    = new TeamInfo(subscription.TeamId),
                Tenant  = new TenantInfo(subscription.TenantId)
            };

            var newMessageText = await Build();

            var newMessage = new Activity
            {
                Type = ActivityTypes.Message,
                Text = newMessageText.FixNewLines(),
            };
            var conversationParams = new ConversationParameters(
                isGroup: true,
                bot: null,
                members: null,
                topicName: title,
                activity: (Activity)newMessage,
                channelData: channelData);

            var connector = new ConnectorClient(new Uri(subscription.ServiceUrl), Environment.GetEnvironmentVariable("MicrosoftAppId"), Environment.GetEnvironmentVariable("MicrosoftAppPassword"));

            MicrosoftAppCredentials.TrustServiceUrl(subscription.ServiceUrl, DateTime.MaxValue);

            if (subscription.LastActivity == null)
            {
                var result = await connector.Conversations.CreateConversationAsync(conversationParams);

                subscription.LastActivity = new LastActivity
                {
                    ConversationId = result.Id,
                    ActitityId     = result.ActivityId
                };
            }
            else
            {
                var result = await connector.Conversations.UpdateActivityAsync(subscription.LastActivity.ConversationId, subscription.LastActivity.ActitityId, newMessage);

                subscription.LastActivity.ActitityId = result.Id;
            }

            await subscriptionFacade.UpdateBotSubscription(subscription);
        }
Example #23
0
        public async Task <IActionResult> PostAsync()
        {
            var form = await Request.ReadFormAsync();

            if (form != null)
            {
                // Ugly formatted response comes back from Vodafone - likely to be different format for other GSM providers
                // BAL=Yourbalanceis#2.98.Tocheckanyremainingallowancespleasecall1345,forfree.Thankyou OK VIDEX GSM
                string balanceText = form["Body"];
                if (balanceText != null)
                {
                    Regex regex       = new Regex(@"([^#]\d*[.]+\d{0,2})");
                    var   regexAmount = regex.Match(balanceText);

                    if (regexAmount.Success)
                    {
                        decimal amount       = Convert.ToDecimal(regexAmount.Value);
                        string  responseText = $"Your current balance is £{amount}";

                        Activity videxResponse = new Activity()
                        {
                            Type = "message", InputHint = "acceptingInput", Text = responseText
                        };

                        if (!_conversationReferences.IsEmpty)
                        {
                            foreach (var conversationReference in _conversationReferences.Values)
                            {
                                await((BotAdapter)_adapter).ContinueConversationAsync(
                                    _appId,
                                    conversationReference,
                                    (ITurnContext turnContext, CancellationToken cancellationToken) =>
                                {
                                    MicrosoftAppCredentials.TrustServiceUrl(conversationReference.ServiceUrl);
                                    return(turnContext.SendActivityAsync(videxResponse));
                                }, default);
                            }
                        }
                    }
                }
            }

            var mr = new MessagingResponse();

            Response.ContentType = "text/xml";
            Response.StatusCode  = StatusCodes.Status200OK;
            return(TwiML(mr));
        }
Example #24
0
        /// <summary>
        /// Registers dependencies with the <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder"> The container builder.</param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <ConnectorStore>()
            .AsSelf()
            .InstancePerLifetimeScope();

            // if application settings indicate that bot should use the table storage,
            // TableBotDataStore will be registered as underlying storage
            // otherwise bot connector state service will be used.
            if (ShouldUseTableStorage())
            {
                builder.Register(c => MakeTableBotDataStore())
                .Keyed <IBotDataStore <BotData> >(Key_DataStore)
                .AsSelf()
                .SingleInstance();
            }
            else
            {
                builder.Register(c => new ConnectorStore(c.Resolve <IStateClient>()))
                .Keyed <IBotDataStore <BotData> >(Key_DataStore)
                .AsSelf()
                .InstancePerLifetimeScope();
            }

            // register the data store with caching data store
            // and set the consistency policy to be "Last write wins".
            builder.Register(c => new CachingBotDataStore(c.ResolveKeyed <IBotDataStore <BotData> >(Key_DataStore),
                                                          CachingBotDataStoreConsistencyPolicy.LastWriteWins))
            .As <IBotDataStore <BotData> >()
            .AsSelf()
            .InstancePerLifetimeScope();

            // register the appropriate StateClient based on the state api url.
            builder.Register(c =>
            {
                var activity = c.Resolve <IActivity>();
                if (activity.ChannelId == "emulator")
                {
                    // for emulator we should use serviceUri of the emulator for storage
                    return(new StateClient(new Uri(activity.ServiceUrl)));
                }

                MicrosoftAppCredentials.TrustServiceUrl(BotService.stateApi.Value, DateTime.MaxValue);
                return(new StateClient(new Uri(BotService.stateApi.Value)));
            })
            .As <IStateClient>()
            .InstancePerLifetimeScope();
        }
Example #25
0
 private static async Task AnswerAsync(Activity activity, CancellationToken ct)
 {
     try
     {
         var client = new ConnectorClient(new Uri(activity.ServiceUrl),
                                          new MicrosoftAppCredentials("26a47099-ba81-49e1-a425-23b4152cd5fe", @"BOD554=%enkzmpmQRWB88[#"));
         var answer = activity.CreateReply(activity.Text, activity.Locale);
         MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);
         await client.Conversations.ReplyToActivityAsync(answer, ct);
     }
     catch (Exception e)
     {
         Trace.TraceError(e.ToString());
         throw;
     }
 }
Example #26
0
        public async Task <string> SendToChannel(IActivity activity)
        {
            MicrosoftAppCredentials.TrustServiceUrl(ServiceUrl, DateTime.MaxValue);
            var connector   = new ConnectorClient(new Uri(ServiceUrl));
            var channelData = new TeamsChannelData(channel: new ChannelInfo(TeamsChannelId));

            var conversationParameters = new ConversationParameters(
                isGroup: true,
                bot: new ChannelAccount(id: BotId, name: BotName),
                channelData: channelData,
                topicName: "New question",
                activity: (Activity)activity
                );

            return((await connector.Conversations.CreateConversationAsync(conversationParameters)).Id);
        }
Example #27
0
        /// <summary>
        /// This method creates a bot connector client per service URL.
        /// </summary>
        /// <param name="serviceUrl">Service URL.</param>
        /// <returns>It returns a bot connector client.</returns>
        public CustomConnectorClient Create(string serviceUrl)
        {
            if (!this.serviceUrlToConnectorClientMap.ContainsKey(serviceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

                var connectorClient = new CustomConnectorClient(
                    new Uri(serviceUrl),
                    this.configurationSettings.MicrosoftAppId,
                    this.configurationSettings.MicrosoftAppPassword);

                this.serviceUrlToConnectorClientMap.TryAdd(serviceUrl, connectorClient);
            }

            return(this.serviceUrlToConnectorClientMap[serviceUrl]);
        }
        public async Task PostContentEventAsync()
        {
            using (var readStream = new StreamReader(Request.Body, Encoding.UTF8))
            {
                var body = await readStream.ReadToEndAsync();

                if (!Authenticate(Request, body))
                {
                    return;
                }

                var wbhookData = JsonConvert.DeserializeObject <Models.Webhook.WebhookData>(body);

                foreach (var change in wbhookData.body.changes)
                {
                    if ([email protected] == "ContentEvent" && change?.originatorMetadata?.role == "ASSIGNED_AGENT")
                    {
                        if ([email protected] != null)
                        {
                            var humanActivity = MessageFactory.Text([email protected]);

                            ConversationRecord conversationRec;
                            if (_conversationMap.ConversationRecords.TryGetValue(change.conversationId, out conversationRec))
                            {
                                if (!conversationRec.IsClosed)
                                {
                                    MicrosoftAppCredentials.TrustServiceUrl(conversationRec.ConversationReference.ServiceUrl);

                                    await((BotFrameworkHttpAdapter)_adapter).ContinueConversationAsync(
                                        _creds.MsAppId,
                                        conversationRec.ConversationReference,
                                        (ITurnContext turnContext, CancellationToken cancellationToken) =>
                                        turnContext.SendActivityAsync(humanActivity, cancellationToken),
                                        default(CancellationToken));
                                }
                            }
                            else
                            {
                                // The bot has no record of this conversation, this should not happen
                                throw new Exception("Cannot find conversation");
                            }
                        }
                    }
                }
            }
            Response.StatusCode = (int)HttpStatusCode.OK;
        }
Example #29
0
        /// <summary>
        /// This method is used to send notifications to all channels of a group activity.
        /// </summary>
        /// <param name="request">notification request object.</param>
        /// <returns>Task.</returns>
        private async Task SendNotificationsAsync(NotificationRequest request)
        {
            if (request != null)
            {
                string serviceUrl = request.ServiceUrl;
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
                foreach (GroupNotification channel in request.GroupNotificationChannels)
                {
                    string teamsChannelId        = channel.RowKey;
                    var    conversationReference = new ConversationReference()
                    {
                        ChannelId = Constants.Channel,
                        Bot       = new ChannelAccount()
                        {
                            Id = this.microsoftAppCredentials.MicrosoftAppId
                        },
                        ServiceUrl   = serviceUrl,
                        Conversation = new ConversationAccount()
                        {
                            ConversationType = Constants.ChannelConversationType, IsGroup = true, Id = teamsChannelId, TenantId = this.tenantId
                        },
                    };

                    this.logger.LogInformation($"sending notification to channelId- {teamsChannelId}");
                    var card = NotificationCard.GetNotificationCardAttachment(request, channel.ChannelName);
                    try
                    {
                        await retryPolicy.ExecuteAsync(async() =>
                        {
                            await((BotFrameworkAdapter)this.adapter).ContinueConversationAsync(
                                this.microsoftAppCredentials.MicrosoftAppId,
                                conversationReference,
                                async(conversationTurnContext, conversationCancellationToken) =>
                            {
                                await conversationTurnContext.SendActivityAsync(MessageFactory.Attachment(card));
                            },
                                CancellationToken.None);
                        });
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, "Error while sending notification to channel from background service.");
                    }
                }
            }
        }
Example #30
0
        private static async Task AnswerAsync(Activity activity, CancellationToken ct)
        {
            try
            {
                var client = new ConnectorClient(new Uri(activity.ServiceUrl),
                                                 new MicrosoftAppCredentials("appid", @"apppassword"));
                var answer = activity.CreateReply(activity.Text, activity.Locale);
                MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);

                await client.Conversations.ReplyToActivityAsync(answer, ct);
            }
            catch (Exception e)
            {
                //Trace.TraceError(e.ToString());
                throw;
            }
        }