public BattleSimulation(BotData bot0, BotData bot1, int depth)
		{
			Turns0 = new List<Field>();
			Turns1 = new List<Field>();

			Bot0 = bot0;
			Bot1 = bot1;
			SearchDepth = depth;
		}
Example #2
0
 private static PuppeteerSharp.Page GetPage(BotData data)
 => data.TryGetObject <PuppeteerSharp.Page>("puppeteerPage") ?? throw new Exception("No pages open!");
Example #3
0
        public static void Search(Message msg, IMessageSenderService sender, IBot bot)
        {
            try
            {
                StaticContent.UsersCommand.Remove(msg.MessageVK.FromId.Value);
            }
            catch (Exception e)
            {
            }
            var search = msg.Text;

            using (var db = new BotData())
            {
                var cars = db.Cars.Where(c => c.Model.ToLower() == search.ToLower());

                CarInfo car = null;

                if (!cars.Any())
                {
                    //поиск по тегам.

                    var tagsModel = JsonConvert.DeserializeObject <TagsCarModel>(File.ReadAllText("Tags.json"));

                    var tagModel = tagsModel.Tags.SingleOrDefault(t => t.Tag.ToLower() == search.ToLower());

                    if (tagModel != null)
                    {
                        car = db.Cars.SingleOrDefault(c => c.CarId == tagModel.CarId);
                    }
                    else
                    {
                        try
                        {
                            StaticContent.UsersCommand.Add(msg.MessageVK.FromId.Value, "search");
                        }
                        catch
                        {
                            StaticContent.UsersCommand.Remove(msg.MessageVK.FromId.Value);

                            StaticContent.UsersCommand.Add(msg.MessageVK.FromId.Value, "search");
                        }
                        var kb = new KeyboardBuilder(bot);
                        kb.AddButton("🔙 Назад", "searchmenu");

                        if (msg.ChatId != msg.MessageVK.FromId)
                        {
                            sender.Text("🔍 Автомобиль не найден. Попробуйте ещё раз", msg.ChatId);
                            return;
                        }
                        sender.Text("🔍 Автомобиль не найден. Попробуйте ещё раз", msg.ChatId, kb.Build());
                        return;
                    }
                }
                else
                {
                    car = cars.ToList()[0];
                }


                var kb1 = new KeyboardBuilder(bot);
                kb1.AddButton("🚗 Открыть информацию", "carinfo", new List <string>()
                {
                    car.CarId.ToString()
                });
                kb1.AddLine();
                kb1.AddButton("🔍 Найти другой", "search");
                kb1.AddLine();
                kb1.AddButton("🔙 Назад", "searchmenu");


                if (msg.ChatId == msg.MessageVK.FromId)
                {
                    sender.Text($"🚗 {car.Model} найден! Нажмите на кнопку ниже, чтобы открыть информацию об авто.", msg.ChatId, kb1.Build());
                }
                else
                {
                    sender.Text($"✔ Автомобиль найден. Напишите авто {car.CarId} чтобы получить информацию об автомобиле", msg.ChatId);
                }
            }
        }
Example #4
0
 // used to parse the user preferences from the state and save them for later use
 public async void ParseSettingsAndSave(string state, BotData userData, Activity activity, IBotDataStore <BotData> service)
 {
     userData.SetProperty <string>("composeExtensionCardType", state);
     await TemplateUtility.SaveBotUserDataObject(service, activity, userData);
 }
