private Activity CreateReceipt(Activity message) {
            Activity replyToConversation = message.CreateReply("Receipt card");
            replyToConversation.Recipient = message.From;
            replyToConversation.Type = "message";
            replyToConversation.Attachments = new List<Attachment>();
            List<CardImage> cardImages = new List<CardImage>();
            cardImages.Add(new CardImage(url: "https://<ImageUrl1>"));
            List<CardAction> cardButtons = new List<CardAction>();
            CardAction plButton = new CardAction() {
                Value = "https://en.wikipedia.org/wiki/Pig_Latin",
                Type = "openUrl",
                Title = "WikiPedia Page"
            };
            cardButtons.Add(plButton);
            ReceiptItem lineItem1 = new ReceiptItem() {
                Title = "Pork Shoulder",
                Subtitle = "8 lbs",
                Text = null,
                Image = new CardImage(url: "https://<ImageUrl1>"),
                Price = "16.25",
                Quantity = "1",
                Tap = null
            };
            ReceiptItem lineItem2 = new ReceiptItem() {
                Title = "Bacon",
                Subtitle = "5 lbs",
                Text = null,
                Image = new CardImage(url: "https://<ImageUrl2>"),
                Price = "34.50",
                Quantity = "2",
                Tap = null
            };
            List<ReceiptItem> receiptList = new List<ReceiptItem>();
            receiptList.Add(lineItem1);
            receiptList.Add(lineItem2);
            ReceiptCard plCard = new ReceiptCard() {
                Title = "I'm a receipt card, isn't this bacon expensive?",
                Buttons = cardButtons,
                Items = receiptList,
                Total = "275.25",
                Tax = "27.52"
            };
            Attachment plAttachment = plCard.ToAttachment();
            replyToConversation.Attachments.Add(plAttachment);
            return replyToConversation;
           

        }
        private Activity CreateCard(Activity message) {
            Activity replyToConversation = message.CreateReply("Should go to conversation, with a thumbnail card");
            replyToConversation.Recipient = message.From;
            replyToConversation.Type = "message";
            replyToConversation.Attachments = new List<Attachment>();
            List<CardImage> cardImages = new List<CardImage>();
            cardImages.Add(new CardImage(url: "https://upload.wikimedia.org/wikipedia/commons/f/ff/Aminah_Cendrakasih%2C_c._1959%2C_by_Tati_Photo_Studio.jpg"));
            List<CardAction> cardButtons = new List<CardAction>();
            CardAction plButton = new CardAction() {
                Value = "https://en.wikipedia.org/wiki/Pig_Latin",
                Type = "openUrl",
                Title = "WikiPedia Page"
            };
            cardButtons.Add(plButton);
            ThumbnailCard plCard = new ThumbnailCard() {
                Title = "I'm a thumbnail card",
                Subtitle = "Pig Latin Wikipedia Page",
                Images = cardImages,
                Buttons = cardButtons
            };
            Attachment plAttachment = plCard.ToAttachment();
            //   plAttachment.ContentType = "application/vnd.microsoft.card.heros";

            replyToConversation.Attachments.Add(plAttachment);
            return replyToConversation;
        }
        private Activity HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return null;
        }
예제 #4
0
        private void RequestLogin(Microsoft.Bot.Connector.Activity message)
        {
            var resumptionCookie        = new ResumptionCookie(message);
            var encodedResumptionCookie = UrlToken.Encode <ResumptionCookie>(resumptionCookie);

            Microsoft.Bot.Connector.Activity oriMessage = resumptionCookie.GetMessage();


            var reply = oriMessage.CreateReply(Messages.BOT_PLEASE_LOGIN);

            reply.Recipient   = oriMessage.From;
            reply.Type        = Microsoft.Bot.Connector.ActivityTypes.Message;
            reply.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
            List <Microsoft.Bot.Connector.CardAction> cardButtons = new List <Microsoft.Bot.Connector.CardAction>();
            var encodedCookie = UrlToken.Encode(resumptionCookie);

            Microsoft.Bot.Connector.CardAction button = new Microsoft.Bot.Connector.CardAction()
            {
                Value = $"{ConfigurationHelper.GetString("AgentLogin_URL")}?cookie={encodedCookie}",
                Type  = "signin",
                Title = Messages.BOT_SIGNIN_BUTTON_TEXT,
                Image = "https://michistorageea.blob.core.windows.net/cdn/login.png"
            };
            cardButtons.Add(button);
            Microsoft.Bot.Connector.SigninCard plCard = new Microsoft.Bot.Connector.SigninCard(
                text: $"{Messages.BOT_PLEASE_LOGIN}",
                buttons: cardButtons);
            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
            reply.Attachments.Add(plAttachment);
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
            var             response  = connector.Conversations.SendToConversation(reply);
        }
