// Override the CheckPermissions method
        public async override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider _services)
        {
            var userStorage = UserDataManager.GetUserStorage();

            //Create xml user credit entry if user does not exist
            if (!userStorage.UserInfo.TryGetValue(context.Message.Author.Id, out var i))
            {
                //Create user profile
                UserDataManager.CreateNewUserXmlEntry(context as SocketCommandContext);
            }


            //Create user stock entry if stock entry does not exist
            if (!File.Exists(CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + context.Message.Author.Id + ".xml"))
            {
                //Create user profile
                //Write user stock amount
                var userStockRecord = new UserStockStorage
                {
                    UserStock = new List <UserStock>
                    {
                        //new UserStock {StockTicker="DUCK", StockAmount=0, StockBuyPrice=0 }
                    }
                };

                XmlManager.ToXmlFile(userStockRecord, CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + context.User.Id.ToString() + ".xml");
            }

            return(PreconditionResult.FromSuccess());
        }
Пример #2
0
        /// <summary>
        /// Opens a virtual CS:GO case, result is sent to Context channel in a method
        /// </summary>
        /// <param name="context">Command context used to determine channel to send result</param>
        /// <returns></returns>
        public static async Task OpenCase(SocketCommandContext context)
        {
            //Test if user has enough credits
            if (UserCreditsHandler.AddCredits(context, -300) == true)
            {
                var result = ItemDropProcessing.CalculateItemCaseRarity();


                //Get item
                var skinItem = ItemDropProcessing.GetItem(result, CsgoDataHandler.rootWeaponSkin, context, false);


                //Add item to user file inventory
                var userSkin = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml"));

                userSkin.UserSkinEntries.Add(new UserSkinEntry {
                    ClassId = skinItem.Classid, OwnerID = context.Message.Author.Id, UnboxDate = DateTime.UtcNow, MarketName = skinItem.Name
                });

                XmlManager.ToXmlFile(userSkin, CoreMethod.GetFileLocation("UserSkinStorage.xml"));

                //Send item into
                await SendOpenedItemInfo(context, skinItem, Convert.ToInt64(skinItem.Price.AllTime.Average), UnboxType.CaseUnboxing);
            }
            else
            {
                await context.Channel.SendMessageAsync("**" + context.Message.Author.ToString().Substring(0, context.Message.Author.ToString().Length - 5) + ", **You do not have enough credits to unbox a case");
            }
        }
Пример #3
0
        public static async Task DisplayMarketStocksAsync(SocketCommandContext Context)
        {
            //User stock list
            List <string> stockTickerList         = new List <string>();
            List <string> stockBuyMarketValueList = new List <string>();

            //Get market stock value from storage
            var marketStockStorage = XmlManager.FromXmlFile <MarketStockStorage>(CoreMethod.GetFileLocation(@"\MarketStocksValue.xml"));

            //Get is market stock closed
            string IsStockMarketOpen = "Closed";

            if (marketStockStorage.MarketOpen == true)
            {
                IsStockMarketOpen = "Open";
            }
            else
            {
                IsStockMarketOpen = "Closed";
            }

            var embedBuilder = new EmbedBuilder()
                               .WithDescription($"Stock market is `{IsStockMarketOpen}`")
                               .WithColor(new Color(6, 221, 238))
                               .WithFooter(footer =>
            {
                footer
                .WithText("Sent by " + Context.Message.Author.ToString())
                .WithIconUrl(Context.Message.Author.GetAvatarUrl());
            })
                               .WithAuthor(author =>
            {
                author
                .WithName("Stock Market")
                .WithIconUrl("https://www.clipartmax.com/png/middle/257-2574787_stock-market-clipart-stock-market-clipart.png");
            });

            foreach (var marketStock in marketStockStorage.MarketStock)
            {
                //Add market stock value to list
                stockTickerList.Add($"**{marketStock.StockTicker}**");
                stockBuyMarketValueList.Add($"**{marketStock.StockPrice}**");
            }

            //Join user stock items
            string joinedUserStockTickerList         = string.Join(" \n ", stockTickerList);
            string joinedUserStockBuyMarketValueList = string.Join(" \n ", stockBuyMarketValueList);

            //Add inline field if stock exists
            if (!string.IsNullOrEmpty(joinedUserStockTickerList) && !string.IsNullOrEmpty(joinedUserStockBuyMarketValueList))
            {
                embedBuilder.AddInlineField("Stock Ticker", string.Join(" \n ", stockTickerList));
                embedBuilder.AddInlineField("Market price", string.Join(" \n ", stockBuyMarketValueList));
            }

            //Send user stock portfolio
            var embed = embedBuilder.Build();

            await Context.Message.Channel.SendMessageAsync(" ", embed : embed).ConfigureAwait(false);
        }
        private static bool GetIsUserWhitelisted(SocketMessage message)
        {
            // If this command was NOT executed by predefined users, return a failure
            List <ulong> whitelistedUsers = new List <ulong>();

            CoreMethod.ReadFromFileToList(CoreMethod.GetFileLocation("UserWhitelist.txt")).ForEach(u => whitelistedUsers.Add(ulong.Parse(u)));

            //Test if user is whitelisted
            bool userIsWhiteListed = false;

            foreach (var user in whitelistedUsers)
            {
                if (message.Author.Id == user)
                {
                    userIsWhiteListed = true;
                }
            }

            bool userWhiteListed = false;

            if (userIsWhiteListed == true)
            {
                userWhiteListed = true;
            }

            return(userWhiteListed);
        }
        public async Task BankruptcyAsync()
        {
            await ReplyAsync($"Are you sure you want to proceed with bankruptcy {Context.Message.Author.Mention}? \n Type **Y** to confirm");

            //Get response
            var response = await NextMessageAsync();

            if (response.ToString().ToLower() == "y")
            {
                try
                {
                    //Delete user profile
                    UserCreditsHandler.SetCredits(Context, 0);
                    UserDebtHandler.SetDebt(Context, 0);
                    //Delete user stocks
                    File.Delete(CoreMethod.GetFileLocation(@"\UserStocks") + $@"\{Context.Message.Author.Id}.xml");

                    //Send final confirmation
                    await ReplyAsync($"It's all over now {Context.Message.Author.Mention}");
                }
                catch (Exception)
                {
                }
            }
            else
            {
                await ReplyAsync($"Bankruptcy request cancelled {Context.Message.Author.Mention}");
            }
        }
            public async Task UnBlackListUserAsync(ulong userId)
            {
                var filteredBlacklist = CoreMethod.ReadFromFileToList(CoreMethod.GetFileLocation("UserBlacklist.txt"));

                filteredBlacklist = filteredBlacklist.Where(u => u != userId.ToString()).ToList();
                CoreMethod.WriteListToFile(filteredBlacklist, true, CoreMethod.GetFileLocation("UserBlacklist.txt"));
            }
