/// <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"); } }
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); }
// 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()); }
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")); }
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 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}"); } }
private static void GenerateConfigFile() { //Get user input and generate config file Console.WriteLine("It appears this is your first startup of DuckBot"); Console.WriteLine("Configure the bot by entering the paths file where all data will be stored"); Console.WriteLine(); string path = Console.ReadLine(); try { CoreMethod.WriteStringToFile(path, true, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Paths.txt"); Console.WriteLine(); Console.WriteLine("Setup is complete"); Console.WriteLine(); Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); Console.Clear(); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("An error occurred during setup"); Console.WriteLine(); Console.WriteLine("Press ENTER to continue..."); Console.WriteLine(); Console.WriteLine(ex.StackTrace); Console.ReadLine(); Console.Clear(); } }
/// <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")); }
/// <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]); }
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) { } }
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); }
//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); }
private async void listQuestion_SelectionChanged(object sender, SelectionChangedEventArgs e) { var content = await CoreMethod.GetArticle(Convert.ToInt32((e.AddedItems[0] as OneQuestion).Id)); if (content.Status == "OK") { new DetailContentWindow(content.Data as DetailContent, "One · 问题").Show(); } }
private static void WriteUserSkinDataToFile(List <UserSkinEntry> skinEntries) { var filteredUserSkin = new UserSkinStorageRootobject { SkinAmount = 0, UserSkinEntries = skinEntries }; XmlManager.ToXmlFile(filteredUserSkin, CoreMethod.GetFileLocation("UserSkinStorage.xml")); }
private async void InitialData() { var result = await CoreMethod.GetHome(); if (result.Status == "OK") { var home = result.Data as Home; carousel.ItemsSource = home.Ones; carousel.PageIndex = 0; listArticle.ItemsSource = home.Articles; listQuestion.ItemsSource = home.Questions; } }
/// <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")); }
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); }
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); }
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); } }
// Override the CheckPermissions method public async override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider _services) { // Get the client via Depedency Injection var client = _services.GetRequiredService <DiscordSocketClient>(); // Get the ID of the bot's owner var appInfo = await client.GetApplicationInfoAsync().ConfigureAwait(false); var ownerId = appInfo.Owner.Id; // // If this command was NOT executed by predefined users, return a failure List <ulong> whitelistedUsers = new List <ulong>(); whitelistedUsers.Add(ownerId); CoreMethod.ReadFromFileToList("UserWhitelist.txt").ForEach(u => whitelistedUsers.Add(ulong.Parse(u))); //Test if user is whitelisted bool userIsWhiteListed = false; foreach (var user in whitelistedUsers) { if (context.Message.Author.Id == user) { userIsWhiteListed = true; } } if (userIsWhiteListed == false) { await context.Channel.SendMessageAsync(context.Message.Author.Mention + " You must be whitelisted by the great duck commander to use this command"); return(PreconditionResult.FromError("You must be whitelisted by the great duck commander to use this command.")); } else { return(PreconditionResult.FromSuccess()); } }
/// <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"); } }
// 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; } }
public async Task <ModelBase> Get() { return(await CoreMethod.GetHome()); }
private void setAsPhpValueOnGenerator(CodeGenerator cg, BoundExpression valueExpr, CoreMethod setMethod) { var il = cg.Builder; il.EmitLoadArgumentOpcode(3); if (valueExpr == null) { cg.Emit_PhpValue_Null(); } else { cg.Emit(valueExpr); cg.EmitConvertToPhpValue(valueExpr.ResultType, valueExpr.TypeRefMask); } cg.EmitCall(ILOpCode.Call, setMethod); }