Example #5
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                MobileServiceClient azureClient = AzureManager.AzureManagerInstance.AzureClient;


                StateClient stateClient = activity.GetStateClient();
                BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                LUISObject.RootObject luisObj;

                if (activity.Attachments != null)
                {
                    if (activity.Attachments.Count > 0)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"You sent us a photo! We will try and give you your intented action from this photo."));

                        VisionServiceClient VisionServiceClient = new VisionServiceClient("fff4c0ce2c8946a1a4a6bd8b951d13c6");
                        AnalysisResult      analysisResult      = await VisionServiceClient.DescribeAsync(activity.Attachments[0].ContentUrl, 3);

                        activity.Text = analysisResult.Description.Captions[0].Text;
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"The photo you sent us is of " + activity.Text));
                    }
                }

                HttpClient client = new HttpClient();
                string     x      = await client.GetStringAsync(new Uri("https://api.projectoxford.ai/luis/v2.0/apps/a4ab66bf-68bb-4e95-8951-8b179e6f3c21?subscription-key=14b2e4303e5948578989704f3ef1fd87&q=" + activity.Text + "&verbose=true"));

                luisObj = JsonConvert.DeserializeObject <LUISObject.RootObject>(x);

                string intent = luisObj.topScoringIntent.intent;

                if (activity.Text.Length > 8)
                {
                    if (activity.Text.Substring(0, 8).ToLower() == "location")
                    {
                        string location = activity.Text.Substring(9);

                        DirectionsObject.RootObject dirObj;
                        string y = await client.GetStringAsync(new Uri("https://maps.googleapis.com/maps/api/directions/json?origin=" + location + "&destination=" + BANK_ADDRESS + "&key=AIzaSyBUytVVv7rrAWHM45JPuRgj52OEV_LwBnE"));

                        dirObj = JsonConvert.DeserializeObject <DirectionsObject.RootObject>(y);

                        string duration     = dirObj.routes[0].legs[0].duration.text;
                        string distance     = dirObj.routes[0].legs[0].distance.text;
                        string bankLocation = dirObj.routes[0].legs[0].end_address;

                        Activity locateReply = activity.CreateReply($"The distance to the closest bank is " + distance);
                        locateReply.Recipient   = activity.From;
                        locateReply.Type        = "message";
                        locateReply.Attachments = new List <Attachment>();

                        List <CardImage> cardImg = new List <CardImage>();
                        cardImg.Add(new CardImage(url: BANK_MAP));

                        List <CardAction> cardAct = new List <CardAction>();
                        cardAct.Add(new CardAction()
                        {
                            Value = "https://www.google.co.nz/maps/dir/" + location + "/" + BANK_ADDRESS,
                            Type  = "openUrl",
                            Title = "Open Google Maps"
                        });

                        HeroCard plCard = new HeroCard()
                        {
                            Title    = "Closest Bank",
                            Subtitle = "The closest bank is at " + BANK_ADDRESS + " and is " + duration + " away.",
                            Images   = cardImg,
                            Buttons  = cardAct
                        };

                        locateReply.Attachments.Add(plCard.ToAttachment());
                        await connector.Conversations.SendToConversationAsync(locateReply);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (activity.Text == "CancelPayment")
                    {
                        await connector.Conversations.SendToConversationAsync(activity.CreateReply($"This payment has been cancelled!"));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        if (activity.Text.Length >= 14)
                        {
                            if (activity.Text.Substring(0, 14) == "ConfirmPayment")
                            {
                                string[] stringParts = activity.Text.Split(' ');
                                double   amount      = Convert.ToDouble(stringParts[1]);
                                string   payee       = stringParts[2];

                                ACCOUNT = await AzureManager.AzureManagerInstance.getAccount(userData.GetProperty <string>("Name"));

                                if (ACCOUNT.Amount >= amount && await AzureManager.AzureManagerInstance.DoesExist(payee))
                                {
                                    ACCOUNT.Amount = ACCOUNT.Amount - amount;
                                    await AzureManager.AzureManagerInstance.UpdateAccount(ACCOUNT);

                                    BankAccount other = await AzureManager.AzureManagerInstance.getAccount(payee);

                                    other.Amount = other.Amount + amount;
                                    await AzureManager.AzureManagerInstance.UpdateAccount(other);

                                    await connector.Conversations.SendToConversationAsync(activity.CreateReply($"Payment to " + payee + " of $" + amount + " has been made."));

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                                else if (!(await AzureManager.AzureManagerInstance.DoesExist(payee)))
                                {
                                    await connector.Conversations.SendToConversationAsync(activity.CreateReply($"Payee could not be found!"));

                                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                                }
                                else
                                {
                                    await connector.Conversations.SendToConversationAsync(activity.CreateReply($"Payment could not be made due to insufficient funds!"));

                                    return(Request.CreateResponse(HttpStatusCode.NotAcceptable));
                                }
                            }
                        }
                    }
                }

                if (!userData.GetProperty <bool>("LoggedIn") && intent == "Greeting")
                {
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Hello! Please login to continue..."));

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

                if (intent == "SetName")
                {
                    string newName = luisObj.topScoringIntent.actions[0].parameters[0].value[0].entity;

                    ACCOUNT = await AzureManager.AzureManagerInstance.getAccount(newName);

                    if (ACCOUNT == null)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Account Not Found"));

                        return(Request.CreateResponse(HttpStatusCode.NotFound));
                    }

                    userData.SetProperty <string>("Name", " " + newName.Substring(0, 1).ToUpper() + newName.Substring(1));
                    userData.SetProperty <bool>("LoggedIn", true);
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Hello" + userData.GetProperty <string>("Name") + "!"));

                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else if (intent == "ClearData")
                {
                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                    ACCOUNT = null;
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"You have been logged out"));

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

                if (!userData.GetProperty <bool>("LoggedIn"))
                {
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Please login!"));

                    return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }

                ACCOUNT = await AzureManager.AzureManagerInstance.getAccount(userData.GetProperty <string>("Name"));

                if (!userData.GetProperty <bool>("SendGreeting"))
                {
                    userData.SetProperty <bool>("SendGreeting", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    if (intent == "Greeting" || intent == "None")
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Hello" + userData.GetProperty <string>("Name") + "! How can I help you?"));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Hello" + userData.GetProperty <string>("Name") + "!"));
                    }
                }
                else
                {
                    if (intent == "Greeting")
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply($"Hello Again" + userData.GetProperty <string>("Name") + "!"));

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

                string output = "";

                if (intent == "None")
                {
                    output = "Sorry I didn't quite understand what you meant. Could you please phrase it differently?";
                }
                else if (intent == "FindBank")
                {
                    output = "Please reply with \"location\" and then your current address";
                }
                else if (intent == "CheckBalance")
                {
                    output = "You have $" + ACCOUNT.Amount + " in your account " + ACCOUNT.AccountNumber;
                }
                else if (intent == "MakePayment")
                {
                    string  z      = luisObj.topScoringIntent.actions[0].parameters[3].value[0].entity;
                    decimal amount = Convert.ToDecimal(z.Substring(1));

                    string payee = "undefined";
                    if (luisObj.topScoringIntent.actions[0].parameters[1].value != null)
                    {
                        payee = luisObj.topScoringIntent.actions[0].parameters[1].value[0].entity;
                    }
                    else if (luisObj.topScoringIntent.actions[0].parameters[2].value != null)
                    {
                        payee = luisObj.topScoringIntent.actions[0].parameters[2].value[0].entity;
                    }

                    Activity replyWeb = activity.CreateReply($"You wish to make a payment of " + amount + " to " + payee + " from " + ACCOUNT.AccountNumber);
                    replyWeb.Recipient   = activity.From;
                    replyWeb.Type        = "message";
                    replyWeb.Attachments = new List <Attachment>();

                    List <CardImage> cardImg = new List <CardImage>();
                    cardImg.Add(new CardImage(url: BANK_LOGO));

                    // ADD LOGIC TO BUTTONS
                    List <CardAction> cardAct = new List <CardAction>();
                    cardAct.Add(new CardAction()
                    {
                        Value = "ConfirmPayment " + amount + " " + payee,
                        Type  = "postBack",
                        Title = "Confirm",
                        Image = TICK_IMAGE
                    });
                    cardAct.Add(new CardAction()
                    {
                        Value = "CancelPayment",
                        Type  = "postBack",
                        Title = "Cancel",
                        Image = CROSS_IMAGE
                    });

                    HeroCard plCard = new HeroCard()
                    {
                        Title    = "Confirm Payment",
                        Subtitle = "Please confirm that you wish to make this payment",
                        Images   = cardImg,
                        Buttons  = cardAct
                    };

                    replyWeb.Attachments.Add(plCard.ToAttachment());
                    await connector.Conversations.ReplyToActivityAsync(replyWeb);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else if (intent == "Website")
                {
                    Activity replyWeb = activity.CreateReply($"Here is our website");
                    replyWeb.Recipient   = activity.From;
                    replyWeb.Type        = "message";
                    replyWeb.Attachments = new List <Attachment>();

                    List <CardImage> cardImg = new List <CardImage>();
                    cardImg.Add(new CardImage(url: BANK_LOGO));

                    List <CardAction> cardAct = new List <CardAction>();
                    cardAct.Add(new CardAction()
                    {
                        Value = "http://msa.ms",
                        Type  = "openUrl",
                        Title = "Open Website"
                    });

                    HeroCard plCard = new HeroCard()
                    {
                        Title    = "Contoso Website",
                        Subtitle = "Take a look at our website for even more options.",
                        Images   = cardImg,
                        Buttons  = cardAct
                    };

                    replyWeb.Attachments.Add(plCard.ToAttachment());
                    await connector.Conversations.ReplyToActivityAsync(replyWeb);

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

                if (output != "")
                {
                    Activity reply = activity.CreateReply($"" + output);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #6
0
 /// <summary>
 /// Checks the comparison between left and right member.
 /// </summary>
 /// <param name="data">The BotData used for variable replacement.</param>
 /// <returns>Whether the comparison is valid</returns>
 public bool CheckKey(BotData data)
 {
     return(ConditionChecker.Verify(LeftTerm, Condition, RightTerm, data));
 }
Example #7
0
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            //проверка и подписка на рассылку, если пользователь пользуется ботом первый раз.
            var usrs1 = JsonConvert.DeserializeObject <MailingModel>(File.ReadAllText("MailingUsers.json"));

            if (usrs1.Users.All(u => u.UserId != msg.MessageVK.FromId.Value))
            {
                usrs1.Users.Add(new ValuesMail()
                {
                    IsActive = true,
                    UserId   = msg.MessageVK.FromId.Value
                });

                File.WriteAllText("MailingUsers.json", JsonConvert.SerializeObject(usrs1));
            }

            var file   = File.ReadAllText("AdminsConfig.json");
            var admins = JsonConvert.DeserializeObject <Models.AdminsModels>(file);

            bool isAdmin = admins.Users.Any(u => u == msg.MessageVK.FromId);



            int offset, server = 0;

            if (msg.Text.Split("-")[0] == "com")
            {
                offset = (int.Parse(msg.Text.Split("-")[1]) - 1) * 10;
                server = int.Parse(msg.Text.Split("-")[2]);
            }
            else
            {
                var argument = msg.Payload.Arguments[0];
                offset = int.Parse(msg.Payload.Arguments[1]);
                server = int.Parse(argument);
            }


            var vkNet = new VkApi();

            vkNet.Authorize(new ApiAuthParams()
            {
                AccessToken = "e7980081cccad8d0df1ce342355da76e6e0d8de37509d76fb08ff1f065823dc19e5f4ed7f4578314cc772"
            });

            var ids = new List <long>();
            var kb  = new KeyboardBuilder(bot);

            using (var db = new BotData())
            {
                var ads = db.Ads.Where(a => a.Server == server);

                string s          = string.Empty;
                var    stringText = string.Empty;

                if (ads.Count() != 0)
                {
                    bool isAddNextCommand = true;
                    int  counter          = 0;
                    for (int i = offset; i < offset + 10; i++)
                    {
                        try
                        {
                            var ad = ads.OrderByDescending(a => a.DateCreate).ToList()[i];
                            var id = $"| ID:{ad.AdId}";
                            ids.Add(ad.Owner);
                            stringText += $"💎[{i}] -{ad.Owner}- сервер - {ad.Server} {id} : {ad.Text} \n";
                            kb.AddButton(i.ToString(), "showad", new List <string>()
                            {
                                ad.AdId.ToString()
                            });

                            if (counter == 4)
                            {
                                kb.AddLine();
                                counter = 0;
                            }
                        }
                        catch
                        {
                            isAddNextCommand = false;
                        }
                    }

                    kb.AddLine();
                    kb.SetOneTime();


                    if (offset > 0)
                    {
                        kb.AddButton("⏮ Назад", "adsFilter", new List <string>()
                        {
                            server.ToString(), $"{offset-10}"
                        });
                    }
                    if (isAddNextCommand)
                    {
                        kb.AddButton("⏭ Вперед", "adsFilter", new List <string>()
                        {
                            server.ToString(), $"{offset + 10}"
                        });
                    }


                    var usrs = vkNet.Users.Get(ids);

                    foreach (var usr in usrs)
                    {
                        stringText = stringText.Replace($"-{usr.Id}-", $"{usr.FirstName} {usr.LastName}");
                    }
                }
                else
                {
                    stringText += "Объявлений нет.";
                }

                kb.AddLine();
                kb.AddButton("🔙 Назад  в меню", "ads");

                if (msg.ChatId != msg.MessageVK.FromId)
                {
                    sender.Text($"🎫 Объявления: \n {stringText}", msg.ChatId);
                }
                else
                {
                    sender.Text($"🎫 Объявления: \n {stringText}", msg.ChatId, kb.Build());
                }
            }
        }
Example #8
0
        public static async Task PuppeteerOpenBrowser(BotData data)
        {
            data.Logger.LogHeader();

            // Check if there is already an open browser
            if (data.Objects.ContainsKey("puppeteer") && !((PuppeteerSharp.Browser)data.Objects["puppeteer"]).IsClosed)
            {
                data.Logger.Log("The browser is already open, close it if you want to open a new browser", LogColors.DarkSalmon);
                return;
            }

            var args = data.ConfigSettings.PuppeteerSettings.CommandLineArgs;

            if (data.Proxy != null && data.UseProxy)
            {
                if (data.Proxy.Type == ProxyType.Http || !data.Proxy.NeedsAuthentication)
                {
                    args += $" --proxy-server={data.Proxy.Type.ToString().ToLower()}://{data.Proxy.Host}:{data.Proxy.Port}";
                }
                else
                {
                    var proxyType   = data.Proxy.Type == ProxyType.Socks5 ? Yove.Proxy.ProxyType.Socks5 : Yove.Proxy.ProxyType.Socks4;
                    var proxyClient = new ProxyClient(
                        data.Proxy.Host, data.Proxy.Port,
                        data.Proxy.Username, data.Proxy.Password,
                        proxyType);
                    data.Objects["puppeteer.yoveproxy"] = proxyClient;
                    args += $" --proxy-server={proxyClient.GetProxy(null).Authority}";
                }
            }

            // Configure the options
            var launchOptions = new LaunchOptions
            {
                Args            = new string[] { args },
                ExecutablePath  = data.Providers.PuppeteerBrowser.ChromeBinaryLocation,
                Headless        = data.ConfigSettings.PuppeteerSettings.Headless,
                DefaultViewport = null // This is important
            };

            // Add the plugins
            var extra = new PuppeteerExtra();

            extra.Use(new StealthPlugin());

            // Launch the browser
            var browser = await extra.LaunchAsync(launchOptions);

            browser.IgnoreHTTPSErrors = data.ConfigSettings.PuppeteerSettings.IgnoreHttpsErrors;

            // Save the browser for further use
            data.Objects["puppeteer"] = browser;
            var page = (await browser.PagesAsync()).First();

            SetPageAndFrame(data, page);
            await SetPageLoadingOptions(data, page);

            // Authenticate if the proxy requires auth
            if (data.UseProxy && data.Proxy is { NeedsAuthentication : true, Type : ProxyType.Http } proxy)
            {
                await page.AuthenticateAsync(new Credentials { Username = proxy.Username, Password = proxy.Password });
            }

            data.Logger.Log($"{(launchOptions.Headless ? "Headless " : "")}Browser opened successfully!", LogColors.DarkSalmon);
        }
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            //проверка и подписка на рассылку, если пользователь пользуется ботом первый раз.
            var usrs1 = JsonConvert.DeserializeObject <MailingModel>(File.ReadAllText("MailingUsers.json"));

            if (usrs1.Users.All(u => u.UserId != msg.MessageVK.FromId.Value))
            {
                usrs1.Users.Add(new ValuesMail()
                {
                    IsActive = true,
                    UserId   = msg.MessageVK.FromId.Value
                });

                File.WriteAllText("MailingUsers.json", JsonConvert.SerializeObject(usrs1));
            }

            StaticContent.UsersCommand.Remove(msg.MessageVK.FromId.Value);
            bool isChat = msg.ChatId != msg.MessageVK.FromId.Value;

            using (var db = new BotData())
            {
                var target = db.Targets.SingleOrDefault(t => t.UserId == msg.MessageVK.FromId);
                if (target is null)
                {
                    var kb1 = new KeyboardBuilder(bot);
                    kb1.AddButton("🔙 В меню", "menu");
                    kb1.SetOneTime();

                    if (isChat)
                    {
                        sender.Text("✈ Вы пока что не установили цель", msg.ChatId);
                    }
                    else
                    {
                        sender.Text("✈ Вы пока что не установили цель", msg.ChatId, kb1.Build());
                    }
                    return;
                }

                var car = db.Cars.SingleOrDefault(c => c.CarId == target.CarId);

                long priceRub = 0;

                long priceDoll = 0;
                long priceEuro = 0;

                var courseText = File.ReadAllText("CourceConfig.json");
                var course     = JsonConvert.DeserializeObject <CourseModel>(courseText);

                if (car.Currency == 1) //руб
                {
                    priceRub  = car.Price;
                    priceDoll = Convert.ToInt64(Convert.ToSingle(car.Price) / course.Dollar);
                    priceEuro = Convert.ToInt64(Convert.ToSingle(car.Price) / course.Euro);
                }
                else if (car.Currency == 2)  //долл
                {
                    priceRub  = Convert.ToInt64(course.Dollar * Convert.ToSingle(car.Price));
                    priceDoll = car.Price;
                    priceEuro = Convert.ToInt64(Convert.ToSingle(priceRub) / course.Euro);
                }
                else if (car.Currency == 3)  //евро
                {
                    priceRub  = Convert.ToInt64(course.Euro * Convert.ToSingle(car.Price));
                    priceEuro = car.Price;
                    priceDoll = Convert.ToInt64(Convert.ToSingle(priceRub) / course.Dollar);
                }

                var kb = new KeyboardBuilder(bot);
                kb.AddButton("➕ Изменить собранную сумму", "targetedit");
                kb.AddLine();
                kb.AddButton("🔙 В меню", "menu");
                kb.SetOneTime();

                var text = $"✈ Ваша цель: " +
                           $"\n 🚗 {car.Model}" +
                           $"\n 💎 Собрано {target.Count.ToString("N1")} из {priceRub.ToString("N1")} ₽ ({target.Count/(priceRub/100)}%)";

                if (isChat)
                {
                    sender.Text(text, msg.ChatId);
                }
                else
                {
                    sender.Text(text, msg.ChatId, kb.Build());
                }
            }
        }
Example #10
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)
            {
                ConnectorClient connector   = new ConnectorClient(new Uri(activity.ServiceUrl));
                StateClient     stateClient = activity.GetStateClient();
                BotData         userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                string text     = (activity.Text ?? string.Empty).ToLower();
                int    length   = text.Length;
                string replyStr = string.Empty;

                string name     = String.Empty;
                string userId   = activity.From.Id.ToString();
                bool   loggedIn = false;

                try
                {
                    loggedIn = await authoriseUser(activity, connector, text, userId);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    System.Diagnostics.Debug.WriteLine($"ERROR! : {e.Message}");
                }

                if (!loggedIn)
                {
                    var responseOut = Request.CreateResponse(HttpStatusCode.OK);
                    return(responseOut);
                }

                Accounts userAccount;
                try
                {
                    userAccount = await getUserAccount(name);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    System.Diagnostics.Debug.WriteLine($"ERROR! : {e.Message}");
                    userAccount = new Accounts();
                }


                string responderName = userData.GetProperty <string>("Responder");
                System.Diagnostics.Debug.WriteLine(userData.GetProperty <string>("Responder"));
                if (responderName == null)
                {
                    responderName = "boring";
                    userData.SetProperty <string>("Responder", responderName);
                }
                Responder responder = Responder.GetResponder(responderName);

                //If block for user input
                if (text.StartsWith("clear"))
                {
                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                    Auth auth = await getUserAuth(userId);

                    await AzureManager.AzureManagerInstance.DeleteAuths(auth);

                    replyStr = responder.affirmative();
                }
                if (text.StartsWith("set"))
                {
                    Auth auth = await getUserAuth(userId);

                    string[] input = text.Substring(4).Split(':');
                    if (input.Length != 2)
                    {
                        replyStr = responder.unknown();
                    }
                    else
                    {
                        auth.Name     = input[0];
                        auth.Password = input[1];
                        replyStr      = responder.affirmative();
                    }
                }
                else if (text.StartsWith("use"))
                {
                    //Sets the users preferred responder
                    //Does not check if a responder exists with that name
                    userData.SetProperty <string>("Responder", text.Substring(4));
                    responderName = userData.GetProperty <string>("Responder");
                    responder     = Responder.GetResponder(responderName);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    Activity greetingCard = await buildCardResponse(activity, $"Now using {responder.getName()}", "", responder.greeting(), responder.neutralImageUrl());

                    await connector.Conversations.SendToConversationAsync(greetingCard);
                }
                else if (text.StartsWith("quote"))
                {
                    string   quote     = getRandomQuote(responder.getName());
                    Activity quoteCard = await buildCardResponse(activity, "", "", quote, responder.neutralImageUrl());

                    await connector.Conversations.SendToConversationAsync(quoteCard);
                }
                else if (text.StartsWith("balance"))
                {
                    Activity balanceCardReply = await getFullBalance(userAccount, responder, activity);

                    await connector.Conversations.SendToConversationAsync(balanceCardReply);
                }
                else if (text.StartsWith("cheque"))
                {
                    try
                    {
                        string change      = text.Substring(7);
                        double changeValue = Double.Parse(change);
                        userAccount.Cheque = userAccount.Cheque + changeValue;

                        await AzureManager.AzureManagerInstance.UpdateAccounts(userAccount);

                        string imageUrl;
                        if (changeValue >= 0.0)
                        {
                            imageUrl = responder.positiveImageUrl();
                        }
                        else
                        {
                            imageUrl = responder.negativeImageUrl();
                        }

                        Activity confirmCard = await buildCardResponse(activity, responder.affirmative(), "Balance updated", $"{userAccount.Cheque}", imageUrl);

                        await connector.Conversations.SendToConversationAsync(confirmCard);
                    }
                    catch (Exception e)
                    {
                        Activity unkownCard = await buildCardResponse(activity, "", "", responder.unknown(), responder.negativeImageUrl());

                        await connector.Conversations.SendToConversationAsync(unkownCard);
                    }
                }
                else if (text.StartsWith("savings"))
                {
                    string change = text.Substring(8);
                    try
                    {
                        double changeValue = Double.Parse(change);
                        userAccount.Savings = userAccount.Savings + changeValue;

                        await AzureManager.AzureManagerInstance.UpdateAccounts(userAccount);

                        string imageUrl;
                        if (changeValue >= 0.0)
                        {
                            imageUrl = responder.positiveImageUrl();
                        }
                        else
                        {
                            imageUrl = responder.negativeImageUrl();
                        }

                        Activity confirmCard = await buildCardResponse(activity, responder.affirmative(), "Balance updated", $"{userAccount.Savings}", imageUrl);

                        await connector.Conversations.SendToConversationAsync(confirmCard);
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine($"ERROR! : {e.Message}");
                        System.Diagnostics.Debug.WriteLine($"ERROR! : {change}");
                        Activity unkownCard = await buildCardResponse(activity, "", "", responder.unknown(), responder.negativeImageUrl());

                        await connector.Conversations.SendToConversationAsync(unkownCard);
                    }
                }
                else
                {
                    Activity unkownCard = await buildCardResponse(activity, "", "", responder.unknown(), responder.negativeImageUrl());

                    await connector.Conversations.SendToConversationAsync(unkownCard);
                }


                if (replyStr.Length > 0)
                {
                    // return our reply to the user
                    Activity reply = activity.CreateReply(replyStr);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
        /// <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)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                var userMessage = activity.Text;
                //A list of the currencies for which the fixer.io API has data for
                string[] currencyArray = new string[] { "nzd", "aud", "bgn", "brl", "cad", "chf", "cny", "czk", "dkk", "gbp", "hkd", "hrk", "huf", "idr", "ils", "inr", "jpy", "krw", "mxn", "myr", "nok", "php", "pln", "ron", "rub", "sek", "sgd", "thb", "try", "usd", "zar", "eur" };

                StateClient stateClient = activity.GetStateClient();
                BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                bool isCurrencyRequest = false;

                if ((userMessage.Length > 8) && (userMessage.ToLower().Substring(0, 7).Equals("convert")))
                {
                    isCurrencyRequest = true;
                }

                string endOutput = "Welcome, I am the Contoso Bank Bot, Please enter your name";



                bool greeting = userData.GetProperty <bool>("SentGreeting"); //set to false by default

                if ((userMessage.Length > 11) && (userMessage.ToLower().Substring(0, 10).Equals("my name is")))
                {
                    string name = userMessage.Substring(11);
                    userData.SetProperty <string>("Name", name);    //Saves the user's name
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    endOutput = "Hello " + name + "? How can I help you?";
                }
                else if ((userMessage.Length > 18) && (userMessage.ToLower().Substring(0, 17).Equals("set base currency")))
                {
                    string baseCurrency = (userMessage.Substring(18, 3)).ToLower();
                    if (!((currencyArray).Contains(baseCurrency)))
                    {
                        endOutput = "Info for the input currency is not available";
                    }
                    else
                    {
                        userData.SetProperty <string>("BaseCurrency", baseCurrency);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        endOutput = "Base Currency is set to " + baseCurrency.ToUpper();
                    }
                }
                else if (greeting == true)
                {
                    string name = userData.GetProperty <string>("Name");
                    endOutput = "How can I help you, " + name + "?";



                    if (name == null)
                    {
                        endOutput = "Welcome, I am the Contoso Bank Bot, Please enter your name"; //Asks for user's name

                        userData.SetProperty <bool>("SentGreeting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    else
                    {
                        userData.SetProperty <bool>("SentGreeting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                }
                else
                {
                    userData.SetProperty <bool>("SentGreeting", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                }



                if (userMessage.ToLower().Contains("clear"))
                {
                    endOutput = "User data has been cleared";

                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);
                }
                else if (userMessage.ToLower().Equals("base currency"))
                {
                    string baseCurrency = userData.GetProperty <string>("BaseCurrency");

                    if (baseCurrency == null)
                    {
                        endOutput = "Base currency not assigned";
                    }
                    else
                    {
                        endOutput = "Base Currency is " + baseCurrency.ToUpper();
                    }
                }

                if (userMessage.ToLower().Equals("list of currencies"))
                {
                    Activity replyToConversation = activity.CreateReply("List of Available Currencies");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();
                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://pbs.twimg.com/profile_images/709620078/contosobanklogo.jpg"));
                    List <CardAction> cardButtons = new List <CardAction>();
                    CardAction        plButton    = new CardAction()
                    {
                        Value = "http://finance.yahoo.com/currencies",
                        Type  = "openUrl",
                        Title = "Currency Website"
                    };
                    cardButtons.Add(plButton);
                    ThumbnailCard plCard = new ThumbnailCard()
                    {
                        Title = "NZD,AUD,BGN,BRL,CAD,CHF,CNY,CZK,DKK,GBP,HKD,HRK,HUF,IDR,ILS,INR,JPY,KRW,MXN,MYR,NOK,PHP,PLN,RON,RUB,SEK,SGD,THB,TRY,USD,ZAR,EUR",//"Visit Fixer.io",

                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                if ((userMessage.Length > 8) && (userMessage.ToLower().Substring(0, 7).Equals("account")))
                {
                    List <moneyTable> listaccounts = await AzureManager.AzureManagerInstance.GetAccount();

                    List <double> passwordList = new List <double>();

                    foreach (moneyTable listaccount in listaccounts)
                    {
                        passwordList.Add(listaccount.Password);
                    }


                    if (userMessage.ToLower().Substring(0, 12).Equals("account view"))
                    {
                        string passwordString = userMessage.Substring(13);
                        bool   isAllDigits    = !passwordString.Any(ch => ch <'0' || ch> '9');

                        if ((passwordString.Length != 5) || !(isAllDigits))
                        {
                            endOutput = "Please ensure password is a positive 5 digit number";
                        }
                        else
                        {
                            int encryptedPassword = ((int.Parse(passwordString)) * 10) - 1;
                            if (!((passwordList).Contains(encryptedPassword)))
                            {
                                endOutput = "No account in our database matches that password";
                            }
                            else
                            {
                                List <moneyTable> accounts = await AzureManager.AzureManagerInstance.GetAccount();

                                foreach (moneyTable account in accounts)
                                {
                                    if (account.Password == encryptedPassword)
                                    {
                                        endOutput = " Account Number: " + passwordString + ", Balance: $" + account.Balance; //+ "\n\n";
                                    }
                                }
                            }
                        }
                    }


                    if (userMessage.ToLower().Substring(0, 11).Equals("account new"))
                    {
                        string passwordString = userMessage.Substring(12);
                        bool   isAllDigits    = !passwordString.Any(ch => ch <'0' || ch> '9');

                        if ((passwordString.Length != 5) || !(isAllDigits))
                        {
                            endOutput = "Please ensure password is a positive 5 digit number";
                        }
                        else
                        {
                            int encryptedPassword = ((int.Parse(passwordString)) * 10) - 1;
                            if (((passwordList).Contains(encryptedPassword)))
                            {
                                endOutput = "This password already exists in our Database, please try again with a different 5 digit password";
                            }
                            else
                            {
                                moneyTable account = new moneyTable()
                                {
                                    Balance  = 0,
                                    Password = encryptedPassword
                                };

                                await AzureManager.AzureManagerInstance.CreateAccount(account);

                                endOutput = "Account created ";
                            }
                        }
                    }

                    if (userMessage.ToLower().Substring(0, 14).Equals("account update"))
                    {
                        string passwordString = userMessage.Substring(15, 5); //extract password
                        bool   isAllDigits    = !passwordString.Any(ch => ch <'0' || ch> '9');

                        if ((passwordString.Length != 5) || !(isAllDigits))
                        {
                            endOutput = "Please ensure password is a positive 5 digit number";
                        }
                        else
                        {
                            int encryptedPassword = ((int.Parse(passwordString)) * 10) - 1;
                            if (!((passwordList).Contains(encryptedPassword)))
                            {
                                endOutput = "This account does not exist in our Database, please try again with a different 5 digit password";
                            }
                            else
                            {
                                string balanceString = userMessage.Substring(21);
                                Double num           = 0;
                                bool   isDouble      = false;



                                isDouble = Double.TryParse(balanceString, out num); //tries to see if the balanceString represents a value of type double
                                if (isDouble)
                                {
                                    List <moneyTable> accounts = await AzureManager.AzureManagerInstance.GetAccount();

                                    foreach (moneyTable moneyAccount in accounts)
                                    {
                                        if (moneyAccount.Password == encryptedPassword)
                                        {
                                            moneyAccount.Balance = Convert.ToDouble(balanceString);

                                            endOutput = "Account No. " + passwordString + " has had its balance updated to $" + balanceString;
                                            await AzureManager.AzureManagerInstance.UpdateAccount(moneyAccount);
                                        }
                                    }
                                }
                                else
                                {
                                    endOutput = "Please enter a valid bank account balance ";
                                }
                            }
                        }
                    }


                    if (userMessage.ToLower().Substring(0, 14).Equals("account delete"))
                    {
                        string passwordString = userMessage.Substring(15);
                        bool   isAllDigits    = !passwordString.Any(ch => ch <'0' || ch> '9');

                        if ((passwordString.Length != 5) || !(isAllDigits))
                        {
                            endOutput = "Please ensure password is a positive 5 digit number";
                        }
                        else
                        {
                            int encryptedPassword = ((int.Parse(passwordString)) * 10) - 1;
                            if (!((passwordList).Contains(encryptedPassword)))
                            {
                                endOutput = "This account does not exist in our Database, please try again with a different 5 digit password";
                            }
                            else
                            {
                                List <moneyTable> accounts = await AzureManager.AzureManagerInstance.GetAccount();

                                string idAccountToDelete = "";
                                foreach (moneyTable moneyAccount in accounts)
                                {
                                    if (moneyAccount.Password == encryptedPassword)
                                    {
                                        idAccountToDelete = moneyAccount.ID;
                                        moneyTable account = new moneyTable()
                                        {
                                            ID = idAccountToDelete
                                        };
                                        endOutput = "Account No. " + passwordString + " has been deleted";
                                        await AzureManager.AzureManagerInstance.DeleteAccount(account);
                                    }
                                }
                            }
                        }
                    }

                    Activity replyToConversation = activity.CreateReply("Bank Account");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();
                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://pbs.twimg.com/profile_images/709620078/contosobanklogo.jpg"));

                    ThumbnailCard plCard = new ThumbnailCard()
                    {
                        Subtitle = endOutput,
                        Images   = cardImages
                    };
                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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


                if (userMessage.ToLower().Equals("help"))
                {
                    Activity replyToConversation = activity.CreateReply("List of Valid Commands");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();
                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://pbs.twimg.com/profile_images/709620078/contosobanklogo.jpg"));

                    ThumbnailCard plCard = new ThumbnailCard()  //Each command gets its own thumbnail so as to improve readability
                    {
                        Subtitle = "'my name is <insert name here>'- Stores the user's name",
                    };
                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);

                    ThumbnailCard plCard1 = new ThumbnailCard()
                    {
                        Subtitle = "'list of currencies'- Lists the currencies for which exchange rates are available",
                    };
                    Attachment plAttachment1 = plCard1.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment1);

                    ThumbnailCard plCard2 = new ThumbnailCard()
                    {
                        Subtitle = "'base currency'- displays the base currency",
                    };
                    Attachment plAttachment2 = plCard2.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment2);

                    ThumbnailCard plCard3 = new ThumbnailCard()
                    {
                        Subtitle = "'set base currency <insert 3-digit currency code here>'- sets the base currency",
                    };
                    Attachment plAttachment3 = plCard3.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment3);

                    ThumbnailCard plCard4 = new ThumbnailCard()
                    {
                        Subtitle = "'help'- displays a list of available commands",
                    };
                    Attachment plAttachment4 = plCard4.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment4);

                    ThumbnailCard plCard5 = new ThumbnailCard()
                    {
                        Subtitle = "'account view <insert 5 digit password here>'- Retrieves the bank balance for an account that corresponds to the input password",
                    };
                    Attachment plAttachment5 = plCard5.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment5);

                    ThumbnailCard plCard6 = new ThumbnailCard()
                    {
                        Subtitle = "'account new <insert 5 digit password here>'- Creates an account that corresponds to the input password",
                    };
                    Attachment plAttachment6 = plCard6.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment6);

                    ThumbnailCard plCard7 = new ThumbnailCard()
                    {
                        Subtitle = "'account update <insert 5 digit password here> <insert bank balance here>'- Updates the balance of the account that corresponds to the input password",
                    };
                    Attachment plAttachment7 = plCard7.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment7);

                    ThumbnailCard plCard8 = new ThumbnailCard()
                    {
                        Subtitle = "'account delete <insert 5 digit password here>'- Deletes the account that corresponds to the input password",
                    };
                    Attachment plAttachment8 = plCard8.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment8);

                    ThumbnailCard plCard12 = new ThumbnailCard()
                    {
                        Subtitle = "'clear' - Clear's the user's data",
                        Images   = cardImages,
                    };
                    Attachment plAttachment12 = plCard12.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment12);

                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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


                if (!isCurrencyRequest)
                {
                    // return our reply to the user
                    Activity infoReply = activity.CreateReply(endOutput);

                    await connector.Conversations.ReplyToActivityAsync(infoReply);

                    // return a reply to the user telling them to type "help" to get a list of commands
                    Activity infoHelpReply = activity.CreateReply("Enter 'help' to view list of available commands");

                    await connector.Conversations.ReplyToActivityAsync(infoHelpReply);
                }
                else
                {
                    string currency;
                    double amount;
                    string baseCurrency = userData.GetProperty <string>("BaseCurrency");
                    if (userMessage.Length > 16)
                    {
                        if (userMessage.ToLower().Substring(0, 15).Equals("convert base to"))
                        {
                            currency = (userMessage.Substring(16)).ToLower();//extracts input currency that base needs to be converted to

                            if (!((currencyArray).Contains(currency)))
                            {
                                endOutput = "Info for the input currency is not available";
                            }
                            else if (baseCurrency == null)
                            {
                                endOutput = "base currency not set";
                            }
                            else
                            {
                                HttpClient client = new HttpClient();
                                string     y      = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + baseCurrency.ToUpper() + "&symbols=" + currency.ToUpper()));

                                y = y.Substring(49);
                                y = y.Substring(0, 6);
                                double rate = Convert.ToDouble(y);
                                endOutput = "1 " + baseCurrency.ToUpper() + " yields " + y + " units of " + currency.ToUpper();
                            }
                        }
                    }
                    else if (userMessage.Length > 8)
                    {
                        if (userMessage.ToLower().Substring(0, 7).Equals("convert"))
                        {
                            currency = (userMessage.Substring(8, 3)).ToLower();//extracts input currency that base needs to be converted to
                            amount   = Convert.ToDouble((userMessage.Substring(12)));

                            if (!((currencyArray).Contains(currency)))
                            {
                                endOutput = "Info for the input currency is not available";
                            }
                            else if (baseCurrency == null)
                            {
                                endOutput = "base currency not set";
                            }
                            else
                            {
                                HttpClient client = new HttpClient();
                                string     y      = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + baseCurrency.ToUpper() + "&symbols=" + currency.ToUpper()));

                                y = y.Substring(49);
                                y = y.Substring(0, 6);
                                double rate                  = Convert.ToDouble(y);
                                string stringAmount          = Convert.ToString(amount);
                                double convertedAmount       = rate * amount;
                                string stringConvertedAmount = Convert.ToString(convertedAmount);
                                endOutput = stringAmount + " " + baseCurrency.ToUpper() + " yields " + stringConvertedAmount + " units of " + currency.ToUpper();
                            }
                        }
                    }

                    Activity replyToConversation = activity.CreateReply("Currency Conversion");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();
                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://pbs.twimg.com/profile_images/709620078/contosobanklogo.jpg"));
                    List <CardAction> cardButtons = new List <CardAction>();
                    CardAction        plButton    = new CardAction()
                    {
                        Value = "http://fixer.io",
                        Type  = "openUrl",
                        Title = "Currency Website"
                    };
                    cardButtons.Add(plButton);
                    ThumbnailCard plCard = new ThumbnailCard()
                    {
                        Title = endOutput,

                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #12
0
        private async Task Run()
        {
            try
            {
                // Build the C# script if not in CSharp mode
                if (Config.Mode != ConfigMode.CSharp)
                {
                    Config.CSharpScript = Config.Mode == ConfigMode.Stack
                        ? Stack2CSharpTranspiler.Transpile(Config.Stack, Config.Settings)
                        : Loli2CSharpTranspiler.Transpile(Config.LoliCodeScript, Config.Settings);
                }
            }
            catch (Exception ex)
            {
                await js.AlertException(ex);
            }

            if (options.UseProxy && !options.TestProxy.Contains(':'))
            {
                await js.AlertError(Loc["InvalidProxy"], Loc["InvalidProxyMessage"]);

                return;
            }

            if (!options.PersistLog)
            {
                logger.Clear();
            }

            // Close any previously opened browser
            if (lastBrowser != null)
            {
                await lastBrowser.CloseAsync();
            }

            options.Variables.Clear();
            isRunning = true;
            cts       = new CancellationTokenSource();
            var sw = new Stopwatch();

            var wordlistType = RuriLibSettings.Environment.WordlistTypes.First(w => w.Name == options.WordlistType);
            var dataLine     = new DataLine(options.TestData, wordlistType);
            var proxy        = options.UseProxy ? Proxy.Parse(options.TestProxy, options.ProxyType) : null;

            var providers = new Providers(RuriLibSettings)
            {
                RNG = RNGProvider
            };

            if (RuriLibSettings.RuriLibSettings.GeneralSettings.UseCustomUserAgentsList)
            {
                providers.RandomUA = RandomUAProvider;
            }

            // Build the BotData
            var data = new BotData(providers, Config.Settings, logger, dataLine, proxy, options.UseProxy);

            data.CancellationToken = cts.Token;
            data.Objects.Add("httpClient", new HttpClient());
            var runtime  = Python.CreateRuntime();
            var pyengine = runtime.GetEngine("py");
            var pco      = (PythonCompilerOptions)pyengine.GetCompilerOptions();

            pco.Module &= ~ModuleOptions.Optimized;
            data.Objects.Add("ironPyEngine", pyengine);

            var script = new ScriptBuilder()
                         .Build(Config.CSharpScript, Config.Settings.ScriptSettings, PluginRepo);

            logger.Log($"Sliced {dataLine.Data} into:");
            foreach (var slice in dataLine.GetVariables())
            {
                var sliceValue = data.ConfigSettings.DataSettings.UrlEncodeDataAfterSlicing
                    ? Uri.EscapeDataString(slice.AsString())
                    : slice.AsString();

                logger.Log($"{slice.Name}: {sliceValue}");
            }

            logger.NewEntry += OnNewEntry;

            try
            {
                var scriptGlobals = new ScriptGlobals(data, new ExpandoObject());
                foreach (var input in Config.Settings.InputSettings.CustomInputs)
                {
                    (scriptGlobals.input as IDictionary <string, object>).Add(input.VariableName, input.DefaultAnswer);
                }

                sw.Start();
                var state = await script.RunAsync(scriptGlobals, null, cts.Token);

                foreach (var scriptVar in state.Variables)
                {
                    try
                    {
                        var type = DescriptorsRepository.ToVariableType(scriptVar.Type);

                        if (type.HasValue && !scriptVar.Name.StartsWith("tmp_"))
                        {
                            var variable = DescriptorsRepository.ToVariable(scriptVar.Name, scriptVar.Type, scriptVar.Value);
                            variable.MarkedForCapture = data.MarkedForCapture.Contains(scriptVar.Name);
                            options.Variables.Add(variable);
                        }
                    }
                    catch
                    {
                        // The type is not supported, e.g. it was generated using custom C# code and not blocks
                        // so we just disregard it
                    }
                }
            }
            catch (OperationCanceledException)
            {
                data.STATUS = "ERROR";
                logger.Log($"Operation canceled", LogColors.Tomato);
            }
            catch (Exception ex)
            {
                data.STATUS = "ERROR";

                var logErrorMessage = RuriLibSettings.RuriLibSettings.GeneralSettings.VerboseMode
                    ? ex.ToString()
                    : ex.Message;

                logger.Log($"[{data.ExecutionInfo}] {ex.GetType().Name}: {logErrorMessage}", LogColors.Tomato);
                await js.AlertError(ex.GetType().Name, $"[{data.ExecutionInfo}] {ex.Message}");
            }
            finally
            {
                sw.Stop();
                isRunning = false;

                logger.Log($"BOT ENDED AFTER {sw.ElapsedMilliseconds} ms WITH STATUS: {data.STATUS}");

                // Save the browser for later use
                lastBrowser = data.Objects.ContainsKey("puppeteer") && data.Objects["puppeteer"] is Browser currentBrowser
                    ? currentBrowser
                    : null;

                // Dispose all disposable objects
                foreach (var obj in data.Objects.Where(o => o.Value is IDisposable))
                {
                    if (obj.Key.Contains("puppeteer"))
                    {
                        continue;
                    }

                    try
                    {
                        (obj.Value as IDisposable).Dispose();
                    }
                    catch
                    {
                    }
                }
            }

            await loggerViewer?.Refresh();

            variablesViewer?.Refresh();
            await InvokeAsync(StateHasChanged);
        }
Example #13
0
        /// <summary>
        /// Creates an <see cref="HttpOperationResponse"/>.
        /// </summary>
        /// <param name="channelId">The channel id.</param>
        /// <param name="userId">The user id.</param>
        /// <param name="conversationId">The conversation id.</param>
        /// <param name="storeType">The story type.</param>
        /// <param name="data">The data.</param>
        /// <returns>A <see cref="HttpOperationResponse"/>.</returns>
        protected async Task <HttpOperationResponse <object> > UpdateAndInsertData(string channelId, string userId, string conversationId, BotStoreType storeType, BotData data)
        {
            var result = new HttpOperationResponse <object> {
                Request = new HttpRequestMessage()
            };

            try
            {
                var address = this.AddressFrom(channelId, userId, conversationId);
                await this.memoryDataStore.SaveAsync(address, storeType, data, CancellationToken.None);
            }
            catch (HttpException e)
            {
                result.Body     = e.Data;
                result.Response = new HttpResponseMessage {
                    StatusCode = HttpStatusCode.PreconditionFailed
                };
                return(result);
            }
            catch (Exception)
            {
                result.Response = new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                };
                return(result);
            }

            result.Body     = data;
            result.Response = new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            };
            return(result);
        }