예제 #5
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                var update = (IConversationUpdateActivity)activity;
                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    var client = scope.Resolve <IConnectorClient>();
                    if (update.MembersAdded.Any(x => x.Id != activity.Recipient.Id))
                    {
                        var newMembers = update.MembersAdded.Where(x => x.Id != activity.Recipient.Id).ToList();
                        foreach (var newMember in newMembers)
                        {
                            var reply = activity.CreateReply($"Welcome to Foo Bar Bot {newMember.Name}! (:");
                            await client.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
예제 #6
0
        private async Task <Microsoft.Bot.Connector.DirectLine.Activity> PostToAgentBotAsync2(Microsoft.Bot.Connector.DirectLine.Activity activityFromUser)
        {
            var directLineSecret = Configuration.ConfigurationHelper.GetString("AgentBot_DirectLine_Secret");
            var agentStatusDB    = Configuration.ConfigurationHelper.GetString("BotStatusDBConnectionString");
            var agentStorage     = new AgentStatusStorage(agentStatusDB);
            var agent            = await agentStorage.QueryAgentStatusAsync(activityFromUser.Recipient.Id);

            using (var client = new ConnectorClient(new Uri("https://smba.trafficmanager.net/apis")))
            {
                var recipient = new Microsoft.Bot.Connector.ChannelAccount(/*agent.AgentIdInChannel*/ "29:1Gk7vrlkdaMoN6fCtrycxkJfHcPS8zvi49Gukq4XuZAo");
                var from      = new Microsoft.Bot.Connector.ChannelAccount("");
                //var conversatoin = await client.Conversations.CreateDirectConversationAsync(from, recipient);
                var message = new Microsoft.Bot.Connector.Activity
                {
                    Text         = activityFromUser.Text,
                    From         = from,
                    Conversation = new Microsoft.Bot.Connector.ConversationAccount
                    {
                        Id = agent.ConversationId
                    },
                    Recipient = recipient
                };
                var response = await client.Conversations.SendToConversationAsync(message);

                return(null);
            }
        }
예제 #7
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                if (IsSpellCorrectionEnabled)
                {
                    try
                    {
                        activity.Text = await this.spellService.GetCorrectedTextAsync(activity.Text);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.ToString());
                    }
                }

                await Conversation.SendAsync(activity, () => new RootLuisDialog());
            }
            else
            {
                this.HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
예제 #8
0
        //private async Task ReadBotMessagesAsync(DirectLineClient client, string conversationId)
        //{
        //    try
        //    {
        //        while (true)
        //        {

        //            // get response from heath service bot
        //            var activitySet = await client.Conversations.GetActivitiesAsync(conversationId, watermark);
        //            watermark = activitySet?.Watermark;

        //            var activities = from x in activitySet.Activities
        //                             where x.From.Id == botId
        //                             select x;

        //            // respond to user
        //            foreach (Microsoft.Bot.Connector.DirectLine.Activity dactivity in activities)
        //            {
        //                Console.WriteLine(dactivity.Text);

        //                Microsoft.Bot.Connector.Activity reply = activity.CreateReply(dactivity.Text);

        //                if (dactivity.Attachments != null)
        //                {
        //                    foreach (Microsoft.Bot.Connector.DirectLine.Attachment attachment in dactivity.Attachments)
        //                    {
        //                        switch (attachment.ContentType)
        //                        {
        //                            case "application/vnd.microsoft.card.hero":
        //                                var heroCard = JsonConvert.DeserializeObject<Microsoft.Bot.Connector.HeroCard>(attachment.Content.ToString());
        //                                reply.Attachments.Add(heroCard.ToAttachment());
        //                                break;
        //                            default:
        //                                break;
        //                        }
        //                    }
        //                }

        //                //await connector.Conversations.SendToConversationAsync(reply);

        //                await connector.Conversations.ReplyToActivityAsync(reply);
        //            }

        //            await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine(ex.ToString());
        //        throw;
        //    }
        //}

        private Microsoft.Bot.Connector.Activity HandleSystemMessage(Microsoft.Bot.Connector.Activity message)
        {
            if (message.Type == Microsoft.Bot.Connector.ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == Microsoft.Bot.Connector.ActivityTypes.ConversationUpdate)
            {
                //if (connector != null)
                //{
                //    connector.Dispose();
                //    connector = null;
                //}
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
            }
            else if (message.Type == Microsoft.Bot.Connector.ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == Microsoft.Bot.Connector.ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == Microsoft.Bot.Connector.ActivityTypes.Ping)
            {
            }

            return(null);
        }
예제 #9
0
        /// <summary>
        /// Get a client connected to the system at present
        /// </summary>
        /// <param name="activity">The activity from the api controller</param>
        /// <returns></returns>
        private BotClient GetClient([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            // Get the client (if existing) from the connection
            BotClient connectingClient = Global.botClients.FirstOrDefault(bc => ((bc.BotURL == activity.ServiceUrl) && (bc.UserID == activity.From.Id)));

            // Check if we have a valid client...
            if (connectingClient == null)
            {
                // ... else create a connecting client
                connectingClient                     = new BotClient();
                connectingClient.UserID              = activity.From.Id;
                connectingClient.UserName            = activity.From.Name;
                connectingClient.BotURL              = activity.ServiceUrl;
                connectingClient.ConversationAccount = activity.Conversation;
                connectingClient.FromID              = activity.Recipient.Id;
                connectingClient.ChannelType         = activity.ChannelId;

                // Add it to the list of clients - will be useful for later
                Global.botClients.Add(connectingClient);

                // Tell the client that a connection has been established
                BotClientUtility.SendMessage(connectingClient, "Connection Established");
            }

            // Return the client for use elsewhere
            return(connectingClient);
        }
예제 #10
0
        private async Task <bool> CheckEnableDisable(Activity activity, CancellationToken cancellationToken)
        {
            bool   success        = false;
            string successMessage = null;

            if (_teamsToggleLogic.Value.IsDisablingBot(activity.Text))
            {
                success = await _teamsToggleLogic.Value.DisableBotInChannel(activity, cancellationToken);

                successMessage = Strings.DisableBotSuccess;
            }
            else if (_teamsToggleLogic.Value.IsEnablingBot(activity.Text))
            {
                success = await _teamsToggleLogic.Value.EnableBotInChannel(activity, cancellationToken);

                successMessage = Strings.EnableBotSuccess;
            }

            if (success)
            {
                var reply = activity.CreateReply(successMessage, activity.Locale);

                using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);
                }
            }

            return(success);
        }
