From 08015c61023fb57c37812eb57c34f7ecd7631185 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 13 May 2018 21:06:41 +0200 Subject: [PATCH] Port !stats, !role, !wiki and !slap, fix messages in rank, add roleselfservicemodel to db --- Geekbot.net/Commands/Admin/Role.cs | 48 +++++++++------- .../Commands/Integrations/Wikipedia.cs | 12 ++-- Geekbot.net/Commands/Randomness/Ship.cs | 37 +++++++----- Geekbot.net/Commands/Randomness/Slap.cs | 57 ++++++++++++++++--- Geekbot.net/Commands/User/Ranking/Rank.cs | 24 +++----- Geekbot.net/Commands/User/Stats.cs | 21 ++++--- Geekbot.net/Database/DatabaseContext.cs | 4 +- .../Database/Models/RoleSelfServiceModel.cs | 12 +++- 8 files changed, 141 insertions(+), 74 deletions(-) diff --git a/Geekbot.net/Commands/Admin/Role.cs b/Geekbot.net/Commands/Admin/Role.cs index 8624e66..a3a649e 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/Geekbot.net/Commands/Admin/Role.cs @@ -5,24 +5,25 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.Net; -using Geekbot.net.Lib; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; using Geekbot.net.Lib.ErrorHandling; +using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.ReactionListener; -using StackExchange.Redis; namespace Geekbot.net.Commands.Admin { [Group("role")] public class Role : ModuleBase { + private readonly DatabaseContext _database; private readonly IErrorHandler _errorHandler; - private readonly IDatabase _redis; private readonly IReactionListener _reactionListener; - public Role(IErrorHandler errorHandler, IDatabase redis, IReactionListener reactionListener) + public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener) { + _database = database; _errorHandler = errorHandler; - _redis = redis; _reactionListener = reactionListener; } @@ -32,8 +33,8 @@ namespace Geekbot.net.Commands.Admin { try { - var roles = _redis.HashGetAll($"{Context.Guild.Id}:RoleWhitelist"); - if (roles.Length == 0) + var roles = _database.RoleSelfService.Where(g => g.GuildId.Equals(Context.Guild.Id.AsLong())).ToList(); + if (roles.Count == 0) { await ReplyAsync("There are no roles configured for this server"); return; @@ -42,7 +43,7 @@ namespace Geekbot.net.Commands.Admin var sb = new StringBuilder(); sb.AppendLine($"**Self Service Roles on {Context.Guild.Name}**"); sb.AppendLine("To get a role, use `!role name`"); - foreach (var role in roles) sb.AppendLine($"- {role.Name}"); + foreach (var role in roles) sb.AppendLine($"- {role.WhiteListName}"); await ReplyAsync(sb.ToString()); } catch (Exception e) @@ -58,18 +59,19 @@ namespace Geekbot.net.Commands.Admin try { var roleName = roleNameRaw.ToLower(); - if (_redis.HashExists($"{Context.Guild.Id}:RoleWhitelist", roleName)) + var roleFromDb = _database.RoleSelfService.FirstOrDefault(e => + e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName)); + if (roleFromDb != null) { var guildUser = (IGuildUser) Context.User; - var roleId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:RoleWhitelist", roleName)); - var role = Context.Guild.Roles.First(r => r.Id == roleId); + var role = Context.Guild.Roles.First(r => r.Id == roleFromDb.RoleId.AsUlong()); if (role == null) { await ReplyAsync("That role doesn't seem to exist"); return; } - if (guildUser.RoleIds.Contains(roleId)) + if (guildUser.RoleIds.Contains(role.Id)) { await guildUser.RemoveRoleAsync(role); await ReplyAsync($"Removed you from {role.Name}"); @@ -113,12 +115,17 @@ namespace Geekbot.net.Commands.Admin || role.Permissions.KickMembers) { await ReplyAsync( - "Woah, i don't think you want to add that role to self service as it contains some dangerous permissions"); + "You cannot add that role to self service because it contains one or more dangerous permissions"); return; } - _redis.HashSet($"{Context.Guild.Id}:RoleWhitelist", - new[] {new HashEntry(roleName.ToLower(), role.Id.ToString())}); + _database.RoleSelfService.Add(new RoleSelfServiceModel + { + GuildId = Context.Guild.Id.AsLong(), + RoleId = role.Id.AsLong(), + WhiteListName = roleName + }); + _database.SaveChanges(); await ReplyAsync($"Added {role.Name} to the whitelist"); } catch (Exception e) @@ -134,16 +141,17 @@ namespace Geekbot.net.Commands.Admin { try { - - var success = _redis.HashDelete($"{Context.Guild.Id}:RoleWhitelist", roleName.ToLower()); - if (success) + var roleFromDb = _database.RoleSelfService.FirstOrDefault(e => + e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName)); + if (roleFromDb != null) { + _database.RoleSelfService.Remove(roleFromDb); + _database.SaveChanges(); await ReplyAsync($"Removed {roleName} from the whitelist"); return; } - await ReplyAsync("There is not whitelisted role with that name..."); - + await ReplyAsync("There is not whitelisted role with that name"); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Integrations/Wikipedia.cs b/Geekbot.net/Commands/Integrations/Wikipedia.cs index e2e8928..069ba8c 100644 --- a/Geekbot.net/Commands/Integrations/Wikipedia.cs +++ b/Geekbot.net/Commands/Integrations/Wikipedia.cs @@ -5,10 +5,10 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; +using Geekbot.net.Database; using Geekbot.net.Lib.ErrorHandling; +using Geekbot.net.Lib.Extensions; using HtmlAgilityPack; -using StackExchange.Redis; using WikipediaApi; using WikipediaApi.Page; @@ -18,13 +18,13 @@ namespace Geekbot.net.Commands.Integrations { private readonly IErrorHandler _errorHandler; private readonly IWikipediaClient _wikipediaClient; - private readonly IDatabase _redis; + private readonly DatabaseContext _database; - public Wikipedia(IErrorHandler errorHandler, IWikipediaClient wikipediaClient, IDatabase redis) + public Wikipedia(IErrorHandler errorHandler, IWikipediaClient wikipediaClient, DatabaseContext database) { _errorHandler = errorHandler; _wikipediaClient = wikipediaClient; - _redis = redis; + _database = database; } [Command("wiki", RunMode = RunMode.Async)] @@ -33,7 +33,7 @@ namespace Geekbot.net.Commands.Integrations { try { - var wikiLang = _redis.HashGet($"{Context.Guild.Id}:Settings", "WikiLang").ToString(); + var wikiLang = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(Context.Guild.Id.AsLong()))?.WikiLang; if (string.IsNullOrEmpty(wikiLang)) { wikiLang = "en"; diff --git a/Geekbot.net/Commands/Randomness/Ship.cs b/Geekbot.net/Commands/Randomness/Ship.cs index 735bd51..2e3588d 100644 --- a/Geekbot.net/Commands/Randomness/Ship.cs +++ b/Geekbot.net/Commands/Randomness/Ship.cs @@ -1,21 +1,23 @@ using System; +using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; using Geekbot.net.Lib.ErrorHandling; -using StackExchange.Redis; +using Geekbot.net.Lib.Extensions; namespace Geekbot.net.Commands.Randomness { public class Ship : ModuleBase { private readonly IErrorHandler _errorHandler; - private readonly IDatabase _redis; + private readonly DatabaseContext _database; - public Ship(IDatabase redis, IErrorHandler errorHandler) + public Ship(DatabaseContext database, IErrorHandler errorHandler) { - _redis = redis; + _database = database; _errorHandler = errorHandler; } @@ -25,22 +27,29 @@ namespace Geekbot.net.Commands.Randomness { try { - var dbstring = ""; - if (user1.Id > user2.Id) - dbstring = $"{user1.Id}-{user2.Id}"; - else - dbstring = $"{user2.Id}-{user1.Id}"; + var userKeys = user1.Id < user2.Id + ? new Tuple(user1.Id.AsLong(), user2.Id.AsLong()) + : new Tuple(user2.Id.AsLong(), user1.Id.AsLong()); - var dbval = _redis.HashGet($"{Context.Guild.Id}:Ships", dbstring); + var dbval = _database.Ships.FirstOrDefault(s => + s.FirstUserId.Equals(userKeys.Item1) && + s.SecondUserId.Equals(userKeys.Item2)); + var shippingRate = 0; - if (dbval.IsNullOrEmpty) + if (dbval == null) { shippingRate = new Random().Next(1, 100); - _redis.HashSet($"{Context.Guild.Id}:Ships", dbstring, shippingRate); + _database.Ships.Add(new ShipsModel() + { + FirstUserId = userKeys.Item1, + SecondUserId = userKeys.Item2, + Strength = shippingRate + }); + _database.SaveChanges(); } else { - shippingRate = int.Parse(dbval.ToString()); + shippingRate = dbval.Strength; } var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n"; diff --git a/Geekbot.net/Commands/Randomness/Slap.cs b/Geekbot.net/Commands/Randomness/Slap.cs index 2cac9d2..b37742b 100644 --- a/Geekbot.net/Commands/Randomness/Slap.cs +++ b/Geekbot.net/Commands/Randomness/Slap.cs @@ -1,23 +1,25 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; using Geekbot.net.Lib.ErrorHandling; -using StackExchange.Redis; +using Geekbot.net.Lib.Extensions; namespace Geekbot.net.Commands.Randomness { public class Slap : ModuleBase { private readonly IErrorHandler _errorHandler; - private readonly IDatabase _redis; + private readonly DatabaseContext _database; - public Slap(IErrorHandler errorHandler, IDatabase redis) + public Slap(IErrorHandler errorHandler, DatabaseContext database) { _errorHandler = errorHandler; - _redis = redis; + _database = database; } [Command("slap", RunMode = RunMode.Async)] @@ -76,16 +78,53 @@ namespace Geekbot.net.Commands.Randomness "dictionary", "powerless banhammer" }; - - _redis.HashIncrement($"{Context.Guild.Id}:SlapsRecieved", user.Id.ToString()); - _redis.HashIncrement($"{Context.Guild.Id}:SlapsGiven", Context.User.Id.ToString()); - + await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(things.Count - 1)]}"); + + UpdateRecieved(user.Id); + UpdateGiven(Context.User.Id); + _database.SaveChanges(); } catch (Exception e) { _errorHandler.HandleCommandException(e, Context); } } + + private void UpdateGiven(ulong userId) + { + var user = GetUser(userId); + user.Given++; + _database.Slaps.Update(user); + } + + private void UpdateRecieved(ulong userId) + { + var user = GetUser(userId); + user.Recieved++; + _database.Slaps.Update(user); + } + + private SlapsModel GetUser(ulong userId) + { + var user = _database.Slaps.FirstOrDefault(e => + e.GuildId.Equals(Context.Guild.Id.AsLong()) && + e.UserId.Equals(userId.AsLong()) + ); + + if (user != null) return user; + + _database.Slaps.Add(new SlapsModel + { + GuildId = Context.Guild.Id.AsLong(), + UserId = userId.AsLong(), + Recieved = 0, + Given = 0 + }); + _database.SaveChanges(); + return _database.Slaps.FirstOrDefault(e => + e.GuildId.Equals(Context.Guild.Id.AsLong()) && + e.UserId.Equals(userId.AsLong())); + } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/User/Ranking/Rank.cs b/Geekbot.net/Commands/User/Ranking/Rank.cs index dd1d026..027f41f 100644 --- a/Geekbot.net/Commands/User/Ranking/Rank.cs +++ b/Geekbot.net/Commands/User/Ranking/Rank.cs @@ -6,12 +6,12 @@ using System.Threading.Tasks; using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Database; -using Geekbot.net.Lib; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.UserRepository; +using StackExchange.Redis; namespace Geekbot.net.Commands.User.Ranking { @@ -23,9 +23,10 @@ namespace Geekbot.net.Commands.User.Ranking private readonly DatabaseContext _database; private readonly IUserRepository _userRepository; private readonly DiscordSocketClient _client; + private readonly IDatabase _redis; public Rank(DatabaseContext database, IErrorHandler errorHandler, IGeekbotLogger logger, IUserRepository userRepository, - IEmojiConverter emojiConverter, DiscordSocketClient client) + IEmojiConverter emojiConverter, DiscordSocketClient client, IDatabase redis) { _database = database; _errorHandler = errorHandler; @@ -33,6 +34,7 @@ namespace Geekbot.net.Commands.User.Ranking _userRepository = userRepository; _emojiConverter = emojiConverter; _client = client; + _redis = redis; } [Command("rank", RunMode = RunMode.Async)] @@ -74,8 +76,8 @@ namespace Geekbot.net.Commands.User.Ranking list = GetRollsList(amount); break; default: - list = new Dictionary(); - break; + await ReplyAsync("Valid types are '`messages`' '`karma`', '`rolls`'"); + return; } if (!list.Any()) @@ -142,18 +144,10 @@ namespace Geekbot.net.Commands.User.Ranking private Dictionary GetMessageList(int amount) { - var data = _database.Messages - .Where(k => k.GuildId.Equals(Context.Guild.Id.AsLong())) - .OrderByDescending(o => o.MessageCount) - .Take(amount); - - var dict = new Dictionary(); - foreach (var user in data) - { - dict.Add(user.UserId.AsUlong(), user.MessageCount); - } - return dict; + var data = _redis.HashGetAll($"{Context.Guild.Id}:Messages").ToDictionary().Take(amount + 1); + + return data.Where(user => !user.Key.Equals(0)).ToDictionary(user => ulong.Parse(user.Key), user => int.Parse(user.Value)); } private Dictionary GetKarmaList(int amount) diff --git a/Geekbot.net/Commands/User/Stats.cs b/Geekbot.net/Commands/User/Stats.cs index 93bddef..01d169e 100644 --- a/Geekbot.net/Commands/User/Stats.cs +++ b/Geekbot.net/Commands/User/Stats.cs @@ -1,9 +1,11 @@ using System; +using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; +using Geekbot.net.Database; using Geekbot.net.Lib.ErrorHandling; +using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Levels; using StackExchange.Redis; @@ -14,10 +16,12 @@ namespace Geekbot.net.Commands.User private readonly IErrorHandler _errorHandler; private readonly ILevelCalc _levelCalc; private readonly IDatabase _redis; + private readonly DatabaseContext _database; - public Stats(IDatabase redis, IErrorHandler errorHandler, ILevelCalc levelCalc) + public Stats(IDatabase redis, DatabaseContext database, IErrorHandler errorHandler, ILevelCalc levelCalc) { _redis = redis; + _database = database; _errorHandler = errorHandler; _levelCalc = levelCalc; } @@ -47,20 +51,23 @@ namespace Geekbot.net.Commands.User .WithName(userInfo.Username)); eb.WithColor(new Color(221, 255, 119)); - var karma = _redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString()); - var correctRolls = _redis.HashGet($"{Context.Guild.Id}:Rolls", userInfo.Id.ToString()); + var karma = _database.Karma.FirstOrDefault(e => + e.GuildId.Equals(Context.Guild.Id.AsLong()) && + e.UserId.Equals(userInfo.Id.AsLong())); + var correctRolls = _database.Rolls.FirstOrDefault(e => + e.GuildId.Equals(Context.Guild.Id.AsLong()) && + e.UserId.Equals(userInfo.Id.AsLong())); eb.AddInlineField("Discordian Since", $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)") .AddInlineField("Joined Server", $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)") - .AddInlineField("Karma", karma.ToString() ?? "0") + .AddInlineField("Karma", karma?.Karma ?? 0) .AddInlineField("Level", level) .AddInlineField("Messages Sent", messages) .AddInlineField("Server Total", $"{percent}%"); - if (!correctRolls.IsNullOrEmpty) - eb.AddInlineField("Guessed Rolls", correctRolls); + if (correctRolls != null) eb.AddInlineField("Guessed Rolls", correctRolls.Rolls); await ReplyAsync("", false, eb.Build()); } diff --git a/Geekbot.net/Database/DatabaseContext.cs b/Geekbot.net/Database/DatabaseContext.cs index e4fab28..e9de32c 100644 --- a/Geekbot.net/Database/DatabaseContext.cs +++ b/Geekbot.net/Database/DatabaseContext.cs @@ -15,8 +15,8 @@ namespace Geekbot.net.Database public DbSet Messages { get; set; } public DbSet Slaps { get; set; } public DbSet Globals { get; set; } - + public DbSet RoleSelfService { get; set; } + // public DbSet UserSettings { get; set; } - // public DbSet RoleSelfService { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Database/Models/RoleSelfServiceModel.cs b/Geekbot.net/Database/Models/RoleSelfServiceModel.cs index 4bb7f01..de8c341 100644 --- a/Geekbot.net/Database/Models/RoleSelfServiceModel.cs +++ b/Geekbot.net/Database/Models/RoleSelfServiceModel.cs @@ -1,7 +1,17 @@ -namespace Geekbot.net.Database.Models +using System.ComponentModel.DataAnnotations; + +namespace Geekbot.net.Database.Models { public class RoleSelfServiceModel { + [Key] + public int Id { get; set; } + [Required] + public long GuildId { get; set; } + + public long RoleId { get; set; } + + public string WhiteListName { get; set; } } } \ No newline at end of file