Example #14
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity message)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

            if (message.Type == "message")
            {
                string     StockRateString;
                CountyLUIS StLUIS = await GetEntityFromLUIS(message.Text);

                if (StLUIS.intents.Count() > 0 && StLUIS.entities.Count() > 1)
                {
                    switch (StLUIS.intents[0].intent)
                    {
                    case "AddComplaints":
                        StockRateString = await AddComplaint(StLUIS.entities[0].entity, StLUIS.entities[1].entity, message.Text);

                        break;

                    case "GetComplaintsStatus":
                        StockRateString = await AddComplaint(StLUIS.entities[0].entity, "empty", message.Text);

                        break;

                    default:
                        StockRateString = "Sorry, I am not getting you. :(\nPlease try contacting our super friendly officer at  +1 425-882-8080";
                        break;
                    }
                }

                else if (StLUIS.intents.Count() > 0 && StLUIS.entities.Count() > 0)
                {
                    StateClient stateClient = message.GetStateClient();
                    BotData     userData    = await stateClient.BotState.GetUserDataAsync(message.ChannelId, message.From.Id);

                    switch (StLUIS.intents[0].intent)
                    {
                    case "AddComplaints":


                        userData.SetProperty <string>("entity1", StLUIS.entities[0].entity);
                        await stateClient.BotState.SetUserDataAsync(message.ChannelId, message.From.Id, userData);

                        StockRateString = await AddComplaint(StLUIS.entities[0].entity);

                        break;

                    case "GetComplaintsStatus":
                        StockRateString = await AddComplaint(StLUIS.entities[0].entity, "empty", message.Text);

                        break;

                    case "EnterLocation":

                        string intent = userData.GetProperty <string>("entity1").ToString();
                        StockRateString = await AddComplaint(intent, StLUIS.entities[0].entity, message.Text);

                        break;

                    default:
                        StockRateString = "Sorry, I am not getting you. :(\nPlease try contacting our super friendly officer at  +1 425-882-8080";
                        break;
                    }
                }
                else
                {
                    StockRateString = "Sorry, I am not getting you. :(\nPlease try contacting our super friendly officer at  +1 425-882-8080";
                }

                // return our reply to the user
                Activity m = message.CreateReply(StockRateString);
                await connector.Conversations.ReplyToActivityAsync(m);
            }
            else
            {
                HandleSystemMessage(message);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #15
0
        public static async Task <string> TcpSendReadHttp(BotData data, string message, bool unescape = true,
                                                          int timeoutMilliseconds = 60000)
        {
            data.Logger.LogHeader();

            using var cts       = new CancellationTokenSource(timeoutMilliseconds);
            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, data.CancellationToken);
            var netStream = GetStream(data);

            // Unescape codes like \r\n
            if (unescape)
            {
                message = Regex.Unescape(message);
            }

            // Append \r\n at the end if not present
            if (!message.EndsWith("\r\n"))
            {
                message += "\r\n";
            }

            // Send the message
            var txBytes = Encoding.ASCII.GetBytes(message);
            await netStream.WriteAsync(txBytes.AsMemory(0, txBytes.Length), linkedCts.Token).ConfigureAwait(false);

            // Receive data
            var payload = string.Empty;

            using var ms = new MemoryStream();
            await netStream.CopyToAsync(ms, linkedCts.Token).ConfigureAwait(false); // Read the whole response stream

            ms.Position = 0;
            var rxBytes = ms.ToArray();

            // Find where the headers are finished
            var index   = BinaryMatch(rxBytes, Encoding.ASCII.GetBytes("\r\n\r\n")) + 4;
            var headers = Encoding.UTF8.GetString(rxBytes, 0, index);

            ms.Position = index;

            // If gzip, decompress
            if (headers.IndexOf("Content-Encoding: gzip", StringComparison.OrdinalIgnoreCase) > 0)
            {
                using var decompressionStream = new GZipStream(ms, CompressionMode.Decompress);
                using var decompressedMemory  = new MemoryStream();
                decompressionStream.CopyTo(decompressedMemory);
                decompressedMemory.Position = 0;
                payload = Encoding.UTF8.GetString(decompressedMemory.ToArray());
            }
            else
            {
                payload = Encoding.UTF8.GetString(rxBytes, index, rxBytes.Length - index);
            }

            var response = $"{headers}{payload}";

            data.Logger.Log($"Sent message\r\n{message}", LogColors.Mauve);
            data.Logger.Log($"The server says\r\n{response}", LogColors.Mauve);

            return(response);
        }
		private void RunSimulation(BotData bot0, BotData bot1, MT19937Generator rnd)
		{
			Console.Write("\r{0:d\\.hh\\:mm\\:ss} {1:#,##0} ({2:0.00} /sec) Last ID: {3}  ",
				sw.Elapsed,
				Simulations,
				Simulations / sw.Elapsed.TotalSeconds,
				Bots.LastId);

			var simulation = new BattleSimulation(bot0, bot1, SearchDepth);
			var result = simulation.Run(rnd, LogGames);

			Results.Enqueue(new BattlePairing(bot0, bot1) { Result = result });

			lock (lockElo)
			{
				Simulations++;
			}
		}