Пример #7
0
        /// <summary>
        /// Adds a guild role for the specified guild
        /// </summary>
        /// <param name="guildID">Target guild id to add role</param>
        /// <param name="RoleName">Name of role to add</param>
        /// <param name="GuildRoleID">Id of guild role</param>
        public static void AddGuildRole(ulong guildID, string RoleName, ulong GuildRoleID)
        {
            //Get roles from file
            var roleStorage = XmlManager.FromXmlFile <GuildRoleStorage>(CoreMethod.GetFileLocation(@"\GuildRoles.xml"));

            //Check for overlapping role ids or names
            bool conflictingEntryExists = false;

            foreach (var roleEntry in roleStorage.GuildRoles)
            {
                if (roleEntry.GuildID == guildID)
                {
                    if (roleEntry.RoleName == RoleName)
                    {
                        conflictingEntryExists = true;
                    }
                    if (roleEntry.GuildRoleID == GuildRoleID)
                    {
                        conflictingEntryExists = true;
                    }
                }
            }

            //Add new entry if it does not exist
            if (conflictingEntryExists == false)
            {
                roleStorage.GuildRoles.Add(new GuildRoleEntry {
                    GuildID = guildID, RoleName = RoleName, GuildRoleID = GuildRoleID
                });
            }

            //Write back to file
            XmlManager.ToXmlFile(roleStorage, CoreMethod.GetFileLocation(@"\GuildRoles.xml"));
        }
Пример #8
0
        /// <summary>
        /// Removes a guild role for the specified guild
        /// </summary>
        /// <param name="guildID">Target guild id to remove role</param>
        /// <param name="RoleName">Name of role to removes</param>
        /// <param name="GuildRoleID">Id of guild role</param>
        public static void RemoveGuildRole(ulong guildID, string RoleName, ulong GuildRoleID)
        {
            //Get roles from file
            var roleStorage = XmlManager.FromXmlFile <GuildRoleStorage>(CoreMethod.GetFileLocation(@"\GuildRoles.xml"));

            List <GuildRoleEntry> returnRoleEntries = new List <GuildRoleEntry>();

            //Filter role entry to those not matching one to remove
            foreach (var role in roleStorage.GuildRoles)
            {
                if (role.GuildID == guildID && role.RoleName == RoleName && role.GuildRoleID == GuildRoleID)
                {
                }
                else
                {
                    returnRoleEntries.Add(role);
                }
            }

            //Write back to file

            var returnRoleStorage = new GuildRoleStorage
            {
                GuildRoles = returnRoleEntries
            };

            XmlManager.ToXmlFile(returnRoleStorage, CoreMethod.GetFileLocation(@"\GuildRoles.xml"));
        }
        /// <summary>
        /// Returns the command prefix for the current guild message is sent in
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetGuildCommandPrefix(SocketCommandContext context)
        {
            //Find guild id
            var chnl    = context.Channel as SocketGuildChannel;
            var guildId = chnl.Guild.Id;

            //Just in case the file is null
            if (GuildPrefixDictionary == null || GuildPrefixDictionary.GuildPrefixes == null)
            {
                GuildPrefixDictionary = new CommandPrefix {
                    GuildPrefixes = new Dictionary <ulong, string>()
                };
                GuildPrefixDictionary.GuildPrefixes.Add(guildId, ".d");

                //Write new dictionary to file
                string newJson = JsonConvert.SerializeObject(GuildPrefixDictionary);
                CoreMethod.WriteStringToFile(newJson, true, CoreMethod.GetFileLocation("GuildCommandPrefix.json"));
            }

            //Look for guild prefix, in event guild does not have one, use default
            if (!GuildPrefixDictionary.GuildPrefixes.TryGetValue(guildId, out var i))
            {
                GuildPrefixDictionary.GuildPrefixes.Add(guildId, ".d");

                //Write new dictionary to file
                string newJson = JsonConvert.SerializeObject(GuildPrefixDictionary);
                CoreMethod.WriteStringToFile(newJson, true, CoreMethod.GetFileLocation("GuildCommandPrefix.json"));
            }

            return(GuildPrefixDictionary.GuildPrefixes[guildId]);
        }
Пример #10
0
        public static async Task SellAllInventoryItemAsync(SocketCommandContext Context)
        {
            //Get price data
            var rootSkinData = CsgoDataHandler.GetRootWeaponSkin();
            var userSkin     = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml"));

            try
            {
                long weaponSkinValue = GetItemValue(userSkin.UserSkinEntries, rootSkinData);

                //Give user credits
                UserCreditsHandler.AddCredits(Context, weaponSkinValue, true);

                //Remove skin from inventory
                var filteredUserSkinEntries = userSkin.UserSkinEntries.Where(s => s.OwnerID == Context.Message.Author.Id).Where(s => s.OwnerID != Context.Message.Author.Id).ToList();

                //Write to file
                WriteUserSkinDataToFile(filteredUserSkinEntries);

                //Send receipt
                await Context.Channel.SendMessageAsync(
                    UserInteraction.BoldUserName(Context) + $", you sold your inventory" +
                    $" for **{UserBankingHandler.CreditCurrencyFormatter(weaponSkinValue)} Credits** " +
                    $"| A total of **{UserBankingHandler.CreditCurrencyFormatter(UserCreditsTaxHandler.TaxCollector(weaponSkinValue))} Credits was taken off as tax**");
            }
            catch (Exception)
            {
            }
        }
