Exemplo n.º 1
0
        public async Task RemoveCoin(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            var val = result.Entities;

            try
            {
                var t = await CoinMarketCapService.GetTicker(val[1].Entity);

                var count = val[0].Entity;
                if (ConversationStarter.ToPortfolio(t.Id, new Coin("-" + count, t)))
                {
                    await context.PostAsync($"You remove {count} {t.Name} from your Portfolio");
                }
                else
                {
                    await context.PostAsync($"You don't have enough in your portfolio to remuve {count} {t.Name}");
                }
            }
            catch (No​​Currency​​FoundException e)
            {
                await context.PostAsync("No ​​such currency​​ found or luis don't get it");
            }

            context.Wait(this.MessageReceived);
        }
        public async Task <HttpResponseMessage> SendMessage()
        {
            try
            {
                if (!string.IsNullOrEmpty(ConversationStarter.fromId))
                {
                    await ConversationStarter.Resume(ConversationStarter.conversationId, ConversationStarter.channelId); //We don't need to wait for this, just want to start the interruption here

                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent($"<html><body><h1>Nice Work!</h1><a href=\"http://*****:*****@"text/html");

                    return(resp);
                }
                else
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent($"<html><body>You need to talk to the bot first so it can capture your details.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Exemplo n.º 3
0
 public void TimerEvent(object target)
 {
     Contador.Count++;
     if (Contador.Count == 5)
     {
         ConversationStarter.Resume();
     }
 }
Exemplo n.º 4
0
        private async void timerEvent(object target)
        {
            t.Dispose();
            await ConversationStarter.Resume(ConversationStarter.conversationId,
                                             ConversationStarter
                                             .channelId);

            t = new Timer(new TimerCallback(timerEvent), null, 1000 * 60 * 5, Timeout.Infinite);
        }
        public string StartConversation([FromBody] ConversationStarter conversationStarter)
        {
            System.Diagnostics.Trace.WriteLine(conversationStarter.PhoneNumber);
            System.Diagnostics.Trace.WriteLine("Json: " + conversationStarter);

            // OmniBotService.StartConversation(conversationStarter);
            System.Diagnostics.Trace.WriteLine("Starting Conversation");

            return("??");
        }
Exemplo n.º 6
0
        public void Update(ConversationStarter item)
        {
            var itemToUpdate = _context.ConversationStarters.FirstOrDefault(c => c.Id == item.Id);

            if (itemToUpdate != null)
            {
                itemToUpdate.DateUpdated = DateTimeOffset.UtcNow;
                itemToUpdate.Text        = item.Text;
                itemToUpdate.Language    = item.Language;
            }

            _context.SaveChanges();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Notify the user with the Dialog
        /// </summary>
        private async Task Notify(IDialog <object> dialog, string userId, string channelId, string serviceUri, int lcid)
        {
            await ConversationStarter.Resume(dialog, userId, channelId, serviceUri);

            if (channelId.ToLower() == "directline")
            {
                var url    = HttpContext.Current.Request.Url;
                var webUrl = $"{url.Scheme}://{url.Host}:{url.Port}/api/LineMessages/Notify?mids={userId}&lcid={lcid}";
                using (HttpClient client = new HttpClient())
                {
                    await client.PostAsync(webUrl, null);
                }
            }
        }
Exemplo n.º 8
0
        private void registerUserForChannel(Activity activity)
        {
            string givenUserName = activity.Text.Substring(9);
            var    curUser       = db.Users.Where(u => u.UserName.ToLower() == givenUserName.ToLower()).FirstOrDefault();

            //ApplicationUser curUser = getUserFromActivity(activity);
            if (curUser != null)
            {
                var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                ConversationStarter cs = new ConversationStarter();
                cs.ToId            = activity.From.Id;
                cs.ToName          = activity.From.Name;
                cs.FromId          = activity.Recipient.Id;
                cs.FromName        = activity.Recipient.Name;
                cs.ServiceUrl      = activity.ServiceUrl;
                cs.ChannelId       = activity.ChannelId;
                cs.ConversationId  = activity.Conversation.Id;
                cs.ApplicationUser = curUser;
                cs.LastTimeUsed    = DateTime.UtcNow - TimeSpan.FromDays(1);


                bool found = false;
                var  css   = db.CSs.Where(c => c.ApplicationUser.UserName == curUser.UserName);
                ConversationStarter        csToRemove = new ConversationStarter();
                List <ConversationStarter> csList     = css.ToList();
                foreach (ConversationStarter c in csList)
                {
                    if (c.ChannelId == cs.ChannelId)
                    {
                        found      = true;
                        csToRemove = c;
                        break;
                    }
                }
                if (found)
                {
                    db.CSs.Remove(csToRemove);
                }


                db.CSs.Add(cs);
                db.SaveChanges();


                string   text  = "Для пользователя " + curUser.UserName + " зарегистрирован канал связи:\nUserName - " + cs.ToName + ", UserId - " + cs.ToId + ", ChannelID - " + cs.ChannelId;
                Activity reply = activity.CreateReply(text);
                connector.Conversations.ReplyToActivity(reply);
            }
        }
Exemplo n.º 9
0
        public void StartConversation(ConversationStarter conversationStarter) // TODO put this here?
        {
            Person       person       = PersonService.GetPersonByPhoneNumber(conversationStarter.PhoneNumber);
            Conversation conversation = ConversationService.CreateConversation(conversationStarter, person);

            DataClasses.Message firstMessage = ScriptService.GetFirstMessageFromScript(conversation.Script);

            conversation.CurrentMessage = firstMessage;

            Communication text = CommunicationService.CreateOutgoingCommunication(conversation, firstMessage);

            conversation.Communications.Add(text);
            Context.SaveChanges();

            MessagingService.SendMessage(person.PhoneNumber, firstMessage.Body);
        }
Exemplo n.º 10
0
        public DataClasses.Script GetScriptByConversationStarter(ConversationStarter conversationStarter)
        {
            DataClasses.Script script = null;

            if (conversationStarter.ScriptName != null)
            {
                script = GetScriptByName(conversationStarter.ScriptName);
            }

            if (script == null)
            {
                script = GetScriptById(conversationStarter.ScriptId);
            }

            return(script);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Notify the user with message
 /// </summary>
 private async Task Notify(string message, string userId, string channelId, string serviceUri, int lcid)
 {
     // As directline doesn't support push, directly call push for LINE channel
     if (channelId.ToLower() == "directline")
     {
         var url    = HttpContext.Current.Request.Url;
         var webUrl = $"{url.Scheme}://{url.Host}:{url.Port}/api/LineMessages/Notify?message={message}&mids={userId}&lcid={lcid}";
         using (HttpClient client = new HttpClient())
         {
             await client.PostAsync(webUrl, null);
         }
     }
     else
     {
         await ConversationStarter.Resume(message, userId, channelId, serviceUri);
     }
 }
Exemplo n.º 12
0
        public IActionResult Create([Bind("Text", "Language")][FromBody] ConversationStarter item)
        {
            if (item == null)
            {
                return(new BadRequestResult());
            }

            var itemDomain = new ConversationStarter()
            {
                DateAdded = item.DateAdded,
                Language  = item.Language,
                Text      = item.Text
            };

            ConvStarterRepo.Add(itemDomain);

            return(new CreatedAtRouteResult("GetConvStarterById", new { controller = "ConvStarter", id = item.Id }, item));
        }
Exemplo n.º 13
0
        public IActionResult Update(int id, [FromBody] ConversationStarter item)
        {
            if (item == null)
            {
                return(new BadRequestResult());
            }

            var convStarterObj = ConvStarterRepo.Find(id);

            if (convStarterObj == null)
            {
                return(new BadRequestResult());
            }

            // Updated - pass item param instead of object retrieved from repo
            ConvStarterRepo.Update(item);

            return(new NoContentResult());
        }
Exemplo n.º 14
0
        public async Task AddCoin(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            var val = result.Entities;

            //todo:get rid of 2 the same parts of code
            try
            {
                var t = await CoinMarketCapService.GetTicker(val[1].Entity);

                var count = val[0].Entity;
                if (ConversationStarter.ToPortfolio(t.Id, new Coin(count, t)))
                {
                    await context.PostAsync($"You added {count} {t.Name} to your portfolio");
                }
            }
            catch (No​​Currency​​FoundException e)
            {
                await context.PostAsync("No ​​such currency​​ found or Luis don't get it");
            }
            context.Wait(this.MessageReceived);
        }
Exemplo n.º 15
0
        public virtual async Task AddCoin(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            try
            {
                var message = await result;
                var text    = message.Text;

                var r = Regex.Matches(text, pattern, RegexOptions.IgnoreCase);

                //todo:get rid of 2 the same parts of code
                var t = await CoinMarketCapService.GetTicker(r[1].Value);

                var count = r[0].Value;
                if (ConversationStarter.ToPortfolio(t.Id, new Coin(count, t)))
                {
                    await context.PostAsync($"You added {count} {t.Name} to your portfolio");
                }
            }
            catch (No​​Currency​​FoundException e)
            {
                await context.PostAsync("No ​​such currency​​ found or Luis don't get it");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            var locale = activity.Locale ?? "ja-JP";

            Thread.CurrentThread.CurrentCulture   = new CultureInfo(locale);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(locale);

            List <string> menus = new List <string>()
            {
                Resource.Menu_SearchProduct,
                Resource.Menu_Appointment_For_Today,
                Resource.Menu_Create_Appointment,
                Resource.Menu_Logout,
                Resource.Menu_Task_Menu,
                Resource.Menu_Daily_Report,
                Resource.Menu_Help
            };

            if (activity.Type == ActivityTypes.Message)
            {
                // If user sends menu, then reset all dialog stack.
                if (menus.Contains(activity.Text))
                {
                    await ConversationStarter.Reset(activity.From.Id, activity.ChannelId, activity.ServiceUrl);
                }

                await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Exemplo n.º 17
0
        public async Task <HttpResponseMessage> SendMessage()
        {
            try
            {
                if (!string.IsNullOrEmpty(ConversationStarter.resumptionCookie))
                {
                    await ConversationStarter.Resume(); //We don't need to wait for this, just want to start the interruption here

                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent($"<html><body>Message sent, thanks.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    return(resp);
                }
                else
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent($"<html><body>You need to talk to the bot first so it can capture your details.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Exemplo n.º 18
0
        private void basicTelegramReminder(ConversationStarter cs)
        {
            ApplicationUser curUser = cs.ApplicationUser;


            var userAccount = new ChannelAccount(cs.ToId, cs.ToName);
            var botAccount  = new ChannelAccount(cs.FromId, cs.FromName);
            var connector   = new ConnectorClient(new Uri(cs.ServiceUrl));

            Activity activity = new Activity();

            activity.Type         = ActivityTypes.Message;
            activity.From         = botAccount;
            activity.Recipient    = userAccount;
            activity.Conversation = new ConversationAccount(id: cs.ConversationId);
            activity.Id           = "1";
            string text = "Нужно сделать ставки!";

            DateTime             curDate = (DateTime.UtcNow + MvcApplication.utcMoscowShift).Date;
            List <Bet>           bets    = db.Bets.Where(b => b.ApplicationUser.UserName == curUser.UserName & b.Program.TvDate == curDate & !b.IsLocked).ToList();
            TeleBot              tb      = new TeleBot();
            InlineKeyboardMarkup kb      = tb.createKeabordFromBets(bets, true);
            string jsonKb = JsonConvert.SerializeObject(kb);

            activity.ChannelData = new TelegramChannelData()
            {
                method     = "sendMessage",
                parameters = new TelegramParameters()
                {
                    text         = text,
                    parse_mode   = "Markdown",
                    reply_markup = jsonKb
                }
            };
            connector.Conversations.SendToConversation(activity);
        }
Exemplo n.º 19
0
        public Conversation CreateConversation(ConversationStarter conversationStarter, Person person)
        {
            Conversation conversation = GetActiveConversationForPerson(person);

            if (conversation != null)
            {
                throw new OmniBotException(person + " already has an active conversation and cannot be started on a new one.");
            }

            DataClasses.Script script = ScriptService.GetScriptByConversationStarter(conversationStarter);

            conversation = new Conversation()
            {
                Id       = -1,
                Person   = person,
                Script   = script,
                StatusId = StatusService.getInstance().conversationStatuses[StatusType.STARTED.ToString()].Id,
                Active   = true
            };

            Context.Conversations.Add(conversation);

            return(conversation);
        }
Exemplo n.º 20
0
        public void MessagingFullTest()
        {
            LocalUser                 user = Login(username: "******", password: "******");
            var                       statusGetterConversation = ConversationGetter.GetStatus.UnknownError;
            var                       statusStarter            = ConversationStarter.ConversationStatus.UnknownError;
            var                       statusPoster             = MessagePoster.MessageStatus.UnknownError;
            var                       statusGetterMessages     = MessageGetter.MessageStatus.UnknownError;
            bool                      done          = false;
            Conversation              conversation  = null;
            string                    message       = null;
            List <Message>            messages      = null;
            List <Conversation>       conversations = null;
            Dictionary <String, User> users         = null;


            var getterConv = new ConversationGetter(user, (_status, _conversations, _users) => {
                statusGetterConversation = _status;
                conversations            = _conversations;
                users = _users;
                done  = true;
            });

            var conversationStarter = new ConversationStarter(user, (_status, _conversation, _users) =>
            {
                statusStarter = _status;
                conversation  = _conversation;
                users         = _users;
                done          = true;
            });

            var messagePoster = new MessagePoster(user, (_status, _conversation, _message) =>
            {
                statusPoster = _status;
                conversation = _conversation;
                message      = _message;
                done         = true;
            });

            var messageGetter = new MessageGetter(user, (_status, _messages) =>
            {
                statusGetterMessages = _status;
                messages             = _messages;
                done = true;
            });

            ///Pradedam Conversation
            done = false;
            conversationStarter.start("test4");

            while (!done)
            {
            }
            Assert.AreEqual(statusStarter, ConversationStarter.ConversationStatus.Success);
            Assert.AreNotEqual(conversation, null);
            ///

            ///Gaunam messages
            done = false;
            messageGetter.get(conversation, 0, false);

            while (!done)
            {
            }
            Assert.AreEqual(statusGetterMessages, MessageGetter.MessageStatus.Success);
            Assert.AreNotEqual(messages, null);
            var timestamp = (messages.Count == 0 ? 0 : messages[messages.Count - 1].Timestamp);
            ///

            ///Siunčiam message
            var random = new Random();

            done = false;
            messagePoster.post(conversation, random.Next().ToString());

            while (!done)
            {
            }
            Assert.AreEqual(statusPoster, MessagePoster.MessageStatus.Success);
            Assert.AreNotEqual(message, null);
            ///

            ///Gaunam messages
            done = false;
            messageGetter.get(conversation, timestamp, false);

            while (!done)
            {
            }
            Assert.AreEqual(statusGetterMessages, MessageGetter.MessageStatus.Success);
            Assert.AreNotEqual(messages, null);
            ///Tikrinam ar nusisiuntė
            var myMessage = messages.Find((_message) =>
            {
                return(_message.Text == message &&
                       _message.Username == user.Username);
            });

            Assert.AreNotEqual(myMessage, null);
            ///

            ///Gaunam conversations
            done = false;
            getterConv.get(true);
            while (!done)
            {
            }

            Assert.AreEqual(statusGetterConversation, ConversationGetter.GetStatus.Success);
            Assert.AreNotEqual(users, null);
            Assert.AreNotEqual(conversations, null);

            var myConversation = conversations.Find((_conversation) =>
            {
                return(_conversation.Id == conversation.Id);
            });

            Assert.AreNotEqual(myConversation, null);
            ///
        }
Exemplo n.º 21
0
        private void TimerEventAsync(object target)
        {
            //remove previously created timers
            var ret = ConversationStarter.Timers[me.conversationId + me.channelId];

            if (ret != tAlert.GetHashCode())
            {
                tAlert.Dispose();
                return;
            }

            if (StartAlert.Add(alert.MaxTime) <= DateTimeOffset.Now)
            {
                tAlert.Dispose();
                ConversationStarter.EndAlerts(me.conversationId, me.channelId);
            }
            if (NumberAlerts > AlertMaxNumber)
            {
                tAlert.Dispose();
                ConversationStarter.EndAlertsMax(me.conversationId, me.channelId);
            }
            Electricity res         = null;
            float       consumption = 0;

            if (alert.IsInstant)
            {
                var t = myWivaldy.GetMeasures(DateTimeOffset.Now.Add(-alert.Interval), DateTimeOffset.Now);
                t.Wait();
                res = t.Result;
                if (res != null)
                {
                    foreach (var wat in res.Consumptions)
                    {
                        if (wat.watts >= alert.Threshold)
                        {
                            if (consumption < wat.watts)
                            {
                                consumption = wat.watts;
                            }
                        }
                    }
                }
            }
            else
            {
                DateTimeOffset today = new DateTimeOffset(DateTimeOffset.Now.Year, DateTimeOffset.Now.Month, DateTimeOffset.Now.Day, 0, 0, 0, DateTimeOffset.Now.Offset);
                var            t     = myWivaldy.GetDayMeasures(today);
                t.Wait();
                res = t.Result;
                if (res != null)
                {
                    var cons = GetKiloWattHour(res);
                    if (cons >= alert.Threshold)
                    {
                        consumption = (float)cons;
                    }
                }
            }
            if (consumption > 0)
            {
                NumberAlerts++;
                ConversationStarter.Resume(me.conversationId, me.channelId, consumption, alert);
            }
        }
Exemplo n.º 22
0
 public void Add(ConversationStarter item)
 {
     _context.ConversationStarters.Add(item);
     _context.SaveChanges();
 }
Exemplo n.º 23
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;

            if (message.Text == "logon")
            {
                if (string.IsNullOrEmpty(await context.GetAccessToken(AuthSettings.Scopes)))
                {
                    await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, message, CancellationToken.None);
                }
                else
                {
                    await TokenSample(context);
                }
            }
            else if (message.Text == "echo")
            {
                await context.PostAsync("echo");

                context.Wait(this.MessageReceivedAsync);
            }
            else if (message.Text == "token")
            {
                await TokenSample(context);
            }
            else if (message.Text.StartsWith("NDBDATA"))
            {
                var messageinfo = message.Text.Split(';');

                try
                {
                    var body = messageinfo[1];
                    Trace.TraceInformation($"ActionDialog: parsing {body}.");
                    var messageDictionary = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(body);
                    var conversationId    = messageDictionary["conversationId"];
                    var channelId         = messageDictionary["channelId"];
                    var recipientId       = messageDictionary["recipientId"];
                    var recipientName     = messageDictionary["recipientName"];
                    var serviceUrl        = messageDictionary["serviceUrl"];
                    var token             = messageDictionary["token"];

                    Trace.TraceInformation($"ActionDialog: Sending notification to {recipientName}.");
                    await ConversationStarter.Resume(conversationId, channelId, recipientId, recipientName, message.Recipient.Id, message.Recipient.Name, serviceUrl, token);

                    Trace.TraceInformation($"ActionDialog: Notification to {recipientName}.");
                }
                catch (Exception e)
                {
                    Trace.TraceError($"ActionDialog: Error parsing NDBDATA. Exception={e.Message}");
                }

                context.Wait(this.MessageReceivedAsync);
            }
            else if (message.Text == "logout")
            {
                await context.Logout();

                context.Wait(this.MessageReceivedAsync);
            }
            else
            {
                context.Wait(MessageReceivedAsync);
            }
        }
Exemplo n.º 24
0
        private void TimerEventAsync(object target)
        {
            //remove previously created timers
            var ret = ConversationStarter.Timers[me.conversationId + me.channelId];

            if (ret != tAlert.GetHashCode())
            {
                tAlert.Dispose();
                return;
            }

            if (StartAlert.Add(alert.MaxTime) <= DateTimeOffset.Now)
            {
                tAlert.Dispose();
                ConversationStarter.EndAlerts(me.conversationId, me.channelId);
            }
            if (NumberAlerts > AlertMaxNumber)
            {
                tAlert.Dispose();
                ConversationStarter.EndAlertsMax(me.conversationId, me.channelId);
            }
            Electricity res         = null;
            float       consumption = 0;

            switch (alert.AlertType)
            {
            case AlertEnum.Instant:
                var t = myWivaldy.GetMeasures(DateTimeOffset.Now.Add(-alert.Interval), DateTimeOffset.Now);
                t.Wait();
                res = t.Result;
                if (res != null)
                {
                    foreach (var wat in res.Consumptions)
                    {
                        if (wat.watts >= alert.Threshold)
                        {
                            if (consumption < wat.watts)
                            {
                                consumption = wat.watts;
                            }
                        }
                    }
                }
                break;

            case AlertEnum.Total:
                DateTimeOffset today = new DateTimeOffset(DateTimeOffset.Now.Year, DateTimeOffset.Now.Month, DateTimeOffset.Now.Day, 0, 0, 0, DateTimeOffset.Now.Offset);
                var            t1    = myWivaldy.GetDayMeasures(today);
                t1.Wait();
                res = t1.Result;
                if (res != null)
                {
                    var cons = GetKiloWattHour(res);
                    if (cons >= alert.Threshold)
                    {
                        consumption = (float)cons;
                    }
                }
                break;

            case AlertEnum.Switch:
                var cmd = myWivaldy.GetRemoteCommand();
                cmd.Wait();
                RemoteCommand rmc = cmd.Result;
                if (rmc != null)
                {
                    if (rmc.date.millis > remoteCommand.date.millis)
                    {
                        remoteCommand = rmc;
                        //raise an alert
                        ConversationStarter.ResumeCommand(me.conversationId, me.channelId, rmc.commandType, alert);
                    }
                }

                break;

            default:
                break;
            }
            if (consumption > 0)
            {
                NumberAlerts++;
                ConversationStarter.Resume(me.conversationId, me.channelId, consumption, alert);
            }
        }
Exemplo n.º 25
0
 public void timerEvent(object target)
 {
     t.Dispose();
     ConversationStarter.Resume(ConversationStarter.conversationId, ConversationStarter.channelId); //We don't need to wait for this, just want to start the interruption here
 }