Example #17
0
        /// <summary>
        /// Runs a script with a different language inside the LoliScript.
        /// </summary>
        /// <param name="script">The script as a string with linebreaks</param>
        /// <param name="language">The language of the script</param>
        /// <param name="outputs">The variables that should be extracted from the script's scope and set into the BotData local variables</param>
        /// <param name="data">The BotData needed for variable replacement</param>
        private void RunScript(string script, ScriptingLanguage language, string outputs, BotData data, string jsFilePath = "")
        {
            // Set the console output to stringwriter
            var sw = new StringWriter();

            Console.SetOut(sw);
            Console.SetError(sw);

            jsFilePath = BlockBase.ReplaceValues(jsFilePath, data);

            if (jsFilePath != string.Empty && File.Exists(jsFilePath))
            {
                script += File.ReadAllText(jsFilePath);
            }

            // Parse variables to get out
            List <string> outVarList = new List <string>();

            if (outputs != string.Empty)
            {
                try { outVarList = outputs.Split(',').Select(x => x.Trim()).ToList(); }
                catch { }
            }

            var start = DateTime.Now;

            try
            {
                switch (language)
                {
                case ScriptingLanguage.JavaScript:

                    switch (jsEngine.ToLower())
                    {
                    case "jint":
                        InvokeJint();
                        break;

                    case "noesis":
                        InvokeNoesis();
                        break;

                    default:
                        InvokeJint();
                        break;
                    }

                    void InvokeNoesis()
                    {
                        var taskExecuteJs = Task.Run(() =>
                        {
                            object jsRetValue  = null;
                            bool disposeEngine = false;

                            JavascriptContext context = null;

                            if (disposeEngine = data.JsEngine == null)
                            {
                                context = new JavascriptContext();
                                JsEngine.SetParameter(context, data);
                            }
                            else
                            {
                                context = data.JsEngine.GetOrCreateEngine(data);
                            }

                            // Execute JS
                            try
                            {
                                jsRetValue = context.Run(script);
                            }
                            catch (JavascriptException ex)
                            {
                                throw new Exception($"Executing js error {ex.Message}\nline: {ex.Line}\nStart column:{ex.StartColumn}");
                            }

                            // Print results to log
                            data.Log(new LogEntry($"DEBUG LOG: {sw}", Colors.White));

                            // Get variables out
                            data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                            foreach (var name in outVarList)
                            {
                                try
                                {
                                    //Add it to the variables and print info
                                    var value   = context.GetParameter(name);
                                    var isArray = value.GetType().IsArray || value is string[] || value.GetType().Name.Contains("Dictionary");
                                    if (isArray)
                                    {
                                        try { data.Variables.Set(new CVar(name, CVar.VarType.List, (List <string>)value)); } catch (Exception ex) { data.Log(new LogEntry("[SET VARS] ERROR: " + ex.Message, Colors.Yellow)); }
                                    }
                                    else
                                    {
                                        data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString()));
                                    }

                                    data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow));
                                }
                                catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                            }
                            if (disposeEngine)
                            {
                                context.Dispose();
                            }

                            //Print other info
                            if (jsRetValue != null && !jsRetValue.GetType().Name.Contains("Dictionary"))
                            {
                                data.Log(new LogEntry($"Return value: {jsRetValue}", Colors.White));
                            }
                        });

                        taskExecuteJs.Wait();
                        taskExecuteJs.Dispose();
                    }

                    void InvokeJint()
                    {
                        // Redefine log() function
                        var jsEngine = new Jint.Engine().SetValue("log", new Action <object>(Console.WriteLine));

                        // Add in all the variables
                        foreach (var variable in data.Variables.All)
                        {
                            try
                            {
                                switch (variable.Type)
                                {
                                case CVar.VarType.List:
                                    jsEngine.SetValue(variable.Name, (variable.Value as List <string>).ToArray());
                                    break;

                                default:
                                    jsEngine.SetValue(variable.Name, variable.Value.ToString());
                                    break;
                                }
                            }
                            catch { }
                        }

                        // Execute JS
                        jsEngine.Execute(script);

                        // Print results to log
                        data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White));

                        // Get variables out
                        data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                        foreach (var name in outVarList)
                        {
                            try
                            {
                                // Add it to the variables and print info
                                var value   = jsEngine.Global.GetProperty(name).Value;
                                var isArray = value.IsArray();
                                if (isArray)
                                {
                                    data.Variables.Set(new CVar(name, CVar.VarType.List, value.TryCast <List <string> >()));
                                }
                                else
                                {
                                    data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString()));
                                }
                                data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value.ToString()}", Colors.Yellow));
                            }
                            catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                        }

                        // Print other info
                        if (jsEngine.GetCompletionValue() != null)
                        {
                            data.Log(new LogEntry($"Completion value: {jsEngine.GetCompletionValue()}", Colors.White));
                        }
                    }

                    break;

                case ScriptingLanguage.IronPython:

                    // Initialize the engine
                    var runtime  = Python.CreateRuntime();
                    var pyengine = runtime.GetEngine("py");
                    PythonCompilerOptions pco = (PythonCompilerOptions)pyengine.GetCompilerOptions();
                    pco.Module &= ~ModuleOptions.Optimized;
                    //var pyengine = Python.CreateEngine();
                    var scope = pyengine.CreateScope();
                    var code  = pyengine.CreateScriptSourceFromString(script);

                    // Add in all the variables
                    foreach (var variable in data.Variables.All)
                    {
                        try { scope.SetVariable(variable.Name, variable.Value); } catch { }
                    }

                    // Execute it
                    var result = code.Execute(scope);
                    //var result = pyengine.Execute(script, scope);

                    // Print the logs
                    data.Log(new LogEntry($"DEBUG LOG: {sw}", Colors.White));

                    // Get variables out
                    data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                    foreach (var name in outVarList)
                    {
                        try
                        {
                            // Add it to the variables and print info
                            var value = scope.GetVariable(name);
                            data.Variables.Set(new CVar(name, (value.GetType() == typeof(string[])) ? CVar.VarType.List : CVar.VarType.Single, value.ToString()));
                            data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow));
                        }
                        catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                    }

                    // Print other info
                    if (result != null)
                    {
                        data.Log(new LogEntry($"Completion value: {result}", Colors.White));
                    }

                    break;

                default:
                    break;
                }

                data.Log(new LogEntry($"Execution completed in {(DateTime.Now - start).TotalSeconds} seconds", Colors.GreenYellow));
            }
            catch (Exception e)
            {
                data.Log(new LogEntry($"[ERROR] INFO: {e.Message}", Colors.White));
            }
            finally
            {
                var standardOutput = new StreamWriter(Console.OpenStandardOutput());
                var standardError  = new StreamWriter(Console.OpenStandardError());
                standardOutput.AutoFlush = true;
                standardError.AutoFlush  = true;
                Console.SetOut(standardOutput);
                Console.SetError(standardError);
            }
        }