Пример #11
0
        public static async Task DisplayUserStocksAsync(SocketCommandContext Context)
        {
            //User stock list
            List <string> userStockTickerList         = new List <string>();
            List <string> userStockBuyMarketValueList = new List <string>();

            //Get user portfolio
            var userStockStorage = XmlManager.FromXmlFile <UserStockStorage>(CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + Context.User.Id.ToString() + ".xml");

            var embedBuilder = new EmbedBuilder()
                               .WithColor(new Color(40, 144, 175))
                               .WithFooter(footer =>
            {
                footer
                .WithText("Sent by " + Context.Message.Author.ToString())
                .WithIconUrl(Context.Message.Author.GetAvatarUrl());
            })
                               .WithAuthor(author =>
            {
                author
                .WithName("Stock Portfolio - " + Context.Message.Author.ToString())
                .WithIconUrl("https://melbournechapter.net/images/transparent-folder-2.png");
            });

            //Add stock listing to embed
            foreach (var userStock in userStockStorage.UserStock)
            {
                //get stock market value
                var marketStockStorage = XmlManager.FromXmlFile <MarketStockStorage>(CoreMethod.GetFileLocation(@"\MarketStocksValue.xml"));

                long userStockMarketPrice = 0;
                foreach (var marketStock in marketStockStorage.MarketStock)
                {
                    if (marketStock.StockTicker == userStock.StockTicker)
                    {
                        userStockMarketPrice = marketStock.StockPrice;
                    }
                }

                userStockTickerList.Add($"**{userStock.StockTicker}** - **{userStock.StockAmount}**");
                userStockBuyMarketValueList.Add($"**{userStock.StockBuyPrice}** || **{userStockMarketPrice}**");
            }

            //Join user stock items
            string joinedUserStockTickerList         = string.Join(" \n ", userStockTickerList);
            string joinedUserStockBuyMarketValueList = string.Join(" \n ", userStockBuyMarketValueList);

            //Add inline field if user has stocks
            if (!string.IsNullOrEmpty(joinedUserStockTickerList) && !string.IsNullOrEmpty(joinedUserStockBuyMarketValueList))
            {
                embedBuilder.AddInlineField("Stock Ticker - Amount", joinedUserStockTickerList);
                embedBuilder.AddInlineField("Buy price || Market price", joinedUserStockBuyMarketValueList);
            }

            //Send user stock portfolio
            var embed = embedBuilder.Build();

            await Context.Message.Channel.SendMessageAsync(" ", embed : embed).ConfigureAwait(false);
        }
Пример #12
0
        //Main
        public async Task MainAsync()
        {
            var _config = new DiscordSocketConfig {
                MessageCacheSize = 100
            };

            _client   = new DiscordSocketClient(_config);
            _commands = new CommandService();
            _services = new ServiceCollection()
                        .AddSingleton(_client)
                        .AddSingleton <InteractiveService>()

                        //BuildsServiceProvider
                        .BuildServiceProvider();

            //Bot init
            try
            {
                //Get token
                string token = File.ReadAllLines(CoreMethod.GetFileLocation("BotToken.txt")).FirstOrDefault();

                //Connect to discord
                await _client.LoginAsync(TokenType.Bot, token);

                await _client.StartAsync();
            }
            catch (Exception)
            {
                throw new Exception("Unable to initialize! - Could it be because of an invalid token?");
            }

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly());

            stopwatch.Stop();
            EventLogger.LogMessage($"Ready! - Took {stopwatch.ElapsedMilliseconds} milliseconds");


            //EVENT HANDLERS
            //Log user / console messages
            _client.Log             += EventLogger.LogAsync;
            _client.MessageReceived += EventLogger.LogUserMessageAsync;

            //Moderation Message received
            _client.MessageReceived += ModerationManager.ModerationManagerMessageReceivedAsync;

            //User joined
            _client.UserJoined += UserJoinHandler.DisplayUserGenderChoiceAsync;

            //Joining a guild first time, display help text
            _client.JoinedGuild += GuildJoinInteraction.SendFirstTimeHelpMenuAsync;

            //Handles command on message received event
            _client.MessageReceived += HandleCommandAsync;



            //All commands before this
            await Task.Delay(-1);
        }
 public async Task BlackListUserAsync(ulong userId)
 {
     //If user does not exist in block list, block
     if (!CoreMethod.ReadFromFileToList(CoreMethod.GetFileLocation("UserBlacklist.txt")).Contains(userId.ToString()))
     {
         CoreMethod.WriteStringToFile(userId.ToString(), false, CoreMethod.GetFileLocation("UserBlacklist.txt"));
     }
 }
        public static PaginatedMessage DisplayUserCsgoInventory(SocketCommandContext context)
        {
            string botCommandPrefix = CommandGuildPrefixManager.GetGuildCommandPrefix(context);

            //Reset fields
            embedFieldsMaster      = new List <string>();
            embedPriceFieldsMaster = new List <string>();

            //Get user skins from xml file
            UserSkinStorageRootobject userSkin = new UserSkinStorageRootobject();

            try
            {
                userSkin = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml"));
            }
            catch (Exception)
            {
            }

            List <UserSkinEntry> foundUserSkins = new List <UserSkinEntry>();

            //Filter userSkinEntries xml file down to skins belonging to sender
            foreach (var userSkinEntry in userSkin.UserSkinEntries)
            {
                //Filter skin search to those owned by user
                if (userSkinEntry.OwnerID == context.Message.Author.Id)
                {
                    foundUserSkins.Add(new UserSkinEntry {
                        OwnerID = context.Message.Author.Id, ClassId = userSkinEntry.ClassId, UnboxDate = userSkinEntry.UnboxDate
                    });
                }
            }

            //Generate fields
            AddSkinFieldEntry(foundUserSkins);

            //Configurate paginated message
            var paginationConfig = new PaginationConfig
            {
                AuthorName = context.Message.Author.ToString().Substring(0, context.Message.Author.ToString().Length - 5) + " Inventory",
                AuthorURL  = context.Message.Author.GetAvatarUrl(),

                Description = $"To sell items, use `{botCommandPrefix} cs sell [name]` \n To sell all items matching filter, use `{botCommandPrefix} cs sellall [name]`",

                DefaultFieldHeader      = "You do not have any skins",
                DefaultFieldDescription = $"Go unbox some with `{botCommandPrefix} case open`",

                Field1Header = "Item Name",
                Field2Header = "Market Value",
            };

            var paginationManager = new PaginationManager();

            //Generate paginated message
            var pager = paginationManager.GeneratePaginatedMessage(embedFieldsMaster, embedPriceFieldsMaster, paginationConfig);

            return(pager);
        }
