public async Task <bool> AddCurrencyForUser(ulong userID, int amount) { if (connectionString == "") { return(false); } using (var connection = new SqliteConnection($"Data Source={connectionString}")) { try { var command = connection.CreateCommand(); command.CommandText = "UPDATE DiscordUser SET CurrencyAmount = CurrencyAmount + $int1 WHERE UserId = $int2"; command.Parameters.AddWithValue("$int1", amount); command.Parameters.AddWithValue("$int2", userID); await connection.OpenAsync(); await command.ExecuteNonQueryAsync(); _logger.Log($"Command Executed", "ValDB"); } catch (Exception ex) { _logger.Log($"Exception: {ex.Message}", "ValDB"); return(false); } } return(true); }
public async Task AsyncMain() { _config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText(@"data/config.json")); _config.Shutdown = false; _random = new FloraRandom(); _reactions = new Reactions(_random); await _reactions.LoadReactionsFromDatabase(); _botGames = new BotGameHandler(_random, _client, _logger); await _botGames.LoadBotGamesFromDB(); //Services InitServices(); var provider = _map.BuildServiceProvider(); //Command Setup await InitCommands(provider); _commands.Log += Log; await _client.LoginAsync(TokenType.Bot, _config.Token); await _client.StartAsync(); provider.GetRequiredService <CommandHandler>(); //provider.GetRequiredService<StartupHandler>(); provider.GetRequiredService <ReactionHandler>(); provider.GetRequiredService <ImageRateLimitHandler>(); provider.GetRequiredService <ReactionHandler>(); _logger.Log("Updating User List", "Startup"); foreach (SocketGuild guild in _client.Guilds) { await guild.DownloadUsersAsync(); } if (_config.RotatingGames) { _logger.Log("Starting game rotation", "RotatingGames"); WorkingTask(); } //Block task until program is closed await Task.Delay(-1); }
public async Task Matt() { //Get a name string FetchedName = NameCaching(); //Caching debug _logger.Log("Fetched name: " + FetchedName, "debug"); //Check name isn't null if (String.IsNullOrEmpty(FetchedName)) { return; } //Now we do await Context.Channel.SendMessageAsync(FetchedName); }
public async Task Restore([Summary("Discord User to Restore")] IGuildUser user) { var sID = Context.Guild.Id; var uID = user.Id; _logger.Log(uID.ToString(), "Restore"); //Server directory path string directory = @"data/roles/" + sID; //Path to storage string filePath = directory + @"/" + uID + ".json"; //Woah hold up there, they've not had roles saved if (!File.Exists(filePath)) { return; } _logger.Log(filePath, "Restore"); //Get the roles List <string> SavedRoles = JsonConvert.DeserializeObject <List <string> >(File.ReadAllText(filePath)); //Collection of roles List <IRole> roles = new List <IRole>(); //Sort out the roles now foreach (string id in SavedRoles) { IRole role = Context.Guild.GetRole(ulong.Parse(id)); if (!(role == Context.Guild.EveryoneRole)) { roles.Add(role); } } //Add the roles they deserve await user.AddRolesAsync(roles); //Now tell the user we did it! Yay await Context.Channel.SendSuccessAsync("Restored roles for " + user.Mention); }
public UserRating GetUserRating(ulong userID) { try { return(_set.FirstOrDefault(x => x.UserID == userID)); } catch (Exception ex) { logger.Log("No User Rating Found - " + ex.Message.ToString(), "UserRating"); return(null); } }
public async Task Roll(string roll, int modifier = 0, string advantage = "") { _logger.Log(roll, "DnD"); roll = roll.Trim(); if (!Regex.IsMatch(roll, @"\d[d]\d*")) { await Context.Channel.SendErrorAsync("Invalid dice string"); return; } string[] sep = roll.Split('d'); int count = Int32.Parse(sep[0]); int dice = Int32.Parse(sep[1]); if (count == 0) { return; } if (count > 50) { return; } List <int> rolls = new List <int>(); if (advantage.ToLower().Equals("a") || advantage.ToLower().Equals("d")) { count = 2; } for (int i = 0; i < count; i++) { rolls.Add(_random.Next(dice) + 1); } string title = $"Rolling {rolls.Count}d{dice} {modifier.ToString("+0;-#")}"; if (advantage.ToLower().Equals("a")) { title += " | Rolling with advantage."; } if (advantage.ToLower().Equals("d")) { title += " | Rolling with disadvantage."; } var embed = new EmbedBuilder().WithDnDColour().WithTitle(title); string desc = ""; foreach (int i in rolls) { desc += $"`{i}` "; } desc.TrimEnd(); embed.AddField(efb => efb.WithName("Rolls").WithValue(desc).WithIsInline(true)).AddField(efb => efb.WithName("Modifier").WithValue(modifier.ToString("+0;-#")).WithIsInline(true)); string finaltotal = ""; if (advantage.ToLower().Equals("a")) { finaltotal += $"{rolls.Max() + modifier}"; } else if (advantage.ToLower().Equals("d")) { finaltotal += $"{rolls.Min() + modifier}"; } else { finaltotal += $"{rolls.Sum() + modifier}"; } embed.AddField(efb => efb.WithName("Total").WithValue(finaltotal)); await Context.Channel.BlankEmbedAsync(embed.Build()); }
public async Task Create(ulong side, [Remainder] string content) { DateTime curTime = DateTime.Now; DateTime lastMessage; lastMessage = _cooldowns.GetUserCooldownsForCommand("InfiniteDieCreate", Context.User.Id); if (lastMessage + new TimeSpan(3, 0, 0) > curTime) { await Context.Channel.SendErrorAsync("You may only use this command once every 3 hours!"); return; } DBconnection _conn = DBconnection.Instance(); _conn.DBName = "cynicalp_weebnation"; bool isAvailable = false; ulong diceOwnerID = 0; _logger.Log(side.ToString(), "IDie"); if (_conn.IsConnected()) { string query = "SELECT * FROM dice WHERE DiceNumber=@side"; var cmd = new MySqlCommand(query, _conn.Connection); cmd.Parameters.AddWithValue("@side", side); var reader = await cmd.ExecuteReaderAsync(); if (!(reader.HasRows)) { isAvailable = true; } else { while (await reader.ReadAsync()) { diceOwnerID = (ulong)reader.GetInt64(2); } } _conn.Close(); } if (!isAvailable && diceOwnerID != Context.User.Id) { await Context.Channel.SendErrorAsync($"Side {side} is taken."); return; } //They can have it, lets do it. if (diceOwnerID == 0) { if (_conn.IsConnected()) { string query = "INSERT INTO dice(DiceNumber, DiceOwner) VALUES (@side, @uid)"; var cmd = new MySqlCommand(query, _conn.Connection); cmd.Parameters.AddWithValue("@side", side); cmd.Parameters.AddWithValue("@uid", Context.User.Id); await cmd.ExecuteNonQueryAsync(); _conn.Close(); } } long DiceID = 0; if (_conn.IsConnected()) { string query = "SELECT DiceID FROM dice WHERE DiceNumber=@side"; var cmd = new MySqlCommand(query, _conn.Connection); cmd.Parameters.AddWithValue("@side", side); var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { DiceID = reader.GetInt64(0); } if (DiceID == 0) { return; } _conn.Close(); } if (_conn.IsConnected()) { string query2 = "INSERT INTO content(DiceID, Content) VALUES (@did, @cont)"; var cmd2 = new MySqlCommand(query2, _conn.Connection); cmd2.Parameters.AddWithValue("@did", DiceID); cmd2.Parameters.AddWithValue("@cont", content); await cmd2.ExecuteNonQueryAsync(); _conn.Close(); } _cooldowns.AddUserCooldowns("InfiniteDieCreate", Context.User.Id, curTime); await Context.Channel.SendSuccessAsync("Side Added!"); await Context.Channel.SendSuccessAsync("Infinite Die | Side: " + side.ToString(), content, null, "Owner: " + Context.User.Username); }
public async Task SellLog(int count, [Summary("The tree type"), Remainder] string tree) { //first get their log count //Get tree ID string treeString = tree.ToLower().Replace(' ', '_'); int tID; if (!TreeID.TryGetValue(treeString, out tID)) { await Context.Channel.SendErrorAsync("Woodcutting", "Tree does not exist"); return; } _logger.Log("Woodcutting Selling", $"Tree ID: {tID}"); //From treeID we can get their log count Woodcutting wc; using (var uow = DBHandler.UnitOfWork()) { wc = uow.Woodcutting.GetOrCreateWoodcutting(Context.User.Id); } int specificLogCount = 0; switch (tID) { case 0: specificLogCount = wc.NormalTrees; break; case 1: specificLogCount = wc.AcheyTrees; break; case 2: specificLogCount = wc.OakTrees; break; case 3: specificLogCount = wc.WillowTrees; break; case 4: specificLogCount = wc.TeakTrees; break; case 5: specificLogCount = wc.MapleTrees; break; case 6: specificLogCount = wc.HollowTrees; break; case 7: specificLogCount = wc.MahoganyTrees; break; case 8: specificLogCount = wc.ArcticTrees; break; case 9: specificLogCount = wc.YewTrees; break; case 10: specificLogCount = wc.SullTrees; break; case 11: specificLogCount = wc.MagicTrees; break; case 12: specificLogCount = wc.RedwoodTrees; break; } if (specificLogCount < count) { await Context.Channel.SendErrorAsync("Woodcutting", $"You do not have enough {tree} logs."); return; } //We know they have enough. Get value. int logValue = LogValues[tID]; //How much do we need to give them int totalVal = logValue * count; //Okay so a few things we need to do using (var uow = DBHandler.UnitOfWork()) { //First we remove their logs uow.Woodcutting.AddTree(Context.User.Id, tID, -count); //Then we give them the gold uow.Woodcutting.AddGold(Context.User.Id, totalVal); //Then we done wc = uow.Woodcutting.GetOrCreateWoodcutting(Context.User.Id); } //Now we need to tell them we're done await Context.Channel.SendSuccessAsync("Woodcutting", $"{Context.User.Username}, you have just sold {count} {tree} logs for {totalVal} gold ({logValue} per log).\nYou now have a total of {wc.Gold} gold."); }