예제 #11
0
        /// <summary>
        /// POST: api/Messages
        /// receive a message from a user and send replies
        /// </summary>
        /// <param name="activity"></param>
        public virtual async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            if (activity != null)
            {
                // Check if activity is of type message
                if (activity.GetActivityType() == ActivityTypes.Message)
                {
                    await Conversation.SendAsync(activity, () => new RootDialog(appointment, shop));
                }
                else
                {
                    Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                }


                // one of these will have an interface and process it
                //switch (activity.GetActivityType())
                //{
                //    case ActivityTypes.Message:
                //        await Conversation.SendAsync(activity, MakeRootDialog);
                //        break;

                //    case ActivityTypes.ConversationUpdate:
                //    case ActivityTypes.ContactRelationUpdate:
                //    case ActivityTypes.Typing:
                //    case ActivityTypes.DeleteUserData:
                //    default:
                //        Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                //        break;
                //}
            }
            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
예제 #12
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            Trace.TraceInformation("Post called");
            try
            {
                if (activity.Type == ActivityTypes.Message)
                {
                    await Conversation.SendAsync(activity as Microsoft.Bot.Connector.Activity, () => new Dialogs.MainDialog(new ILuisService[] {
                        new LuisService(new LuisModelAttribute(ConfigurationManager.AppSettings["LuisModel"], ConfigurationManager.AppSettings["LuisKey"], LuisApiVersion.V2))
                    }));
                }
                else
                {
                    HandleSystemMessage(activity);
                }
                var response = Request.CreateResponse(HttpStatusCode.OK);
                return(response);
            }
            catch (Exception exp)
            {
                Trace.TraceError($"[Controller][Exception]{exp.Message}");
                Trace.TraceError($"[Controller][Exception]{exp.StackTrace}");

                throw;
            }
            finally
            {
            }
        }