Пример #15
0
        private static void WriteUserSkinDataToFile(List <UserSkinEntry> skinEntries)
        {
            var filteredUserSkin = new UserSkinStorageRootobject
            {
                SkinAmount      = 0,
                UserSkinEntries = skinEntries
            };

            XmlManager.ToXmlFile(filteredUserSkin, CoreMethod.GetFileLocation("UserSkinStorage.xml"));
        }
        /// <summary>
        /// Changes the bot invoke prefix of the message invoke guild to the specified new prefix
        /// </summary>
        /// <param name="context"></param>
        /// <param name="newPrefix"></param>
        public static void ChangeGuildCommandPrefix(SocketCommandContext context, string newPrefix)
        {
            //Find guild id
            var chnl    = context.Channel as SocketGuildChannel;
            var guildId = chnl.Guild.Id;

            //Change prefix
            GuildPrefixDictionary.GuildPrefixes[guildId] = newPrefix;

            //Write new dictionary to file
            string newJson = JsonConvert.SerializeObject(GuildPrefixDictionary);

            CoreMethod.WriteStringToFile(newJson, true, CoreMethod.GetFileLocation("GuildCommandPrefix.json"));
        }
Пример #17
0
        private static string GetStockMarketValue(string stockTicker)
        {
            var marketStockStorage = XmlManager.FromXmlFile <MarketStockStorage>(CoreMethod.GetFileLocation(@"\MarketStocksValue.xml"));

            string stockValue = "";

            foreach (var stock in marketStockStorage.MarketStock)
            {
                //Get the user selected stock from storage
                if (stock.StockTicker == stockTicker)
                {
                    stockValue = stock.StockPrice.ToString();
                }
            }

            return(stockValue);
        }
