/// <summary> /// Writes input setting and setting value to setting file; Will overwrite existing setting if name exists /// </summary> /// <param name="settingName">Name of the setting to add/overwrite</param> /// <param name="settingValue">Value of setting to add/overwrite</param> public static void WriteToConfigFile(string settingName, string settingValue) { try { //Get settings var retrievedSettings = XmlManager.FromXmlFile <SettingsConfig>("Settings.xml"); //Filter out settings not selected var filteredSettings = retrievedSettings.Settings.Where(s => s.SettingName != settingName).ToList(); //Add new setting to filtered list filteredSettings.Add(new Setting { SettingName = settingName, SettingValue = settingValue }); //Write new setting with old ones var settingsConfig = new SettingsConfig { Settings = filteredSettings }; XmlManager.ToXmlFile(settingsConfig, "Settings.xml"); } catch (Exception) { } }
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) { } }
/// <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"); } }
/// <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")); }
/// <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")); }
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); }
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); }
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); }
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); }
/// <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); }
/// <summary> /// Returns the value of input config item as string /// </summary> /// <param name="settingName">Name of the config item</param> /// <returns></returns> public static string RetrieveFromConfigFile(string settingName) { try { //Get settings var retrievedSettings = XmlManager.FromXmlFile <SettingsConfig>("Settings.xml"); //Filter settings by name var filteredRetrievedSettings = retrievedSettings.Settings.Where(s => s.SettingName == settingName).ToList(); //Return filtered setting value return(filteredRetrievedSettings.FirstOrDefault().SettingValue); } catch (Exception) { } return(null); }
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); } }
/// <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); }
//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"); } }
//Buy public static async Task BuyItemFromMarketAsync(SocketCommandContext context, string itemMarketHash) { //Get skin data var rootWeaponSkins = CsgoDataHandler.GetRootWeaponSkin(); try { UserSkinEntry selectedMarketSkin = new UserSkinEntry(); //Get market skin cost long weaponSkinValue = Convert.ToInt64(rootWeaponSkins.ItemsList.Values.Where(s => s.Name.ToLower().Contains(itemMarketHash.ToLower())).FirstOrDefault().Price.AllTime.Average); //Add tax markup :) weaponSkinValue += Convert.ToInt64(weaponSkinValue * float.Parse(SettingsManager.RetrieveFromConfigFile("taxRate"))); bool userSpecifiedSkinExistsInMarket = false; //Make sure skin exists in market foreach (var marketSkin in rootWeaponSkins.ItemsList.Values) { //If it does exist, get info on it if (marketSkin.Name.ToLower().Contains(itemMarketHash.ToLower())) { userSpecifiedSkinExistsInMarket = true; selectedMarketSkin.ClassId = marketSkin.Classid; selectedMarketSkin.OwnerID = context.Message.Author.Id; selectedMarketSkin.UnboxDate = DateTime.UtcNow; selectedMarketSkin.MarketName = marketSkin.Name; } } //Send error if skin does not exist if (userSpecifiedSkinExistsInMarket == false) { await context.Message.Channel.SendMessageAsync(UserInteraction.BoldUserName(context) + $", `{itemMarketHash}` does not exist in the current skin market"); } //Make sure user has enough credits to buy skin else if (UserCreditsHandler.GetUserCredits(context) < weaponSkinValue) { await context.Message.Channel.SendMessageAsync($"**{context.Message.Author.ToString().Substring(0, context.Message.Author.ToString().Length - 5)}**, you do not have enough credits to buy`{itemMarketHash}` | **{UserCreditsHandler.GetUserCredits(context)} Credits**"); } else { //Checks are true, now give user skin and remove credits //Remove user credits UserCreditsHandler.AddCredits(context, -weaponSkinValue, true); //Add skin to inventory var userSkins = XmlManager.FromXmlFile <UserSkinStorageRootobject>(CoreMethod.GetFileLocation("UserSkinStorage.xml")); userSkins.UserSkinEntries.Add(selectedMarketSkin); var filteredUserSkin = new UserSkinStorageRootobject { SkinAmount = 0, UserSkinEntries = userSkins.UserSkinEntries }; XmlManager.ToXmlFile(filteredUserSkin, CoreMethod.GetFileLocation("UserSkinStorage.xml")); //Send receipt await context.Channel.SendMessageAsync( UserInteraction.BoldUserName(context) + $", you bought`{selectedMarketSkin.MarketName}`" + $" for **{UserBankingHandler.CreditCurrencyFormatter(weaponSkinValue)} Credits**"); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } }
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"); } }
//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}"); } } }
public static async Task DisplayCommandHelpMenu(SocketCommandContext Context, string inputCommand) { //Get command help list from storage var commandHelpDefinitionStorage = XmlManager.FromXmlFile <HelpMenuCommands>(CoreMethod.GetFileLocation(@"CommandHelpDescription.xml")); //Create a boolean to warn user that command does not exist if false bool commandHelpDefinitionExists = false; //Search commandHelpDefinitionStorage for command definition foreach (var commandHelpDefinition in commandHelpDefinitionStorage.CommandHelpEntry) { if (commandHelpDefinition.CommandName == inputCommand) { commandHelpDefinitionExists = true; var embedBuilder = new EmbedBuilder() .WithDescription($"**{commandHelpDefinition.CommandDescription}**") .WithColor(new Color(253, 88, 20)) .WithFooter(footer => { footer .WithText("Sent by " + Context.Message.Author.ToString()) .WithIconUrl(Context.Message.Author.GetAvatarUrl()); }) .WithAuthor(author => { author .WithName("Duck Help - " + inputCommand) .WithIconUrl("https://ubisafe.org/images/duck-transparent-jpeg-5.png"); }); if (!string.IsNullOrEmpty(commandHelpDefinition.CommandRequiredPermissions)) { embedBuilder.AddField("Permissions required", $"`{commandHelpDefinition.CommandRequiredPermissions}`"); } embedBuilder.AddField("Usage", $"`{commandHelpDefinition.CommandUsage}`"); if (!string.IsNullOrEmpty(commandHelpDefinition.CommandUsageDefinition)) { embedBuilder.AddField("Definitions", commandHelpDefinition.CommandUsageDefinition); } var embed = embedBuilder.Build(); await Context.Message.Channel.SendMessageAsync(" ", embed : embed).ConfigureAwait(false); } } //Send warning if command definition could not be found if (commandHelpDefinitionExists == false) { string similarItemsString = FindSimilarCommands(commandHelpDefinitionStorage.CommandHelpEntry.Select(i => i.CommandName).ToList(), inputCommand); //If no similar matches are found, send nothing if (string.IsNullOrEmpty(similarItemsString)) { await Context.Channel.SendMessageAsync($"Command **{inputCommand}** could not be found"); } //If similar matches are found, send suggestions else { await Context.Channel.SendMessageAsync($"Command **{inputCommand}** could not be found. Did you mean: \n {similarItemsString}"); } } }
public static async Task SellUserStocksAsync(SocketCommandContext Context, string tickerSymbol, long sellAmount) { var marketStockStorage = XmlManager.FromXmlFile <MarketStockStorage>(CoreMethod.GetFileLocation(@"\MarketStocksValue.xml")); foreach (var stock in marketStockStorage.MarketStock) { if (stock.StockTicker == tickerSymbol) { //Get user portfolio var userStockStorage = XmlManager.FromXmlFile <UserStockStorage>(CoreMethod.GetFileLocation(@"\UserStocks") + @"\" + Context.User.Id.ToString() + ".xml"); //Check if user is selling more stocks than they have try { long userStockAmount = 0; long stockTotalWorth = 0; foreach (var userStock in userStockStorage.UserStock) { if (userStock.StockTicker == tickerSymbol) { userStockAmount = userStock.StockAmount; stockTotalWorth = sellAmount * stock.StockPrice; } } if (userStockAmount - sellAmount < 0) { await Context.Message.Channel.SendMessageAsync($"You do not have enough **{tickerSymbol}** stocks to sell || **{userStockAmount} Stocks**"); } //Check if user is selling 0 or less stocks else if (sellAmount < 1) { await Context.Message.Channel.SendMessageAsync($"You must sell **1 or more** stocks"); } else { //Add user balance UserCreditsHandler.AddCredits( Context, //Subtract tax deductions stockTotalWorth - await UserCreditsTaxHandler.TaxCollectorAsync( Context, stockTotalWorth, $"You sold **{sellAmount} {tickerSymbol}** stocks totaling **{UserBankingHandler.CreditCurrencyFormatter(stockTotalWorth)} Credits**")); //Send user receipt long newStockAmount = userStockAmount - sellAmount; //Write user stock amount //Add existing user stocks to list List <UserStock> userStockStorageList = new List <UserStock>(); foreach (var userStock in userStockStorage.UserStock) { if (userStock.StockTicker != tickerSymbol) { userStockStorageList.Add(userStock); } } //Add newly sold 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"); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } } }
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"); } } } }