예제 #13
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            var activityType = GetActivityTypeFrom(activity);

            if (activityType == ActivityTypes.Message)
            {
                try
                {
                    await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
                }
                catch (Exception e)
                {
                    Trace.TraceError(e.ToString());
                }
            }
            else if (activityType == ActivityTypes.Invoke)
            {
                return(await HandleInvokeMessages(activity));
            }
            else
            {
                await HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
예제 #14
0
        private async Task <HttpResponseMessage> HandleInvokeMessages(Microsoft.Bot.Connector.Activity message)
        {
            string invokeType = (message.Value as dynamic)["type"];
            string command    = (message.Value as dynamic)["commandId"];

            if (invokeType == Constants.ACTIVITY_SELECT_ANSWER)
            {
                await HandleSelectAnswerFromCard(message);
            }
            else if (invokeType == Constants.ACTIVITY_BOT_HELPFUL)
            {
                await HandleBotHelpful(message);
            }
            else if (invokeType == Constants.ACTIVITY_BOT_NOT_HELPFUL)
            {
                await HandleBotNotHelpful(message);
            }
            else if (invokeType == Constants.ACTIVITY_MARKED_ANSWERED)
            {
                await HandleMarkedAnswerFromCard(message);
            }
            else
            {
                if (command == Constants.ACTIVITY_SELECT_ANSWER)
                {
                    return(await HandleSelectAnswerFromMessageAction(message));
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
예제 #15
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            if (activity != null)
            {
                switch (activity.GetActivityType())
                {
                case ActivityTypes.Message:



                    await Conversation.SendAsync(activity, () => new RootDialog(_userService));

                    //await Conversation.SendAsync(activity, MakeRootDialog);


                    break;

                case ActivityTypes.ConversationUpdate:
                case ActivityTypes.ContactRelationUpdate:
                case ActivityTypes.Typing:
                case ActivityTypes.DeleteUserData:
                default:
                    Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                    break;
                }
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
예제 #16
0
        private async Task ShowAccountBalance(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            await context.PostAsync(PostTypingReply(context));

            IMessageActivity message;

            // Can't get this to work...
            //IMessageActivity message = await result ?? new Activity(type: "message", text: _entityProps.Account.Name);

            // Using if statement instead
            if (result != null)
            {
                message = await result;
            }
            else
            {
                message = new Activity(type: "message", text: _entityProps.Account.Name);
            }


            if (VerifyAccountName(message?.Text))
            {
                var reply = context.MakeMessage();
                reply.AttachmentLayout = AttachmentLayoutTypes.List;
                reply.Attachments      = GetAccountAttachments(message?.Text);

                await context.PostAsync(reply);
            }

            context.Done(true);
        }
        private async Task <HttpResponseMessage> RejectMessageFromUnexpectedTenant(Activity activity, ConnectorClient connectorClient)
        {
            //Set the OFFICE_365_TENANT_FILTER key in web.config file with Tenant Information
            //Validate bot for specific teams tenant if any
            string currentTenant = "#ANY#";

            try
            {
                currentTenant = activity.GetTenantId();
            }
            catch (Exception e)
            {
                Trace.TraceError($"Exception from activity.GetTenantId(): {e}");
            }

            if (Middleware.RejectMessageBasedOnTenant(activity, currentTenant))
            {
                Bot.Connector.Activity replyActivity = activity.CreateReply();
                replyActivity.Text = Strings.TenantLevelDeniedAccess;

                await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                          await connectorClient.Conversations.ReplyToActivityAsync(replyActivity));

                {
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }

            return(null);
        }
예제 #18
0
        // Log telemetry about the incoming activity.
        private void LogActivityTelemetry(Activity activity)
        {
            var fromObjectId     = activity.From?.Properties["aadObjectId"]?.ToString();
            var clientInfoEntity = activity.Entities?.Where(e => e.Type == "clientInfo")?.FirstOrDefault();
            var channelData      = (JObject)activity.ChannelData;

            var properties = new Dictionary <string, string>
            {
                { "ActivityId", activity.Id },
                { "ActivityType", activity.Type },
                { "ActivityName", activity.Name },
                { "UserAadObjectId", fromObjectId },
                { "TenantId", activity.GetTenantId() },
                {
                    "ConversationType",
                    string.IsNullOrWhiteSpace(activity.Conversation?.ConversationType) ? "personal" : activity.Conversation.ConversationType
                },
                { "TeamId", channelData?["team"]?["id"]?.ToString() },
                { "SourceName", channelData?["source"]?["name"]?.ToString() },
                { "Locale", clientInfoEntity?.Properties["locale"]?.ToString() },
                { "Platform", clientInfoEntity?.Properties["platform"]?.ToString() },
            };

            this.logProvider.LogEvent("UserActivity", properties);
        }
        /// <summary>
        /// Handles O365 connector card action queries.
        /// </summary>
        /// <param name="activity">Incoming request from Bot Framework.</param>
        /// <param name="connectorClient">Connector client instance for posting to Bot Framework.</param>
        /// <returns>Task tracking operation.</returns>

        private static async Task <HttpResponseMessage> HandleO365ConnectorCardActionQuery(Activity activity)
        {
            var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));

            // Get O365 connector card query data.
            O365ConnectorCardActionQuery o365CardQuery = activity.GetO365ConnectorCardActionQueryData();

            Activity replyActivity = activity.CreateReply();

            replyActivity.TextFormat = "xml";

            replyActivity.Text = $@"

            <h2>Thanks, {activity.From.Name}</h2><br/>

            <h3>Your input action ID:</h3><br/>

            <pre>{o365CardQuery.ActionId}</pre><br/>

            <h3>Your input body:</h3><br/>

            <pre>{o365CardQuery.Body}</pre>

        ";

            await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(replyActivity);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message activity from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> PostMessage([FromBody] Activity activity)
        {
            await Conversation.SendAsync(activity, () => new EchoDialog());

            // Request has been accepted for further processing
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
예제 #21
0
        private Activity HandleSystemMessage(Microsoft.Bot.Connector.Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                DataAnalyticProject.DataAnalyticAPI.RemoveUser(message.From.Id, message.From.Name);
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                switch (message.Action)
                {
                case "add":
                    DataAnalyticProject.DataAnalyticAPI.AddUser(message.From.Id, message.From.Name, message.ChannelId);
                    break;

                case "remove":
                    DataAnalyticProject.DataAnalyticAPI.RemoveUser(message.From.Id, message.From.Name);
                    break;
                }
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
        //private Microsoft.Bot.Connector.Activity message = null;
        private async Task EnsureAuthentication(IDialogContext context, Microsoft.Bot.Connector.Activity activity)
        {
            string token = null;

            if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
            {
                token = await context.GetAccessToken(string.Empty);
            }
            else
            {
                token = await context.GetAccessToken(AuthSettings.Scopes);
            }

            if (string.IsNullOrEmpty(token))
            {
                if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
                {
                    //Cortana channel uses Connected Service for authentication, it has to be authorized to use cortana, we should not get here...
                    throw new InvalidOperationException("Cortana channel has to be used with Conencted Service Account");
                }
                else
                {
                    //message = activity;
                    await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, context.Activity, CancellationToken.None);
                }
            }
            else
            {
                //await MessageReceived(context, Awaitable.FromItem<Microsoft.Bot.Connector.Activity>(activity));
                await base.MessageReceived(context, Awaitable.FromItem <Microsoft.Bot.Connector.Activity>(activity));
            }
        }
예제 #23
0
        private async Task <Activity> HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                Trace.TraceInformation("Conversation update");
                ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

                using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    IBotData botData = scope.Resolve <IBotData>();

                    await botData.LoadAsync(CancellationToken.None);

                    if (!botData.ConversationData.GetValueOrDefault <bool>("init"))
                    {
                        botData.ConversationData.SetValue("init", true);

                        var reply = message.CreateReply("Hi!I'll post some random question every morning.");
                        await client.Conversations.SendToConversationAsync(reply);

                        var reply2 = message.CreateReply("Commands: " + Environment.NewLine +
                                                         "\t\t  - type `tours` to get a list of tours;" + Environment.NewLine +
                                                         "\t\t  - type `new` to get a new question;" + Environment.NewLine +
                                                         "\t\t  - type `answer` to get an answer to the current question;" + Environment.NewLine +
                                                         "\t\t  - type `level` to select a complexity level");
                        await client.Conversations.SendToConversationAsync(reply2);

                        var reply3 = message.CreateReply("*All questions are taken from* " + "https://db.chgk.info/" +
                                                         Environment.NewLine + "Copyright: " + "https://db.chgk.info/copyright");
                        await client.Conversations.SendToConversationAsync(reply3);

                        var reply4 = message.CreateReply("Good luck! ;-)");
                        await client.Conversations.SendToConversationAsync(reply4);
                    }
                }
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
예제 #24
0
 public async Task<Activity> HandleChat(ConnectorClient connector, Activity message) {
     Activity replyToConversation;
     replyToConversation = message.CreateReply(await GetReplyFromLuis(message.Text));
     await connector.Conversations.SendToConversationAsync(replyToConversation);
     Activity proCards = AddRoofHeroCards(replyToConversation);
     await connector.Conversations.SendToConversationAsync(proCards);
     return replyToConversation;
 }
        public static Microsoft.Bot.Connector.Activity CreateReply(Microsoft.Bot.Connector.Activity incoming, string text)
        {
            var reply = incoming.CreateReply(text);

            reply.Speak     = text;
            reply.InputHint = InputHints.ExpectingInput;
            return(reply);
        }
예제 #26
0
        private async Task HandleOneOnOneConversation(Microsoft.Bot.Connector.Activity activity)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // One-on-one chat isn't support yet, encourage to post question in the channel instead
            var defaultReply = activity.CreateReply("Please post your question in the channel instead -- and don't forget to tag me, so I know about it!");
            await connector.Conversations.ReplyToActivityAsync(defaultReply);
        }
예제 #27
0
        private static async Task ReceiveFacebookMessengerAudio(Microsoft.Bot.Connector.Activity activity)
        {
            var ConvertedFileNameAndPath = "";

            var audioAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Equals("audio/aac") ||
                                                                       a.ContentType.Equals("video/mp4") ||
                                                                       a.ContentType.Equals("video/mp3") ||
                                                                       a.ContentType.Equals("audio/wav") ||
                                                                       a.ContentType.Equals("audio") ||
                                                                       a.ContentType.Equals("video") ||
                                                                       a.ContentType.Equals("application/octet-stream"));

            if (audioAttachment != null)
            {
                BotUtilities.Trace("Possui audio. ContentType is " + audioAttachment.ContentType);
                BotUtilities.Trace("Root Directory " + BotUtilities.GetRootDirectory());

                try
                {
                    var voiceMessage = new ReceiveIncomingVoiceMessage(activity);
                    voiceMessage.DownloadFile();
                    var originalAudioFileName = voiceMessage.GetLocalPathAndFileName();
                    BotUtilities.Trace("originalAudioFile " + originalAudioFileName);

                    var wavFolder = Path.Combine(BotUtilities.GetRootDirectory(), WebConfigurationManager.AppSettings["WAVFilesFolder"]);
                    BotUtilities.Trace("wavFolder  " + wavFolder);

                    var audioConverter = new AudioFormatConverterMediaToolkit(originalAudioFileName, wavFolder, voiceMessage.ContentType);
                    audioConverter.ConvertAudioFile();
                    ConvertedFileNameAndPath = audioConverter.ConvertedFileNameAndPath;
                }
                catch (Exception ex)
                {
                    BotUtilities.Trace("Erro ao fazer download do audio: " + ex.ToString());
                }

                try
                {
                    BotUtilities.Trace("Convertendoi áudio WAV para texto");
                    var speech = new SpeechToTextService();
                    if (!string.IsNullOrEmpty(ConvertedFileNameAndPath))
                    {
                        speech.ConvertSpeechToText(ConvertedFileNameAndPath, DictationType.Long);
                        var txt = speech.ResultAsText();
                        activity.Text = txt;
                        await BotUtilities.Say(activity, "Você disse: " + txt);
                    }
                }
                catch (Exception ex)
                {
                    BotUtilities.Trace("Erro ao converter audio para texto: " + ex.ToString());
                }
            }
            else
            {
                BotUtilities.Trace("No Attachment content");
            }
        }
예제 #28
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            try
            {
                if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
                {
                    // Get and process
                    IMessageActivity message = activity.AsMessageActivity();

                    ActivityRequest request = new ActivityRequest(
                        recipient: message.Recipient.Name,
                        text: message.Text,
                        from: message.From.Name,
                        fromId: message.From.Id,
                        channelId: message.ChannelId,
                        conversationId: message.Conversation.Id,
                        isGroup: message.Conversation.IsGroup,
                        attachments: message.Attachments?.Select(
                            attachment => new AttachmentRequest(attachment.ContentUrl, attachment.ContentType)
                            ));

                    ActivityResponse response = await this.ActivityProcessor.ProcessActivityAsync(this.Store, request).ConfigureAwait(false);

                    // Reply (on a new network connection) back.
                    Microsoft.Bot.Connector.Activity reply = activity.CreateReply();
                    reply.Text = response.Text;
                    foreach (AttachmentResponse attachment in response.Attachments)
                    {
                        reply.Attachments.Add(new Attachment(attachment.ContentType, attachment.ContentUrl, null, attachment.Name));
                    }

                    // Send it either as a group message or individually, depending on how we received the message,
                    using (ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
                    {
                        if (message.Conversation.IsGroup.HasValue && message.Conversation.IsGroup.Value)
                        {
                            await connector.Conversations.SendToConversationAsync(reply);
                        }
                        else
                        {
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    Microsoft.Bot.Connector.Activity reply = activity.CreateReply();
                    reply.Text = ex.Message + " " + ex.StackTrace;
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }

            // We always accept the message and send the response using the bot framework on another channel.
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
예제 #29
0
        /// <summary>
        /// This is only here for reference purposes. Not used.
        /// </summary>
        /// <param name="endUserActivity"></param>
        /// <param name="messageToSend"></param>
        /// <param name="agentConversationId"></param>
        /// <returns></returns>
        public static async Task <ConversationResourceResponse> CreateAConversation(IMessageActivity endUserActivity,
                                                                                    string messageToSend,
                                                                                    string agentConversationId)
        {
            var botAccount = endUserActivity.Recipient;

            try
            {
                // To create a new reply chain
                var channelData = new Dictionary <string, object>
                {
                    ["teamsChannelId"] = "19:[email protected]",
                    ["notification"]   = new Dictionary <string, object>()
                    {
                        { "alert", true }
                    }
                };

                IMessageActivity agentMessage = Activity.CreateMessageActivity();
                agentMessage.From       = botAccount;
                agentMessage.Type       = ActivityTypes.Message;
                agentMessage.Text       = messageToSend;
                agentMessage.ChannelId  = MsTeamChannelId;
                agentMessage.ServiceUrl = endUserActivity.ServiceUrl;
                agentMessage.ReplyToId  = agentConversationId;

                var agentMessageActivity = (Activity)agentMessage;

                var conversationParams = new ConversationParameters()
                {
                    IsGroup     = true,
                    Bot         = botAccount,
                    Members     = null,
                    Activity    = agentMessageActivity,
                    ChannelData = channelData,
                };

                using (ConnectorClient connector =
                           await BotConnectorUtility.BuildConnectorClientAsync(endUserActivity.ServiceUrl))
                {
                    var createResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                                                   await connector.Conversations.CreateConversationAsync(conversationParams));

                    return(createResponse);
                }
            }
            catch (Exception e)
            {
                WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                {
                    { "function", "CreateAConversation" },
                    { "messageToSend", messageToSend },
                    { "agentConversationId", agentConversationId },
                });

                throw;
            }
        }
예제 #30
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public HttpResponseMessage Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            this.userID = activity.From.Id;

            if (this.userID.Contains(':'))
            {
                this.userID = this.userID.Replace(':', '-');
            }

            List <BotClient> botClients       = (List <BotClient>)HttpContext.Current.Application["BotClients"];
            BotClient        connectingClient = botClients.FirstOrDefault(bc => ((bc.BotURL == activity.ServiceUrl) && (bc.UserID == this.userID)));

            if (activity.Type == ActivityTypes.Message)
            {
                if (connectingClient == null)
                {
                    NewUser(connectingClient, botClients, activity);
                }
                else
                {
                    new CommandClasses.SMCommandUtility(this.userID).InitateCommand(activity.Text);
                }

                //this.userID = activity.From.Id;

                //ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                //string length = "1";

                //// return our reply to the user
                //Microsoft.Bot.Connector.Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
                //await connector.Conversations.ReplyToActivityAsync(reply);


                //ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                //// calculate something for us to return
                //int length = (activity.Text ?? string.Empty).Length;

                //// return our reply to the user
                //Microsoft.Bot.Connector.Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
                //await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (connectingClient == null)
                {
                    NewUser(connectingClient, botClients, activity);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
        private static async Task ReturnDialogAsync(Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
            // calculate something for us to return
            int length = (activity.Text ?? string.Empty).Length;

            // return our reply to the user
            Activity reply = activity.CreateReply($"RETURN DIALOGUE: You sent {activity.Text} which was {length} characters");
            await connector.Conversations.ReplyToActivityAsync(reply);
        }
예제 #32
0
        private async Task <HttpResponseMessage> HandleActivityTypeMessage(Activity activity, CancellationToken cancellationToken)
        {
            switch (activity.Conversation.ConversationType)
            {
            case "personal":
                return(await HandlePersonalMessage(activity, cancellationToken));

            default:
                return(await HandleGroupMessage(activity, cancellationToken));
            }
        }
예제 #33
0
        private async Task <HttpResponseMessage> SendMessage(string text, Activity activity, CancellationToken cancellationToken)
        {
            var reply = activity.CreateReply(text, activity.Locale);

            using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);
            }

            return(null);
        }
예제 #34
0
        private async Task <HttpResponseMessage> HandleGroupMessage(Activity activity, CancellationToken cancellationToken)
        {
            var enableDisableSucceeded = await CheckEnableDisable(activity, cancellationToken);

            if (enableDisableSucceeded)
            {
                return(null);
            }

            if (!_teamsToggleLogic.Value.IsEnabledInChannel)
            {
                return(null);
            }

            activity.Text = Utilities.TrimWhitespace(activity.Text);

            var scoreboardRegexMatch = _messageLogic.IsGettingScoreboard(activity.Text);

            if (scoreboardRegexMatch.Success)
            {
                return(await HandleScoreboardRequest(activity, scoreboardRegexMatch, cancellationToken));
            }
            else
            {
                var scoreRegexMatch = _messageLogic.IsGettingScore(activity.Text);
                if (scoreRegexMatch.Success)
                {
                    return(await HandleScoreRequest(activity, scoreRegexMatch, cancellationToken));
                }
            }

            // Check for commands.
            if (KarmaLogic.SomeoneReceivedKarmaInWholeMessage(activity.Text))
            {
                // Karma command
                return(await HandleKarmaChange(activity, cancellationToken));
            }

            // Add more commands here.

            if (_messageLogic.IsAskingForHelp(activity.Text))
            {
                return(await SendHelpMessage(activity, cancellationToken));
            }

            // Often, users respond with a gif just after karma has been given.
            // they also accidentally mention @karma. Don't respond to this.
            if (activity.Attachments.Any(a => a.ContentType.Contains("image")))
            {
                return(null);
            }

            return(await SendMessage(Strings.DidNotUnderstand, activity, cancellationToken));
        }
예제 #35
0
 private Activity GetConfirmOrderCard(Activity replyToConversation) {
     replyToConversation.Type = "message";
     replyToConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel;
     replyToConversation.Attachments = new List<Attachment>();
     List<Professional> pros = Professional.GetProfessionalMockData();
     var selectedPro = pros.FirstOrDefault(x => x.FullName == replyToConversation.Text?.Split('-')?[0]);
     Attachment selectedProCard = selectedPro.ToAttachment();
     replyToConversation.Attachments.Add(selectedProCard);
     return replyToConversation;
     
 }
예제 #36
0
 private Activity AddRoofHeroCards(Activity replyToConversation) {
     Activity heroCards = replyToConversation.CreateReply();
     heroCards.Type = "message";
     heroCards.AttachmentLayout = AttachmentLayoutTypes.Carousel;
     heroCards.Attachments = new List<Attachment>();
     List<Professional> pros = Professional.GetProfessionalMockData();
     foreach (var pro in pros) {
         Attachment professionalCard = pro.ToAttachment();
         heroCards.Attachments.Add(professionalCard);
     }
     return heroCards;
 }
예제 #37
0
        private async void SetGreetingSent(Activity message) {
            StateClient stateClient = message.GetStateClient();
            BotData userData = await stateClient.BotState.GetUserDataAsync(message.ChannelId, message.From.Id);
            userData.SetProperty<bool>("SentGreeting", true);
            await stateClient.BotState.SetUserDataAsync(message.ChannelId, message.From.Id, userData);

        }
예제 #38
0
 private async Task<bool> DidSendGreeting(Activity message) {
     StateClient stateClient = message.GetStateClient();
     BotData userData = await stateClient.BotState.GetUserDataAsync(message.ChannelId, message.From.Id);
     bool didSendGreeting = userData.GetProperty<bool?>("SentGreeting") ?? false;
     return didSendGreeting;
 }
 /// <summary>
 /// ReplyToActivity
 /// </summary>
 /// This method allows you to reply to an activity.
 /// 
 /// This is slightly different then SendToConversation().
 /// * SendToConverstion(conversationId) - will simply append a message to the
 /// end of the conversation according to the timestamp or semantics of the
 /// channel
 /// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
 /// threaded conversations, meaning it has the information necessary for the
 /// channel to reply to the actual message being responded to.
 /// 
 /// ReplyToConversation is almost always preferable to SendToConversation()
 /// because it maintains threaded conversations.
 /// 
 /// SendToConversation is appropriate for the first message which initiates a
 /// conversation, or if you don't have a particular activity you are
 /// responding to.
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='conversationId'>
 /// Conversation ID
 /// </param>
 /// <param name='activityId'>
 /// activityId the reply is to (OPTIONAL)
 /// </param>
 /// <param name='activity'>
 /// Activity to send
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<APIResponse> ReplyToActivityAsync(this IConversations operations, string conversationId, string activityId, Activity activity, CancellationToken cancellationToken = default(CancellationToken))
 {
     var _result = await operations.ReplyToActivityWithHttpMessagesAsync(conversationId, activityId, activity, null, cancellationToken).ConfigureAwait(false);
     return _result.Body;
 }
예제 #40
0
 private Activity GetGreetingReply(Activity messageFromUser) {
     Activity toReturn = messageFromUser.CreateReply("Hello there!");
     SetGreetingSent(messageFromUser);
     return toReturn;
 }
 /// <summary>
 /// ReplyToActivity
 /// </summary>
 /// This method allows you to reply to an activity.
 /// 
 /// This is slightly different then SendToConversation().
 /// * SendToConverstion(conversationId) - will simply append a message to the
 /// end of the conversation according to the timestamp or semantics of the
 /// channel
 /// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
 /// threaded conversations, meaning it has the information necessary for the
 /// channel to reply to the actual message being responded to.
 /// 
 /// ReplyToConversation is almost always preferable to SendToConversation()
 /// because it maintains threaded conversations.
 /// 
 /// SendToConversation is appropriate for the first message which initiates a
 /// conversation, or if you don't have a particular activity you are
 /// responding to.
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='conversationId'>
 /// Conversation ID
 /// </param>
 /// <param name='activityId'>
 /// activityId the reply is to (OPTIONAL)
 /// </param>
 /// <param name='activity'>
 /// Activity to send
 /// </param>
 public static APIResponse ReplyToActivity(this IConversations operations, string conversationId, string activityId, Activity activity)
 {
     return Task.Factory.StartNew(s => ((IConversations)s).ReplyToActivityAsync(conversationId, activityId, activity), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// SendToConversation
 /// </summary>
 /// This method allows you to send an activity to a conversation regardless of
 /// previous posts to a conversation.
 /// 
 /// This is slightly different then ReplyToConversation().
 /// * SendToConverstion(conversationId) - will simply append a message to the
 /// end of the conversation according to the timestamp or semantics of the
 /// channel
 /// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
 /// threaded conversations, meaning it has the information necessary for the
 /// channel to reply to the actual message being responded to.
 /// 
 /// SendToConversation is appropriate for the first message which initiates a
 /// conversation, or if you don't have a particular activity you are
 /// responding to.
 /// 
 /// ReplyToConversation is preferable to SendToConversation() because it
 /// maintains threaded conversations.
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='activity'>
 /// Activity to send
 /// </param>
 /// <param name='conversationId'>
 /// Conversation ID
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<APIResponse> SendToConversationAsync(this IConversations operations, Activity activity, string conversationId, CancellationToken cancellationToken = default(CancellationToken))
 {
     var _result = await operations.SendToConversationWithHttpMessagesAsync(activity, conversationId, null, cancellationToken).ConfigureAwait(false);
     return _result.Body;
 }
 /// <summary>
 /// SendToConversation
 /// </summary>
 /// This method allows you to send an activity to a conversation regardless of
 /// previous posts to a conversation.
 /// 
 /// This is slightly different then ReplyToConversation().
 /// * SendToConverstion(conversationId) - will simply append a message to the
 /// end of the conversation according to the timestamp or semantics of the
 /// channel
 /// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
 /// threaded conversations, meaning it has the information necessary for the
 /// channel to reply to the actual message being responded to.
 /// 
 /// SendToConversation is appropriate for the first message which initiates a
 /// conversation, or if you don't have a particular activity you are
 /// responding to.
 /// 
 /// ReplyToConversation is preferable to SendToConversation() because it
 /// maintains threaded conversations.
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='activity'>
 /// Activity to send
 /// </param>
 /// <param name='conversationId'>
 /// Conversation ID
 /// </param>
 public static APIResponse SendToConversation(this IConversations operations, Activity activity, string conversationId)
 {
     return Task.Factory.StartNew(s => ((IConversations)s).SendToConversationAsync(activity, conversationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
예제 #44
0
        private Activity GetSecondReply(Activity messageFromUser) {
            Activity toReturn = messageFromUser.CreateReply("Glad to have you back!");

            return toReturn;
        }
예제 #45
0
        /// <summary>
        /// Reply to an activity in an existing conversation
        /// </summary>
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='activity'>
        /// Activity to send
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static Task<APIResponse> ReplyToActivityAsync(this IConversations operations, Activity activity, CancellationToken cancellationToken = default(CancellationToken))
        {
            // TEMP TODO REMOVE THIS AFTER SKYPE DEPLOYS NEW SERVICE WHICH PROPERLY IMPLEMENTS THIS ENDPOINT
            if (activity.ReplyToId == "0")
                return operations.SendToConversationAsync(activity);

            return operations.ReplyToActivityAsync(activity.Conversation.Id, activity.ReplyToId, activity, cancellationToken);
        }
예제 #46
0
 /// <summary>
 /// Send an activity to a conversation
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='activity'>
 /// Activity to send
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static Task<APIResponse> SendToConversationAsync(this IConversations operations, Activity activity, CancellationToken cancellationToken = default(CancellationToken))
 {
     return operations.SendToConversationAsync(activity, activity.Conversation.Id, cancellationToken);
 }
예제 #47
0
 static async Task Reply(ConnectorClient connector, Activity activity, string message)
 {
     var reply = activity.CreateReply(message);
     await connector.Conversations.ReplyToActivityAsync(reply);
 }
예제 #48
0
        /// <summary>
        /// Reply to an activity in an existing conversation
        /// </summary>
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='activity'>
        /// Activity to send
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static Task<APIResponse> ReplyToActivityAsync(this IConversations operations, Activity activity, CancellationToken cancellationToken = default(CancellationToken))
        {
            // TEMP TODO REMOVE THIS AFTER SKYPE DEPLOYS NEW SERVICE WHICH PROPERLY IMPLEMENTS THIS ENDPOINT
            if (activity.ReplyToId == "0")
                return operations.SendToConversationAsync(activity);

            if (activity.ReplyToId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "ReplyToId");
            }

            return operations.ReplyToActivityAsync(activity.Conversation.Id, activity.ReplyToId, activity, cancellationToken);
        }
 public async Task<bool> PutStuff(Activity message) {
     StateClient stateClient = message.GetStateClient();
     return true;
 }