Пример #18
0
        public static Task LogUserMessageAsync(SocketMessage msg)
        {
            //Log user message to file
            var chnl = msg.Channel as SocketGuildChannel;
            var cc   = Console.BackgroundColor;

            try
            {
                Console.Write($"{DateTime.Now,-19} [    Log] {chnl.Guild.Name} ||  {msg.Channel} - {msg.Author}: ");
            }
            catch (Exception)
            {
                Console.Write($"{DateTime.Now,-19} [    Log] Direct Message >| {msg.Channel} - {msg.Author}: ");
            }

            Console.BackgroundColor = ConsoleColor.DarkGray;
            Console.WriteLine(msg.ToString());

            string logLocation = CoreMethod.GetFileLocation("BotOutputLog.txt");

            try
            {
                using (System.IO.StreamWriter file =
                           new System.IO.StreamWriter(logLocation, true))
                {
                    file.WriteLine($"{DateTime.Now,-19} [    Log] {chnl.Guild.Name} || {msg.Channel} - {msg.Author}: {msg.ToString()}");
                }
            }
            catch (Exception)
            {
                try
                {
                    using (System.IO.StreamWriter file =
                               new System.IO.StreamWriter(logLocation, true))
                    {
                        file.WriteLine($"{DateTime.Now,-19} [    Log] Direct Message >| {msg.Channel} - {msg.Author}: {msg.ToString()}");
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to write to log file!");
                }
            }
            Console.BackgroundColor = cc;
            return(Task.CompletedTask);
        }
Пример #19
0
        /// <summary>
        /// Gets list of custom guild roles for given guild
        /// </summary>
        /// <param name="guildID">Id of target guild</param>
        /// <returns>List of GuildRoleEntry containing guild id, role name, guild role id</returns>
        public static List <GuildRoleEntry> GetGuildRoles(ulong guildID)
        {
            //Get roles from file
            var roleStorage = XmlManager.FromXmlFile <GuildRoleStorage>(CoreMethod.GetFileLocation(@"\GuildRoles.xml"));

            List <GuildRoleEntry> guildRoleEntries = new List <GuildRoleEntry>();

            //Filter roles to ones with guild ID
            foreach (var role in roleStorage.GuildRoles)
            {
                if (role.GuildID == guildID)
                {
                    guildRoleEntries.Add(role);
                }
            }

            return(guildRoleEntries);
        }
Пример #20
0
        public static async Task SellAllSelectedInventoryItemAsync(SocketCommandContext Context, string itemMarketHash)
        {
            //Get skin data
            var rootSkinData = CsgoDataHandler.GetRootWeaponSkin();
            var userSkin     = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml"));

            try
            {
                //Find ALL user selected items, make sure it is owned by user
                var selectedSkinToSell = userSkin.UserSkinEntries
                                         .Where(s => s.MarketName.ToLower().Contains(itemMarketHash.ToLower()))
                                         .Where(s => s.OwnerID == Context.Message.Author.Id).ToList();

                //Get item prices
                long weaponSkinValue = GetItemValue(selectedSkinToSell, rootSkinData);

                //Give user credits
                UserCreditsHandler.AddCredits(Context, weaponSkinValue, true);

                //Remove skin from inventory
                List <string> filterUserSkinNames = new List <string>();
                foreach (var item in selectedSkinToSell)
                {
                    //Remove items that were selected to be sold
                    userSkin.UserSkinEntries.Remove(item);

                    filterUserSkinNames.Add(item.MarketName);
                }

                //Write to file
                WriteUserSkinDataToFile(userSkin);

                //Send receipt
                await Context.Channel.SendMessageAsync(
                    UserInteraction.BoldUserName(Context) + $", you sold your \n`{string.Join("\n", filterUserSkinNames)}`" +
                    $" for **{UserBankingHandler.CreditCurrencyFormatter(weaponSkinValue)} Credits** " +
                    $"| A total of **{UserBankingHandler.CreditCurrencyFormatter(UserCreditsTaxHandler.TaxCollector(weaponSkinValue))} Credits was taken off as tax**");
            }
            catch (Exception)
            {
                //Send error if user does not have item
                await Context.Channel.SendMessageAsync($"**{Context.Message.Author.ToString().Substring(0, Context.Message.Author.ToString().Length - 5)}**, you do not have `{itemMarketHash}` in your inventory");
            }
        }
        /// <summary>
        /// Updates the user market stocks
        /// </summary>
        public static void UpdateMarketStocks()
        {
            while (MainProgram._stopThreads == false)
            {
                //Get market stocks
                var marketStockStorage = XmlManager.FromXmlFile <MarketStockStorage>(CoreMethod.GetFileLocation(@"\MarketStocksValue.xml"));

                List <MarketStock> updatedMarketStocks = new List <MarketStock>();

                //Get real price for each
                foreach (var stock in marketStockStorage.MarketStock)
                {
                    long stockPriceNew = 0;

                    try
                    {
                        stockPriceNew = Convert.ToInt64(OnlineStockHandler.GetOnlineStockInfo(stock.StockTicker).LatestPrice * 100);
                    }
                    catch (Exception)
                    {
                    }


                    updatedMarketStocks.Add(new MarketStock {
                        StockTicker = stock.StockTicker, StockPrice = stockPriceNew
                    });
                }

                //Write to file
                var marketStock = new MarketStockStorage
                {
                    MarketOpen  = OnlineStockHandler.GetOnlineIsOpen(),
                    MarketStock = updatedMarketStocks
                };

                XmlManager.ToXmlFile(marketStock, CoreMethod.GetFileLocation(@"\MarketStocksValue.xml"));

                //Wait 10 seconds
                Thread.Sleep(10000);
            }
        }
Пример #22
0
        /// <summary>
        /// virtual CS:GO drop given to user
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static async Task OpenDrop(SocketCommandContext context)
        {
            //Select a rarity, this is slightly modified towards the white side of the spectrum, higher value items are harder to get as this is a drop
            var rarity = ItemDropProcessing.CalculateItemDropRarity();


            //Get item
            var skinItem = ItemDropProcessing.GetItem(rarity, CsgoDataHandler.rootWeaponSkin, context, true);


            //Add item to user file inventory
            var userSkin = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml"));

            userSkin.UserSkinEntries.Add(new UserSkinEntry {
                ClassId = skinItem.Classid, OwnerID = context.Message.Author.Id, UnboxDate = DateTime.UtcNow, MarketName = skinItem.Name
            });

            XmlManager.ToXmlFile(userSkin, CoreMethod.GetFileLocation("UserSkinStorage.xml"));

            //Send item into
            await SendOpenedItemInfo(context, skinItem, Convert.ToInt64(skinItem.Price.AllTime.Average), UnboxType.ItemDrop);
        }
Пример #23
0
        //Sell
        public static async Task SellInventoryItemAsync(SocketCommandContext Context, string itemMarketHash)
        {
            //Get skin data
            var rootWeaponSkin = CsgoDataHandler.GetRootWeaponSkin();
            var rootUserSkin   = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml"));

            try
            {
                //Find user selected item, make sure it is owned by user
                var selectedSkinToSell = rootUserSkin.UserSkinEntries
                                         .Where(s => s.MarketName.ToLower().Contains(itemMarketHash.ToLower()))
                                         .Where(s => s.OwnerID == Context.Message.Author.Id)
                                         .FirstOrDefault();

                //Get item price
                long weaponSkinValue = Convert.ToInt64(rootWeaponSkin.ItemsList.Values.Where(s => s.Name == selectedSkinToSell.MarketName).FirstOrDefault().Price.AllTime.Average);

                //Give user credits
                UserCreditsHandler.AddCredits(Context, weaponSkinValue, true);

                //Remove skin from inventory
                var filteredUserSkinEntries = rootUserSkin.UserSkinEntries.Where(s => s.OwnerID == Context.Message.Author.Id).Where(s => s.ClassId != selectedSkinToSell.ClassId).ToList();

                //Write to file
                WriteUserSkinDataToFile(filteredUserSkinEntries);

                //Send receipt
                await Context.Channel.SendMessageAsync(
                    UserInteraction.BoldUserName(Context) + $", you sold your `{selectedSkinToSell.MarketName}`" +
                    $" for **{UserBankingHandler.CreditCurrencyFormatter(weaponSkinValue)} Credits** " +
                    $"| A total of **{UserBankingHandler.CreditCurrencyFormatter(UserCreditsTaxHandler.TaxCollector(weaponSkinValue))} Credits was taken off as tax**");
            }
            catch (Exception)
            {
                //Send error if user does not have item
                await Context.Channel.SendMessageAsync($"**{Context.Message.Author.ToString().Substring(0, Context.Message.Author.ToString().Length - 5)}**, you do not have `{itemMarketHash}` in your inventory");
            }
        }
        // Override the CheckPermissions method
        public async override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider _services)
        {
            try
            {
                //
                // If this command was executed by predefined users, return a failure
                List <ulong> blacklistedUsers = new List <ulong>();

                CoreMethod.ReadFromFileToList(CoreMethod.GetFileLocation("UserBlacklist.txt")).ForEach(u => blacklistedUsers.Add(ulong.Parse(u)));

                //Test if user is blacklisted
                bool userIsBlackListed = false;
                foreach (var user in blacklistedUsers)
                {
                    if (context.Message.Author.Id == user)
                    {
                        userIsBlackListed = true;
                    }
                }

                if (userIsBlackListed == false)
                {
                    return(PreconditionResult.FromSuccess());
                }
                else
                {
                    await context.Channel.SendMessageAsync(context.Message.Author.Mention + " You have been blocked from using this command");

                    return(PreconditionResult.FromError("You have been blocked from using this command."));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #25
0
        /// <summary>
        /// Gathers weapon skin data, if it has not been processed, it will process it
        /// </summary>
        /// <returns></returns>
        public static RootSkinData GetRootWeaponSkin()
        {
            if (rootWeaponSkin == null)
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                EventLogger.LogMessage("Gathering CS:GO skin data, this may take a while");


                RootSkinData rootWeaponSkinTemp = new RootSkinData();
                //Read skin data from local json file
                using (StreamReader r = new StreamReader(CoreMethod.GetFileLocation("skinData.json")))
                {
                    string json           = r.ReadToEnd();
                    var    rootWeaponSkin = RootSkinData.FromJson(json);

                    rootWeaponSkinTemp = rootWeaponSkin;
                }

                //It json has not been formatted yet for use, format it
                if (!rootWeaponSkinTemp.Processed)
                {
                    EventLogger.LogMessage("CS:GO skin data has not been formatted yet, formatting... this WILL take a while");

                    //Sort items
                    foreach (var skin in rootWeaponSkinTemp.ItemsList.Values)
                    {
                        //Multiply all prices by 100 to remove decimals on price
                        if (skin.Price != null)
                        {
                            rootWeaponSkinTemp.ItemsList[skin.Name].Price.AllTime.Average = skin.Price.AllTime.Average * 100;
                        }
                        else
                        {
                            rootWeaponSkinTemp.ItemsList = rootWeaponSkinTemp.ItemsList.Where(s => s.Key != skin.Name).ToDictionary(x => x.Key, y => y.Value);
                        }

                        //Sort each skin into corropsonding cases
                        //Read from case data config
                        var skinCases = CsgoUnboxingHandler.csgoContiners;

                        //Find the container for each skin
                        foreach (var skinCase in skinCases.Containers)
                        {
                            //Check for each skin in each container
                            foreach (var skinCaseItem in skinCase.ContainerEntries)
                            {
                                List <string> comparisonItems = new List <string>();

                                //if FN, MW, ETC, it will find all skin conditions + stattrak

                                //For above, append statements for wear
                                if (!skinCase.IsSouvenir)
                                {
                                    comparisonItems.Add(skinCaseItem.SkinName + " (Factory New)");
                                    comparisonItems.Add(skinCaseItem.SkinName + " (Minimal Wear)");
                                    comparisonItems.Add(skinCaseItem.SkinName + " (Field-Tested)");
                                    comparisonItems.Add(skinCaseItem.SkinName + " (Well-Worn)");
                                    comparisonItems.Add(skinCaseItem.SkinName + " (Battle-Scarred)");

                                    //Add StatTrak\u2122 before to check for stattrak
                                    comparisonItems.Add("StatTrak\u2122 " + skinCaseItem.SkinName + " (Factory New)");
                                    comparisonItems.Add("StatTrak\u2122 " + skinCaseItem.SkinName + " (Minimal Wear)");
                                    comparisonItems.Add("StatTrak\u2122 " + skinCaseItem.SkinName + " (Field-Tested)");
                                    comparisonItems.Add("StatTrak\u2122 " + skinCaseItem.SkinName + " (Well-Worn)");
                                    comparisonItems.Add("StatTrak\u2122 " + skinCaseItem.SkinName + " (Battle-Scarred)");

                                    //KNIVES

                                    //\u2605 for knives
                                    comparisonItems.Add("\u2605 " + skinCaseItem.SkinName + " (Factory New)");
                                    comparisonItems.Add("\u2605 " + skinCaseItem.SkinName + " (Minimal Wear)");
                                    comparisonItems.Add("\u2605 " + skinCaseItem.SkinName + " (Field-Tested)");
                                    comparisonItems.Add("\u2605 " + skinCaseItem.SkinName + " (Well-Worn)");
                                    comparisonItems.Add("\u2605 " + skinCaseItem.SkinName + " (Battle-Scarred)");

                                    //\u2605 StatTrak\u2122 for knife stattrak
                                    comparisonItems.Add("\u2605 StatTrak\u2122 " + skinCaseItem.SkinName + " (Factory New)");
                                    comparisonItems.Add("\u2605 StatTrak\u2122 " + skinCaseItem.SkinName + " (Minimal Wear)");
                                    comparisonItems.Add("\u2605 StatTrak\u2122 " + skinCaseItem.SkinName + " (Field-Tested)");
                                    comparisonItems.Add("\u2605 StatTrak\u2122 " + skinCaseItem.SkinName + " (Well-Worn)");
                                    comparisonItems.Add("\u2605 StatTrak\u2122 " + skinCaseItem.SkinName + " (Battle-Scarred)");
                                }

                                //Souvenir
                                else if (skinCase.IsSouvenir)
                                {
                                    comparisonItems.Add("Souvenir " + skinCaseItem.SkinName + " (Factory New)");
                                    comparisonItems.Add("Souvenir " + skinCaseItem.SkinName + " (Minimal Wear)");
                                    comparisonItems.Add("Souvenir " + skinCaseItem.SkinName + " (Field-Tested)");
                                    comparisonItems.Add("Souvenir " + skinCaseItem.SkinName + " (Well-Worn)");
                                    comparisonItems.Add("Souvenir " + skinCaseItem.SkinName + " (Battle-Scarred)");
                                }

                                //Check for possible matches, matching CASE skin name
                                foreach (var comparisonItem in comparisonItems)
                                {
                                    //Use UnicodeLiteralConverter.DecodeToNonAsciiCharacters() before comparason to decode unicode
                                    if (UnicodeLiteralConverter.DecodeToNonAsciiCharacters(skin.Name) == UnicodeLiteralConverter.DecodeToNonAsciiCharacters(comparisonItem))
                                    {
                                        //If skin.Cases is null, create a new list
                                        if (skin.Cases == null)
                                        {
                                            skin.Cases = new List <Case>();
                                        }

                                        //If item matches, set the cases property of the item to current name of the case it is checking
                                        skin.Cases.Add(new Case
                                        {
                                            CaseName       = skinCase.Name,
                                            CaseCollection = skinCase.CollectionName
                                        });
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    rootWeaponSkinTemp.Processed = true;

                    //Write results to skin data file
                    string jsonToWrite = JsonConvert.SerializeObject(rootWeaponSkinTemp);
                    CoreMethod.WriteStringToFile(jsonToWrite, true, CoreMethod.GetFileLocation("skinData.json"));
                }

                rootWeaponSkin = rootWeaponSkinTemp;

                stopwatch.Stop();
                EventLogger.LogMessage($"Gathering CS:GO skin data, this may take a while --- Done! - Took {stopwatch.Elapsed.TotalMilliseconds} milliseconds");
            }


            return(rootWeaponSkin);
        }
Пример #26
0
        public static async Task BuyUserStocksAsync(SocketCommandContext Context, string tickerSymbol, long buyAmount)
        {
            var marketStockStorage = XmlManager.FromXmlFile <MarketStockStorage>(CoreMethod.GetFileLocation(@"\MarketStocksValue.xml"));

            foreach (var stock in marketStockStorage.MarketStock)
            {
                //Get the user selected stock from storage
                if (stock.StockTicker == tickerSymbol)
                {
                    //Sets buystockExists to true so it won't send a warning saying stock does not exist
                    bool buyStockExists = true;

                    //Get user portfolio
                    var userStocksStorage = XmlManager.FromXmlFile <UserStockStorage>(CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + Context.User.Id.ToString() + ".xml");

                    //Calculate stock price
                    long stockTotalCost = stock.StockPrice * buyAmount;

                    //Return error if stock value is currently at 0
                    if (stock.StockPrice <= 0)
                    {
                        await Context.Message.Channel.SendMessageAsync($"There are no available sellers for stock **{tickerSymbol}**");
                    }
                    //Check if user can buy stock
                    else if (UserCreditsHandler.GetUserCredits(Context) - stockTotalCost < 0)
                    {
                        await Context.Message.Channel.SendMessageAsync($"You do not have enough credits to buy **{buyAmount} {tickerSymbol}** stocks at price of **{UserBankingHandler.CreditCurrencyFormatter(stock.StockPrice)} each** totaling **{UserBankingHandler.CreditCurrencyFormatter(stockTotalCost)} Credits**");
                    }
                    //Check if user is buying 0 or less stocks
                    else if (buyAmount < 1)
                    {
                        await Context.Message.Channel.SendMessageAsync($"You must buy **1 or more** stocks");
                    }
                    else
                    {
                        //Subtract user balance
                        UserCreditsHandler.AddCredits(Context, Convert.ToInt64(-stockTotalCost));


                        //Check if user already has some of stock currently buying
                        //If true, Calculates new user stock total
                        long newStockAmount = buyAmount;
                        foreach (var userStock in userStocksStorage.UserStock)
                        {
                            if (userStock.StockTicker == tickerSymbol)
                            {
                                newStockAmount += userStock.StockAmount;
                            }
                        }


                        //Send user receipt
                        await Context.Message.Channel.SendMessageAsync($"You purchased **{buyAmount} {tickerSymbol}** stocks at price of **{stock.StockPrice} each** totaling **{stockTotalCost} Credits**");


                        //Add existing user stocks to list
                        var userStockStorage = XmlManager.FromXmlFile <UserStockStorage>(CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + Context.User.Id.ToString() + ".xml");
                        List <UserStock> userStockStorageList = new List <UserStock>();

                        foreach (var userStock in userStockStorage.UserStock)
                        {
                            if (userStock.StockTicker != tickerSymbol)
                            {
                                userStockStorageList.Add(userStock);
                            }
                        }

                        //Add new stock
                        userStockStorageList.Add(new UserStock {
                            StockTicker = tickerSymbol, StockAmount = newStockAmount, StockBuyPrice = stock.StockPrice
                        });

                        //Write user stock amount
                        var userStockRecord = new UserStockStorage
                        {
                            UserStock = userStockStorageList
                        };

                        XmlManager.ToXmlFile(userStockRecord, CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + Context.User.Id.ToString() + ".xml");
                    }

                    //Send warning if stock does not exist
                    if (buyStockExists == false)
                    {
                        await Context.Message.Channel.SendMessageAsync($"Stock **{tickerSymbol}** does not exist in the market");
                    }
                }
            }
        }
        public static async Task ProhibitedWordsHandler(SocketMessage message)
        {
            //Return is sender is a bot
            if (message.Author.IsBot)
            {
                return;
            }

            CultureInfo   culture      = new CultureInfo("en-CA", false);
            List <string> blockedWords = new List <string>();

            bool userWhiteListed  = GetIsUserWhitelisted(message);
            bool sendSwearWarning = false;

            //Prohibited word detection

            //Reads list of prohibited words from file, checks if message contains words
            var prohibitedWords = File.ReadAllLines(CoreMethod.GetFileLocation("ProhibitedWords.txt"));

            foreach (var forbiddenWord in prohibitedWords)
            {
                if (culture.CompareInfo.IndexOf(message.Content, forbiddenWord, CompareOptions.IgnoreCase) >= 0 && message.Author.IsBot != true)
                {
                    blockedWords.Add(forbiddenWord);
                    sendSwearWarning = true;
                }
            }

            //Sends swear warning to user if previous statement detected swear word
            if (sendSwearWarning == true && userWhiteListed == false)
            {
                string userReturnString = string.Join(", ", blockedWords);

                bool sendWarning = false;
                if (!UserTracker.TryGetValue(message.Author.Id, out var selectedUserTracker))
                {
                    //If user does not exist in tracker, add it
                    UserTracker.Add(message.Author.Id, new ProhibitedWordsUserTracker
                    {
                        SentProhibitedWords = blockedWords,
                        SentTime            = DateTime.UtcNow
                    });

                    sendWarning = true;
                }
                //If user has not sent the same words
                else
                {
                    foreach (var badWord in blockedWords)
                    {
                        if (!selectedUserTracker.SentProhibitedWords.Contains(badWord))
                        {
                            sendWarning = true;

                            //Set blocked words to current words
                            UserTracker[message.Author.Id].SentProhibitedWords = blockedWords;
                        }
                    }
                }

                //Send swear warning
                if (sendWarning == true)
                {
                    await message.Channel.SendMessageAsync(message.Author.Mention + " HEY `" + message.Author.Username + "` WATCH IT! THIS IS A F*****G CHRISTIAN F*****G DISCORD SERVER, `" + userReturnString + "` IS NOT ALLOWED HERE");
                }



                //Logs user swear amount to local counter
                //Get user storage
                var userStorage = XmlManager.FromXmlFile <UserStorage>(CoreMethod.GetFileLocation(@"\UserStorage") + @"\" + message.Author.Id + ".xml");

                userStorage.UserInfo[message.Author.Id].UserProhibitedWordsStorage.SwearCount = userStorage.UserInfo[message.Author.Id].UserProhibitedWordsStorage.SwearCount + 1;

                //write new swear count to user profile
                var userRecord = new UserStorage
                {
                    UserInfo = userStorage.UserInfo
                };

                XmlManager.ToXmlFile(userRecord, CoreMethod.GetFileLocation(@"\UserStorage") + @"\" + message.Author.Id + ".xml");
            }
        }
Пример #28
0
        public static void WriteUserStorage(UserStorage userStorage)
        {
            string jsonToWrite = JsonConvert.SerializeObject(userStorage);

            CoreMethod.WriteStringToFile(jsonToWrite, true, CoreMethod.GetFileLocation("UserStorage.json"));
        }
Пример #29
0
        public static UserStorage GetUserStorage()
        {
            var json = CoreMethod.ReadFromFile(CoreMethod.GetFileLocation("UserStorage.json"));

            return(JsonConvert.DeserializeObject <UserStorage>(json));
        }
Пример #30
0
        //Command Handler
        public async Task HandleCommandAsync(SocketMessage messageParam)
        {
            // Don't process the command if it was a system message, if sender is bot
            SocketUserMessage message = messageParam as SocketUserMessage;

            if (message == null)
            {
                return;
            }

            if (message.Author.IsBot)
            {
                return;
            }

            //integer to determine when commands start
            int argPos = 0;


            //Ignore commands that are not using the prefix
            var    context       = new SocketCommandContext(_client, message);
            string commandPrefix = CommandGuildPrefixManager.GetGuildCommandPrefix(context);

            if (!(message.HasStringPrefix(commandPrefix + " ", ref argPos) ||
                  message.Author.IsBot))
            {
                return;
            }

            var result = await _commands.ExecuteAsync(context : context, argPos : argPos, services : _services);


            //COMMAND LOGGING
            // Inform the user if the command fails
            if (!result.IsSuccess)
            {
                var guild   = _client.GetGuild(384492615745142784);
                var channel = guild.GetTextChannel(504375404547801138);

                if (result.Error == CommandError.UnknownCommand)
                {
                    //Find similar commands
                    var    commandHelpDefinitionStorage = XmlManager.FromXmlFile <HelpMenuCommands>(CoreMethod.GetFileLocation(@"CommandHelpDescription.xml"));
                    string similarItemsString           = UserHelpHandler.FindSimilarCommands(
                        commandHelpDefinitionStorage.CommandHelpEntry.Select(i => i.CommandName).ToList(),
                        message.ToString().Substring(CommandGuildPrefixManager.GetGuildCommandPrefix(context).Length + 1));

                    //If no similar matches are found, send nothing
                    if (string.IsNullOrEmpty(similarItemsString))
                    {
                        await context.Channel.SendMessageAsync("Invalid command, use `.d help` for a list of commands");
                    }
                    //If similar matches are found, send suggestions
                    else
                    {
                        await context.Channel.SendMessageAsync($"Invalid command, use `.d help` for a list of commands. Did you mean: \n {similarItemsString}");
                    }
                }
                else if (result.Error == CommandError.BadArgCount)
                {
                    await context.Channel.SendMessageAsync($"Invalid command usage, use `.d help <command>` for correct command usage");
                }
                else if (result.Error != CommandError.UnmetPrecondition)
                {
                    await channel.SendMessageAsync($"[ERROR] **{message.Author.ToString()}** `{message}`  >|  {result.ErrorReason}");
                }
            }
        }