Example #18
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)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                var userMessage = activity.Text;

                StateClient stateClient = activity.GetStateClient();
                BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                // Set greeting
                string output = "Hello! What can I do for you?";
                if ((!userData.GetProperty <bool>("SetAppointmentWaiting")) && (!userData.GetProperty <bool>("SetUserWaiting")))
                {
                    if (userData.GetProperty <bool>("Greeting"))
                    {
                        output = "Hello again! What can I do for you?";
                    }
                    else
                    {
                        userData.SetProperty <bool>("Greeting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                }


                if (userData.GetProperty <bool>("ImageWaiting"))
                {
                    VisionServiceClient VisionServiceClient = new VisionServiceClient("72eb5e0c1cdb41b380e77b67c1797b81");

                    AnalysisResult analysisResult = await VisionServiceClient.DescribeAsync(activity.Attachments[0].ContentUrl, 3);

                    string visionReply = $"{analysisResult.Description.Captions[0].Text}";
                    if (visionReply.ToLower().Contains("coin"))
                    {
                        userData.SetProperty <bool>("ImageWaiting", false);
                        userData.SetProperty <bool>("ImageYesOrNoWaiting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity reply1 = activity.CreateReply($"Your image shows: {visionReply}. Is your request money related?");
                        await connector.Conversations.ReplyToActivityAsync(reply1);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        userData.SetProperty <bool>("ImageWaiting", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity reply1 = activity.CreateReply($"Your image shows: {visionReply}. Sorry it's not related to our bank service.");
                        await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userData.GetProperty <bool>("ImageYesOrNoWaiting"))
                {
                    if (userMessage.ToLower() == "yes")
                    {
                        output = "You answered yes! Tell me more about your appointment please:";
                        userData.SetProperty <bool>("ImageYesOrNoWaiting", false);
                        userData.SetProperty <bool>("SetAppointmentWaiting", true);
                        userData.SetProperty <string>("RequestType", "Money");
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    else
                    {
                        output = "You answered no! Tell me more about your appointment please:";
                        userData.SetProperty <bool>("ImageYesOrNoWaiting", false);
                        userData.SetProperty <bool>("SetAppointmentWaiting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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


                //HttpClient LUISClient = new HttpClient();
                //string LUISReply = await LUISClient.GetStringAsync();

                if (userData.GetProperty <bool>("SetAppointmentWaiting"))
                {
                    userData.SetProperty <bool>("SetAppointmentWaiting", false);
                    userData.SetProperty <bool>("SetAppointment", true);
                    userData.SetProperty <string>("RequestDescription", userMessage);
                    if (userData.GetProperty <string>("RequestType") == "")
                    {
                        userData.SetProperty <string>("RequestType", "General");
                    }

                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    output = "We have received your appointment, do you want to save it?";
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userData.GetProperty <bool>("SetAppointment"))
                {
                    if (userMessage.ToLower() == "yes")
                    {
                        output = "You answered yes! Appointment is saved.";
                        // save appointment to database
                        ServiceRequest request = new ServiceRequest();
                        request.UserId             = userData.GetProperty <string>("UserId");
                        request.RequestDescription = userData.GetProperty <string>("RequestDescription");
                        request.ServiceType        = userData.GetProperty <string>("RequestType");
                        await AzureManager.AzureManagerInstace.SetRequest(request);

                        userData.SetProperty <bool>("SetAppointment", false);
                        userData.SetProperty <string>("RequestDescription", "");
                        userData.SetProperty <string>("RequestType", "");
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    else
                    {
                        output = "You answered no! Appointment is not saved.";
                        userData.SetProperty <bool>("SetAppointment", false);
                        userData.SetProperty <string>("RequestDescription", "");
                        userData.SetProperty <string>("RequestType", "");
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userData.GetProperty <bool>("CurrencyWaiting"))
                {
                    string     baseCurrency    = userMessage.Split(' ')[0];
                    string     compareCurrency = userMessage.Split(' ')[1];
                    HttpClient client          = new HttpClient();
                    string     x = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + baseCurrency + "&symbols=" + compareCurrency));

                    Currency.RootObject rootObject;
                    rootObject = JsonConvert.DeserializeObject <Currency.RootObject>(x);
                    double rate = -1;
                    switch (compareCurrency)
                    {
                    case "AUD":
                        rate = rootObject.rates.AUD;
                        break;

                    case "GBP":
                        rate = rootObject.rates.GBP;
                        break;

                    case "EUR":
                        rate = rootObject.rates.EUR;
                        break;

                    case "CAD":
                        rate = rootObject.rates.CAD;
                        break;

                    case "USD":
                        rate = rootObject.rates.USD;
                        break;

                    default:
                        rate = -1;
                        break;
                    }
                    userData.SetProperty <bool>("CurrencyWaiting", false);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    output = $"1 {rootObject.@base} = {rate} {compareCurrency} ";
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userMessage.ToLower().Contains("image"))
                {
                    userData.SetProperty <bool>("ImageWaiting", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    output = "Please upload an image:";
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userMessage.ToLower().Contains("appointment"))
                {
                    //output = "appointment?";
                    //userData.GetProperty<bool>("SetAppointment")
                    if (userData.GetProperty <bool>("SetUser"))
                    {
                        if (!userData.GetProperty <bool>("SetAppointment"))
                        {
                            output = "Please tell me about your appointment please:";
                            userData.SetProperty <bool>("SetAppointmentWaiting", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        else
                        {
                            // save appointment
                            ServiceRequest request = new ServiceRequest();
                            request.UserId             = userData.GetProperty <string>("UserId");
                            request.RequestDescription = userData.GetProperty <string>("RequestDescription");
                            await AzureManager.AzureManagerInstace.SetRequest(request);

                            output = "Appointment is saved.";
                            Activity reply1 = activity.CreateReply(output);
                            await connector.Conversations.ReplyToActivityAsync(reply1);

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }
                    else
                    {
                        output = "Please tell me your full name please:";
                        userData.SetProperty <bool>("SetUserWaiting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity reply1 = activity.CreateReply(output);
                        await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userMessage.ToLower().Contains("name"))
                {
                    if (userData.GetProperty <bool>("SetUserWaiting"))
                    {
                        string name = userMessage;

                        userData.SetProperty <string>("FirstName", name.Split(' ')[name.Split(' ').Length - 2]);
                        userData.SetProperty <string>("LastName", name.Split(' ')[name.Split(' ').Length - 1]);
                        userData.SetProperty <string>("UserName", name.Split(' ')[name.Split(' ').Length - 2] + name.Split(' ')[name.Split(' ').Length - 1]);
                        //await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        List <User> userinfo = await AzureManager.AzureManagerInstace.GetUsers(userData.GetProperty <string>("UserName"));

                        if (userinfo.Count > 0)
                        {
                            userData.SetProperty <string>("UserId", userinfo[0].ID);
                            userData.SetProperty <bool>("SetUserWaiting", false);
                            userData.SetProperty <bool>("SetUser", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            output = $"Hey, {userData.GetProperty<string>("FirstName")} {userData.GetProperty<string>("LastName")}!";
                            Activity cardToConversation = activity.CreateReply(output);
                            cardToConversation.Recipient   = activity.From;
                            cardToConversation.Type        = "message";
                            cardToConversation.Attachments = new List <Attachment>();
                            List <CardImage> cardImages = new List <CardImage>();
                            cardImages.Add(new CardImage(url: "http://www.drawinghowtodraw.com/drawing-lessons/drawing-animals-creatures-lessons/images/howtodrawducksdrawinglessons_html_5f6ac075.png"));
                            List <CardAction> cardButtons = new List <CardAction>();
                            CardAction        cardButton  = new CardAction()
                            {
                                Value = "http://google.com",
                                Type  = "openUrl",
                                Title = "user name"
                            };
                            cardButtons.Add(cardButton);
                            ThumbnailCard Card = new ThumbnailCard()
                            {
                                Title = $"{userData.GetProperty<string>("FirstName")}'s Info",
                                //Subtitle = userinfo[0].ToString(),
                                Images = cardImages,
                                //Buttons = cardButtons,
                                Text = userinfo[0].Gender + " " + userinfo[0].Email + " " + userinfo[0].IpAddress
                            };
                            Attachment oneAttachment = Card.ToAttachment();
                            cardToConversation.Attachments.Add(oneAttachment);
                            await connector.Conversations.SendToConversationAsync(cardToConversation);

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                        else
                        {
                            output = "No matching name from our database, please try again.";
                            Activity reply1 = activity.CreateReply(output);
                            await connector.Conversations.ReplyToActivityAsync(reply1);

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }
                    if (userData.GetProperty <bool>("SetUser"))
                    {
                        List <User> userinfo = await AzureManager.AzureManagerInstace.GetUsers(userData.GetProperty <string>("UserName"));

                        output = $"Hey, {userData.GetProperty<string>("FirstName")} {userData.GetProperty<string>("LastName")}!";
                        Activity cardToConversation = activity.CreateReply(output);
                        cardToConversation.Recipient   = activity.From;
                        cardToConversation.Type        = "message";
                        cardToConversation.Attachments = new List <Attachment>();
                        List <CardImage> cardImages = new List <CardImage>();
                        cardImages.Add(new CardImage(url: "http://www.drawinghowtodraw.com/drawing-lessons/drawing-animals-creatures-lessons/images/howtodrawducksdrawinglessons_html_5f6ac075.png"));
                        List <CardAction> cardButtons = new List <CardAction>();
                        CardAction        cardButton  = new CardAction()
                        {
                            Value = "http://google.com",
                            Type  = "openUrl",
                            Title = "user name"
                        };
                        cardButtons.Add(cardButton);
                        ThumbnailCard Card = new ThumbnailCard()
                        {
                            Title = $"{userData.GetProperty<string>("FirstName")}'s Info",
                            //Subtitle = userinfo[0].ToString(),
                            Images = cardImages,
                            //Buttons = cardButtons,
                            Text = userinfo[0].Gender + " " + userinfo[0].Email + " " + userinfo[0].IpAddress
                        };
                        Attachment oneAttachment = Card.ToAttachment();
                        cardToConversation.Attachments.Add(oneAttachment);
                        await connector.Conversations.SendToConversationAsync(cardToConversation);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        output = "Please tell me your full name please:";
                        userData.SetProperty <bool>("SetUserWaiting", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity reply1 = activity.CreateReply(output);
                        await connector.Conversations.ReplyToActivityAsync(reply1);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    //else
                    //{
                    //    userData.SetProperty<bool>("SetUserWaiting", true);
                    //    userData.SetProperty<bool>("SetUser", false);
                    //    output = "Please tell me your full name please?";
                    //}
                }

                if (userMessage.ToLower().Contains("clear"))
                {
                    output = "User Info is cleared!";
                    userData.SetProperty <bool>("SetUserWaiting", false);
                    userData.SetProperty <bool>("SetUser", false);
                    userData.SetProperty <string>("FirstName", "");
                    userData.SetProperty <string>("LastName", "");
                    userData.SetProperty <string>("UserName", "");
                    userData.SetProperty <string>("UserId", "");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                if (userMessage.ToLower().Contains("currency"))
                {
                    userData.SetProperty <bool>("CurrencyWaiting", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    output = "Could you tell us the two currencies please?";
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                Stock.RootObject rootObjectLUIS = await GetEntityFromLUIS(userMessage);

                if (rootObjectLUIS.topScoringIntent.intent != "None")
                {
                    switch (rootObjectLUIS.topScoringIntent.intent)
                    {
                    case "StockPrice":
                        output = await GetStock(rootObjectLUIS.entities[0].entity);

                        break;

                    case "StockPrice2":
                        output = await GetStock(rootObjectLUIS.entities[0].entity);

                        break;

                    default:
                        break;
                    }
                    Activity reply1 = activity.CreateReply(output);
                    await connector.Conversations.ReplyToActivityAsync(reply1);

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

                Activity reply = activity.CreateReply(output);

                //List<User> users = await AzureManager.AzureManagerInstace.GetUsers();
                //Activity reply = activity.CreateReply($"{users[0].LastName}");

                // return our reply to the user
                //Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #19
0
        public async Task <Checker> BuildAsync()
        {
            var quickBulletSettings = JsonConvert.DeserializeObject <QuickBulletSettings>(File.ReadAllText(settingsFile));

            var loliScriptManager = new LoliScriptManager();

            (var configSettings, var blocks) = loliScriptManager.Build(_configFile);

            if (string.IsNullOrEmpty(configSettings.Name))
            {
                configSettings.Name = Path.GetFileNameWithoutExtension(_configFile);
            }

            if (!string.IsNullOrEmpty(configSettings.AdditionalInfo))
            {
                AnsiConsole.MarkupLine($"[grey]CONFIG INFO:[/] {configSettings.AdditionalInfo}");
            }

            if (configSettings.CustomInputs.Any())
            {
                AnsiConsole.Write(new Rule("[darkorange]Custom input[/]").RuleStyle("grey").LeftAligned());

                foreach (var customInput in configSettings.CustomInputs)
                {
                    customInput.Value = AnsiConsole.Ask <string>($"{customInput.Description}:");
                }
            }

            var botInputs = File.ReadAllLines(_wordlistFile).Where(w => !string.IsNullOrEmpty(w)).Select(w => new BotInput(w));

            if (configSettings.InputRules.Any())
            {
                botInputs = botInputs.Where(b => configSettings.InputRules.All(i => _checkInputRuleFunctions[i.Name].Invoke(b, i)));
            }

            var useProxy = _proxies.Any();

            var proxyHttpClients = _proxies.Any() ? new List <ProxyHttpClient>(_proxies.Select(p => BuildProxy(p, _proxyType)).Select(p => new ProxyHttpClient(new HttpClientHandler()
            {
                UseCookies = false, Proxy = p
            }, p)
            {
                Timeout = TimeSpan.FromSeconds(15)
            })) : new List <ProxyHttpClient>()
            {
                new ProxyHttpClient(new HttpClientHandler()
                {
                    UseCookies = false
                }, null)
                {
                    Timeout = TimeSpan.FromSeconds(15)
                }
            };

            var proxyHttpClientManager = new ProxyHttpClientManager(proxyHttpClients);

            if (useProxy)
            {
                _ = proxyHttpClientManager.StartValidateAllProxiesAsync();
            }

            var record = GetRecord(configSettings.Name);

            Directory.CreateDirectory(Path.Combine(quickBulletSettings.OutputDirectory, configSettings.Name));

            var skip = _skip == -1 ? record.Progress : _skip;

            var checkerStats = new CheckerStats(skip)
            {
                DegreeOfParallelism = _bots
            };

            var statusesToBreak   = new string[] { "toCheck", "failure", "retry", "ban", "error" };
            var statusesToRecheck = new string[] { "retry", "ban", "error" };

            var readerWriterLock = new ReaderWriterLock();

            var handler = new HttpClientHandler()
            {
                UseCookies = false
            };

            var httpClient = new HttpClient(handler)
            {
                Timeout = TimeSpan.FromSeconds(15)
            };

            var playwright = await Playwright.CreateAsync();

            Func <BotInput, CancellationToken, Task <bool> > check = new(async(input, cancellationToken) =>
            {
                BotData botData = null;

                for (var attempts = 0; attempts < 8; attempts++)
                {
                    var proxyHttpClient = proxyHttpClientManager.GetRandomProxyHttpClient();

                    botData = new BotData(quickBulletSettings, input, httpClient, proxyHttpClient, playwright)
                    {
                        UseProxy = useProxy
                    };

                    botData.Variables.Add("data.proxy", proxyHttpClient.Proxy is null ? string.Empty : proxyHttpClient.Proxy.ToString());

                    foreach (var customInput in configSettings.CustomInputs)
                    {
                        botData.Variables.Add(customInput.Name, customInput.Value);
                    }

                    foreach (var block in blocks)
                    {
                        try
                        {
                            await block.RunAsync(botData);
                        }
                        catch (HttpRequestException)
                        {
                            proxyHttpClient.IsValid = false;
                            botData.Variables["botStatus"] = "retry";
                        }
                        catch (Exception error)
                        {
                            if (error.Message.Contains("HttpClient.Timeout") || error.Message.Contains("ERR_TIMED_OUT"))
                            {
                                proxyHttpClient.IsValid = false;
                            }
                            else if (_verbose)
                            {
                                AnsiConsole.WriteException(error);
                            }
                            botData.Variables["botStatus"] = "retry";
                        }

                        if (statusesToBreak.Contains(botData.Variables["botStatus"], StringComparer.OrdinalIgnoreCase))
                        {
                            break;
                        }
                    }

                    await botData.DisposeAsync();

                    if (statusesToRecheck.Contains(botData.Variables["botStatus"], StringComparer.OrdinalIgnoreCase))
                    {
                        if (botData.Variables["botStatus"].Equals("ban", StringComparison.OrdinalIgnoreCase))
                        {
                            proxyHttpClient.IsValid = false;
                        }
                        checkerStats.Increment(botData.Variables["botStatus"]);
                    }
                    else
                    {
                        break;
                    }
                }

                var botStatus = statusesToRecheck.Contains(botData.Variables["botStatus"], StringComparer.OrdinalIgnoreCase) ? "tocheck" : botData.Variables["botStatus"].ToLower();

                if (botStatus.Equals("failure"))
                {
                    checkerStats.Increment(botData.Variables["botStatus"]);
                }
                else
                {
                    var outputPath = Path.Combine(quickBulletSettings.OutputDirectory, configSettings.Name, $"{botStatus}.txt");
                    var output = botData.Captures.Any() ? new StringBuilder().Append(botData.Input.ToString()).Append(quickBulletSettings.OutputSeparator).AppendJoin(quickBulletSettings.OutputSeparator, botData.Captures.Select(c => $"{c.Key} = {c.Value}")).ToString() : botData.Input.ToString();

                    try
                    {
                        readerWriterLock.AcquireWriterLock(int.MaxValue);
                        using var streamWriter = File.AppendText(outputPath);
                        await streamWriter.WriteLineAsync(output);
                    }
                    finally
                    {
                        readerWriterLock.ReleaseWriterLock();
                    }

                    switch (botStatus)
                    {
                    case "success":
                        AnsiConsole.MarkupLine($"[green4]SUCCESS:[/] {output}");
                        break;

                    case "tocheck":
                        AnsiConsole.MarkupLine($"[cyan3]TOCHECK:[/] {output}");
                        break;

                    default:
                        AnsiConsole.MarkupLine($"[orange3]{botStatus.ToUpper()}:[/] {output}");
                        break;
                    }

                    checkerStats.Increment(botStatus);
                }

                checkerStats.Increment("checked");

                return(true);
            });

            var paradllelizer = ParallelizerFactory <BotInput, bool> .Create(type : ParallelizerType.TaskBased, workItems : botInputs, workFunction : check, degreeOfParallelism : _bots, totalAmount : botInputs.Skip(skip).Count(), skip : skip);

            return(new Checker(paradllelizer, checkerStats, record));
        }
Example #20
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)
            {
                var dbContext = new Model1();

                ConnectorClient connector            = new ConnectorClient(new Uri(activity.ServiceUrl));
                StateClient     sc                   = activity.GetStateClient();
                BotData         userData             = sc.BotState.GetPrivateConversationData(activity.ChannelId, activity.Conversation.Id, activity.From.Id);
                var             userSelectedLanguage = userData.GetProperty <string>("Language");
                var             userSelectedCity     = userData.GetProperty <string>("City");

                var guid = userData.GetProperty <string>("ApartmantId");
                if (string.IsNullOrEmpty(userSelectedLanguage))
                {
                    await Conversation.SendAsync(activity, MakeRootDialog);
                }
                else if (activity.Text == "/deleteprofile")
                {
                    activity.GetStateClient().BotState.DeleteStateForUser(activity.ChannelId, activity.From.Id);
                }
                else
                {
                    var userCity              = userData.GetProperty <string>("City");
                    var userAddress           = userData.GetProperty <string>("Address");
                    var googleApi             = new GoogleTranslateService();
                    var location              = googleApi.GetLocationFromAddress(userAddress + "," + userCity);
                    var administrationService = new AdministrationService();
                    var possibleLocations     = administrationService.GetPossibleLocations(location);
                    if (possibleLocations.FirstOrDefault(x => x.ApartmentId.ToString() == activity.Text) == null && string.IsNullOrEmpty(guid))
                    {
                        if (possibleLocations.Count > 0)
                        {
                            userData.SetProperty <string>("ApartmantId", "IdComming");
                            sc.BotState.SetPrivateConversationData(activity.ChannelId, activity.Conversation.Id, activity.From.Id, userData);

                            Activity replyToConversation = activity.CreateReply(GetTextInSelectedLanguage("Please select your place", userSelectedLanguage));
                            replyToConversation.Recipient   = activity.From;
                            replyToConversation.Type        = "message";
                            replyToConversation.Attachments = new List <Attachment>();

                            List <CardAction> cardButtons = new List <CardAction>();
                            foreach (var button in possibleLocations)
                            {
                                CardAction plButton = new CardAction()
                                {
                                    Value = button.ApartmentId.ToString(),
                                    Type  = "imBack",
                                    Title = button.Name
                                };
                                cardButtons.Add(plButton);
                            }

                            HeroCard plCard = new HeroCard()
                            {
                                Title   = GetTextInSelectedLanguage("Press the button with your accomodation", userSelectedLanguage),
                                Buttons = cardButtons
                            };
                            Attachment plAttachment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttachment);
                            await connector.Conversations.SendToConversationAsync(replyToConversation);


                            await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        else
                        {
                            var      responseText            = GetTextInSelectedLanguage("Sorry, havn't found anything. Try again", userSelectedLanguage);
                            Activity replyToSelectedApartmen = activity.CreateReply($"{responseText}");
                            await connector.Conversations.ReplyToActivityAsync(replyToSelectedApartmen);
                        }
                    }
                    else if (guid == "IdComming")
                    {
                        userData.SetProperty <string>("ApartmantId", activity.Text);
                        guid = activity.Text;
                        sc.BotState.SetPrivateConversationData(activity.ChannelId, activity.Conversation.Id, activity.From.Id, userData);
                        //    await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        var      responseText            = GetTextInSelectedLanguage("Go ahed and ask me something", userSelectedLanguage);
                        Activity replyToSelectedApartmen = activity.CreateReply($"{responseText}");
                        await connector.Conversations.ReplyToActivityAsync(replyToSelectedApartmen);
                    }
                    else
                    {
                        var tokenizedText = googleApi.SentanceDetect(GetTextInEng(activity.Text, userSelectedLanguage));
                        var resText       = administrationService.GetResponeseToQuery(tokenizedText, guid);
                        if (resText != null)
                        {
                            Activity reply = activity.CreateReply($"{resText.Answer}");
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                        else
                        {
                            var      responseText = GetTextInSelectedLanguage("Sorry, have not found anything. Try again", userSelectedLanguage);
                            Activity reply        = activity.CreateReply($"{responseText}");
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }

            return(new HttpResponseMessage());
        }
        /// <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)
            {
                Activity        reply        = activity.CreateReply("Hi! I am the most AMAAAAZING bot of Xizhe Contoso Bank. You can ask me to help you register, check balance, deposit, withdraw or suspend your account. Oh and don't forget I can also check the exchange rate for you. So if you need anything, just come and have a chat with me :)");
                ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                string          manualIntent = "";

                //grabbing state-------------------------------------------------------------------------------------------------------
                StateClient stateClient = activity.GetStateClient();
                BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                if (userData.GetProperty <bool>("loggedIn"))
                {
                    if (DateTime.Compare(userData.GetProperty <DateTime>("loggedOnExpiryTime"), DateTime.Now) > 0)
                    {
                        userData.SetProperty <bool>("loggedin", false);
                    }
                }
                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);


                //clearing user data-------------------------------------------------------------------------------------------------------
                if (activity.Text.ToLower().Contains("clear"))
                {
                    reply = activity.CreateReply("You user data have been cleared");
                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                    await connector.Conversations.ReplyToActivityAsync(reply);

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

                //accessing easytable-------------------------------------------------------------------------------------------------------

                List <xizhesContosoBank> rootObjectList = await AzureManager.AzureManagerInstance.GetxizhesContosoBanks();

                //authorization

                if (userData.GetProperty <bool>("loggingInUserName"))
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("loggingInUserName", false);
                    userData.SetProperty <bool>("loggingInPassword", true);
                    userData.SetProperty <string>("logInUsername", activity.Text);
                    reply = activity.CreateReply("...and your password please? Don't worry I promise I won't steal it~~");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    await connector.Conversations.ReplyToActivityAsync(reply);

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

                if (userData.GetProperty <bool>("loggingInPassword"))
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("loggingInPassword", false);
                    userData.SetProperty <string>("logInPassword", activity.Text);

                    string loggingInUsername = userData.GetProperty <string>("logInUsername");
                    string loggingInPassword = userData.GetProperty <string>("logInPassword");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    reply = activity.CreateReply("Username or password incorrect, try again!");
                    for (int i = 0; i < rootObjectList.Count(); i++)
                    {
                        if (loggingInUsername == rootObjectList[i].userName && loggingInPassword == rootObjectList[i].password)
                        {
                            userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                            userData.SetProperty <bool>("loggedin", true);
                            userData.SetProperty <DateTime>("loggedOnExpiryTime", DateTime.Now.AddMinutes(25));
                            userData.SetProperty <string>("loggedInUserName", loggingInUsername);
                            reply = activity.CreateReply("You are logged on, to log out, enter 'clear'");
                        }
                    }

                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    await connector.Conversations.ReplyToActivityAsync(reply);

                    if (userData.GetProperty <bool>("wantWithdraw"))
                    {
                        manualIntent = "withdraw";
                    }

                    if (userData.GetProperty <bool>("wantDeposit"))
                    {
                        manualIntent = "deposit";
                    }

                    if (userData.GetProperty <bool>("wantView"))
                    {
                        manualIntent = "view";
                    }

                    if (userData.GetProperty <bool>("wantSuspend"))
                    {
                        manualIntent = "suspend";
                    }
                }

                //handling registration-------------------------------------------------------------------------------------------------------

                if (userData.GetProperty <bool>("registerReady"))
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("registerReady", false);
                    if (activity.Text == "Proceed")
                    {
                        xizhesContosoBank xizhesContosoBank = new xizhesContosoBank()
                        {
                            createdAt = DateTime.Now,
                            userName  = userData.GetProperty <string>("userName"),
                            password  = userData.GetProperty <string>("password"),
                            savings   = 0,
                            address   = userData.GetProperty <string>("address"),
                            phone     = userData.GetProperty <string>("phone"),
                        };

                        await AzureManager.AzureManagerInstance.AddxizhesContosoBank(xizhesContosoBank);

                        reply = activity.CreateReply("Your new account has been registered");
                        await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                        await connector.Conversations.ReplyToActivityAsync(reply);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    if (activity.Text == "Retry")
                    {
                        reply = activity.CreateReply("Please try again");
                        await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                        await connector.Conversations.ReplyToActivityAsync(reply);

                        manualIntent = "register";
                    }
                    if (activity.Text == "Cancel")
                    {
                        reply = activity.CreateReply("Your registration has been cancelled");
                        await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                        await connector.Conversations.ReplyToActivityAsync(reply);

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

                if (userData.GetProperty <bool>("registerUserName"))
                {
                    bool repeatedUsername = false;
                    for (int i = 0; i < rootObjectList.Count; i++)
                    {
                        if (rootObjectList[i].userName == activity.Text)
                        {
                            repeatedUsername = true;
                        }
                    }

                    if (repeatedUsername == false)
                    {
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("registerUserName", false);
                        userData.SetProperty <bool>("registerPassword", true);
                        userData.SetProperty <string>("userName", activity.Text);
                        reply = activity.CreateReply("Please enter a new password");
                    }
                    else
                    {
                        reply = activity.CreateReply("Sorry this username has been taken, please try another one.");
                    }
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    await connector.Conversations.ReplyToActivityAsync(reply);

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

                if (userData.GetProperty <bool>("registerPassword"))
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("registerPassword", false);
                    userData.SetProperty <bool>("registerAddress", true);
                    userData.SetProperty <string>("password", activity.Text);
                    reply = activity.CreateReply("Please enter a new address");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    await connector.Conversations.ReplyToActivityAsync(reply);

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

                if (userData.GetProperty <bool>("registerAddress"))
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("registerAddress", false);
                    userData.SetProperty <bool>("registerPhone", true);
                    userData.SetProperty <string>("address", activity.Text);
                    reply = activity.CreateReply("Please enter a new phone number");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    await connector.Conversations.ReplyToActivityAsync(reply);

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

                if (userData.GetProperty <bool>("registerPhone"))
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("registerPhone", false);
                    userData.SetProperty <string>("phone", activity.Text);
                    userData.SetProperty <bool>("registerReady", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    string userName = userData.GetProperty <string>("userName");
                    string password = userData.GetProperty <string>("password");
                    string address  = userData.GetProperty <string>("address");
                    string phone    = userData.GetProperty <string>("phone");

                    Activity replyToConversation = activity.CreateReply();
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardAction> cardButtons   = new List <CardAction>();
                    CardAction        proceedButton = new CardAction()
                    {
                        Value = "Proceed",
                        Type  = "postBack",
                        Title = "Proceed",
                    };
                    cardButtons.Add(proceedButton);

                    CardAction retryButton = new CardAction()
                    {
                        Value = "Retry",
                        Type  = "postBack",
                        Title = "Retry"
                    };
                    cardButtons.Add(retryButton);

                    CardAction cancelButton = new CardAction()
                    {
                        Value = "Cancel",
                        Type  = "postBack",
                        Title = "Cancel"
                    };
                    cardButtons.Add(cancelButton);

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://s16.postimg.org/ffpktvf91/Logomakr_3x_VQy_D.png"));

                    HeroCard plCard = new HeroCard()
                    {
                        Title   = "Confirmation",
                        Text    = $"Username: {userName}  \nPassword: {password}  \nAddress: {address}  \nPhone: {phone}",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);

                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                //handling deposit-------------------------------------------------------------------------------------------------------
                if (userData.GetProperty <bool>("depositing"))
                {
                    double amount;
                    bool   isDouble = double.TryParse(activity.Text, out amount);
                    if (!isDouble)
                    {
                        reply = activity.CreateReply("Invalid amount, please enter a valid number");
                        await connector.Conversations.ReplyToActivityAsync(reply);

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

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("depositing", false);
                    userData.SetProperty <double>("depositAmount", amount);
                    userData.SetProperty <bool>("depositReady", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    Activity replyToConversation = activity.CreateReply();
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardAction> cardButtons   = new List <CardAction>();
                    CardAction        proceedButton = new CardAction()
                    {
                        Value = "Proceed",
                        Type  = "postBack",
                        Title = "Proceed",
                    };
                    cardButtons.Add(proceedButton);

                    CardAction cancelButton = new CardAction()
                    {
                        Value = "Cancel",
                        Type  = "postBack",
                        Title = "Cancel"
                    };
                    cardButtons.Add(cancelButton);

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://s16.postimg.org/ffpktvf91/Logomakr_3x_VQy_D.png"));

                    HeroCard plCard = new HeroCard()
                    {
                        Title   = "Confirmation",
                        Text    = $"You want to deposit ${amount.ToString()}",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);

                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                if (userData.GetProperty <bool>("depositReady"))
                {
                    if (activity.Text == "Proceed")
                    {
                        xizhesContosoBank rootObject = null;

                        for (int i = 0; i < rootObjectList.Count(); i++)
                        {
                            if (userData.GetProperty <string>("loggedInUserName") == rootObjectList[i].userName)
                            {
                                rootObject = rootObjectList[i];
                            }
                        }

                        if (rootObject != null)
                        {
                            rootObject.savings += userData.GetProperty <double>("depositAmount");
                            await AzureManager.AzureManagerInstance.UpdatexizhesContosoBank(rootObject);

                            userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                            userData.SetProperty <bool>("depositReady", false);
                            reply = activity.CreateReply($"Deposit suceeded, you now have ${rootObject.savings}");
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            await connector.Conversations.ReplyToActivityAsync(reply);

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                        else
                        {
                            reply = activity.CreateReply("Error, please contact the bank directly.");
                        }
                    }
                    else if (activity.Text == "Cancel")
                    {
                        reply = activity.CreateReply("Your deposit has been cancelled");
                        await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                        await connector.Conversations.ReplyToActivityAsync(reply);

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

                //handling withdraw-------------------------------------------------------------------------------------------------------
                if (userData.GetProperty <bool>("withdrawing"))
                {
                    double amount;
                    bool   isDouble = double.TryParse(activity.Text, out amount);
                    if (!isDouble)
                    {
                        reply = activity.CreateReply("Invalid amount, please enter a valid number");
                        await connector.Conversations.ReplyToActivityAsync(reply);

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

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("withdrawing", false);
                    userData.SetProperty <double>("withdrawAmount", amount);
                    userData.SetProperty <bool>("withdrawReady", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    Activity replyToConversation = activity.CreateReply();
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardAction> cardButtons   = new List <CardAction>();
                    CardAction        proceedButton = new CardAction()
                    {
                        Value = "Proceed",
                        Type  = "postBack",
                        Title = "Proceed",
                    };
                    cardButtons.Add(proceedButton);

                    CardAction cancelButton = new CardAction()
                    {
                        Value = "Cancel",
                        Type  = "postBack",
                        Title = "Cancel"
                    };
                    cardButtons.Add(cancelButton);

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://s16.postimg.org/ffpktvf91/Logomakr_3x_VQy_D.png"));

                    HeroCard plCard = new HeroCard()
                    {
                        Title   = "Confirmation",
                        Text    = $"You want to withdraw ${amount.ToString()}",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);

                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                if (userData.GetProperty <bool>("withdrawReady"))
                {
                    if (activity.Text == "Proceed")
                    {
                        xizhesContosoBank rootObject = null;

                        for (int i = 0; i < rootObjectList.Count(); i++)
                        {
                            if (userData.GetProperty <string>("loggedInUserName") == rootObjectList[i].userName)
                            {
                                rootObject = rootObjectList[i];
                            }
                        }

                        if (rootObject != null)
                        {
                            rootObject.savings -= userData.GetProperty <double>("withdrawAmount");
                            await AzureManager.AzureManagerInstance.UpdatexizhesContosoBank(rootObject);

                            userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                            userData.SetProperty <bool>("withdrawReady", false);
                            reply = activity.CreateReply($"Withdrawal suceeded, you now have ${rootObject.savings} left in your account");
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                        else
                        {
                            reply = activity.CreateReply("Error, please contact the bank directly.");
                        }
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (activity.Text == "Cancel")
                    {
                        reply = activity.CreateReply("Your withdrawal has been cancelled");
                        await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                        await connector.Conversations.ReplyToActivityAsync(reply);

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

                //handling suspend-------------------------------------------------------------------------------------------------------
                if (userData.GetProperty <bool>("suspending"))
                {
                    if (activity.Text == "Suspend")
                    {
                        xizhesContosoBank rootObject = null;

                        for (int i = 0; i < rootObjectList.Count(); i++)
                        {
                            if (userData.GetProperty <string>("loggedInUserName") == rootObjectList[i].userName)
                            {
                                rootObject = rootObjectList[i];
                            }
                        }

                        await AzureManager.AzureManagerInstance.DeletexizhesContosoBank(rootObject);

                        reply = activity.CreateReply("Your account has been suspended.");
                        await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);
                    }
                    else if (activity.Text == "Cancel")
                    {
                        reply    = activity.CreateReply("Your suspend is cancelled.");
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("suspending", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    await connector.Conversations.ReplyToActivityAsync(reply);

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

                //interpret intent-------------------------------------------------------------------------------------------------------
                HttpClient luisClient   = new HttpClient();
                string     input        = System.Web.HttpUtility.UrlEncode(activity.Text);
                string     luisResponse = await luisClient.GetStringAsync(new Uri("https://api.projectoxford.ai/luis/v2.0/apps/2dbd88e3-96b5-4b48-91bd-2362f25f803f?subscription-key=fbeed415937941c4a78980f81acff101&q=" + input + "&verbose=true"));

                luisObject.RootObject luisRootObject = JsonConvert.DeserializeObject <luisObject.RootObject>(luisResponse);
                string intent = luisRootObject.topScoringIntent.intent;
                double score  = luisRootObject.topScoringIntent.score;

                if (manualIntent == "register")
                {
                    intent = "register";
                }

                if (manualIntent == "withdraw")
                {
                    intent = "withdraw";
                }

                if (manualIntent == "deposit")
                {
                    intent = "deposit";
                }

                if (manualIntent == "view")
                {
                    intent = "view";
                }

                if (manualIntent == "suspend")
                {
                    intent = "suspend";
                }

                //create, register-------------------------------------------------------------------------------------------------------
                if (intent == "register")
                {
                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("registerUserName", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    reply = activity.CreateReply("Please enter a new username");
                }

                //view-------------------------------------------------------------------------------------------------------
                if (intent == "view")
                {
                    if (!userData.GetProperty <bool>("loggedin"))
                    {
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("wantView", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        reply    = activity.CreateReply("Sure but you need to log on first, please enter your username");
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("loggingInUserName", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        await connector.Conversations.ReplyToActivityAsync(reply);

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

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("wantView", false);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    double savings = 0;
                    for (int i = 0; i < rootObjectList.Count(); i++)
                    {
                        if (userData.GetProperty <string>("loggedInUserName") == rootObjectList[i].userName)
                        {
                            savings = rootObjectList[i].savings;
                        }
                    }

                    Activity replyToConversation = activity.CreateReply();
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://s16.postimg.org/ffpktvf91/Logomakr_3x_VQy_D.png"));

                    List <CardAction> cardButtons   = new List <CardAction>();
                    CardAction        proceedButton = new CardAction()
                    {
                        Value = "Deposit",
                        Type  = "postBack",
                        Title = "Deposit",
                    };
                    cardButtons.Add(proceedButton);

                    CardAction cancelButton = new CardAction()
                    {
                        Value = "Withdraw",
                        Type  = "postBack",
                        Title = "Withdraw"
                    };
                    cardButtons.Add(cancelButton);

                    HeroCard plCard = new HeroCard()
                    {
                        Title   = "Account Balance",
                        Text    = $"You have ${savings} in your account",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                //withdraw-------------------------------------------------------------------------------------------------------
                if (intent == "withdraw")
                {
                    if (!userData.GetProperty <bool>("loggedin"))
                    {
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("wantWithdraw", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        reply    = activity.CreateReply("Sure but you need to log on first, please enter your username");
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("loggingInUserName", true);
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

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

                    xizhesContosoBank rootObject = null;

                    for (int i = 0; i < rootObjectList.Count(); i++)
                    {
                        if (userData.GetProperty <string>("loggedInUserName") == rootObjectList[i].userName)
                        {
                            rootObject = rootObjectList[i];
                        }
                    }

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("wantWithdraw", false);
                    userData.SetProperty <bool>("withdrawing", true);
                    reply = activity.CreateReply($"You have ${rootObject.savings} in your account, How much would you like to withdraw? Please specify an amount");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                }

                //deposit-------------------------------------------------------------------------------------------------------
                if (intent == "deposit")
                {
                    if (!userData.GetProperty <bool>("loggedin"))
                    {
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("wantDeposit", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        reply    = activity.CreateReply("Sure but you need to log on first, please enter your username");
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("loggingInUserName", true);
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

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

                    xizhesContosoBank rootObject = null;

                    for (int i = 0; i < rootObjectList.Count(); i++)
                    {
                        if (userData.GetProperty <string>("loggedInUserName") == rootObjectList[i].userName)
                        {
                            rootObject = rootObjectList[i];
                        }
                    }

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("wantDeposit", false);
                    userData.SetProperty <bool>("depositing", true);
                    reply = activity.CreateReply($"You have ${rootObject.savings} in your account, How much would you like to deposit? Please specify an amount");
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                }

                //suspend-------------------------------------------------------------------------------------------------------
                if (intent == "suspend")
                {
                    if (!userData.GetProperty <bool>("loggedin"))
                    {
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("wantSuspend", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        reply    = activity.CreateReply("Sure but you need to log on first, please enter your username");
                        userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                        userData.SetProperty <bool>("loggingInUserName", true);
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

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

                    userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                    userData.SetProperty <bool>("wantSuspend", false);
                    userData.SetProperty <bool>("suspending", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    Activity replyToConversation = activity.CreateReply();
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardAction> cardButtons   = new List <CardAction>();
                    CardAction        proceedButton = new CardAction()
                    {
                        Value = "Suspend",
                        Type  = "imBack",
                        Title = "Suspend"
                    };
                    cardButtons.Add(proceedButton);

                    CardAction cancelButton = new CardAction()
                    {
                        Value = "Cancel",
                        Type  = "imBack",
                        Title = "Cancel"
                    };
                    cardButtons.Add(cancelButton);

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://s16.postimg.org/ffpktvf91/Logomakr_3x_VQy_D.png"));

                    HeroCard plCard = new HeroCard()
                    {
                        Title   = "Confirmation",
                        Text    = $"Are you sure you want to suspend your account?",
                        Images  = cardImages,
                        Buttons = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                //currency-------------------------------------------------------------------------------------------------------
                if (intent == "currency")
                {
                    HttpClient currencyClient   = new HttpClient();
                    string     currencyResponse = await currencyClient.GetStringAsync(new Uri("http://api.fixer.io/latest?base=nzd"));

                    currencyObject.RootObject currency = JsonConvert.DeserializeObject <currencyObject.RootObject>(currencyResponse);

                    double AUD = currency.rates.AUD;
                    double CNY = currency.rates.CNY;
                    double USD = currency.rates.USD;
                    double EUR = currency.rates.EUR;

                    Activity replyToConversation = activity.CreateReply();
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://s16.postimg.org/ffpktvf91/Logomakr_3x_VQy_D.png"));

                    HeroCard plCard = new HeroCard()
                    {
                        Title  = "Exchange rate based on NZD",
                        Text   = $"AUD: {AUD}  \nCNY: {CNY}  \nEUR: {EUR}  \nUSD: {USD}",
                        Images = cardImages
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);

                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                //feedback---------------------------------------------------------------------------------------------------------
                if (intent == "feedback")
                {
                    var client = new HttpClient();

                    // Request headers
                    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "ef8666fa564644f19aad8532f3ca29c5");

                    var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";

                    HttpResponseMessage analyticsResponse;

                    using (var content = new StringContent("{\"documents\": [{\"language\": \"en\",\"id\": \"string\",\"text\": \"" + activity.Text + "\"}]}", Encoding.UTF8, "application/json"))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        analyticsResponse           = await client.PostAsync(uri, content);
                    }
                    string responseString = await analyticsResponse.Content.ReadAsStringAsync();

                    analyticsObject.RootObject analyticsObject = JsonConvert.DeserializeObject <analyticsObject.RootObject>(responseString);
                    if (analyticsObject.documents[0].score > 0.8)
                    {
                        reply = activity.CreateReply("Thank you for liking me! I will sure to be better and better! (Fun fact: I like you too you know? :))");
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (analyticsObject.documents[0].score < 0.3)
                    {
                        reply = activity.CreateReply("I am sorry for disappointing you, I will sure be improving myself and hope to become a better me :(");
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        reply = activity.CreateReply("Thank you for your feedback! I will sure to be working twice as hard to make you like me more!");
                        await connector.Conversations.ReplyToActivityAsync(reply);

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


                // return our reply to the user-------------------------------------------------------------------------------------------------------
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #22
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            switch (activity.Text)
            {
            case "/reset":
                activity.GetStateClient().BotState.DeleteStateForUser(activity.ChannelId, activity.From.Id);
                break;
            }

            BotIO      io       = new BotIO();
            ZMachine   zMachine = new ZMachine(io);
            string     gameFile = Environment.GetEnvironmentVariable("GameFile");
            string     path     = HostingEnvironment.MapPath($"~/Games/{gameFile}");
            FileStream fs       = File.OpenRead(path);

            zMachine.LoadFile(fs);

            BotData data = activity.GetStateClient().BotState.GetUserData(activity.ChannelId, activity.From.Id);

            byte[] state = data.GetProperty <byte[]>("ZState");
            try
            {
                if (state != null)
                {
                    using (MemoryStream ms = new MemoryStream(state))
                        zMachine.RestoreState(ms);
                    zMachine.FinishRead(activity.Text);
                }
            }
            catch (Exception)
            {
                activity.GetStateClient().BotState.DeleteStateForUser(activity.ChannelId, activity.From.Id);
            }

            zMachine.Run(true);
            Stream s = zMachine.SaveState();

            using (MemoryStream ms = new MemoryStream())
            {
                s.CopyTo(ms);
                data.SetProperty("ZState", ms.ToArray());
            }

            activity.GetStateClient().BotState.SetUserData(activity.ChannelId, activity.From.Id, data);

            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                // return our reply to the user
                Activity reply = activity.CreateReply(io.Text);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #23
0
        /// <summary>
        /// Executes a line of the script.
        /// </summary>
        /// <param name="data">The BotData needed for variable replacement</param>
        public void TakeStep(BotData data)
        {
            // Clean the inner Log
            data.LogBuffer.Clear();

            // TODO: Refactor this with a properly written policy
            // If we have a custom status without forced continue OR we have a status that is not NONE or SUCCESS or CUSTOM
            if ((data.Status == BotStatus.CUSTOM && !data.ConfigSettings.ContinueOnCustom) ||
                (data.Status != BotStatus.NONE && data.Status != BotStatus.SUCCESS && data.Status != BotStatus.CUSTOM))
            {
                i = lines.Count(); // Go to the end
                return;
            }

TAKELINE:

            CurrentLine = lines[i];

            // Skip comments and blank lines
            if (IsEmptyOrCommentOrDisabled(CurrentLine))
            {
                i++; // Go to the next
                goto TAKELINE;
            }

            // Lookahead to compact lines. We don't use CompressedLines to be able to provide the line number for errors
            var lookahead = 0;

            // Join the line with the following ones if it's indented
            while (i + 1 + lookahead < lines.Count())
            {
                var nextLine = lines[i + 1 + lookahead];
                if (nextLine.StartsWith(" ") || nextLine.StartsWith("\t"))
                {
                    CurrentLine += $" {nextLine.Trim()}";
                }
                else
                {
                    break;
                }

                lookahead++;
            }

            try
            {
                // If Block -> Process Block
                if (BlockParser.IsBlock(CurrentLine))
                {
                    BlockBase block = null;
                    try
                    {
                        block        = BlockParser.Parse(CurrentLine);
                        CurrentBlock = block.Label;
                        if (!block.Disabled)
                        {
                            block.Process(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        // We log the error message
                        data.LogBuffer.Add(new LogEntry("ERROR: " + ex.Message, Colors.Tomato));

                        // Stop the execution only if the block is vital for the execution of the script (requests)
                        // This way we prevent the interruption of the script and an endless retry cycle e.g. if we fail to parse a response given a specific input
                        if (block != null && (
                                block.GetType() == typeof(BlockRequest) ||
                                block.GetType() == typeof(BlockBypassCF) ||
                                block.GetType() == typeof(BlockImageCaptcha) ||
                                block.GetType() == typeof(BlockRecaptcha)))
                        {
                            data.Status = BotStatus.ERROR;
                            throw new BlockProcessingException(ex.Message);
                        }
                    }
                }

                // If Command -> Process Command
                else if (CommandParser.IsCommand(CurrentLine))
                {
                    try
                    {
                        var action = CommandParser.Parse(CurrentLine, data);
                        action?.Invoke();
                    }
                    catch (Exception ex)
                    {
                        data.LogBuffer.Add(new LogEntry("ERROR: " + ex.Message, Colors.Tomato));
                        data.Status = BotStatus.ERROR;
                    }
                }

                // Try to Process Flow Control
                else
                {
                    var cfLine = CurrentLine;
                    var token  = LineParser.ParseToken(ref cfLine, TokenType.Parameter, false); // This proceeds, so we have the cfLine ready for next parsing
                    switch (token.ToUpper())
                    {
                    case "IF":
                        // Check condition, if not true jump to line after first ELSE or ENDIF (check both at the same time on lines, not separately)
                        if (!ParseCheckCondition(ref cfLine, data))
                        {
                            i = ScanFor(lines, i, true, new string[] { "ENDIF", "ELSE" });
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        break;

                    case "ELSE":
                        // Here jump to ENDIF because you are coming from an IF and you don't need to process the ELSE
                        i = ScanFor(lines, i, true, new string[] { "ENDIF" });
                        data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        break;

                    case "ENDIF":
                        break;

                    case "WHILE":
                        // Check condition, if false jump to first index after ENDWHILE
                        if (!ParseCheckCondition(ref cfLine, data))
                        {
                            i = ScanFor(lines, i, true, new string[] { "ENDWHILE" });
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        }
                        break;

                    case "ENDWHILE":
                        // Jump back to the previous WHILE index
                        i = ScanFor(lines, i, false, new string[] { "WHILE" }) - 1;
                        data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 1}", Colors.White));
                        break;

                    case "JUMP":
                        var label = "";
                        try
                        {
                            label = LineParser.ParseToken(ref cfLine, TokenType.Label, true);
                            i     = ScanFor(lines, -1, true, new string[] { $"{label}" }) - 1;
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 2}", Colors.White));
                        }
                        catch { throw new Exception($"No block with label {label} was found"); }
                        break;

                    case "BEGIN":
                        var beginToken = LineParser.ParseToken(ref cfLine, TokenType.Parameter, true);
                        switch (beginToken.ToUpper())
                        {
                        case "SCRIPT":
                            language = (ScriptingLanguage)LineParser.ParseEnum(ref cfLine, "LANGUAGE", typeof(ScriptingLanguage));
                            int end = 0;
                            try
                            {
                                end = ScanFor(lines, i, true, new string[] { "END" }) - 1;
                            }
                            catch { throw new Exception("No 'END SCRIPT' specified"); }

                            otherScript = string.Join(Environment.NewLine, lines.Skip(i + 1).Take(end - i));
                            i           = end;
                            data.LogBuffer.Add(new LogEntry($"Jumping to line {i + 2}", Colors.White));
                            break;
                        }
                        break;

                    case "END":
                        var endToken = LineParser.ParseToken(ref cfLine, TokenType.Parameter, true);
                        switch (endToken.ToUpper())
                        {
                        case "SCRIPT":
                            LineParser.EnsureIdentifier(ref cfLine, "->");
                            LineParser.EnsureIdentifier(ref cfLine, "VARS");
                            var outputs = LineParser.ParseLiteral(ref cfLine, "OUTPUTS");

                            try
                            {
                                if (otherScript != string.Empty)
                                {
                                    RunScript(otherScript, language, outputs, data);
                                }
                            }
                            catch (Exception ex) { data.LogBuffer.Add(new LogEntry($"The script failed to be executed: {ex.Message}", Colors.Tomato)); }
                            break;
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (BlockProcessingException) { throw; }                                                     // Rethrow the Block Processing Exception so the error can be displayed in the view above
            catch (Exception e) { throw new Exception($"Parsing Exception on line {i + 1}: {e.Message}"); } // Catch inner and throw line exception

            i += 1 + lookahead;
        }
        /// <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)
            {
                ConnectorClient connector   = new ConnectorClient(new Uri(activity.ServiceUrl));
                StateClient     stateClient = activity.GetStateClient();
                BotData         userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                HttpClient client = new HttpClient();
                // declared variables
                var    userInput      = activity.Text;
                string inputCurrency  = "";
                string outputCurrency = "";
                string errormsg       = "";
                double result         = 0;
                //string loginname = "a";
                bool validcurr       = false;
                bool exchangerequest = false;
                bool clearData       = false;
                bool setCurr         = false;
                bool defex           = false;
                bool login           = false;
                bool checkBal        = false;
                bool reg             = false;
                bool del             = false;
                bool trans           = false;
                bool pic             = false;
                if (activity.Type == ActivityTypes.Message && activity.Attachments?.Any() == true)
                {
                    var responseMsg = "";
                    var photoUrl    = activity.Attachments[0].ContentUrl;
                    var photoclient = new HttpClient();
                    var photoStream = await photoclient.GetStreamAsync(photoUrl);

                    Scores               smileScores;
                    double               smilePecentage;
                    const string         emotionApiKey        = "4d0605f9e44b405084c8ac7c4b291dc6";
                    EmotionServiceClient emotionServiceClient = new EmotionServiceClient(emotionApiKey);

                    try
                    {
                        Emotion[] emotionResult = await emotionServiceClient.RecognizeAsync(photoStream);

                        smileScores    = emotionResult[0].Scores;
                        smilePecentage = Math.Ceiling(smileScores.Happiness * 100);
                        responseMsg    = smilePecentage + "% Smile!";
                        Activity reply = activity.CreateReply($"You have a " + responseMsg + " Does that mean you were " + smilePecentage + "% happy with our service? Let us know at 09-CONTOSO or email us [email protected]");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    catch (Exception e)
                    {
                        responseMsg = "Sorry, we were unable to detect your emotions. Please try another photo.";
                        Activity reply = activity.CreateReply(responseMsg);
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }

                    // Return reply

                    pic = true;
                }
                if (userInput.Length > 6 && userInput.Substring(0, 6).ToLower() == "delete")
                {
                    string[] dellist = new string[3];
                    dellist = (userInput.Split());
                    try
                    {
                        string temp  = dellist[1];
                        string temp2 = dellist[2];
                    }catch (Exception dele)
                    {
                        Activity reply = activity.CreateReply($"Please include both username and password along with this command");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    string         delloginname = dellist[1];
                    string         delpassword  = dellist[2];
                    List <myTable> nowrecords   = await AzureManager.AzureManagerInstance.getRecords();

                    bool valid = false;

                    foreach (myTable r in nowrecords)
                    {
                        if (r.userName == delloginname && r.passWord == delpassword)
                        {
                            valid = true;
                            if (r.Balance == 0)
                            {
                                await AzureManager.AzureManagerInstance.deleteRecord(r);

                                Activity reply = activity.CreateReply($"Account has been deleted");
                                await connector.Conversations.ReplyToActivityAsync(reply);
                            }
                            else
                            {
                                Activity reply = activity.CreateReply($"We cannot delete that account as it still has money left in it");
                                await connector.Conversations.ReplyToActivityAsync(reply);
                            }
                        }
                    }

                    if (!valid)
                    {
                        Activity reply = activity.CreateReply($"Incorrect username/password, please try again");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }

                    del = true;
                }
                if (userInput.Length >= 8 && userInput.Substring(0, 8).ToLower() == "register")
                {
                    string[] reglist = new string[3];
                    reglist = (userInput.Split());
                    try
                    {
                        string temp  = reglist[1];
                        string temp2 = reglist[2];
                    }
                    catch (Exception rege)
                    {
                        Activity reply = activity.CreateReply($"Please include both username and password along with this command");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    string         regloginname = reglist[1];
                    string         regpassword  = reglist[2];
                    List <myTable> records      = await AzureManager.AzureManagerInstance.getRecords();

                    bool duplicate = false;
                    foreach (myTable record in records)
                    {
                        if (record.userName == regloginname)
                        {
                            duplicate = true;
                        }
                    }

                    if (duplicate)
                    {
                        Activity reply = activity.CreateReply($"Sorry, this username already exists please try another one");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    else
                    {
                        myTable newRecord = new myTable()
                        {
                            userName = regloginname,
                            passWord = regpassword,
                            Balance  = 0.00
                        };

                        await AzureManager.AzureManagerInstance.addRecord(newRecord);

                        Activity reply = activity.CreateReply($"Register Success");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }

                    reg = true;
                }

                if (userInput.Length > 5 && userInput.Substring(0, 5).ToLower() == "login")
                {
                    login = true;
                    string[] list = new string[3];
                    list = (userInput.Split());
                    try
                    {
                        string temp  = list[1];
                        string temp2 = list[2];
                    }
                    catch (Exception loge)
                    {
                        Activity reply = activity.CreateReply($"Please include both username and password along with this command");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    string         loginname  = list[1];
                    string         password   = list[2];
                    List <myTable> getrecords = await AzureManager.AzureManagerInstance.getRecords();

                    bool exists = false;
                    foreach (myTable record in getrecords)
                    {
                        if (record.userName == loginname)
                        {
                            exists = true;
                        }
                    }
                    if (!exists)
                    {
                        Activity reply = activity.CreateReply($"This username does not exist, please try again");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    else
                    {
                        List <string> records = await AzureManager.AzureManagerInstance.getPassWord(loginname);

                        string output = records[0];

                        if (password == output && exists)
                        {
                            userData.SetProperty <string>("LoginName", loginname);
                            userData.SetProperty <bool>("LoginStatus", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            Activity reply = activity.CreateReply($"Login success");
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                        else
                        {
                            Activity reply = activity.CreateReply($"Incorrect password please try again");
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }

                if (userInput.ToLower() == "my balance")
                {
                    checkBal = true;
                    bool loggedIn = userData.GetProperty <bool>("LoginStatus");
                    if (loggedIn == true)
                    {
                        string        clientLogin   = userData.GetProperty <string>("LoginName");
                        List <double> clientBalance = await AzureManager.AzureManagerInstance.getBalance(clientLogin);

                        double   cash  = clientBalance[0];
                        Activity reply = activity.CreateReply($"You currently have $" + cash + " in your account");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    else
                    {
                        Activity reply = activity.CreateReply($"Please log in first");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                }

                if (userInput.Length > 9 && userInput.Substring(0, 8).ToLower() == "transfer" && userData.GetProperty <bool>("LoginStatus") == true)
                {
                    string[] command = new string[4];
                    command = userInput.Split();
                    try
                    {
                        string temp  = command[1];
                        string temp2 = command[3];
                    }
                    catch (Exception transe)
                    {
                        Activity reply = activity.CreateReply($"The correct format for this command should be 'Transfer $(amount) to (account username)'");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    double         amount       = double.Parse(command[1].Substring(1));
                    string         targetAcc    = command[3];
                    string         srcAcc       = userData.GetProperty <string>("LoginName");
                    List <myTable> transrecords = await AzureManager.AzureManagerInstance.getRecords();

                    bool targetExist = false;

                    /*foreach(var item in transrecords)
                     * {
                     *  //item.Balance = item.Balance + 10;
                     *  await AzureManager.AzureManagerInstance.updateRecord(item);
                     *  Activity reply = activity.CreateReply(item.userName);
                     *  await connector.Conversations.ReplyToActivityAsync(reply);
                     * }*/
                    foreach (myTable t in transrecords)
                    {
                        if (t.userName == targetAcc)
                        {
                            targetExist = true;
                            t.Balance  += amount;
                            await AzureManager.AzureManagerInstance.updateRecord(t);
                        }
                    }
                    if (targetExist)
                    {
                        foreach (myTable t in transrecords)
                        {
                            if (t.userName == srcAcc)
                            {
                                t.Balance = t.Balance - amount;
                                await AzureManager.AzureManagerInstance.updateRecord(t);

                                Activity reply = activity.CreateReply($"Successfully transferred $" + amount + " to " + targetAcc);
                                await connector.Conversations.ReplyToActivityAsync(reply);
                            }
                        }
                    }


                    if (!targetExist)
                    {
                        Activity reply = activity.CreateReply($"Target account does not exist");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }

                    trans = true;
                }
                else if (userInput.Length > 9 && userInput.Substring(0, 8).ToLower() == "transfer" && userData.GetProperty <bool>("LoginStatus") != true)
                {
                    Activity reply = activity.CreateReply($"Please log in first");
                    await connector.Conversations.ReplyToActivityAsync(reply);

                    trans = true;
                }

                if (userInput.Length >= 5 && userInput.Substring(0, 5).ToLower() == "clear")
                {
                    clearData = true;
                    Activity reply = activity.CreateReply($"User data has been cleared");
                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                    await connector.Conversations.ReplyToActivityAsync(reply);
                }

                if (userInput.Length >= 12 && userInput.Substring(0, 12).ToLower() == "set currency")
                {
                    setCurr = true;
                    string defaultCurrency = userInput.Substring(13, 3).ToUpper();
                    userData.SetProperty <string>("DefaultCurrency", defaultCurrency);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                    Activity reply = activity.CreateReply($"User default currency has been set to " + defaultCurrency);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }

                if (userInput.Length >= 11 && userInput.Substring(0, 11).ToLower() == "exchange to")
                {
                    defex = true;
                    string targetCurrency = userInput.Substring(12, 3);
                    string currentUnit    = userData.GetProperty <string>("DefaultCurrency"); //gets preset default currency
                    if (currentUnit == null)
                    {
                        Activity reply = activity.CreateReply($"Please set a default currency first");
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    else
                    {
                        userInput = "exchange rate " + currentUnit + " to " + targetCurrency;
                    }
                }

                if (userInput.Length > 17 && userInput.Substring(0, 13).ToLower() == "exchange rate")
                {
                    exchangerequest = true;
                    inputCurrency   = userInput.Substring(14, 3).ToUpper();
                    outputCurrency  = userInput.Substring(21, 3).ToUpper();
                    if (inputCurrency != "NZD" && inputCurrency != "USD" && inputCurrency != "AUD" && inputCurrency != "EUR" && inputCurrency != "CNY")
                    {
                        goto invalidcurr;
                    }

                    else if (outputCurrency != "NZD" && outputCurrency != "USD" && outputCurrency != "EUR" && outputCurrency != "AUD" && outputCurrency != "CNY")
                    {
                        validcurr = false;
                    }
                    else
                    {
                        validcurr = true;
                    }


                    string currencyApi = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + inputCurrency));

                    CurrencyObjects.RootObject rootObject;

                    rootObject = JsonConvert.DeserializeObject <CurrencyObjects.RootObject>(currencyApi);

                    switch (outputCurrency)
                    {
                    case "NZD":
                        result = rootObject.rates.NZD;

                        break;

                    case "USD":
                        result = rootObject.rates.USD;

                        break;

                    case "AUD":
                        result = rootObject.rates.AUD;

                        break;

                    case "EUR":
                        result = rootObject.rates.EUR;

                        break;

                    case "CNY":
                        result = rootObject.rates.CNY;

                        break;

                    default:

                        break;
                    }
                }

                if (userInput.ToLower() == "other services")
                {
                    Activity replyToConversation = activity.CreateReply("For other services such as loan or mortgage please head to our website");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "https://i.imgur.com/dfsOvah.png"));

                    List <CardAction> cardButtons = new List <CardAction>();
                    CardAction        plButton    = new CardAction()
                    {
                        Value = "http://www.asb.co.nz",
                        Type  = "openUrl",
                        Title = "Click to visit website"
                    };
                    cardButtons.Add(plButton);

                    ThumbnailCard plCard = new ThumbnailCard()
                    {
                        Title    = "Contoso Bank",
                        Subtitle = "For more services please visit our website",
                        Images   = cardImages,
                        Buttons  = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                // return our reply to the user

                if (!exchangerequest && !validcurr && !clearData && !setCurr && !defex && !login && !checkBal && !reg && !del && !trans && !pic)
                {
                    Activity reply = activity.CreateReply($"Hi, my service commands include my balance, login, register, transfer, exchange rate and other services. Please double check your commands if you encounter an error and make sure to include username and password in appropriate commands. You can also send us a photo of yourself to give us feedback");
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
                if (exchangerequest && validcurr)
                {
                    Activity reply = activity.CreateReply($"Currently for every 1 " + inputCurrency + " you can get " + result + " " + outputCurrency + errormsg);
                    await connector.Conversations.ReplyToActivityAsync(reply);

                    exchangerequest = false;
                }
invalidcurr:
                validcurr = false;
                if (exchangerequest && !validcurr)
                {
                    Activity reply = activity.CreateReply($"Oops, something went wrong");
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Example #25
0
        /// <summary>
        /// Runs a script with a different language inside the LoliScript.
        /// </summary>
        /// <param name="script">The script as a string with linebreaks</param>
        /// <param name="language">The language of the script</param>
        /// <param name="outputs">The variables that should be extracted from the script's scope and set into the BotData local variables</param>
        /// <param name="data">The BotData needed for variable replacement</param>
        private void RunScript(string script, ScriptingLanguage language, string outputs, BotData data)
        {
            // Set the console output to stringwriter
            var sw = new StringWriter();

            Console.SetOut(sw);
            Console.SetError(sw);

            // Parse variables to get out
            List <string> outVarList = new List <string>();

            if (outputs != string.Empty)
            {
                try { outVarList = outputs.Split(',').Select(x => x.Trim()).ToList(); }
                catch { }
            }

            var start = DateTime.Now;

            try
            {
                switch (language)
                {
                case ScriptingLanguage.JavaScript:

                    // Redefine log() function
                    var jsengine = new Engine().SetValue("log", new Action <object>(Console.WriteLine));

                    // Add in all the variables
                    foreach (var variable in data.Variables.All)
                    {
                        try
                        {
                            switch (variable.Type)
                            {
                            case CVar.VarType.List:
                                jsengine.SetValue(variable.Name, (variable.Value as List <string>).ToArray());
                                break;

                            default:
                                jsengine.SetValue(variable.Name, variable.Value);
                                break;
                            }
                        }
                        catch { }
                    }

                    // Execute JS
                    jsengine.Execute(script);

                    // Print results to log
                    data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White));

                    // Get variables out
                    data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                    foreach (var name in outVarList)
                    {
                        try
                        {
                            // Add it to the variables and print info
                            var value   = jsengine.Global.GetProperty(name).Value;
                            var isArray = value.IsArray();
                            if (isArray)
                            {
                                data.Variables.Set(new CVar(name, CVar.VarType.List, value.TryCast <List <string> >()));
                            }
                            else
                            {
                                data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString()));
                            }
                            data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value.ToString()}", Colors.Yellow));
                        }
                        catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                    }

                    // Print other info
                    if (jsengine.GetCompletionValue() != null)
                    {
                        data.Log(new LogEntry($"Completion value: {jsengine.GetCompletionValue()}", Colors.White));
                    }

                    break;

                case ScriptingLanguage.IronPython:

                    // Initialize the engine
                    var runtime  = Python.CreateRuntime();
                    var pyengine = runtime.GetEngine("py");
                    PythonCompilerOptions pco = (PythonCompilerOptions)pyengine.GetCompilerOptions();
                    pco.Module &= ~ModuleOptions.Optimized;
                    //var pyengine = Python.CreateEngine();
                    var scope = pyengine.CreateScope();
                    var code  = pyengine.CreateScriptSourceFromString(script);

                    // Add in all the variables
                    foreach (var variable in data.Variables.All)
                    {
                        try { scope.SetVariable(variable.Name, variable.Value); } catch { }
                    }

                    // Execute it
                    var result = code.Execute(scope);
                    //var result = pyengine.Execute(script, scope);

                    // Print the logs
                    data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White));

                    // Get variables out
                    data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                    foreach (var name in outVarList)
                    {
                        try
                        {
                            // Add it to the variables and print info
                            var value = scope.GetVariable(name);
                            data.Variables.Set(new CVar(name, (value.GetType() == typeof(string[])) ? CVar.VarType.List : CVar.VarType.Single, value.ToString()));
                            data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow));
                        }
                        catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                    }

                    // Print other info
                    if (result != null)
                    {
                        data.Log(new LogEntry($"Completion value: {result}", Colors.White));
                    }

                    break;

                default:
                    break;
                }

                data.Log(new LogEntry($"Execution completed in {(DateTime.Now - start).TotalSeconds} seconds", Colors.GreenYellow));
            }
            catch (Exception e)
            {
                data.Log(new LogEntry($"[ERROR] INFO: {e.Message}", Colors.White));
            }
            finally
            {
                var standardOutput = new StreamWriter(Console.OpenStandardOutput());
                var standardError  = new StreamWriter(Console.OpenStandardError());
                standardOutput.AutoFlush = true;
                standardError.AutoFlush  = true;
                Console.SetOut(standardOutput);
                Console.SetError(standardError);
            }
        }
Example #26
0
        protected async Task <HttpOperationResponse <BotData> > UpsertData(string channelId, string userId, string conversationId, BotStoreType storeType, BotData data)
        {
            var _result = new HttpOperationResponse <BotData>();

            _result.Request = new HttpRequestMessage();
            try
            {
                var address = AddressFrom(channelId, userId, conversationId);
                await memoryDataStore.SaveAsync(address, storeType, data, CancellationToken.None);
            }
            catch (HttpException e)
            {
                _result.Body     = null;
                _result.Response = new HttpResponseMessage {
                    StatusCode = HttpStatusCode.PreconditionFailed
                };
                var ex = new HttpOperationException(e?.Message, e);
                ex.Request  = new HttpRequestMessageWrapper(_result.Request, "");
                ex.Response = new HttpResponseMessageWrapper(_result.Response, e?.Message);
                throw ex;
            }
            catch (Exception e)
            {
                _result.Body     = null;
                _result.Response = new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                };
                var ex = new HttpOperationException(e?.Message, e);
                ex.Request  = new HttpRequestMessageWrapper(_result.Request, "");
                ex.Response = new HttpResponseMessageWrapper(_result.Response, e?.Message);
                throw ex;
            }


            _result.Body     = data;
            _result.Response = new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            };
            return(_result);
        }
Example #27
0
 internal Initializer(BotData botConfig)
 {
     this.BotData = botConfig;
     InitializeBotAsync().GetAwaiter().GetResult();
 }
        public async Task <HttpResponseMessage> Callback([FromUri] string code, [FromUri] string state, CancellationToken cancellationToken)
        {
            try
            {
                // Use the state parameter to get correct IAuthProvider and ResumptionCookie
                var           decoded      = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(state));
                var           queryString  = HttpUtility.ParseQueryString(decoded);
                var           assembly     = Assembly.Load(queryString["providerassembly"]);
                var           type         = assembly.GetType(queryString["providertype"]);
                var           providername = queryString["providername"];
                IAuthProvider authProvider;
                if (type.GetConstructor(new Type[] { typeof(string) }) != null)
                {
                    authProvider = (IAuthProvider)Activator.CreateInstance(type, providername);
                }
                else
                {
                    authProvider = (IAuthProvider)Activator.CreateInstance(type);
                }

                // Get the conversation reference
                var conversationRef = UrlToken.Decode <ConversationReference>(queryString["conversationRef"]);

                Activity message = conversationRef.GetPostToBotMessage();
                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    // Get the UserData from the original conversation
                    IStateClient sc       = scope.Resolve <IStateClient>();
                    BotData      userData = await sc.BotState.GetUserDataAsync(message.ChannelId, message.From.Id);

                    // Get Access Token using authorization code
                    var authOptions = userData.GetProperty <AuthenticationOptions>($"{authProvider.Name}{ContextConstants.AuthOptions}");
                    var token       = await authProvider.GetTokenByAuthCodeAsync(authOptions, code);

                    // Generate magic number and attempt to write to userdata
                    int  magicNumber     = GenerateRandomNumber();
                    bool writeSuccessful = false;
                    uint writeAttempts   = 0;
                    while (!writeSuccessful && writeAttempts++ < MaxWriteAttempts)
                    {
                        try
                        {
                            userData.SetProperty($"{authProvider.Name}{ContextConstants.AuthResultKey}", token);
                            if (authOptions.UseMagicNumber)
                            {
                                userData.SetProperty($"{authProvider.Name}{ContextConstants.MagicNumberKey}", magicNumber);
                                userData.SetProperty($"{authProvider.Name}{ContextConstants.MagicNumberValidated}", "false");
                            }
                            sc.BotState.SetUserData(message.ChannelId, message.From.Id, userData);
                            writeSuccessful = true;
                        }
                        catch (HttpOperationException)
                        {
                            writeSuccessful = false;
                        }
                    }
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    if (!writeSuccessful)
                    {
                        message.Text = String.Empty; // fail the login process if we can't write UserData
                        await Conversation.ResumeAsync(conversationRef, message);

                        resp.Content = new StringContent("<html><body>Could not log you in at this time, please try again later</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    }
                    else
                    {
                        await Conversation.ResumeAsync(conversationRef, message);

                        resp.Content = new StringContent($"<html><body>Thank you for authenticating. You can now return back to the bot.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    }
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
 public async Task <XCommasResponse <Bot> > CreateBot(int accountId, Strategy strategy, BotData botData)
 {
     return(await _3CommasClient.CreateBotAsync(accountId, strategy, botData));
 }
Example #30
0
 internal void save()
 {
     BotData data = new BotData(inputRange,inputPoints);
     FileControl.save(data);
 }
Example #31
0
 public static void Shuffle(BotData data, [Variable] List <string> list)
 {
     list.Shuffle(data.Random);
     data.Logger.LogHeader();
     data.Logger.Log("Shuffled the list", LogColors.YellowGreen);
 }
Example #32
0
		private void SaveBotFile(string path)
		{
			var data = new BotData
			{
				Best = _bestBotAttempt,
				ControlProbabilities = ControlProbabilities,
				Maximize = MaximizeAddress,
				TieBreaker1 = TieBreaker1Address,
				TieBreaker2 = TieBreaker2Address,
				TieBreaker3 = TieBreaker3Address,
				FromSlot = FromSlot,
				FrameLength = FrameLength,
				Attempts = Attempts,
				Frames = Frames,
				MemoryDomain = _currentDomain.Name,
				BigEndian = _bigEndian,
				DataSize = _dataSize
			};

			var json = ConfigService.SaveWithType(data);

			File.WriteAllText(path, json);
			CurrentFileName = path;
			Settings.RecentBotFiles.Add(CurrentFileName);
			MessageLabel.Text = Path.GetFileName(CurrentFileName) + " saved";
		}
 public static async Task SaveBotUserDataObject(IBotDataStore <BotData> botDataStore, Activity activity, BotData userData)
 {
     IAddress key = Address.FromActivity(activity);
     await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData, CancellationToken.None);
 }
Example #34
0
		private void SaveBotFile(string path)
		{
			var data = new BotData
			{
				Best = _bestBotAttempt,
				ControlProbabilities = ControlProbabilities,
				Maximize = MaximizeAddress,
				TieBreaker1 = TieBreaker1Address,
				TieBreaker2 = TieBreaker2Address,
				TieBreaker3 = TieBreaker3Address,
				ComparisonTypeMain = MainComparisonType,
				ComparisonTypeTie1 = Tie1ComparisonType,
				ComparisonTypeTie2 = Tie2ComparisonType,
				ComparisonTypeTie3 = Tie3ComparisonType,
				MainCompareToBest = MainBestRadio.Checked,
				TieBreaker1CompareToBest = TieBreak1BestRadio.Checked,
				TieBreaker2CompareToBest = TieBreak2BestRadio.Checked,
				TieBreaker3CompareToBest = TieBreak3BestRadio.Checked,
				MainCompareToValue = (int)MainValueNumeric.Value,
				TieBreaker1CompareToValue = (int)TieBreak1Numeric.Value,
				TieBreaker2CompareToValue = (int)TieBreak2Numeric.Value,
				TieBreaker3CompareToValue = (int)TieBreak3Numeric.Value,
				FromSlot = FromSlot,
				FrameLength = FrameLength,
				Attempts = Attempts,
				Frames = Frames,
				MemoryDomain = _currentDomain.Name,
				BigEndian = _bigEndian,
				DataSize = _dataSize
			};

			var json = ConfigService.SaveWithType(data);

			File.WriteAllText(path, json);
			CurrentFileName = path;
			Settings.RecentBotFiles.Add(CurrentFileName);
			MessageLabel.Text = Path.GetFileName(CurrentFileName) + " saved";
		}
Example #35
0
 private static void SetPageAndFrame(BotData data, PuppeteerSharp.Page page)
 {
     data.Objects["puppeteerPage"] = page;
     SwitchToMainFramePrivate(data);
 }