From 8d9c436cfca349f59bae2757ed87c4941d0657d1 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 23 May 2019 23:23:16 +0200 Subject: [PATCH 001/264] Add GeekbotBase as an extension of ModuleBase --- Geekbot.net/Commands/Randomness/Slap.cs | 7 ++- Geekbot.net/Handlers.cs | 8 ++- Geekbot.net/Lib/Context/GeekbotContext.cs | 56 +++++++++++++++++++ Geekbot.net/Lib/Context/IGeekbotContext.cs | 19 +++++++ Geekbot.net/Lib/GeekbotBase.cs | 9 +++ .../Lib/Localization/ITranslationHandler.cs | 2 + .../Lib/Localization/TranslationHandler.cs | 21 +++++-- Geekbot.net/Program.cs | 2 +- 8 files changed, 113 insertions(+), 11 deletions(-) create mode 100644 Geekbot.net/Lib/Context/GeekbotContext.cs create mode 100644 Geekbot.net/Lib/Context/IGeekbotContext.cs create mode 100644 Geekbot.net/Lib/GeekbotBase.cs diff --git a/Geekbot.net/Commands/Randomness/Slap.cs b/Geekbot.net/Commands/Randomness/Slap.cs index 20e83c3..3165581 100644 --- a/Geekbot.net/Commands/Randomness/Slap.cs +++ b/Geekbot.net/Commands/Randomness/Slap.cs @@ -6,12 +6,13 @@ using Discord; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; namespace Geekbot.net.Commands.Randomness { - public class Slap : ModuleBase + public class Slap : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; @@ -24,7 +25,7 @@ namespace Geekbot.net.Commands.Randomness [Command("slap", RunMode = RunMode.Async)] [Summary("slap someone")] - public async Task Slapper([Summary("@someone")] IUser user) + public async Task Slapper([Summary("@someone")] IGuildUser user) { try { @@ -79,7 +80,7 @@ namespace Geekbot.net.Commands.Randomness "powerless banhammer" }; - await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(things.Count - 1)]}"); + await ReplyAsync($"{Context.GuildUser.Nickname} slapped {user.Nickname} with a {things[new Random().Next(things.Count - 1)]}"); await UpdateRecieved(user.Id); await UpdateGiven(Context.User.Id); diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index a254c14..79390cc 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -9,7 +9,9 @@ using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Database.Models; using Geekbot.net.Lib.AlmostRedis; +using Geekbot.net.Lib.Context; using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; @@ -27,11 +29,12 @@ namespace Geekbot.net private readonly CommandService _commands; private readonly IUserRepository _userRepository; private readonly IReactionListener _reactionListener; + private readonly ITranslationHandler _translationHandler; private readonly DatabaseContext _messageCounterDatabaseContext; public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, - IReactionListener reactionListener) + IReactionListener reactionListener, ITranslationHandler translationHandler) { _database = databaseInitializer.Initialize(); _messageCounterDatabaseContext = databaseInitializer.Initialize(); @@ -42,6 +45,7 @@ namespace Geekbot.net _commands = commands; _userRepository = userRepository; _reactionListener = reactionListener; + _translationHandler = translationHandler; } // @@ -79,7 +83,7 @@ namespace Geekbot.net if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask; - var context = new CommandContext(_client, message); + var context = new GeekbotContext(_client, message, _translationHandler); var commandExec = _commands.ExecuteAsync(context, argPos, _servicesProvider); _logger.Information(LogSource.Command, context.Message.Content.Split(" ")[0].Replace("!", ""), diff --git a/Geekbot.net/Lib/Context/GeekbotContext.cs b/Geekbot.net/Lib/Context/GeekbotContext.cs new file mode 100644 index 0000000..dfc4281 --- /dev/null +++ b/Geekbot.net/Lib/Context/GeekbotContext.cs @@ -0,0 +1,56 @@ +using Discord; +using Geekbot.net.Lib.Localization; + +namespace Geekbot.net.Lib.Context +{ + /// The context of a command which may contain the client, user, guild, channel, and message. + public class GeekbotContext : IGeekbotContext + { + /// + public IDiscordClient Client { get; } + + /// + public IGuild Guild { get; } + + /// + public IMessageChannel Channel { get; } + + /// + public IUser User { get; } + + /// + public IUserMessage Message { get; } + + /// + public IGuildUser GuildUser { get; } + + /// + public TranslationGuildContext Translations { get; } + + /// Indicates whether the channel that the command is executed in is a private channel. + public bool IsPrivate + { + get + { + return this.Channel is IPrivateChannel; + } + } + + /// + /// Initializes a new class with the provided client and message. + /// + /// The underlying client. + /// The underlying message. + /// the translation handler + public GeekbotContext(IDiscordClient client, IUserMessage msg, ITranslationHandler translationHandler) + { + this.Client = client; + this.Guild = (msg.Channel as IGuildChannel)?.Guild; + this.Channel = msg.Channel; + this.User = msg.Author; + this.GuildUser = msg.Author as IGuildUser; + this.Message = msg; + this.Translations = translationHandler.GetGuildContext(this.Guild, this.Message).Result; + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/Context/IGeekbotContext.cs b/Geekbot.net/Lib/Context/IGeekbotContext.cs new file mode 100644 index 0000000..61884e1 --- /dev/null +++ b/Geekbot.net/Lib/Context/IGeekbotContext.cs @@ -0,0 +1,19 @@ +using Discord; +using Discord.Commands; +using Geekbot.net.Lib.Localization; + +namespace Geekbot.net.Lib.Context +{ + public interface IGeekbotContext : ICommandContext + { + /// + /// Gets the who executed the command. + /// + IGuildUser GuildUser { get; } + + /// + /// Gets the containing the necessary tools for command localization. + /// + TranslationGuildContext Translations { get; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/GeekbotBase.cs b/Geekbot.net/Lib/GeekbotBase.cs new file mode 100644 index 0000000..e92f212 --- /dev/null +++ b/Geekbot.net/Lib/GeekbotBase.cs @@ -0,0 +1,9 @@ +using Discord.Commands; +using Geekbot.net.Lib.Context; + +namespace Geekbot.net.Lib +{ + public abstract class GeekbotBase : ModuleBase + { + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/Localization/ITranslationHandler.cs b/Geekbot.net/Lib/Localization/ITranslationHandler.cs index 9cd0680..3672c26 100644 --- a/Geekbot.net/Lib/Localization/ITranslationHandler.cs +++ b/Geekbot.net/Lib/Localization/ITranslationHandler.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Threading.Tasks; +using Discord; using Discord.Commands; namespace Geekbot.net.Lib.Localization @@ -10,6 +11,7 @@ namespace Geekbot.net.Lib.Localization string GetString(string language, string command, string stringName); Task> GetDict(ICommandContext context, string command); Task GetGuildContext(ICommandContext context); + Task GetGuildContext(IGuild guild, IUserMessage message); Task SetLanguage(ulong guildId, string language); List SupportedLanguages { get; } } diff --git a/Geekbot.net/Lib/Localization/TranslationHandler.cs b/Geekbot.net/Lib/Localization/TranslationHandler.cs index 3d1ee3a..f1a30e5 100644 --- a/Geekbot.net/Lib/Localization/TranslationHandler.cs +++ b/Geekbot.net/Lib/Localization/TranslationHandler.cs @@ -3,13 +3,12 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using Discord; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Logger; -using Utf8Json; -using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; namespace Geekbot.net.Lib.Localization @@ -137,12 +136,17 @@ namespace Geekbot.net.Lib.Localization return translation; } - private async Task> GetDict(ICommandContext context) + private Task> GetDict(ICommandContext context) + { + return GetDict(context.Guild, context.Message); + } + + private async Task> GetDict(IGuild guild, IUserMessage message) { try { - var command = context.Message.Content.Split(' ').First().TrimStart('!').ToLower(); - var serverLanguage = await GetServerLanguage(context.Guild?.Id ?? 0); + var command = message.Content.Split(' ').First().TrimStart('!').ToLower(); + var serverLanguage = await GetServerLanguage(guild?.Id ?? 0); return _translations[serverLanguage][command]; } catch (Exception e) @@ -159,6 +163,13 @@ namespace Geekbot.net.Lib.Localization return new TranslationGuildContext(this, language, dict); } + public async Task GetGuildContext(IGuild guild, IUserMessage message) + { + var dict = await GetDict(guild, message); + var language = await GetServerLanguage(guild?.Id ?? 0); + return new TranslationGuildContext(this, language, dict); + } + public async Task> GetDict(ICommandContext context, string command) { try diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index b7251a8..9833b3a 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -170,7 +170,7 @@ namespace Geekbot.net _servicesProvider = _services.BuildServiceProvider(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener); + var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener, translationHandler); _client.MessageReceived += handlers.RunCommand; _client.MessageDeleted += handlers.MessageDeleted; From 295a1d575dbd06687daead500b5c374c73b9784c Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 23 May 2019 23:38:07 +0200 Subject: [PATCH 002/264] Use GeebotBase in every command --- Geekbot.net/Commands/Admin/Admin.cs | 3 ++- Geekbot.net/Commands/Admin/Mod.cs | 3 ++- Geekbot.net/Commands/Admin/Owner/Owner.cs | 3 ++- Geekbot.net/Commands/Admin/Role.cs | 5 +++-- Geekbot.net/Commands/Games/Pokedex.cs | 3 ++- Geekbot.net/Commands/Games/Roll.cs | 5 +++-- Geekbot.net/Commands/Integrations/Google/Google.cs | 3 ++- Geekbot.net/Commands/Integrations/MagicTheGathering.cs | 3 ++- Geekbot.net/Commands/Integrations/Mal.cs | 3 ++- .../Commands/Integrations/UbranDictionary/UrbanDictionary.cs | 3 ++- Geekbot.net/Commands/Integrations/Wikipedia.cs | 3 ++- Geekbot.net/Commands/Integrations/Youtube.cs | 3 ++- .../Commands/Randomness/BenedictCumberbatchNameGenerator.cs | 3 ++- Geekbot.net/Commands/Randomness/Cat/Cat.cs | 3 ++- Geekbot.net/Commands/Randomness/CheckEm.cs | 3 ++- Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs | 3 ++- Geekbot.net/Commands/Randomness/Dad/DadJokes.cs | 3 ++- Geekbot.net/Commands/Randomness/Dog/Dog.cs | 3 ++- Geekbot.net/Commands/Randomness/EightBall.cs | 3 ++- Geekbot.net/Commands/Randomness/Fortune.cs | 3 ++- Geekbot.net/Commands/Randomness/Gdq.cs | 3 ++- Geekbot.net/Commands/Randomness/Kanye/Kanye.cs | 3 ++- Geekbot.net/Commands/Randomness/RandomAnimals.cs | 3 ++- Geekbot.net/Commands/Randomness/Ship.cs | 3 ++- Geekbot.net/Commands/Rpg/Cookies.cs | 3 ++- Geekbot.net/Commands/User/GuildInfo.cs | 3 ++- Geekbot.net/Commands/User/Karma.cs | 3 ++- Geekbot.net/Commands/User/Ranking/Rank.cs | 3 ++- Geekbot.net/Commands/User/Stats.cs | 3 ++- Geekbot.net/Commands/Utils/AvatarGetter.cs | 3 ++- Geekbot.net/Commands/Utils/Changelog/Changelog.cs | 3 ++- Geekbot.net/Commands/Utils/Choose.cs | 3 ++- Geekbot.net/Commands/Utils/Dice/Dice.cs | 3 ++- Geekbot.net/Commands/Utils/Emojify.cs | 3 ++- Geekbot.net/Commands/Utils/Help.cs | 3 ++- Geekbot.net/Commands/Utils/Info.cs | 2 +- Geekbot.net/Commands/Utils/Ping.cs | 3 ++- Geekbot.net/Commands/Utils/Quote/Quote.cs | 3 ++- 38 files changed, 77 insertions(+), 40 deletions(-) diff --git a/Geekbot.net/Commands/Admin/Admin.cs b/Geekbot.net/Commands/Admin/Admin.cs index 15b4df1..6377c60 100644 --- a/Geekbot.net/Commands/Admin/Admin.cs +++ b/Geekbot.net/Commands/Admin/Admin.cs @@ -7,6 +7,7 @@ using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -17,7 +18,7 @@ namespace Geekbot.net.Commands.Admin [Group("admin")] [RequireUserPermission(GuildPermission.Administrator)] [DisableInDirectMessage] - public class Admin : ModuleBase + public class Admin : GeekbotBase { private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Admin/Mod.cs b/Geekbot.net/Commands/Admin/Mod.cs index 1188504..a2a2f4e 100644 --- a/Geekbot.net/Commands/Admin/Mod.cs +++ b/Geekbot.net/Commands/Admin/Mod.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.UserRepository; @@ -15,7 +16,7 @@ namespace Geekbot.net.Commands.Admin [RequireUserPermission(GuildPermission.ManageMessages)] [RequireUserPermission(GuildPermission.ManageRoles)] [DisableInDirectMessage] - public class Mod : ModuleBase + public class Mod : GeekbotBase { private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Admin/Owner/Owner.cs b/Geekbot.net/Commands/Admin/Owner/Owner.cs index 996d848..e395a44 100644 --- a/Geekbot.net/Commands/Admin/Owner/Owner.cs +++ b/Geekbot.net/Commands/Admin/Owner/Owner.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Geekbot.net.Lib.Logger; @@ -12,7 +13,7 @@ namespace Geekbot.net.Commands.Admin.Owner { [Group("owner")] [RequireOwner] - public class Owner : ModuleBase + public class Owner : GeekbotBase { private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Admin/Role.cs b/Geekbot.net/Commands/Admin/Role.cs index 85b7160..345ce34 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/Geekbot.net/Commands/Admin/Role.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -7,6 +7,7 @@ using Discord.Commands; using Discord.Net; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -17,7 +18,7 @@ namespace Geekbot.net.Commands.Admin { [Group("role")] [DisableInDirectMessage] - public class Role : ModuleBase + public class Role : GeekbotBase { private readonly DatabaseContext _database; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Games/Pokedex.cs b/Geekbot.net/Commands/Games/Pokedex.cs index a0d2ae0..32fd8eb 100644 --- a/Geekbot.net/Commands/Games/Pokedex.cs +++ b/Geekbot.net/Commands/Games/Pokedex.cs @@ -3,13 +3,14 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; using PokeAPI; namespace Geekbot.net.Commands.Games { - public class Pokedex : ModuleBase + public class Pokedex : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Games/Roll.cs b/Geekbot.net/Commands/Games/Roll.cs index dfecb13..39b44cf 100644 --- a/Geekbot.net/Commands/Games/Roll.cs +++ b/Geekbot.net/Commands/Games/Roll.cs @@ -1,9 +1,10 @@ -using System; +using System; using System.Linq; using System.Threading.Tasks; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -13,7 +14,7 @@ using StackExchange.Redis; namespace Geekbot.net.Commands.Games { - public class Roll : ModuleBase + public class Roll : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IAlmostRedis _redis; diff --git a/Geekbot.net/Commands/Integrations/Google/Google.cs b/Geekbot.net/Commands/Integrations/Google/Google.cs index db059b4..76c3795 100644 --- a/Geekbot.net/Commands/Integrations/Google/Google.cs +++ b/Geekbot.net/Commands/Integrations/Google/Google.cs @@ -4,13 +4,14 @@ using System.Net; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Newtonsoft.Json; namespace Geekbot.net.Commands.Integrations.Google { - public class Google : ModuleBase + public class Google : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IGlobalSettings _globalSettings; diff --git a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs b/Geekbot.net/Commands/Integrations/MagicTheGathering.cs index ef16fee..a9d2251 100644 --- a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs +++ b/Geekbot.net/Commands/Integrations/MagicTheGathering.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -11,7 +12,7 @@ using MtgApiManager.Lib.Service; namespace Geekbot.net.Commands.Integrations { - public class MagicTheGathering : ModuleBase + public class MagicTheGathering : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IMtgManaConverter _manaConverter; diff --git a/Geekbot.net/Commands/Integrations/Mal.cs b/Geekbot.net/Commands/Integrations/Mal.cs index ecc91bf..ace49f4 100644 --- a/Geekbot.net/Commands/Integrations/Mal.cs +++ b/Geekbot.net/Commands/Integrations/Mal.cs @@ -4,13 +4,14 @@ using System.Web; using System.Xml; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; namespace Geekbot.net.Commands.Integrations { - public class Mal : ModuleBase + public class Mal : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IMalClient _malClient; diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 4f29f10..420d2b4 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -4,13 +4,14 @@ using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; using Newtonsoft.Json; namespace Geekbot.net.Commands.Integrations.UbranDictionary { - public class UrbanDictionary : ModuleBase + public class UrbanDictionary : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Integrations/Wikipedia.cs b/Geekbot.net/Commands/Integrations/Wikipedia.cs index 9124670..1bc2390 100644 --- a/Geekbot.net/Commands/Integrations/Wikipedia.cs +++ b/Geekbot.net/Commands/Integrations/Wikipedia.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Database; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; using HtmlAgilityPack; @@ -14,7 +15,7 @@ using WikipediaApi.Page; namespace Geekbot.net.Commands.Integrations { - public class Wikipedia : ModuleBase + public class Wikipedia : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IWikipediaClient _wikipediaClient; diff --git a/Geekbot.net/Commands/Integrations/Youtube.cs b/Geekbot.net/Commands/Integrations/Youtube.cs index 1672bab..26f0e9c 100644 --- a/Geekbot.net/Commands/Integrations/Youtube.cs +++ b/Geekbot.net/Commands/Integrations/Youtube.cs @@ -1,6 +1,7 @@ using System; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Google.Apis.Services; @@ -8,7 +9,7 @@ using Google.Apis.YouTube.v3; namespace Geekbot.net.Commands.Integrations { - public class Youtube : ModuleBase + public class Youtube : GeekbotBase { private readonly IGlobalSettings _globalSettings; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs b/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs index 501f891..fa734fd 100644 --- a/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs +++ b/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs @@ -2,12 +2,13 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.RandomNumberGenerator; namespace Geekbot.net.Commands.Randomness { - public class BenedictCumberbatchNameGenerator : ModuleBase + public class BenedictCumberbatchNameGenerator : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IRandomNumberGenerator _randomNumberGenerator; diff --git a/Geekbot.net/Commands/Randomness/Cat/Cat.cs b/Geekbot.net/Commands/Randomness/Cat/Cat.cs index 4d43a4c..b752955 100644 --- a/Geekbot.net/Commands/Randomness/Cat/Cat.cs +++ b/Geekbot.net/Commands/Randomness/Cat/Cat.cs @@ -3,12 +3,13 @@ using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Cat { - public class Cat : ModuleBase + public class Cat : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/CheckEm.cs b/Geekbot.net/Commands/Randomness/CheckEm.cs index f8191ad..790dce8 100644 --- a/Geekbot.net/Commands/Randomness/CheckEm.cs +++ b/Geekbot.net/Commands/Randomness/CheckEm.cs @@ -3,12 +3,13 @@ using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Media; namespace Geekbot.net.Commands.Randomness { - public class CheckEm : ModuleBase + public class CheckEm : GeekbotBase { private readonly IMediaProvider _checkEmImages; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs b/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs index 07ea41f..ceb559c 100644 --- a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs +++ b/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs @@ -3,12 +3,13 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Chuck { - public class ChuckNorrisJokes : ModuleBase + public class ChuckNorrisJokes : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs b/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs index 2c51781..4bb204b 100644 --- a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs +++ b/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs @@ -3,12 +3,13 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Dad { - public class DadJokes : ModuleBase + public class DadJokes : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/Dog/Dog.cs b/Geekbot.net/Commands/Randomness/Dog/Dog.cs index 176cbad..6ea0d25 100644 --- a/Geekbot.net/Commands/Randomness/Dog/Dog.cs +++ b/Geekbot.net/Commands/Randomness/Dog/Dog.cs @@ -3,12 +3,13 @@ using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Dog { - public class Dog : ModuleBase + public class Dog : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/EightBall.cs b/Geekbot.net/Commands/Randomness/EightBall.cs index d07451d..e72f85e 100644 --- a/Geekbot.net/Commands/Randomness/EightBall.cs +++ b/Geekbot.net/Commands/Randomness/EightBall.cs @@ -2,11 +2,12 @@ using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; namespace Geekbot.net.Commands.Randomness { - public class EightBall : ModuleBase + public class EightBall : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/Fortune.cs b/Geekbot.net/Commands/Randomness/Fortune.cs index d4f6b5f..582cc75 100644 --- a/Geekbot.net/Commands/Randomness/Fortune.cs +++ b/Geekbot.net/Commands/Randomness/Fortune.cs @@ -1,10 +1,11 @@ using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.Media; namespace Geekbot.net.Commands.Randomness { - public class Fortune : ModuleBase + public class Fortune : GeekbotBase { private readonly IFortunesProvider _fortunes; diff --git a/Geekbot.net/Commands/Randomness/Gdq.cs b/Geekbot.net/Commands/Randomness/Gdq.cs index 2685b33..3bed944 100644 --- a/Geekbot.net/Commands/Randomness/Gdq.cs +++ b/Geekbot.net/Commands/Randomness/Gdq.cs @@ -2,11 +2,12 @@ using System.Net; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; namespace Geekbot.net.Commands.Randomness { - public class Gdq : ModuleBase + public class Gdq : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs index 42a6ca7..a37fbc3 100644 --- a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs +++ b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs @@ -4,13 +4,14 @@ using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; using Geekbot.net.Commands.Randomness.Dad; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Microsoft.AspNetCore.Hosting.Internal; using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Kanye { - public class Kanye : ModuleBase + public class Kanye : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Randomness/RandomAnimals.cs b/Geekbot.net/Commands/Randomness/RandomAnimals.cs index 8562908..8a15551 100644 --- a/Geekbot.net/Commands/Randomness/RandomAnimals.cs +++ b/Geekbot.net/Commands/Randomness/RandomAnimals.cs @@ -1,11 +1,12 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.Media; namespace Geekbot.net.Commands.Randomness { - public class RandomAnimals : ModuleBase + public class RandomAnimals : GeekbotBase { private readonly IMediaProvider _mediaProvider; diff --git a/Geekbot.net/Commands/Randomness/Ship.cs b/Geekbot.net/Commands/Randomness/Ship.cs index 2571891..3f43710 100644 --- a/Geekbot.net/Commands/Randomness/Ship.cs +++ b/Geekbot.net/Commands/Randomness/Ship.cs @@ -5,13 +5,14 @@ using Discord; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.RandomNumberGenerator; namespace Geekbot.net.Commands.Randomness { - public class Ship : ModuleBase + public class Ship : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly IRandomNumberGenerator _randomNumberGenerator; diff --git a/Geekbot.net/Commands/Rpg/Cookies.cs b/Geekbot.net/Commands/Rpg/Cookies.cs index f22eccf..f681a4e 100644 --- a/Geekbot.net/Commands/Rpg/Cookies.cs +++ b/Geekbot.net/Commands/Rpg/Cookies.cs @@ -5,6 +5,7 @@ using Discord; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -15,7 +16,7 @@ namespace Geekbot.net.Commands.Rpg { [DisableInDirectMessage] [Group("cookies")] - public class Cookies : ModuleBase + public class Cookies : GeekbotBase { private readonly DatabaseContext _database; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/User/GuildInfo.cs b/Geekbot.net/Commands/User/GuildInfo.cs index 6c8b941..e55506c 100644 --- a/Geekbot.net/Commands/User/GuildInfo.cs +++ b/Geekbot.net/Commands/User/GuildInfo.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Database; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -11,7 +12,7 @@ using Geekbot.net.Lib.Levels; namespace Geekbot.net.Commands.User { - public class GuildInfo : ModuleBase + public class GuildInfo : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; diff --git a/Geekbot.net/Commands/User/Karma.cs b/Geekbot.net/Commands/User/Karma.cs index ed221ff..1eb51be 100644 --- a/Geekbot.net/Commands/User/Karma.cs +++ b/Geekbot.net/Commands/User/Karma.cs @@ -5,6 +5,7 @@ using Discord; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -13,7 +14,7 @@ using Geekbot.net.Lib.Localization; namespace Geekbot.net.Commands.User { [DisableInDirectMessage] - public class Karma : ModuleBase + public class Karma : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; diff --git a/Geekbot.net/Commands/User/Ranking/Rank.cs b/Geekbot.net/Commands/User/Ranking/Rank.cs index 0ad21d5..60c8459 100644 --- a/Geekbot.net/Commands/User/Ranking/Rank.cs +++ b/Geekbot.net/Commands/User/Ranking/Rank.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Discord.Commands; using Geekbot.net.Database; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; @@ -15,7 +16,7 @@ using Geekbot.net.Lib.UserRepository; namespace Geekbot.net.Commands.User.Ranking { - public class Rank : ModuleBase + public class Rank : GeekbotBase { private readonly IEmojiConverter _emojiConverter; private readonly IHighscoreManager _highscoreManager; diff --git a/Geekbot.net/Commands/User/Stats.cs b/Geekbot.net/Commands/User/Stats.cs index 6ddf7d4..1ee85bf 100644 --- a/Geekbot.net/Commands/User/Stats.cs +++ b/Geekbot.net/Commands/User/Stats.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Database; +using Geekbot.net.Lib; using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; @@ -12,7 +13,7 @@ using Geekbot.net.Lib.Levels; namespace Geekbot.net.Commands.User { - public class Stats : ModuleBase + public class Stats : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly ILevelCalc _levelCalc; diff --git a/Geekbot.net/Commands/Utils/AvatarGetter.cs b/Geekbot.net/Commands/Utils/AvatarGetter.cs index 142b3e3..2077fa5 100644 --- a/Geekbot.net/Commands/Utils/AvatarGetter.cs +++ b/Geekbot.net/Commands/Utils/AvatarGetter.cs @@ -2,11 +2,12 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; namespace Geekbot.net.Commands.Utils { - public class AvatarGetter : ModuleBase + public class AvatarGetter : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs index adcc9a3..e86851a 100644 --- a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs +++ b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs @@ -7,12 +7,13 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Newtonsoft.Json; namespace Geekbot.net.Commands.Utils.Changelog { - public class Changelog : ModuleBase + public class Changelog : GeekbotBase { private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Utils/Choose.cs b/Geekbot.net/Commands/Utils/Choose.cs index 62069bd..2483865 100644 --- a/Geekbot.net/Commands/Utils/Choose.cs +++ b/Geekbot.net/Commands/Utils/Choose.cs @@ -1,12 +1,13 @@ using System; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Localization; namespace Geekbot.net.Commands.Utils { - public class Choose : ModuleBase + public class Choose : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly ITranslationHandler _translation; diff --git a/Geekbot.net/Commands/Utils/Dice/Dice.cs b/Geekbot.net/Commands/Utils/Dice/Dice.cs index 6b95903..5cea32e 100644 --- a/Geekbot.net/Commands/Utils/Dice/Dice.cs +++ b/Geekbot.net/Commands/Utils/Dice/Dice.cs @@ -4,11 +4,12 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.RandomNumberGenerator; namespace Geekbot.net.Commands.Utils.Dice { - public class Dice : ModuleBase + public class Dice : GeekbotBase { private readonly IRandomNumberGenerator _randomNumberGenerator; diff --git a/Geekbot.net/Commands/Utils/Emojify.cs b/Geekbot.net/Commands/Utils/Emojify.cs index 5355aff..ddf1762 100644 --- a/Geekbot.net/Commands/Utils/Emojify.cs +++ b/Geekbot.net/Commands/Utils/Emojify.cs @@ -1,12 +1,13 @@ using System; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; namespace Geekbot.net.Commands.Utils { - public class Emojify : ModuleBase + public class Emojify : GeekbotBase { private readonly IEmojiConverter _emojiConverter; private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Utils/Help.cs b/Geekbot.net/Commands/Utils/Help.cs index a6f0084..73f1956 100644 --- a/Geekbot.net/Commands/Utils/Help.cs +++ b/Geekbot.net/Commands/Utils/Help.cs @@ -3,11 +3,12 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; namespace Geekbot.net.Commands.Utils { - public class Help : ModuleBase + public class Help : GeekbotBase { private readonly IErrorHandler _errorHandler; diff --git a/Geekbot.net/Commands/Utils/Info.cs b/Geekbot.net/Commands/Utils/Info.cs index b1d5403..2ca8d8b 100644 --- a/Geekbot.net/Commands/Utils/Info.cs +++ b/Geekbot.net/Commands/Utils/Info.cs @@ -11,7 +11,7 @@ using Geekbot.net.Lib.Extensions; namespace Geekbot.net.Commands.Utils { - public class Info : ModuleBase + public class Info : GeekbotBase { private readonly DiscordSocketClient _client; private readonly CommandService _commands; diff --git a/Geekbot.net/Commands/Utils/Ping.cs b/Geekbot.net/Commands/Utils/Ping.cs index 18cf9cb..a794b3a 100644 --- a/Geekbot.net/Commands/Utils/Ping.cs +++ b/Geekbot.net/Commands/Utils/Ping.cs @@ -1,9 +1,10 @@ using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; namespace Geekbot.net.Commands.Utils { - public class Ping : ModuleBase + public class Ping : GeekbotBase { [Command("👀", RunMode = RunMode.Async)] [Summary("Look at the bot.")] diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index f06c6ab..8f5de91 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -5,6 +5,7 @@ using Discord; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -16,7 +17,7 @@ namespace Geekbot.net.Commands.Utils.Quote { [Group("quote")] [DisableInDirectMessage] - public class Quote : ModuleBase + public class Quote : GeekbotBase { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; From 7fb88bd106f89bc81d3590681dafa259b717dfd5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 23 May 2019 23:43:48 +0200 Subject: [PATCH 003/264] Take advantage of the translations in the context object --- Geekbot.net/Commands/Admin/Role.cs | 35 +++++++++-------------- Geekbot.net/Commands/Games/Roll.cs | 15 ++++------ Geekbot.net/Commands/Rpg/Cookies.cs | 24 ++++++---------- Geekbot.net/Commands/User/Karma.cs | 35 ++++++++++------------- Geekbot.net/Commands/User/Ranking/Rank.cs | 18 ++++-------- Geekbot.net/Commands/Utils/Choose.cs | 7 ++--- Geekbot.net/Commands/Utils/Quote/Quote.cs | 26 +++++++---------- 7 files changed, 62 insertions(+), 98 deletions(-) diff --git a/Geekbot.net/Commands/Admin/Role.cs b/Geekbot.net/Commands/Admin/Role.cs index 345ce34..22b4249 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/Geekbot.net/Commands/Admin/Role.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,7 +11,6 @@ using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.ReactionListener; namespace Geekbot.net.Commands.Admin @@ -23,14 +22,12 @@ namespace Geekbot.net.Commands.Admin private readonly DatabaseContext _database; private readonly IErrorHandler _errorHandler; private readonly IReactionListener _reactionListener; - private readonly ITranslationHandler _translationHandler; - public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener, ITranslationHandler translationHandler) + public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener) { _database = database; _errorHandler = errorHandler; _reactionListener = reactionListener; - _translationHandler = translationHandler; } [Command(RunMode = RunMode.Async)] @@ -39,17 +36,16 @@ namespace Geekbot.net.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); var roles = _database.RoleSelfService.Where(g => g.GuildId.Equals(Context.Guild.Id.AsLong())).ToList(); if (roles.Count == 0) { - await ReplyAsync(transContext.GetString("NoRolesConfigured")); + await ReplyAsync(Context.Translations.GetString("NoRolesConfigured")); return; } var sb = new StringBuilder(); - sb.AppendLine(transContext.GetString("ListHeader", Context.Guild.Name)); - sb.AppendLine(transContext.GetString("ListInstruction")); + sb.AppendLine(Context.Translations.GetString("ListHeader", Context.Guild.Name)); + sb.AppendLine(Context.Translations.GetString("ListInstruction")); foreach (var role in roles) sb.AppendLine($"- {role.WhiteListName}"); await ReplyAsync(sb.ToString()); } @@ -65,7 +61,6 @@ namespace Geekbot.net.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); var roleName = roleNameRaw.ToLower(); var roleFromDb = _database.RoleSelfService.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName)); @@ -75,23 +70,23 @@ namespace Geekbot.net.Commands.Admin var role = Context.Guild.Roles.First(r => r.Id == roleFromDb.RoleId.AsUlong()); if (role == null) { - await ReplyAsync(transContext.GetString("RoleNotFound")); + await ReplyAsync(Context.Translations.GetString("RoleNotFound")); return; } if (guildUser.RoleIds.Contains(role.Id)) { await guildUser.RemoveRoleAsync(role); - await ReplyAsync(transContext.GetString("RemovedUserFromRole", role.Name)); + await ReplyAsync(Context.Translations.GetString("RemovedUserFromRole", role.Name)); return; } await guildUser.AddRoleAsync(role); - await ReplyAsync(transContext.GetString("AddedUserFromRole", role.Name)); + await ReplyAsync(Context.Translations.GetString("AddedUserFromRole", role.Name)); return; } - await ReplyAsync(transContext.GetString("RoleNotFound")); + await ReplyAsync(Context.Translations.GetString("RoleNotFound")); } catch (HttpException e) { @@ -110,10 +105,9 @@ namespace Geekbot.net.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); if (role.IsManaged) { - await ReplyAsync(transContext.GetString("CannotAddManagedRole")); + await ReplyAsync(Context.Translations.GetString("CannotAddManagedRole")); return; } @@ -123,7 +117,7 @@ namespace Geekbot.net.Commands.Admin || role.Permissions.BanMembers || role.Permissions.KickMembers) { - await ReplyAsync(transContext.GetString("CannotAddDangerousRole")); + await ReplyAsync(Context.Translations.GetString("CannotAddDangerousRole")); return; } @@ -134,7 +128,7 @@ namespace Geekbot.net.Commands.Admin WhiteListName = roleName }); await _database.SaveChangesAsync(); - await ReplyAsync(transContext.GetString("CannotAddDangerousRole", role.Name)); + await ReplyAsync(Context.Translations.GetString("CannotAddDangerousRole", role.Name)); } catch (Exception e) { @@ -149,18 +143,17 @@ namespace Geekbot.net.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); var roleFromDb = _database.RoleSelfService.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName)); if (roleFromDb != null) { _database.RoleSelfService.Remove(roleFromDb); await _database.SaveChangesAsync(); - await ReplyAsync(transContext.GetString("RemovedRoleFromWhitelist", roleName)); + await ReplyAsync(Context.Translations.GetString("RemovedRoleFromWhitelist", roleName)); return; } - await ReplyAsync(transContext.GetString("RoleNotFound")); + await ReplyAsync(Context.Translations.GetString("RoleNotFound")); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Games/Roll.cs b/Geekbot.net/Commands/Games/Roll.cs index 39b44cf..965f9c1 100644 --- a/Geekbot.net/Commands/Games/Roll.cs +++ b/Geekbot.net/Commands/Games/Roll.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Threading.Tasks; using Discord.Commands; @@ -18,14 +18,12 @@ namespace Geekbot.net.Commands.Games { private readonly IErrorHandler _errorHandler; private readonly IAlmostRedis _redis; - private readonly ITranslationHandler _translation; private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Roll(IAlmostRedis redis, IErrorHandler errorHandler, ITranslationHandler translation, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) + public Roll(IAlmostRedis redis, IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) { _redis = redis; - _translation = translation; _database = database; _randomNumberGenerator = randomNumberGenerator; _errorHandler = errorHandler; @@ -40,7 +38,6 @@ namespace Geekbot.net.Commands.Games var number = _randomNumberGenerator.Next(1, 100); var guess = 1000; int.TryParse(stuff, out guess); - var transContext = await _translation.GetGuildContext(Context); if (guess <= 100 && guess > 0) { var prevRoll = _redis.Db.HashGet($"{Context.Guild.Id}:RollsPrevious2", Context.Message.Author.Id).ToString()?.Split('|'); @@ -48,17 +45,17 @@ namespace Geekbot.net.Commands.Games { if (prevRoll[0] == guess.ToString() && DateTime.Parse(prevRoll[1]) > DateTime.Now.AddDays(-1)) { - await ReplyAsync(transContext.GetString("NoPrevGuess", Context.Message.Author.Mention)); + await ReplyAsync(Context.Translations.GetString("NoPrevGuess", Context.Message.Author.Mention)); return; } } _redis.Db.HashSet($"{Context.Guild.Id}:RollsPrevious2", new[] {new HashEntry(Context.Message.Author.Id, $"{guess}|{DateTime.Now}")}); - await ReplyAsync(transContext.GetString("Rolled", Context.Message.Author.Mention, number, guess)); + await ReplyAsync(Context.Translations.GetString("Rolled", Context.Message.Author.Mention, number, guess)); if (guess == number) { - await ReplyAsync(transContext.GetString("Gratz", Context.Message.Author)); + await ReplyAsync(Context.Translations.GetString("Gratz", Context.Message.Author)); _redis.Db.HashIncrement($"{Context.Guild.Id}:Rolls", Context.User.Id.ToString()); var user = await GetUser(Context.User.Id); user.Rolls += 1; @@ -68,7 +65,7 @@ namespace Geekbot.net.Commands.Games } else { - await ReplyAsync(transContext.GetString("RolledNoGuess", Context.Message.Author.Mention, number)); + await ReplyAsync(Context.Translations.GetString("RolledNoGuess", Context.Message.Author.Mention, number)); } } catch (Exception e) diff --git a/Geekbot.net/Commands/Rpg/Cookies.cs b/Geekbot.net/Commands/Rpg/Cookies.cs index f681a4e..69e3d68 100644 --- a/Geekbot.net/Commands/Rpg/Cookies.cs +++ b/Geekbot.net/Commands/Rpg/Cookies.cs @@ -20,14 +20,12 @@ namespace Geekbot.net.Commands.Rpg { private readonly DatabaseContext _database; private readonly IErrorHandler _errorHandler; - private readonly ITranslationHandler _translation; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Cookies(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translation , IRandomNumberGenerator randomNumberGenerator) + public Cookies(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator) { _database = database; _errorHandler = errorHandler; - _translation = translation; _randomNumberGenerator = randomNumberGenerator; } @@ -37,18 +35,17 @@ namespace Geekbot.net.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (actor.LastPayout.Value.AddHours(24) > DateTimeOffset.Now) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.LastPayout.Value.AddHours(24)); - await ReplyAsync(transContext.GetString("WaitForMoreCookies", formatedWaitTime)); + var formatedWaitTime = Context.Translations.FormatDateTimeAsRemaining(actor.LastPayout.Value.AddHours(24)); + await ReplyAsync(Context.Translations.GetString("WaitForMoreCookies", formatedWaitTime)); return; } actor.Cookies += 10; actor.LastPayout = DateTimeOffset.Now; await SetUser(actor); - await ReplyAsync(transContext.GetString("GetCookies", 10, actor.Cookies)); + await ReplyAsync(Context.Translations.GetString("GetCookies", 10, actor.Cookies)); } catch (Exception e) @@ -63,9 +60,8 @@ namespace Geekbot.net.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); - await ReplyAsync(transContext.GetString("InYourJar", actor.Cookies)); + await ReplyAsync(Context.Translations.GetString("InYourJar", actor.Cookies)); } catch (Exception e) { @@ -79,12 +75,11 @@ namespace Geekbot.net.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var giver = await GetUser(Context.User.Id); if (giver.Cookies < amount) { - await ReplyAsync(transContext.GetString("NotEnoughToGive")); + await ReplyAsync(Context.Translations.GetString("NotEnoughToGive")); return; } @@ -96,7 +91,7 @@ namespace Geekbot.net.Commands.Rpg await SetUser(giver); await SetUser(taker); - await ReplyAsync(transContext.GetString("Given", amount, user.Username)); + await ReplyAsync(Context.Translations.GetString("Given", amount, user.Username)); } catch (Exception e) { @@ -110,12 +105,11 @@ namespace Geekbot.net.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (actor.Cookies < 5) { - await ReplyAsync(transContext.GetString("NotEnoughCookiesToEat")); + await ReplyAsync(Context.Translations.GetString("NotEnoughCookiesToEat")); return; } @@ -124,7 +118,7 @@ namespace Geekbot.net.Commands.Rpg await SetUser(actor); - await ReplyAsync(transContext.GetString("AteCookies", amount, actor.Cookies)); + await ReplyAsync(Context.Translations.GetString("AteCookies", amount, actor.Cookies)); } catch (Exception e) { diff --git a/Geekbot.net/Commands/User/Karma.cs b/Geekbot.net/Commands/User/Karma.cs index 1eb51be..fd4a82d 100644 --- a/Geekbot.net/Commands/User/Karma.cs +++ b/Geekbot.net/Commands/User/Karma.cs @@ -9,7 +9,6 @@ using Geekbot.net.Lib; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; namespace Geekbot.net.Commands.User { @@ -18,13 +17,11 @@ namespace Geekbot.net.Commands.User { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; - private readonly ITranslationHandler _translation; - public Karma(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translation) + public Karma(DatabaseContext database, IErrorHandler errorHandler) { _database = database; _errorHandler = errorHandler; - _translation = translation; } [Command("good", RunMode = RunMode.Async)] @@ -33,16 +30,15 @@ namespace Geekbot.net.Commands.User { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { - await ReplyAsync(transContext.GetString("CannotChangeOwn", Context.User.Username)); + await ReplyAsync(Context.Translations.GetString("CannotChangeOwn", Context.User.Username)); } else if (TimeoutFinished(actor.TimeOut)) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(transContext.GetString("WaitUntill", Context.User.Username, formatedWaitTime)); + var formatedWaitTime = Context.Translations.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); + await ReplyAsync(Context.Translations.GetString("WaitUntill", Context.User.Username, formatedWaitTime)); } else { @@ -61,10 +57,10 @@ namespace Geekbot.net.Commands.User .WithName(user.Username)); eb.WithColor(new Color(138, 219, 146)); - eb.Title = transContext.GetString("Increased"); - eb.AddInlineField(transContext.GetString("By"), Context.User.Username); - eb.AddInlineField(transContext.GetString("Amount"), "+1"); - eb.AddInlineField(transContext.GetString("Current"), target.Karma); + eb.Title = Context.Translations.GetString("Increased"); + eb.AddInlineField(Context.Translations.GetString("By"), Context.User.Username); + eb.AddInlineField(Context.Translations.GetString("Amount"), "+1"); + eb.AddInlineField(Context.Translations.GetString("Current"), target.Karma); await ReplyAsync("", false, eb.Build()); } } @@ -80,16 +76,15 @@ namespace Geekbot.net.Commands.User { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { - await ReplyAsync(transContext.GetString("CannotChangeOwn", Context.User.Username)); + await ReplyAsync(Context.Translations.GetString("CannotChangeOwn", Context.User.Username)); } else if (TimeoutFinished(actor.TimeOut)) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(transContext.GetString("WaitUntill", Context.User.Username, formatedWaitTime)); + var formatedWaitTime = Context.Translations.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); + await ReplyAsync(Context.Translations.GetString("WaitUntill", Context.User.Username, formatedWaitTime)); } else { @@ -108,10 +103,10 @@ namespace Geekbot.net.Commands.User .WithName(user.Username)); eb.WithColor(new Color(138, 219, 146)); - eb.Title = transContext.GetString("Decreased"); - eb.AddInlineField(transContext.GetString("By"), Context.User.Username); - eb.AddInlineField(transContext.GetString("Amount"), "-1"); - eb.AddInlineField(transContext.GetString("Current"), target.Karma); + eb.Title = Context.Translations.GetString("Decreased"); + eb.AddInlineField(Context.Translations.GetString("By"), Context.User.Username); + eb.AddInlineField(Context.Translations.GetString("Amount"), "-1"); + eb.AddInlineField(Context.Translations.GetString("Current"), target.Karma); await ReplyAsync("", false, eb.Build()); } } diff --git a/Geekbot.net/Commands/User/Ranking/Rank.cs b/Geekbot.net/Commands/User/Ranking/Rank.cs index 60c8459..03d2e31 100644 --- a/Geekbot.net/Commands/User/Ranking/Rank.cs +++ b/Geekbot.net/Commands/User/Ranking/Rank.cs @@ -20,20 +20,15 @@ namespace Geekbot.net.Commands.User.Ranking { private readonly IEmojiConverter _emojiConverter; private readonly IHighscoreManager _highscoreManager; - private readonly ITranslationHandler _translationHandler; private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; - private readonly IUserRepository _userRepository; - public Rank(DatabaseContext database, IErrorHandler errorHandler, IUserRepository userRepository, - IEmojiConverter emojiConverter, IHighscoreManager highscoreManager, ITranslationHandler translationHandler) + public Rank(DatabaseContext database, IErrorHandler errorHandler, IEmojiConverter emojiConverter, IHighscoreManager highscoreManager) { _database = database; _errorHandler = errorHandler; - _userRepository = userRepository; _emojiConverter = emojiConverter; _highscoreManager = highscoreManager; - _translationHandler = translationHandler; } [Command("rank", RunMode = RunMode.Async)] @@ -43,7 +38,6 @@ namespace Geekbot.net.Commands.User.Ranking { try { - var transContext = await _translationHandler.GetGuildContext(Context); HighscoreTypes type; try { @@ -52,14 +46,14 @@ namespace Geekbot.net.Commands.User.Ranking } catch { - await ReplyAsync(transContext.GetString("InvalidType")); + await ReplyAsync(Context.Translations.GetString("InvalidType")); return; } var replyBuilder = new StringBuilder(); if (amount > 20) { - await ReplyAsync(transContext.GetString("LimitingTo20Warning")); + await ReplyAsync(Context.Translations.GetString("LimitingTo20Warning")); amount = 20; } @@ -71,7 +65,7 @@ namespace Geekbot.net.Commands.User.Ranking } catch (HighscoreListEmptyException) { - await ReplyAsync(transContext.GetString("NoTypeFoundForServer", type)); + await ReplyAsync(Context.Translations.GetString("NoTypeFoundForServer", type)); return; } @@ -86,8 +80,8 @@ namespace Geekbot.net.Commands.User.Ranking var failedToRetrieveUser = highscoreUsers.Any(e => string.IsNullOrEmpty(e.Key.Username)); - if (failedToRetrieveUser) replyBuilder.AppendLine(transContext.GetString("FailedToResolveAllUsernames")); - replyBuilder.AppendLine(transContext.GetString("HighscoresFor", type.ToString().CapitalizeFirst(), Context.Guild.Name)); + if (failedToRetrieveUser) replyBuilder.AppendLine(Context.Translations.GetString("FailedToResolveAllUsernames")); + replyBuilder.AppendLine(Context.Translations.GetString("HighscoresFor", type.ToString().CapitalizeFirst(), Context.Guild.Name)); var highscorePlace = 1; foreach (var user in highscoreUsers) { diff --git a/Geekbot.net/Commands/Utils/Choose.cs b/Geekbot.net/Commands/Utils/Choose.cs index 2483865..84ba62a 100644 --- a/Geekbot.net/Commands/Utils/Choose.cs +++ b/Geekbot.net/Commands/Utils/Choose.cs @@ -10,12 +10,10 @@ namespace Geekbot.net.Commands.Utils public class Choose : GeekbotBase { private readonly IErrorHandler _errorHandler; - private readonly ITranslationHandler _translation; - public Choose(IErrorHandler errorHandler, ITranslationHandler translation) + public Choose(IErrorHandler errorHandler) { _errorHandler = errorHandler; - _translation = translation; } [Command("choose", RunMode = RunMode.Async)] @@ -25,10 +23,9 @@ namespace Geekbot.net.Commands.Utils { try { - var transContext = await _translation.GetGuildContext(Context); var choicesArray = choices.Split(';'); var choice = new Random().Next(choicesArray.Length); - await ReplyAsync(transContext.GetString("Choice", choicesArray[choice].Trim())); + await ReplyAsync(Context.Translations.GetString("Choice", choicesArray[choice].Trim())); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index 8f5de91..6cfd3f6 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -22,14 +22,12 @@ namespace Geekbot.net.Commands.Utils.Quote private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - private readonly ITranslationHandler _translationHandler; - public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translationHandler) + public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) { _errorHandler = errorHandler; _database = database; _randomNumberGenerator = randomNumberGenerator; - _translationHandler = translationHandler; } [Command] @@ -42,8 +40,7 @@ namespace Geekbot.net.Commands.Utils.Quote if (!s.Any()) { - var transContext = await _translationHandler.GetGuildContext(Context); - await ReplyAsync(transContext.GetString("NoQuotesFound")); + await ReplyAsync(Context.Translations.GetString("NoQuotesFound")); return; } @@ -65,16 +62,15 @@ namespace Geekbot.net.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); if (user.Id == Context.Message.Author.Id) { - await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); + await ReplyAsync(Context.Translations.GetString("CannotSaveOwnQuotes")); return; } if (user.IsBot) { - await ReplyAsync(transContext.GetString("CannotQuoteBots")); + await ReplyAsync(Context.Translations.GetString("CannotQuoteBots")); return; } @@ -86,7 +82,7 @@ namespace Geekbot.net.Commands.Utils.Quote await _database.SaveChangesAsync(); var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("QuoteAdded"), false, embed.Build()); + await ReplyAsync(Context.Translations.GetString("QuoteAdded"), false, embed.Build()); } catch (Exception e) { @@ -101,17 +97,16 @@ namespace Geekbot.net.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); var message = await Context.Channel.GetMessageAsync(messageId); if (message.Author.Id == Context.Message.Author.Id) { - await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); + await ReplyAsync(Context.Translations.GetString("CannotSaveOwnQuotes")); return; } if (message.Author.IsBot) { - await ReplyAsync(transContext.GetString("CannotQuoteBots")); + await ReplyAsync(Context.Translations.GetString("CannotQuoteBots")); return; } @@ -120,7 +115,7 @@ namespace Geekbot.net.Commands.Utils.Quote await _database.SaveChangesAsync(); var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("QuoteAdded"), false, embed.Build()); + await ReplyAsync(Context.Translations.GetString("QuoteAdded"), false, embed.Build()); } catch (Exception e) { @@ -175,18 +170,17 @@ namespace Geekbot.net.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); var quote = _database.Quotes.Where(e => e.GuildId == Context.Guild.Id.AsLong() && e.InternalId == id)?.FirstOrDefault(); if (quote != null) { _database.Quotes.Remove(quote); await _database.SaveChangesAsync(); var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("Removed", id), false, embed.Build()); + await ReplyAsync(Context.Translations.GetString("Removed", id), false, embed.Build()); } else { - await ReplyAsync(transContext.GetString("NotFoundWithId")); + await ReplyAsync(Context.Translations.GetString("NotFoundWithId")); } } catch (Exception e) From 288c976674afe692af29e27b1f8f19962e68e4d5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 28 May 2019 20:32:15 +0200 Subject: [PATCH 004/264] rename bdcc to bdcb --- .../Commands/Randomness/BenedictCumberbatchNameGenerator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs b/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs index 501f891..838dff2 100644 --- a/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs +++ b/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs @@ -18,7 +18,7 @@ namespace Geekbot.net.Commands.Randomness _randomNumberGenerator = randomNumberGenerator; } - [Command("bdcc", RunMode = RunMode.Async)] + [Command("bdcb", RunMode = RunMode.Async)] [Summary("Benedict Cumberbatch Name Generator")] public async Task GetQuote() { @@ -59,4 +59,4 @@ namespace Geekbot.net.Commands.Randomness } } } -} \ No newline at end of file +} From 8fadff4092d2c92f495555c677ce2963e2f2f5d0 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 4 Jun 2019 23:00:16 +0200 Subject: [PATCH 005/264] Cookies timeout is now at midnight instead of every 24h --- Geekbot.net/Commands/Rpg/Cookies.cs | 4 ++-- Geekbot.net/Lib/Localization/Translations.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Geekbot.net/Commands/Rpg/Cookies.cs b/Geekbot.net/Commands/Rpg/Cookies.cs index f22eccf..3c41044 100644 --- a/Geekbot.net/Commands/Rpg/Cookies.cs +++ b/Geekbot.net/Commands/Rpg/Cookies.cs @@ -38,9 +38,9 @@ namespace Geekbot.net.Commands.Rpg { var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); - if (actor.LastPayout.Value.AddHours(24) > DateTimeOffset.Now) + if (actor.LastPayout.Value.AddDays(1).Date > DateTime.Now.Date) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.LastPayout.Value.AddHours(24)); + var formatedWaitTime = transContext.FormatDateTimeAsRemaining(DateTimeOffset.Now.AddDays(1).Date); await ReplyAsync(transContext.GetString("WaitForMoreCookies", formatedWaitTime)); return; } diff --git a/Geekbot.net/Lib/Localization/Translations.yml b/Geekbot.net/Lib/Localization/Translations.yml index 04835a2..4bf4d14 100644 --- a/Geekbot.net/Lib/Localization/Translations.yml +++ b/Geekbot.net/Lib/Localization/Translations.yml @@ -90,8 +90,8 @@ cookies: EN: "You got {0} cookies, there are now {1} cookies in you cookie jar" CHDE: "Du häsch {0} guetzli becho, du häsch jetzt {1} guetzli ih dr büchse" WaitForMoreCookies: - EN: "You already got cookies in the last 24 hours, you can have more cookies in {0}" - CHDE: "Du hesch scho guetzli becho ih de letzti 24 stund, du chasch meh ha in {0}" + EN: "You already got cookies today, you can have more cookies in {0}" + CHDE: "Du hesch scho guetzli becho hüt, du chasch meh ha in {0}" InYourJar: EN: "There are {0} cookies in you cookie jar" CHDE: "Es hät {0} guetzli ih dineri büchs" From ac43d087b175686081b8e29d1e0f86e008b09e8c Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 21 Jul 2019 13:00:02 +0200 Subject: [PATCH 006/264] Add the !cookie alias and allow yaml alliases in the translations file --- Geekbot.net/Commands/Rpg/Cookies.cs | 1 + Geekbot.net/Lib/Localization/TranslationHandler.cs | 6 +++--- Geekbot.net/Lib/Localization/Translations.yml | 5 ++++- Tests/Lib/Localization/Translations.test.cs | 4 +++- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Geekbot.net/Commands/Rpg/Cookies.cs b/Geekbot.net/Commands/Rpg/Cookies.cs index 3c41044..b1a2d7d 100644 --- a/Geekbot.net/Commands/Rpg/Cookies.cs +++ b/Geekbot.net/Commands/Rpg/Cookies.cs @@ -15,6 +15,7 @@ namespace Geekbot.net.Commands.Rpg { [DisableInDirectMessage] [Group("cookies")] + [Alias("cookie")] public class Cookies : ModuleBase { private readonly DatabaseContext _database; diff --git a/Geekbot.net/Lib/Localization/TranslationHandler.cs b/Geekbot.net/Lib/Localization/TranslationHandler.cs index 3d1ee3a..a7a1a12 100644 --- a/Geekbot.net/Lib/Localization/TranslationHandler.cs +++ b/Geekbot.net/Lib/Localization/TranslationHandler.cs @@ -8,8 +8,7 @@ using Geekbot.net.Database; using Geekbot.net.Database.Models; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Logger; -using Utf8Json; -using YamlDotNet.RepresentationModel; +using YamlDotNet.Core; using YamlDotNet.Serialization; namespace Geekbot.net.Lib.Localization @@ -39,8 +38,9 @@ namespace Geekbot.net.Lib.Localization // Deserialize var input = new StringReader(translationFile); + var mergingParser = new MergingParser(new Parser(input)); var deserializer = new DeserializerBuilder().Build(); - var rawTranslations = deserializer.Deserialize>>>(input); + var rawTranslations = deserializer.Deserialize>>>(mergingParser); // Sort var sortedPerLanguage = new Dictionary>>(); diff --git a/Geekbot.net/Lib/Localization/Translations.yml b/Geekbot.net/Lib/Localization/Translations.yml index 4bf4d14..730ea40 100644 --- a/Geekbot.net/Lib/Localization/Translations.yml +++ b/Geekbot.net/Lib/Localization/Translations.yml @@ -85,7 +85,7 @@ roll: NoPrevGuess: EN: ":red_circle: {0}, you can't guess the same number again" CHDE: ":red_circle: {0}, du chasch nid nomol es gliche rate" -cookies: +cookies: &cookiesAlias GetCookies: EN: "You got {0} cookies, there are now {1} cookies in you cookie jar" CHDE: "Du häsch {0} guetzli becho, du häsch jetzt {1} guetzli ih dr büchse" @@ -107,6 +107,9 @@ cookies: AteCookies: EN: "You ate {0} cookies, you've only got {1} cookies left" CHDE: "Du hesch {0} guetzli gesse und hesch jezt no {1} übrig" +cookie: + # because command aliases are to hard to deal with... + <<: *cookiesAlias role: NoRolesConfigured: EN: "There are no roles configured for this server" diff --git a/Tests/Lib/Localization/Translations.test.cs b/Tests/Lib/Localization/Translations.test.cs index fc43091..736ed83 100644 --- a/Tests/Lib/Localization/Translations.test.cs +++ b/Tests/Lib/Localization/Translations.test.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using FluentAssertions; using Xunit; +using YamlDotNet.Core; using YamlDotNet.Serialization; namespace Tests.Lib.Localization @@ -17,8 +18,9 @@ namespace Tests.Lib.Localization // Deserialize var input = new StringReader(translationFile); + var mergingParser = new MergingParser(new Parser(input)); var deserializer = new DeserializerBuilder().Build(); - var rawTranslations = deserializer.Deserialize>>>(input); + var rawTranslations = deserializer.Deserialize>>>(mergingParser); // These languages must be supported var supportedLanguages = new List From 7a250f664215d3a36739469b30ced674e32546f4 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 30 Jul 2019 00:42:08 +0200 Subject: [PATCH 007/264] Ignore commands on certain serves --- Geekbot.net/Handlers.cs | 28 +++++++++++++++++++++++++--- Geekbot.net/Program.cs | 3 ++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index a254c14..d16750b 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -28,10 +29,12 @@ namespace Geekbot.net private readonly IUserRepository _userRepository; private readonly IReactionListener _reactionListener; private readonly DatabaseContext _messageCounterDatabaseContext; + private readonly RestApplication _applicationInfo; + private readonly List _ignoredServers; public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, - IReactionListener reactionListener) + IReactionListener reactionListener, RestApplication applicationInfo) { _database = databaseInitializer.Initialize(); _messageCounterDatabaseContext = databaseInitializer.Initialize(); @@ -42,6 +45,14 @@ namespace Geekbot.net _commands = commands; _userRepository = userRepository; _reactionListener = reactionListener; + _applicationInfo = applicationInfo; + // ToDo: create a clean solution for this... + _ignoredServers = new List() + { + 228623803201224704, // SwitzerLAN + 169844523181015040, // EEvent + 248531441548263425 // MYI + }; } // @@ -56,10 +67,21 @@ namespace Geekbot.net if (message.Author.IsBot) return Task.CompletedTask; var argPos = 0; + var guildId = ((SocketGuildChannel) message.Channel).Guild.Id; + // Some guilds only wanted very specific functionally without any of the commands, a quick hack that solves that short term... + // ToDo: cleanup + if (_ignoredServers.Contains(guildId)) + { + if (message.Author.Id != _applicationInfo.Owner.Id) + { + return Task.CompletedTask; + } + } + var lowCaseMsg = message.ToString().ToLower(); if (lowCaseMsg.StartsWith("hui")) { - var hasPing = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(((SocketGuildChannel) message.Channel).Guild.Id.AsLong()))?.Hui ?? false; + var hasPing = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong()))?.Hui ?? false; if (hasPing) { message.Channel.SendMessageAsync("hui!!!"); @@ -69,7 +91,7 @@ namespace Geekbot.net if (lowCaseMsg.StartsWith("ping ") || lowCaseMsg.Equals("ping")) { - var hasPing = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(((SocketGuildChannel) message.Channel).Guild.Id.AsLong()))?.Ping ?? false; + var hasPing = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong()))?.Ping ?? false; if (hasPing) { message.Channel.SendMessageAsync("pong"); diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index b7251a8..72ec6d5 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -156,6 +156,7 @@ namespace Geekbot.net var isConneted = await IsConnected(); if (isConneted) { + var applicationInfo = await _client.GetApplicationInfoAsync(); await _client.SetGameAsync(_globalSettings.GetKey("Game")); _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); @@ -170,7 +171,7 @@ namespace Geekbot.net _servicesProvider = _services.BuildServiceProvider(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener); + var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); _client.MessageReceived += handlers.RunCommand; _client.MessageDeleted += handlers.MessageDeleted; From fe4a78b7433fc096472353831159033317e6eace Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 30 Jul 2019 00:47:32 +0200 Subject: [PATCH 008/264] Allow failure on sentry during deployment --- .gitlab-ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 8c7a530..fc60d1b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -23,6 +23,7 @@ build: sentry: stage: ops image: getsentry/sentry-cli + allow_failure: true only: - master dependencies: From 1bfd7c7a129fc675f19a317bb3554e3d5b19d80b Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 5 Aug 2019 09:14:58 +0200 Subject: [PATCH 009/264] Ignore the discord bots server aswell --- Geekbot.net/Handlers.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index d16750b..09f95be 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -51,7 +51,8 @@ namespace Geekbot.net { 228623803201224704, // SwitzerLAN 169844523181015040, // EEvent - 248531441548263425 // MYI + 248531441548263425, // MYI + 110373943822540800 // Discord Bots }; } From 143722eccf3b775dc2eaf0a0d5ea4b90c218c916 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 5 Aug 2019 09:18:16 +0200 Subject: [PATCH 010/264] Stop using redis for counting messages --- Geekbot.net/Handlers.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 09f95be..4671e07 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -129,7 +129,6 @@ namespace Geekbot.net var channel = (SocketGuildChannel) message.Channel; - // just testing, redis will remain the source of truth for now var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlCommandAsync( "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", channel.Guild.Id.AsLong(), @@ -147,9 +146,6 @@ namespace Geekbot.net _messageCounterDatabaseContext.SaveChanges(); } - await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", message.Author.Id.ToString()); - await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString()); - if (message.Author.IsBot) return; _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); } From f1387f824e34e99b8fd017767d620be7563f1736 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 19 Sep 2019 13:40:02 +0200 Subject: [PATCH 011/264] Remove the google command --- .../Commands/Integrations/Google/Google.cs | 68 ------------------- .../Google/GoogleKgApiDetailedDto.cs | 9 --- .../Google/GoogleKgApiElementDto.cs | 8 --- .../Google/GoogleKgApiImageDto.cs | 8 --- .../Google/GoogleKgApiResponseDto.cs | 9 --- .../Google/GoogleKgApiResultDto.cs | 10 --- 6 files changed, 112 deletions(-) delete mode 100644 Geekbot.net/Commands/Integrations/Google/Google.cs delete mode 100644 Geekbot.net/Commands/Integrations/Google/GoogleKgApiDetailedDto.cs delete mode 100644 Geekbot.net/Commands/Integrations/Google/GoogleKgApiElementDto.cs delete mode 100644 Geekbot.net/Commands/Integrations/Google/GoogleKgApiImageDto.cs delete mode 100644 Geekbot.net/Commands/Integrations/Google/GoogleKgApiResponseDto.cs delete mode 100644 Geekbot.net/Commands/Integrations/Google/GoogleKgApiResultDto.cs diff --git a/Geekbot.net/Commands/Integrations/Google/Google.cs b/Geekbot.net/Commands/Integrations/Google/Google.cs deleted file mode 100644 index db059b4..0000000 --- a/Geekbot.net/Commands/Integrations/Google/Google.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using Discord; -using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.GlobalSettings; -using Newtonsoft.Json; - -namespace Geekbot.net.Commands.Integrations.Google -{ - public class Google : ModuleBase - { - private readonly IErrorHandler _errorHandler; - private readonly IGlobalSettings _globalSettings; - - public Google(IErrorHandler errorHandler, IGlobalSettings globalSettings) - { - _errorHandler = errorHandler; - _globalSettings = globalSettings; - } - - [Command("google", RunMode = RunMode.Async)] - [Summary("Google Something.")] - public async Task AskGoogle([Remainder, Summary("search-text")] string searchText) - { - try - { - using (var client = new WebClient()) - { - var apiKey = _globalSettings.GetKey("GoogleGraphKey"); - if (string.IsNullOrEmpty(apiKey)) - { - await ReplyAsync("No Google API key has been set, please contact my owner"); - return; - } - - var url = new Uri($"https://kgsearch.googleapis.com/v1/entities:search?languages=en&limit=1&query={searchText}&key={apiKey}"); - var responseString = client.DownloadString(url); - var response = JsonConvert.DeserializeObject(responseString); - - if (!response.ItemListElement.Any()) - { - await ReplyAsync("No results were found..."); - return; - } - - var data = response.ItemListElement.First().Result; - var eb = new EmbedBuilder - { - Title = data.Name - }; - if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description); - if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.Url)) eb.WithUrl(data.DetailedDtoDescription.Url); - if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDtoDescription.ArticleBody); - if(!string.IsNullOrEmpty(data.Image?.ContentUrl)) eb.WithThumbnailUrl(data.Image.ContentUrl); - - await ReplyAsync("", false, eb.Build()); - } - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context); - } - } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiDetailedDto.cs b/Geekbot.net/Commands/Integrations/Google/GoogleKgApiDetailedDto.cs deleted file mode 100644 index 031d1e7..0000000 --- a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiDetailedDto.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Geekbot.net.Commands.Integrations.Google -{ - public class GoogleKgApiDetailedDto - { - public string ArticleBody { get; set; } - public string Url { get; set; } - public string License { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiElementDto.cs b/Geekbot.net/Commands/Integrations/Google/GoogleKgApiElementDto.cs deleted file mode 100644 index a48b184..0000000 --- a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiElementDto.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Geekbot.net.Commands.Integrations.Google -{ - public class GoogleKgApiElementDto - { - public GoogleKgApiResultDto Result { get; set; } - public double ResultScore { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiImageDto.cs b/Geekbot.net/Commands/Integrations/Google/GoogleKgApiImageDto.cs deleted file mode 100644 index fe7cdaa..0000000 --- a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiImageDto.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Geekbot.net.Commands.Integrations.Google -{ - public class GoogleKgApiImageDto - { - public string ContentUrl { get; set; } - public string Url { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiResponseDto.cs b/Geekbot.net/Commands/Integrations/Google/GoogleKgApiResponseDto.cs deleted file mode 100644 index af337db..0000000 --- a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiResponseDto.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace Geekbot.net.Commands.Integrations.Google -{ - public class GoogleKgApiResponseDto - { - public List ItemListElement { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiResultDto.cs b/Geekbot.net/Commands/Integrations/Google/GoogleKgApiResultDto.cs deleted file mode 100644 index 465f1d7..0000000 --- a/Geekbot.net/Commands/Integrations/Google/GoogleKgApiResultDto.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Geekbot.net.Commands.Integrations.Google -{ - public class GoogleKgApiResultDto - { - public string Name { get; set; } - public string Description { get; set; } - public GoogleKgApiImageDto Image { get; set; } - public GoogleKgApiDetailedDto DetailedDtoDescription { get; set; } - } -} \ No newline at end of file From 309f06370b73c6c656adbebe9e21e45f341c6bc9 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 19 Sep 2019 13:42:48 +0200 Subject: [PATCH 012/264] Cut urban dictionary word definitions at the 1800 character mark --- .../Commands/Integrations/UbranDictionary/UrbanDictionary.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 4f29f10..932425b 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -48,7 +48,7 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary Url = definition.Permalink }); eb.WithColor(new Color(239, 255, 0)); - if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = definition.Definition; + if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = definition.Definition.Substring(0, 1800); if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)"); if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp); if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown); From 19df65fc760bec170ffc1f9652f9e2ce94d68559 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 19 Sep 2019 21:27:34 +0200 Subject: [PATCH 013/264] Fix out of bounds error in the urban dict. command --- .../Integrations/UbranDictionary/UrbanDictionary.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 932425b..254c2bb 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -41,6 +41,12 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example)); + var description = definition.Definition; + if (description.Length > 1801) + { + description = description.Substring(0, 1800) + " [...]"; + } + var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder { @@ -48,7 +54,7 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary Url = definition.Permalink }); eb.WithColor(new Color(239, 255, 0)); - if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = definition.Definition.Substring(0, 1800); + if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = description; if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)"); if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp); if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown); From b7b4a600cd69b0f03d0a1087101778d6e53d3dbf Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 11 Oct 2019 00:55:55 +0200 Subject: [PATCH 014/264] Fix message when a role has been added to the whitelist --- Geekbot.net/Commands/Admin/Role.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Geekbot.net/Commands/Admin/Role.cs b/Geekbot.net/Commands/Admin/Role.cs index 85b7160..decb7fc 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/Geekbot.net/Commands/Admin/Role.cs @@ -133,7 +133,7 @@ namespace Geekbot.net.Commands.Admin WhiteListName = roleName }); await _database.SaveChangesAsync(); - await ReplyAsync(transContext.GetString("CannotAddDangerousRole", role.Name)); + await ReplyAsync(transContext.GetString("AddedRoleToWhitelist", role.Name)); } catch (Exception e) { From 8dd914e0124471974e56c07bcc4f88a774d0888b Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 11 Oct 2019 01:08:59 +0200 Subject: [PATCH 015/264] Properly log errors when adding a role emoji --- Geekbot.net/Commands/Admin/Role.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Geekbot.net/Commands/Admin/Role.cs b/Geekbot.net/Commands/Admin/Role.cs index decb7fc..b0df4bb 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/Geekbot.net/Commands/Admin/Role.cs @@ -196,8 +196,7 @@ namespace Geekbot.net.Commands.Admin } catch (Exception e) { - await Context.Channel.SendMessageAsync("Something went wrong... please try again on a new message"); - Console.WriteLine(e); + await _errorHandler.HandleCommandException(e, Context); } } } From 20c75019f9391a612380f96571e4f8377826991a Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 26 Oct 2019 21:54:34 +0200 Subject: [PATCH 016/264] Upgrade to dotnet core 3 and update dependencies --- .gitlab-ci.yml | 2 +- Geekbot.net/Geekbot.net.csproj | 41 +++++++++++++++----------------- Geekbot.net/Handlers.cs | 2 +- Tests/Tests.csproj | 6 ++--- WikipediaApi/WikipediaApi.csproj | 2 +- 5 files changed, 25 insertions(+), 28 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index fc60d1b..7e32f69 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,7 +10,7 @@ before_script: build: stage: build - image: mcr.microsoft.com/dotnet/core/sdk:2.2 + image: mcr.microsoft.com/dotnet/core/sdk:3.0 artifacts: expire_in: 1h paths: diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 4749374..3fb4ee1 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -1,7 +1,7 @@  Exe - netcoreapp2.2 + netcoreapp3.0 win-x64;linux-x64 derp.ico 4.1.0 @@ -20,33 +20,30 @@ true - - - 2.1.0 - - - + + + + - + - - - - - - - - - + + + + + + + + + - - - - - + + + + diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 4671e07..7317274 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -129,7 +129,7 @@ namespace Geekbot.net var channel = (SocketGuildChannel) message.Channel; - var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlCommandAsync( + var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlRawAsync( "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", channel.Guild.Id.AsLong(), message.Author.Id.AsLong() diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 1c07b9c..854efc4 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -1,13 +1,13 @@  - netcoreapp2.2 + netcoreapp3.0 false NU1701 xUnit1026 - - + + diff --git a/WikipediaApi/WikipediaApi.csproj b/WikipediaApi/WikipediaApi.csproj index 3e82c68..349fc0b 100644 --- a/WikipediaApi/WikipediaApi.csproj +++ b/WikipediaApi/WikipediaApi.csproj @@ -1,6 +1,6 @@  - netcoreapp2.2 + netcoreapp3.0 From cd04549834ca7eb4756a70866462c329b5f303ab Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 26 Oct 2019 22:20:22 +0200 Subject: [PATCH 017/264] Fix deployment to accomodate dotnet core 3 changes --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 7e32f69..13858d2 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -16,9 +16,9 @@ build: paths: - Geekbot.net/Binaries/ script: - - dotnet restore -s https://api.nuget.org/v3/index.json -s https://www.myget.org/F/discord-net/api/v3/index.json + - dotnet restore - dotnet test Tests - - dotnet publish --version-suffix ${CI_COMMIT_SHA:0:8} --configuration Release -o Binaries ./ + - dotnet publish --version-suffix ${CI_COMMIT_SHA:0:8} --configuration Release -o ./Geekbot.net/Binaries ./Geekbot.net/ sentry: stage: ops From dd9cf3c5d7ec02384f79b82e3bed054064ad300e Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Feb 2020 15:32:58 +0100 Subject: [PATCH 018/264] Upgrade to dotnet core 3.1 --- .gitlab-ci.yml | 2 +- Geekbot.net/Geekbot.net.csproj | 34 ++++++++++++++++---------------- Tests/Tests.csproj | 8 ++++---- WikipediaApi/WikipediaApi.csproj | 4 ++-- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 13858d2..cffe539 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,7 +10,7 @@ before_script: build: stage: build - image: mcr.microsoft.com/dotnet/core/sdk:3.0 + image: mcr.microsoft.com/dotnet/core/sdk:3.1 artifacts: expire_in: 1h paths: diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 3fb4ee1..fe2f8cc 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -1,7 +1,7 @@  Exe - netcoreapp3.0 + netcoreapp3.1 win-x64;linux-x64 derp.ico 4.1.0 @@ -20,32 +20,32 @@ true - + - - + + - - - - - - - - + + + + + + + + - - - - + + + + - + diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 854efc4..235cc0b 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -1,14 +1,14 @@  - netcoreapp3.0 + netcoreapp3.1 false NU1701 xUnit1026 - - - + + + diff --git a/WikipediaApi/WikipediaApi.csproj b/WikipediaApi/WikipediaApi.csproj index 349fc0b..24c20f7 100644 --- a/WikipediaApi/WikipediaApi.csproj +++ b/WikipediaApi/WikipediaApi.csproj @@ -1,8 +1,8 @@  - netcoreapp3.0 + netcoreapp3.1 - + \ No newline at end of file From 21f813d342b847ce552fda6576f7a9459ccf3860 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Feb 2020 15:42:42 +0100 Subject: [PATCH 019/264] Remove redundant code --- Geekbot.net/Commands/Randomness/Kanye/Kanye.cs | 2 -- Geekbot.net/Commands/Utils/Dice/Dice.cs | 3 +-- Geekbot.net/Database/DatabaseInitializer.cs | 1 - Geekbot.net/Handlers.cs | 2 +- Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs | 3 +-- Geekbot.net/Lib/GeekbotExitCode.cs | 2 +- Geekbot.net/Lib/Highscores/HighscoreManager.cs | 2 -- .../Lib/Localization/TranslationGuildContext.cs | 1 - .../Lib/ReactionListener/ReactionListener.cs | 4 +--- Geekbot.net/Program.cs | 15 ++++++++------- .../WebApi/Controllers/Commands/CommandDto.cs | 3 +-- Geekbot.net/WebApi/WebApiStartup.cs | 10 +++++----- 12 files changed, 19 insertions(+), 29 deletions(-) diff --git a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs index 42a6ca7..dcd3bdc 100644 --- a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs +++ b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs @@ -3,9 +3,7 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Commands.Randomness.Dad; using Geekbot.net.Lib.ErrorHandling; -using Microsoft.AspNetCore.Hosting.Internal; using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Kanye diff --git a/Geekbot.net/Commands/Utils/Dice/Dice.cs b/Geekbot.net/Commands/Utils/Dice/Dice.cs index 6b95903..bc0244e 100644 --- a/Geekbot.net/Commands/Utils/Dice/Dice.cs +++ b/Geekbot.net/Commands/Utils/Dice/Dice.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; diff --git a/Geekbot.net/Database/DatabaseInitializer.cs b/Geekbot.net/Database/DatabaseInitializer.cs index 6adff44..582327f 100644 --- a/Geekbot.net/Database/DatabaseInitializer.cs +++ b/Geekbot.net/Database/DatabaseInitializer.cs @@ -2,7 +2,6 @@ using Geekbot.net.Database.LoggingAdapter; using Geekbot.net.Lib; using Geekbot.net.Lib.Logger; -using Microsoft.EntityFrameworkCore; using Npgsql.Logging; namespace Geekbot.net.Database diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 7317274..13f523c 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -103,7 +103,7 @@ namespace Geekbot.net if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask; var context = new CommandContext(_client, message); - var commandExec = _commands.ExecuteAsync(context, argPos, _servicesProvider); + _commands.ExecuteAsync(context, argPos, _servicesProvider); _logger.Information(LogSource.Command, context.Message.Content.Split(" ")[0].Replace("!", ""), SimpleConextConverter.ConvertContext(context)); diff --git a/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs b/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs index 5323ee6..7c9d8ff 100644 --- a/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs +++ b/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs @@ -3,7 +3,6 @@ using System.Net; using System.Threading.Tasks; using Discord.Commands; using Discord.Net; -using Geekbot.net.Lib.GlobalSettings; using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Logger; using SharpRaven; @@ -19,7 +18,7 @@ namespace Geekbot.net.Lib.ErrorHandling private readonly IRavenClient _raven; private readonly bool _errorsInChat; - public ErrorHandler(IGeekbotLogger logger, ITranslationHandler translation, IGlobalSettings globalSettings, bool errorsInChat) + public ErrorHandler(IGeekbotLogger logger, ITranslationHandler translation, bool errorsInChat) { _logger = logger; _translation = translation; diff --git a/Geekbot.net/Lib/GeekbotExitCode.cs b/Geekbot.net/Lib/GeekbotExitCode.cs index d68aa4a..130d435 100644 --- a/Geekbot.net/Lib/GeekbotExitCode.cs +++ b/Geekbot.net/Lib/GeekbotExitCode.cs @@ -1,6 +1,6 @@ namespace Geekbot.net.Lib { - public enum GeekbotExitCode : int + public enum GeekbotExitCode { // General Clean = 0, diff --git a/Geekbot.net/Lib/Highscores/HighscoreManager.cs b/Geekbot.net/Lib/Highscores/HighscoreManager.cs index f3b3a18..e668ff2 100644 --- a/Geekbot.net/Lib/Highscores/HighscoreManager.cs +++ b/Geekbot.net/Lib/Highscores/HighscoreManager.cs @@ -1,9 +1,7 @@ -using System; using System.Collections.Generic; using System.Linq; using Geekbot.net.Database; using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.UserRepository; namespace Geekbot.net.Lib.Highscores diff --git a/Geekbot.net/Lib/Localization/TranslationGuildContext.cs b/Geekbot.net/Lib/Localization/TranslationGuildContext.cs index 6181c04..fb65aa6 100644 --- a/Geekbot.net/Lib/Localization/TranslationGuildContext.cs +++ b/Geekbot.net/Lib/Localization/TranslationGuildContext.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; using System.Threading.Tasks; diff --git a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs index 18490db..26a60d3 100644 --- a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs +++ b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs @@ -18,7 +18,7 @@ namespace Geekbot.net.Lib.ReactionListener LoadListeners(); } - private Task LoadListeners() + private void LoadListeners() { var ids = _redis.SetMembers("MessageIds"); _listener = new Dictionary>(); @@ -43,8 +43,6 @@ namespace Geekbot.net.Lib.ReactionListener } _listener.Add(messageId, emojiDict); } - - return Task.CompletedTask; } public bool IsListener(ulong id) diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 72ec6d5..4907431 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -21,6 +21,7 @@ using Geekbot.net.Lib.Media; using Geekbot.net.Lib.RandomNumberGenerator; using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; +using Geekbot.net.WebApi; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using WikipediaApi; @@ -125,8 +126,8 @@ namespace Geekbot.net var wikipediaClient = new WikipediaClient(); var randomNumberGenerator = new RandomNumberGenerator(); - _services.AddSingleton(_redis); - _services.AddSingleton(_userRepository); + _services.AddSingleton(_redis); + _services.AddSingleton(_userRepository); _services.AddSingleton(logger); _services.AddSingleton(levelCalc); _services.AddSingleton(emojiConverter); @@ -136,9 +137,9 @@ namespace Geekbot.net _services.AddSingleton(mtgManaConverter); _services.AddSingleton(wikipediaClient); _services.AddSingleton(randomNumberGenerator); - _services.AddSingleton(_globalSettings); - _services.AddTransient((e) => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); - _services.AddTransient((e) => _databaseInitializer.Initialize()); + _services.AddSingleton(_globalSettings); + _services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); + _services.AddTransient(e => _databaseInitializer.Initialize()); logger.Information(LogSource.Geekbot, "Connecting to Discord"); @@ -162,7 +163,7 @@ namespace Geekbot.net _logger.Information(LogSource.Geekbot, "Registering Stuff"); var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); - var errorHandler = new ErrorHandler(_logger, translationHandler, _globalSettings, _runParameters.ExposeErrors); + var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); var reactionListener = new ReactionListener(_redis.Db); _services.AddSingleton(errorHandler); _services.AddSingleton(translationHandler); @@ -207,7 +208,7 @@ namespace Geekbot.net { _logger.Information(LogSource.Api, "Starting Webserver"); var highscoreManager = new HighscoreManager(_databaseInitializer.Initialize(), _userRepository); - WebApi.WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); + WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); return Task.CompletedTask; } } diff --git a/Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs b/Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs index 68c4e74..981d0f2 100644 --- a/Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs +++ b/Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace Geekbot.net.WebApi.Controllers.Commands { diff --git a/Geekbot.net/WebApi/WebApiStartup.cs b/Geekbot.net/WebApi/WebApiStartup.cs index 2459362..7d3adc9 100644 --- a/Geekbot.net/WebApi/WebApiStartup.cs +++ b/Geekbot.net/WebApi/WebApiStartup.cs @@ -29,11 +29,11 @@ namespace Geekbot.net.WebApi .ConfigureServices(services => { services.AddMvc(); - services.AddSingleton(commandService); - services.AddSingleton(databaseContext); - services.AddSingleton(client); - services.AddSingleton(globalSettings); - services.AddSingleton(highscoreManager); + services.AddSingleton(commandService); + services.AddSingleton(databaseContext); + services.AddSingleton(client); + services.AddSingleton(globalSettings); + services.AddSingleton(highscoreManager); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", From 3568b61f38412abc4080474fcf2b6a6179c472be Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Feb 2020 15:58:17 +0100 Subject: [PATCH 020/264] Use the new Csharp 8 features (pattern matching and using assignments) and cleanup some insignificant resparper complaints --- Geekbot.net/Commands/Admin/Mod.cs | 4 +- .../Integrations/MagicTheGathering.cs | 30 ++++---- .../UbranDictionary/UrbanDictionary.cs | 68 +++++++++---------- Geekbot.net/Commands/Randomness/Cat/Cat.cs | 31 +++++---- Geekbot.net/Commands/Randomness/CheckEm.cs | 2 +- .../Randomness/Chuck/ChuckNorrisJokes.cs | 28 ++++---- .../Commands/Randomness/Dad/DadJokes.cs | 28 ++++---- Geekbot.net/Commands/Randomness/Dog/Dog.cs | 30 ++++---- Geekbot.net/Commands/Randomness/Gdq.cs | 10 ++- .../Commands/Randomness/Kanye/Kanye.cs | 28 ++++---- Geekbot.net/Commands/Randomness/Ship.cs | 10 +-- Geekbot.net/Commands/User/Karma.cs | 4 +- Geekbot.net/Commands/User/Ranking/Rank.cs | 4 +- Geekbot.net/Commands/User/Stats.cs | 2 +- .../Commands/Utils/Changelog/Changelog.cs | 52 +++++++------- Geekbot.net/Commands/Utils/Quote/Quote.cs | 4 +- .../LoggingAdapter/NpgsqlLoggingAdapter.cs | 25 +++---- Geekbot.net/Lib/Clients/MalClient.cs | 2 +- .../DisableInDirectMessageAttribute.cs | 2 +- .../Lib/Converters/MtgManaConverter.cs | 2 +- .../Lib/Highscores/HighscoreManager.cs | 31 +++------ Geekbot.net/Lib/Levels/LevelCalc.cs | 11 +-- .../Lib/Logger/SimpleConextConverter.cs | 2 +- .../Lib/ReactionListener/ReactionListener.cs | 7 +- .../Callback/CallbackController.cs | 18 ++--- .../HighscoreControllerPostBodyDto.cs | 4 +- Geekbot.net/WebApi/Logging/AspLogger.cs | 28 +++----- 27 files changed, 217 insertions(+), 250 deletions(-) diff --git a/Geekbot.net/Commands/Admin/Mod.cs b/Geekbot.net/Commands/Admin/Mod.cs index 1188504..f4beb54 100644 --- a/Geekbot.net/Commands/Admin/Mod.cs +++ b/Geekbot.net/Commands/Admin/Mod.cs @@ -35,7 +35,7 @@ namespace Geekbot.net.Commands.Admin try { var userRepo = _userRepository.Get(user.Id); - if (userRepo != null && userRepo.UsedNames != null) + if (userRepo?.UsedNames != null) { var sb = new StringBuilder(); sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:"); @@ -50,7 +50,7 @@ namespace Geekbot.net.Commands.Admin catch (Exception e) { await _errorHandler.HandleCommandException(e, Context, - $"I don't have enough permissions do that"); + "I don't have enough permissions do that"); } } } diff --git a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs b/Geekbot.net/Commands/Integrations/MagicTheGathering.cs index ef16fee..1075c46 100644 --- a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs +++ b/Geekbot.net/Commands/Integrations/MagicTheGathering.cs @@ -41,9 +41,11 @@ namespace Geekbot.net.Commands.Integrations return; } - var eb = new EmbedBuilder(); - eb.Title = card.Name; - eb.Description = card.Type; + var eb = new EmbedBuilder + { + Title = card.Name, + Description = card.Type + }; if (card.Colors != null) eb.WithColor(GetColor(card.Colors)); @@ -74,21 +76,15 @@ namespace Geekbot.net.Commands.Integrations private Color GetColor(IEnumerable colors) { var color = colors.FirstOrDefault(); - switch (color) + return color switch { - case "Black": - return new Color(203, 194, 191); - case "White": - return new Color(255, 251, 213); - case "Blue": - return new Color(170, 224, 250); - case "Red": - return new Color(250, 170, 143); - case "Green": - return new Color(155, 211, 174); - default: - return new Color(204, 194, 212); - } + "Black" => new Color(203, 194, 191), + "White" => new Color(255, 251, 213), + "Blue" => new Color(170, 224, 250), + "Red" => new Color(250, 170, 143), + "Green" => new Color(155, 211, 174), + _ => new Color(204, 194, 212) + }; } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 254c2bb..1f33573 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -25,43 +25,43 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary { try { - using (var client = new HttpClient()) + using var client = new HttpClient { - client.BaseAddress = new Uri("https://api.urbandictionary.com"); - var response = await client.GetAsync($"/v0/define?term={word}"); - response.EnsureSuccessStatusCode(); + BaseAddress = new Uri("https://api.urbandictionary.com") + }; + var response = await client.GetAsync($"/v0/define?term={word}"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var definitions = JsonConvert.DeserializeObject(stringResponse); - if (definitions.List.Count == 0) - { - await ReplyAsync("That word hasn't been defined..."); - return; - } - - var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example)); - - var description = definition.Definition; - if (description.Length > 1801) - { - description = description.Substring(0, 1800) + " [...]"; - } - - var eb = new EmbedBuilder(); - eb.WithAuthor(new EmbedAuthorBuilder - { - Name = definition.Word, - Url = definition.Permalink - }); - eb.WithColor(new Color(239, 255, 0)); - if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = description; - if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)"); - if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp); - if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown); - if (definitions.Tags?.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags)); - - await ReplyAsync("", false, eb.Build()); + var stringResponse = await response.Content.ReadAsStringAsync(); + var definitions = JsonConvert.DeserializeObject(stringResponse); + if (definitions.List.Count == 0) + { + await ReplyAsync("That word hasn't been defined..."); + return; } + + var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example)); + + var description = definition.Definition; + if (description.Length > 1801) + { + description = description.Substring(0, 1800) + " [...]"; + } + + var eb = new EmbedBuilder(); + eb.WithAuthor(new EmbedAuthorBuilder + { + Name = definition.Word, + Url = definition.Permalink + }); + eb.WithColor(new Color(239, 255, 0)); + if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = description; + if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)"); + if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp); + if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown); + if (definitions.Tags?.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags)); + + await ReplyAsync("", false, eb.Build()); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Randomness/Cat/Cat.cs b/Geekbot.net/Commands/Randomness/Cat/Cat.cs index 4d43a4c..3ac0764 100644 --- a/Geekbot.net/Commands/Randomness/Cat/Cat.cs +++ b/Geekbot.net/Commands/Randomness/Cat/Cat.cs @@ -23,24 +23,27 @@ namespace Geekbot.net.Commands.Randomness.Cat { try { - using (var client = new HttpClient()) + + try { - try + using var client = new HttpClient { - client.BaseAddress = new Uri("https://aws.random.cat"); - var response = await client.GetAsync("/meow"); - response.EnsureSuccessStatusCode(); + BaseAddress = new Uri("https://aws.random.cat") + }; + var response = await client.GetAsync("/meow"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var catFile = JsonConvert.DeserializeObject(stringResponse); - var eb = new EmbedBuilder(); - eb.ImageUrl = catFile.File; - await ReplyAsync("", false, eb.Build()); - } - catch + var stringResponse = await response.Content.ReadAsStringAsync(); + var catFile = JsonConvert.DeserializeObject(stringResponse); + var eb = new EmbedBuilder { - await ReplyAsync("Seems like the dog cought the cat (error occured)"); - } + ImageUrl = catFile.File + }; + await ReplyAsync("", false, eb.Build()); + } + catch + { + await ReplyAsync("Seems like the dog cought the cat (error occured)"); } } catch (Exception e) diff --git a/Geekbot.net/Commands/Randomness/CheckEm.cs b/Geekbot.net/Commands/Randomness/CheckEm.cs index f8191ad..0596872 100644 --- a/Geekbot.net/Commands/Randomness/CheckEm.cs +++ b/Geekbot.net/Commands/Randomness/CheckEm.cs @@ -61,7 +61,7 @@ namespace Geekbot.net.Commands.Randomness while (num > 0) { listOfInts.Add(num % 10); - num = num / 10; + num /= 10; } listOfInts.Reverse(); diff --git a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs b/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs index 07ea41f..5c28a9a 100644 --- a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs +++ b/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs @@ -23,23 +23,21 @@ namespace Geekbot.net.Commands.Randomness.Chuck { try { - using (var client = new HttpClient()) + try { - try - { - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - var response = await client.GetAsync("https://api.chucknorris.io/jokes/random"); - response.EnsureSuccessStatusCode(); + using var client = new HttpClient(); + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); + var response = await client.GetAsync("https://api.chucknorris.io/jokes/random"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.Value); - } - catch (HttpRequestException) - { - await ReplyAsync("Api down..."); - } + var stringResponse = await response.Content.ReadAsStringAsync(); + var data = JsonConvert.DeserializeObject(stringResponse); + await ReplyAsync(data.Value); + } + catch (HttpRequestException) + { + await ReplyAsync("Api down..."); } } catch (Exception e) diff --git a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs b/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs index 2c51781..bcedd96 100644 --- a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs +++ b/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs @@ -23,23 +23,21 @@ namespace Geekbot.net.Commands.Randomness.Dad { try { - using (var client = new HttpClient()) + try { - try - { - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - var response = await client.GetAsync("https://icanhazdadjoke.com/"); - response.EnsureSuccessStatusCode(); + using var client = new HttpClient(); + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); + var response = await client.GetAsync("https://icanhazdadjoke.com/"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.Joke); - } - catch (HttpRequestException) - { - await ReplyAsync("Api down..."); - } + var stringResponse = await response.Content.ReadAsStringAsync(); + var data = JsonConvert.DeserializeObject(stringResponse); + await ReplyAsync(data.Joke); + } + catch (HttpRequestException) + { + await ReplyAsync("Api down..."); } } catch (Exception e) diff --git a/Geekbot.net/Commands/Randomness/Dog/Dog.cs b/Geekbot.net/Commands/Randomness/Dog/Dog.cs index 176cbad..d7404c6 100644 --- a/Geekbot.net/Commands/Randomness/Dog/Dog.cs +++ b/Geekbot.net/Commands/Randomness/Dog/Dog.cs @@ -23,24 +23,26 @@ namespace Geekbot.net.Commands.Randomness.Dog { try { - using (var client = new HttpClient()) + try { - try + using var client = new HttpClient { - client.BaseAddress = new Uri("http://random.dog"); - var response = await client.GetAsync("/woof.json"); - response.EnsureSuccessStatusCode(); + BaseAddress = new Uri("http://random.dog") + }; + var response = await client.GetAsync("/woof.json"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var dogFile = JsonConvert.DeserializeObject(stringResponse); - var eb = new EmbedBuilder(); - eb.ImageUrl = dogFile.Url; - await ReplyAsync("", false, eb.Build()); - } - catch (HttpRequestException e) + var stringResponse = await response.Content.ReadAsStringAsync(); + var dogFile = JsonConvert.DeserializeObject(stringResponse); + var eb = new EmbedBuilder { - await ReplyAsync($"Seems like the dog got lost (error occured)\r\n{e.Message}"); - } + ImageUrl = dogFile.Url + }; + await ReplyAsync("", false, eb.Build()); + } + catch (HttpRequestException e) + { + await ReplyAsync($"Seems like the dog got lost (error occured)\r\n{e.Message}"); } } catch (Exception e) diff --git a/Geekbot.net/Commands/Randomness/Gdq.cs b/Geekbot.net/Commands/Randomness/Gdq.cs index 2685b33..4c16bed 100644 --- a/Geekbot.net/Commands/Randomness/Gdq.cs +++ b/Geekbot.net/Commands/Randomness/Gdq.cs @@ -21,13 +21,11 @@ namespace Geekbot.net.Commands.Randomness { try { - using (var client = new WebClient()) - { - var url = new Uri("http://taskinoz.com/gdq/api/"); - var response = client.DownloadString(url); + using var client = new WebClient(); + var url = new Uri("http://taskinoz.com/gdq/api/"); + var response = client.DownloadString(url); - await ReplyAsync(response); - } + await ReplyAsync(response); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs index dcd3bdc..36f1d1a 100644 --- a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs +++ b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs @@ -23,23 +23,21 @@ namespace Geekbot.net.Commands.Randomness.Kanye { try { - using (var client = new HttpClient()) + try { - try - { - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - var response = await client.GetAsync("https://api.kanye.rest/"); - response.EnsureSuccessStatusCode(); + using var client = new HttpClient(); + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); + var response = await client.GetAsync("https://api.kanye.rest/"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.Quote); - } - catch (HttpRequestException) - { - await ReplyAsync("Api down..."); - } + var stringResponse = await response.Content.ReadAsStringAsync(); + var data = JsonConvert.DeserializeObject(stringResponse); + await ReplyAsync(data.Quote); + } + catch (HttpRequestException) + { + await ReplyAsync("Api down..."); } } catch (Exception e) diff --git a/Geekbot.net/Commands/Randomness/Ship.cs b/Geekbot.net/Commands/Randomness/Ship.cs index 2571891..bf52a73 100644 --- a/Geekbot.net/Commands/Randomness/Ship.cs +++ b/Geekbot.net/Commands/Randomness/Ship.cs @@ -56,8 +56,8 @@ namespace Geekbot.net.Commands.Randomness } var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n"; - reply = reply + $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n"; - reply = reply + $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}"; + reply += $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n"; + reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}"; await ReplyAsync(reply); } catch (Exception e) @@ -87,13 +87,13 @@ namespace Geekbot.net.Commands.Randomness for (var i = 1; i <= 10; i++) if (i <= amount) { - blocks = blocks + ":white_medium_small_square:"; + blocks += ":white_medium_small_square:"; if (i == amount) - blocks = blocks + $" {rate}% "; + blocks += $" {rate}% "; } else { - blocks = blocks + ":black_medium_small_square:"; + blocks += ":black_medium_small_square:"; } return blocks; diff --git a/Geekbot.net/Commands/User/Karma.cs b/Geekbot.net/Commands/User/Karma.cs index ed221ff..bf85c91 100644 --- a/Geekbot.net/Commands/User/Karma.cs +++ b/Geekbot.net/Commands/User/Karma.cs @@ -46,7 +46,7 @@ namespace Geekbot.net.Commands.User else { var target = await GetUser(user.Id); - target.Karma = target.Karma + 1; + target.Karma += 1; SetUser(target); actor.TimeOut = DateTimeOffset.Now; @@ -93,7 +93,7 @@ namespace Geekbot.net.Commands.User else { var target = await GetUser(user.Id); - target.Karma = target.Karma - 1; + target.Karma -= 1; SetUser(target); actor.TimeOut = DateTimeOffset.Now; diff --git a/Geekbot.net/Commands/User/Ranking/Rank.cs b/Geekbot.net/Commands/User/Ranking/Rank.cs index 0ad21d5..9021b4e 100644 --- a/Geekbot.net/Commands/User/Ranking/Rank.cs +++ b/Geekbot.net/Commands/User/Ranking/Rank.cs @@ -74,7 +74,7 @@ namespace Geekbot.net.Commands.User.Ranking return; } - int guildMessages = 0; + var guildMessages = 0; if (type == HighscoreTypes.messages) { guildMessages = _database.Messages @@ -99,7 +99,7 @@ namespace Geekbot.net.Commands.User.Ranking : $"**{user.Key.Id}**"); replyBuilder.Append(type == HighscoreTypes.messages - ? $" - {user.Value} {type} - {Math.Round((double) (100 * user.Value) / guildMessages, digits: 2)}%\n" + ? $" - {user.Value} {type} - {Math.Round((double) (100 * user.Value) / guildMessages, 2)}%\n" : $" - {user.Value} {type}\n"); highscorePlace++; diff --git a/Geekbot.net/Commands/User/Stats.cs b/Geekbot.net/Commands/User/Stats.cs index 6ddf7d4..05ea324 100644 --- a/Geekbot.net/Commands/User/Stats.cs +++ b/Geekbot.net/Commands/User/Stats.cs @@ -51,7 +51,7 @@ namespace Geekbot.net.Commands.User var level = _levelCalc.GetLevel(messages); - var percent = Math.Round((double) (100 * messages) / guildMessages, digits: 2); + var percent = Math.Round((double) (100 * messages) / guildMessages, 2); var cookies = _database.Cookies ?.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.UserId.Equals(userInfo.Id.AsLong())) diff --git a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs index adcc9a3..02981df 100644 --- a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs +++ b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs @@ -29,34 +29,34 @@ namespace Geekbot.net.Commands.Utils.Changelog { try { - using (var client = new HttpClient()) + using var client = new HttpClient { - client.BaseAddress = new Uri("https://api.github.com"); - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", - "http://developer.github.com/v3/#user-agent-required"); - var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits"); - response.EnsureSuccessStatusCode(); + BaseAddress = new Uri("https://api.github.com") + }; + client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", + "http://developer.github.com/v3/#user-agent-required"); + var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits"); + response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - var commits = JsonConvert.DeserializeObject>(stringResponse); - var eb = new EmbedBuilder(); - eb.WithColor(new Color(143, 165, 102)); - eb.WithAuthor(new EmbedAuthorBuilder - { - IconUrl = _client.CurrentUser.GetAvatarUrl(), - Name = "Latest Updates", - Url = "https://geekbot.pizzaandcoffee.rocks/updates" - }); - var sb = new StringBuilder(); - foreach (var commit in commits.Take(10)) - sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.Author.Date:yyyy-MM-dd})"); - eb.Description = sb.ToString(); - eb.WithFooter(new EmbedFooterBuilder - { - Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}" - }); - await ReplyAsync("", false, eb.Build()); - } + var stringResponse = await response.Content.ReadAsStringAsync(); + var commits = JsonConvert.DeserializeObject>(stringResponse); + var eb = new EmbedBuilder(); + eb.WithColor(new Color(143, 165, 102)); + eb.WithAuthor(new EmbedAuthorBuilder + { + IconUrl = _client.CurrentUser.GetAvatarUrl(), + Name = "Latest Updates", + Url = "https://geekbot.pizzaandcoffee.rocks/updates" + }); + var sb = new StringBuilder(); + foreach (var commit in commits.Take(10)) + sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.Author.Date:yyyy-MM-dd})"); + eb.Description = sb.ToString(); + eb.WithFooter(new EmbedFooterBuilder + { + Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}" + }); + await ReplyAsync("", false, eb.Build()); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index f06c6ab..e9c4706 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -46,7 +46,7 @@ namespace Geekbot.net.Commands.Utils.Quote return; } - var random = _randomNumberGenerator.Next(0, s.Count()); + var random = _randomNumberGenerator.Next(0, s.Count); var quote = s[random]; var embed = QuoteBuilder(quote); @@ -238,7 +238,7 @@ namespace Geekbot.net.Commands.Utils.Quote var last = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())) .OrderByDescending(e => e.InternalId).FirstOrDefault(); - int internalId = 1; + var internalId = 1; if (last != null) internalId = last.InternalId + 1; return new QuoteModel() { diff --git a/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs b/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs index e8850cd..ceebd56 100644 --- a/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs +++ b/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs @@ -54,23 +54,16 @@ namespace Geekbot.net.Database.LoggingAdapter private static LogLevel ToGeekbotLogLevel(NpgsqlLogLevel level) { - switch (level) + return level switch { - case NpgsqlLogLevel.Trace: - return LogLevel.Trace; - case NpgsqlLogLevel.Debug: - return LogLevel.Debug; - case NpgsqlLogLevel.Info: - return LogLevel.Info; - case NpgsqlLogLevel.Warn: - return LogLevel.Warn; - case NpgsqlLogLevel.Error: - return LogLevel.Error; - case NpgsqlLogLevel.Fatal: - return LogLevel.Fatal; - default: - throw new ArgumentOutOfRangeException(nameof(level)); - } + NpgsqlLogLevel.Trace => LogLevel.Trace, + NpgsqlLogLevel.Debug => LogLevel.Debug, + NpgsqlLogLevel.Info => LogLevel.Info, + NpgsqlLogLevel.Warn => LogLevel.Warn, + NpgsqlLogLevel.Error => LogLevel.Error, + NpgsqlLogLevel.Fatal => LogLevel.Fatal, + _ => throw new ArgumentOutOfRangeException(nameof(level)) + }; } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/Clients/MalClient.cs b/Geekbot.net/Lib/Clients/MalClient.cs index a014cf1..8e5d950 100644 --- a/Geekbot.net/Lib/Clients/MalClient.cs +++ b/Geekbot.net/Lib/Clients/MalClient.cs @@ -22,7 +22,7 @@ namespace Geekbot.net.Lib.Clients ReloadClient(); } - public bool ReloadClient() + private bool ReloadClient() { var malCredentials = _globalSettings.GetKey("MalCredentials"); if (!string.IsNullOrEmpty(malCredentials)) diff --git a/Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs b/Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs index 110b69b..2bb5cfd 100644 --- a/Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs +++ b/Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs @@ -4,7 +4,7 @@ using Discord.Commands; namespace Geekbot.net.Lib.CommandPreconditions { - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class DisableInDirectMessageAttribute : PreconditionAttribute { public override Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) diff --git a/Geekbot.net/Lib/Converters/MtgManaConverter.cs b/Geekbot.net/Lib/Converters/MtgManaConverter.cs index c29e1e0..31a2db0 100644 --- a/Geekbot.net/Lib/Converters/MtgManaConverter.cs +++ b/Geekbot.net/Lib/Converters/MtgManaConverter.cs @@ -7,7 +7,7 @@ namespace Geekbot.net.Lib.Converters { public class MtgManaConverter : IMtgManaConverter { - private Dictionary _manaDict; + private readonly Dictionary _manaDict; public MtgManaConverter() { diff --git a/Geekbot.net/Lib/Highscores/HighscoreManager.cs b/Geekbot.net/Lib/Highscores/HighscoreManager.cs index e668ff2..8218532 100644 --- a/Geekbot.net/Lib/Highscores/HighscoreManager.cs +++ b/Geekbot.net/Lib/Highscores/HighscoreManager.cs @@ -20,26 +20,15 @@ namespace Geekbot.net.Lib.Highscores public Dictionary GetHighscoresWithUserData(HighscoreTypes type, ulong guildId, int amount) { - Dictionary list; - switch (type) + var list = type switch { - case HighscoreTypes.messages: - list = GetMessageList(guildId, amount); - break; - case HighscoreTypes.karma: - list = GetKarmaList(guildId, amount); - break; - case HighscoreTypes.rolls: - list = GetRollsList(guildId, amount); - break; - case HighscoreTypes.cookies: - list = GetCookiesList(guildId, amount); - break; - default: - list = new Dictionary(); - break; - } - + HighscoreTypes.messages => GetMessageList(guildId, amount), + HighscoreTypes.karma => GetKarmaList(guildId, amount), + HighscoreTypes.rolls => GetRollsList(guildId, amount), + HighscoreTypes.cookies => GetCookiesList(guildId, amount), + _ => new Dictionary() + }; + if (!list.Any()) { throw new HighscoreListEmptyException($"No {type} found for guild {guildId}"); @@ -103,8 +92,8 @@ namespace Geekbot.net.Lib.Highscores .Take(amount) .ToDictionary(key => key.UserId.AsUlong(), key => key.Rolls); } - - public Dictionary GetCookiesList(ulong guildId, int amount) + + private Dictionary GetCookiesList(ulong guildId, int amount) { return _database.Cookies .Where(k => k.GuildId.Equals(guildId.AsLong())) diff --git a/Geekbot.net/Lib/Levels/LevelCalc.cs b/Geekbot.net/Lib/Levels/LevelCalc.cs index f5b6b80..74747b7 100644 --- a/Geekbot.net/Lib/Levels/LevelCalc.cs +++ b/Geekbot.net/Lib/Levels/LevelCalc.cs @@ -1,11 +1,12 @@ using System; using System.Collections.Generic; +using System.Linq; namespace Geekbot.net.Lib.Levels { public class LevelCalc : ILevelCalc { - private int[] _levels; + private readonly int[] _levels; public LevelCalc() { @@ -21,13 +22,7 @@ namespace Geekbot.net.Lib.Levels public int GetLevel(int? messages) { - var returnVal = 1; - foreach (var level in _levels) - { - if (level > messages) break; - returnVal++; - } - return returnVal; + return 1 + _levels.TakeWhile(level => !(level > messages)).Count(); } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/Logger/SimpleConextConverter.cs b/Geekbot.net/Lib/Logger/SimpleConextConverter.cs index 8b8b0ed..d01da67 100644 --- a/Geekbot.net/Lib/Logger/SimpleConextConverter.cs +++ b/Geekbot.net/Lib/Logger/SimpleConextConverter.cs @@ -37,7 +37,7 @@ namespace Geekbot.net.Lib.Logger } public static MessageDto ConvertSocketMessage(SocketMessage message, bool isPrivate = false) { - SocketGuildChannel channel = isPrivate ? null : (SocketGuildChannel) message.Channel; + var channel = isPrivate ? null : (SocketGuildChannel) message.Channel; return new MessageDto { Message = new MessageDto.MessageContent diff --git a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs index 26a60d3..2349028 100644 --- a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs +++ b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs @@ -63,8 +63,11 @@ namespace Geekbot.net.Lib.ReactionListener _listener[messageId].Add(emoji, role.Id); return Task.CompletedTask; } - var dict = new Dictionary(); - dict.Add(emoji, role.Id); + + var dict = new Dictionary + { + {emoji, role.Id} + }; _listener.Add(messageId, dict); return Task.CompletedTask; } diff --git a/Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs b/Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs index 58bdb83..78fb38d 100644 --- a/Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs +++ b/Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs @@ -32,14 +32,16 @@ namespace Geekbot.net.WebApi.Controllers.Callback var accessToken = _globalSettings.GetKey("OAuthToken"); var callbackUrl = _globalSettings.GetKey("OAuthCallbackUrl"); - var form = new Dictionary(); - form.Add("client_id", appInfo.Id.ToString()); - form.Add("client_secret", accessToken); - form.Add("grant_type", "authorization_code"); - form.Add("code", code); - form.Add("scope", "identify email guilds"); - form.Add("redirect_uri", callbackUrl); - + var form = new Dictionary + { + {"client_id", appInfo.Id.ToString()}, + {"client_secret", accessToken}, + {"grant_type", "authorization_code"}, + {"code", code}, + {"scope", "identify email guilds"}, + {"redirect_uri", callbackUrl} + }; + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var result = await client.PostAsync("/api/oauth2/token", new FormUrlEncodedContent(form)); result.EnsureSuccessStatusCode(); diff --git a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs b/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs index 22da3c7..6e7aec3 100644 --- a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs +++ b/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs @@ -8,9 +8,9 @@ namespace Geekbot.net.WebApi.Controllers.Highscores [Required] public ulong GuildId { get; set; } - public HighscoreTypes Type { get; set; } = HighscoreTypes.messages; + public HighscoreTypes Type { get; } = HighscoreTypes.messages; [Range(1, 150)] - public int Amount { get; set; } = 50; + public int Amount { get; } = 50; } } \ No newline at end of file diff --git a/Geekbot.net/WebApi/Logging/AspLogger.cs b/Geekbot.net/WebApi/Logging/AspLogger.cs index 3316150..5899b26 100644 --- a/Geekbot.net/WebApi/Logging/AspLogger.cs +++ b/Geekbot.net/WebApi/Logging/AspLogger.cs @@ -55,25 +55,17 @@ namespace Geekbot.net.WebApi.Logging private static NLog.LogLevel ToGeekbotLogLevel(LogLevel level) { - switch (level) + return level switch { - case LogLevel.Trace: - return NLog.LogLevel.Trace; - case LogLevel.Debug: - return NLog.LogLevel.Debug; - case LogLevel.Information: - return NLog.LogLevel.Info; - case LogLevel.Warning: - return NLog.LogLevel.Warn; - case LogLevel.Error: - return NLog.LogLevel.Error; - case LogLevel.Critical: - return NLog.LogLevel.Fatal; - case LogLevel.None: - return NLog.LogLevel.Off; - default: - throw new ArgumentOutOfRangeException(nameof(level)); - } + LogLevel.Trace => NLog.LogLevel.Trace, + LogLevel.Debug => NLog.LogLevel.Debug, + LogLevel.Information => NLog.LogLevel.Info, + LogLevel.Warning => NLog.LogLevel.Warn, + LogLevel.Error => NLog.LogLevel.Error, + LogLevel.Critical => NLog.LogLevel.Fatal, + LogLevel.None => NLog.LogLevel.Off, + _ => throw new ArgumentOutOfRangeException(nameof(level)) + }; } } } \ No newline at end of file From 3bd7274d68c633599b3fbcbd4eff10f9c1f466aa Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 4 Apr 2020 21:21:15 +0200 Subject: [PATCH 021/264] Remove some unnecessary text from the dice command --- Geekbot.net/Commands/Utils/Dice/Dice.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Dice/Dice.cs b/Geekbot.net/Commands/Utils/Dice/Dice.cs index bc0244e..c335982 100644 --- a/Geekbot.net/Commands/Utils/Dice/Dice.cs +++ b/Geekbot.net/Commands/Utils/Dice/Dice.cs @@ -67,7 +67,6 @@ namespace Geekbot.net.Commands.Utils.Dice rep.Append("**Result:** "); var resultStrings = new List(); var total = 0; - var extraText = ""; foreach (var dice in dices) { var results = new List(); @@ -76,8 +75,6 @@ namespace Geekbot.net.Commands.Utils.Dice var roll = _randomNumberGenerator.Next(1, dice.Sides); total += roll; results.Add(roll); - if (roll == dice.Sides) extraText = "**Critical Hit!**"; - if (roll == 1) extraText = "**Critical Fail!**"; } resultStrings.Add($"{dice.DiceType} ({string.Join(",", results)})"); @@ -92,7 +89,6 @@ namespace Geekbot.net.Commands.Utils.Dice rep.AppendLine(); rep.AppendLine($"**Total:** {total}"); - if (extraText != "") rep.AppendLine(extraText); await ReplyAsync(rep.ToString()); } From f12bdcf4cd1d1794a22b7997d3ef7416092f66e8 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 4 Apr 2020 23:05:18 +0200 Subject: [PATCH 022/264] Translate the ship command --- Geekbot.net/Commands/Randomness/Ship.cs | 33 +++++++++++-------- Geekbot.net/Lib/Localization/Translations.yml | 22 ++++++++++++- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/Geekbot.net/Commands/Randomness/Ship.cs b/Geekbot.net/Commands/Randomness/Ship.cs index bf52a73..d5386d4 100644 --- a/Geekbot.net/Commands/Randomness/Ship.cs +++ b/Geekbot.net/Commands/Randomness/Ship.cs @@ -7,6 +7,7 @@ using Geekbot.net.Database; using Geekbot.net.Database.Models; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.RandomNumberGenerator; namespace Geekbot.net.Commands.Randomness @@ -15,13 +16,15 @@ namespace Geekbot.net.Commands.Randomness { private readonly IErrorHandler _errorHandler; private readonly IRandomNumberGenerator _randomNumberGenerator; + private readonly ITranslationHandler _translation; private readonly DatabaseContext _database; - public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator) + public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translation) { _database = database; _errorHandler = errorHandler; _randomNumberGenerator = randomNumberGenerator; + _translation = translation; } [Command("Ship", RunMode = RunMode.Async)] @@ -55,9 +58,11 @@ namespace Geekbot.net.Commands.Randomness shippingRate = dbval.Strength; } - var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n"; + var transContext = await _translation.GetGuildContext(Context); + + var reply = $":heartpulse: **{transContext.GetString("Matchmaking")}** :heartpulse:\r\n"; reply += $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n"; - reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}"; + reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate, transContext)}"; await ReplyAsync(reply); } catch (Exception e) @@ -66,22 +71,22 @@ namespace Geekbot.net.Commands.Randomness } } - private string DeterminateSuccess(int rate) + private string DeterminateSuccess(int rate, TranslationGuildContext transContext) { - if (rate < 20) - return "Not gonna happen"; - if (rate >= 20 && rate < 40) - return "Not such a good idea"; - if (rate >= 40 && rate < 60) - return "There might be a chance"; - if (rate >= 60 && rate < 80) - return "Almost a match, but could work"; - return rate >= 80 ? "It's a match" : "a"; + return (rate / 20) switch + { + 0 => transContext.GetString("NotGonnaToHappen"), + 1 => transContext.GetString("NotSuchAGoodIdea"), + 2 => transContext.GetString("ThereMightBeAChance"), + 3 => transContext.GetString("CouldWork"), + 4 => transContext.GetString("ItsAMatch"), + _ => "nope" + }; } private string BlockCounter(int rate) { - var amount = Math.Floor(decimal.Floor(rate / 10)); + var amount = rate / 10; Console.WriteLine(amount); var blocks = ""; for (var i = 1; i <= 10; i++) diff --git a/Geekbot.net/Lib/Localization/Translations.yml b/Geekbot.net/Lib/Localization/Translations.yml index 730ea40..5744741 100644 --- a/Geekbot.net/Lib/Localization/Translations.yml +++ b/Geekbot.net/Lib/Localization/Translations.yml @@ -175,4 +175,24 @@ rank: CHDE: ":warning: Ich han nid alli benutzername gfunde. villiicht hend sie de server verlah?\n" HighscoresFor: EN: ":bar_chart: **{0} Highscore for {1}**" - CHDE: ":bar_chart: **{0} Highscore für {1}**" \ No newline at end of file + CHDE: ":bar_chart: **{0} Highscore für {1}**" +ship: + Matchmaking: + EN: "Matchmaking" + CHDE: "Verkupple" + NotGonnaToHappen: + EN: "Not gonna happen" + CHDE: "Wird nöd klappe" + NotSuchAGoodIdea: + EN: "Not such a good idea" + CHDE: "Nöd so ä gueti idee" + ThereMightBeAChance: + EN: "There might be a chance" + CHDE: "Es gid eventuel ä chance" + CouldWork: + EN: "Almost a match" + CHDE: "Fasch en match" + ItsAMatch: + EN: "It's a match" + CHDE: "Es isch es traumpaar" + \ No newline at end of file From 77b3d612f2da6dbbcf8fca008deef0c307962583 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 6 Apr 2020 15:35:28 +0200 Subject: [PATCH 023/264] Re-use the database connection everywhere --- Geekbot.net/Handlers.cs | 15 +++++---------- Geekbot.net/Program.cs | 23 ++++++++++++----------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 13f523c..48bf966 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -9,7 +9,6 @@ using Discord.Rest; using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Database.Models; -using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.ReactionListener; @@ -23,24 +22,20 @@ namespace Geekbot.net private readonly DatabaseContext _database; private readonly IDiscordClient _client; private readonly IGeekbotLogger _logger; - private readonly IAlmostRedis _redis; private readonly IServiceProvider _servicesProvider; private readonly CommandService _commands; private readonly IUserRepository _userRepository; private readonly IReactionListener _reactionListener; - private readonly DatabaseContext _messageCounterDatabaseContext; private readonly RestApplication _applicationInfo; private readonly List _ignoredServers; - public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, + public Handlers(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IReactionListener reactionListener, RestApplication applicationInfo) { - _database = databaseInitializer.Initialize(); - _messageCounterDatabaseContext = databaseInitializer.Initialize(); + _database = database; _client = client; _logger = logger; - _redis = redis; _servicesProvider = servicesProvider; _commands = commands; _userRepository = userRepository; @@ -129,7 +124,7 @@ namespace Geekbot.net var channel = (SocketGuildChannel) message.Channel; - var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlRawAsync( + var rowId = await _database.Database.ExecuteSqlRawAsync( "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", channel.Guild.Id.AsLong(), message.Author.Id.AsLong() @@ -137,13 +132,13 @@ namespace Geekbot.net if (rowId == 0) { - _messageCounterDatabaseContext.Messages.Add(new MessagesModel + await _database.Messages.AddAsync(new MessagesModel { UserId = message.Author.Id.AsLong(), GuildId = channel.Guild.Id.AsLong(), MessageCount = 1 }); - _messageCounterDatabaseContext.SaveChanges(); + await _database.SaveChangesAsync(); } if (message.Author.IsBot) return; diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 4907431..9ff6e90 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -41,6 +41,7 @@ namespace Geekbot.net private IUserRepository _userRepository; private RunParameters _runParameters; private IAlmostRedis _redis; + private DatabaseContext _database; private static void Main(string[] args) { @@ -87,11 +88,11 @@ namespace Geekbot.net _commands = new CommandService(); _databaseInitializer = new DatabaseInitializer(runParameters, logger); - var database = _databaseInitializer.Initialize(); - database.Database.EnsureCreated(); - if(!_runParameters.InMemory) database.Database.Migrate(); + _database = _databaseInitializer.Initialize(); + _database.Database.EnsureCreated(); + if(!_runParameters.InMemory) _database.Database.Migrate(); - _globalSettings = new GlobalSettings(database); + _globalSettings = new GlobalSettings(_database); try { @@ -116,7 +117,7 @@ namespace Geekbot.net _services = new ServiceCollection(); - _userRepository = new UserRepository(_databaseInitializer.Initialize(), logger); + _userRepository = new UserRepository(_database, logger); var fortunes = new FortunesProvider(logger); var mediaProvider = new MediaProvider(logger); var malClient = new MalClient(_globalSettings, logger); @@ -137,9 +138,9 @@ namespace Geekbot.net _services.AddSingleton(mtgManaConverter); _services.AddSingleton(wikipediaClient); _services.AddSingleton(randomNumberGenerator); + _services.AddSingleton(_database); _services.AddSingleton(_globalSettings); - _services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); - _services.AddTransient(e => _databaseInitializer.Initialize()); + _services.AddTransient(e => new HighscoreManager(_database, _userRepository)); logger.Information(LogSource.Geekbot, "Connecting to Discord"); @@ -162,7 +163,7 @@ namespace Geekbot.net _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); _logger.Information(LogSource.Geekbot, "Registering Stuff"); - var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); + var translationHandler = new TranslationHandler(_database, _logger); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); var reactionListener = new ReactionListener(_redis.Db); _services.AddSingleton(errorHandler); @@ -172,7 +173,7 @@ namespace Geekbot.net _servicesProvider = _services.BuildServiceProvider(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); + var handlers = new Handlers(_database, _client, _logger, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); _client.MessageReceived += handlers.RunCommand; _client.MessageDeleted += handlers.MessageDeleted; @@ -207,8 +208,8 @@ namespace Geekbot.net private Task StartWebApi() { _logger.Information(LogSource.Api, "Starting Webserver"); - var highscoreManager = new HighscoreManager(_databaseInitializer.Initialize(), _userRepository); - WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); + var highscoreManager = new HighscoreManager(_database, _userRepository); + WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _database, _client, _globalSettings, highscoreManager); return Task.CompletedTask; } } From 2a616f8c5d315f253834802821fc0399f81cc618 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 6 Apr 2020 15:51:28 +0200 Subject: [PATCH 024/264] Revert "Re-use the database connection everywhere" This reverts commit 77b3d612f2da6dbbcf8fca008deef0c307962583. --- Geekbot.net/Handlers.cs | 15 ++++++++++----- Geekbot.net/Program.cs | 23 +++++++++++------------ 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 48bf966..13f523c 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -9,6 +9,7 @@ using Discord.Rest; using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Database.Models; +using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.ReactionListener; @@ -22,20 +23,24 @@ namespace Geekbot.net private readonly DatabaseContext _database; private readonly IDiscordClient _client; private readonly IGeekbotLogger _logger; + private readonly IAlmostRedis _redis; private readonly IServiceProvider _servicesProvider; private readonly CommandService _commands; private readonly IUserRepository _userRepository; private readonly IReactionListener _reactionListener; + private readonly DatabaseContext _messageCounterDatabaseContext; private readonly RestApplication _applicationInfo; private readonly List _ignoredServers; - public Handlers(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, + public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IReactionListener reactionListener, RestApplication applicationInfo) { - _database = database; + _database = databaseInitializer.Initialize(); + _messageCounterDatabaseContext = databaseInitializer.Initialize(); _client = client; _logger = logger; + _redis = redis; _servicesProvider = servicesProvider; _commands = commands; _userRepository = userRepository; @@ -124,7 +129,7 @@ namespace Geekbot.net var channel = (SocketGuildChannel) message.Channel; - var rowId = await _database.Database.ExecuteSqlRawAsync( + var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlRawAsync( "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", channel.Guild.Id.AsLong(), message.Author.Id.AsLong() @@ -132,13 +137,13 @@ namespace Geekbot.net if (rowId == 0) { - await _database.Messages.AddAsync(new MessagesModel + _messageCounterDatabaseContext.Messages.Add(new MessagesModel { UserId = message.Author.Id.AsLong(), GuildId = channel.Guild.Id.AsLong(), MessageCount = 1 }); - await _database.SaveChangesAsync(); + _messageCounterDatabaseContext.SaveChanges(); } if (message.Author.IsBot) return; diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 9ff6e90..4907431 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -41,7 +41,6 @@ namespace Geekbot.net private IUserRepository _userRepository; private RunParameters _runParameters; private IAlmostRedis _redis; - private DatabaseContext _database; private static void Main(string[] args) { @@ -88,11 +87,11 @@ namespace Geekbot.net _commands = new CommandService(); _databaseInitializer = new DatabaseInitializer(runParameters, logger); - _database = _databaseInitializer.Initialize(); - _database.Database.EnsureCreated(); - if(!_runParameters.InMemory) _database.Database.Migrate(); + var database = _databaseInitializer.Initialize(); + database.Database.EnsureCreated(); + if(!_runParameters.InMemory) database.Database.Migrate(); - _globalSettings = new GlobalSettings(_database); + _globalSettings = new GlobalSettings(database); try { @@ -117,7 +116,7 @@ namespace Geekbot.net _services = new ServiceCollection(); - _userRepository = new UserRepository(_database, logger); + _userRepository = new UserRepository(_databaseInitializer.Initialize(), logger); var fortunes = new FortunesProvider(logger); var mediaProvider = new MediaProvider(logger); var malClient = new MalClient(_globalSettings, logger); @@ -138,9 +137,9 @@ namespace Geekbot.net _services.AddSingleton(mtgManaConverter); _services.AddSingleton(wikipediaClient); _services.AddSingleton(randomNumberGenerator); - _services.AddSingleton(_database); _services.AddSingleton(_globalSettings); - _services.AddTransient(e => new HighscoreManager(_database, _userRepository)); + _services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); + _services.AddTransient(e => _databaseInitializer.Initialize()); logger.Information(LogSource.Geekbot, "Connecting to Discord"); @@ -163,7 +162,7 @@ namespace Geekbot.net _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); _logger.Information(LogSource.Geekbot, "Registering Stuff"); - var translationHandler = new TranslationHandler(_database, _logger); + var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); var reactionListener = new ReactionListener(_redis.Db); _services.AddSingleton(errorHandler); @@ -173,7 +172,7 @@ namespace Geekbot.net _servicesProvider = _services.BuildServiceProvider(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - var handlers = new Handlers(_database, _client, _logger, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); + var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); _client.MessageReceived += handlers.RunCommand; _client.MessageDeleted += handlers.MessageDeleted; @@ -208,8 +207,8 @@ namespace Geekbot.net private Task StartWebApi() { _logger.Information(LogSource.Api, "Starting Webserver"); - var highscoreManager = new HighscoreManager(_database, _userRepository); - WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _database, _client, _globalSettings, highscoreManager); + var highscoreManager = new HighscoreManager(_databaseInitializer.Initialize(), _userRepository); + WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); return Task.CompletedTask; } } From ee548390a560aa95842d2efd344a03d2d9d48fdb Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 17 Apr 2020 23:48:50 +0200 Subject: [PATCH 025/264] Add Prometheus with 1 metric --- Geekbot.net/Geekbot.net.csproj | 1 + Geekbot.net/Handlers.cs | 6 ++++++ Geekbot.net/Lib/RunParameters.cs | 9 +++++++++ Geekbot.net/Program.cs | 11 +++++++++++ 4 files changed, 27 insertions(+) diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index fe2f8cc..e50613a 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -44,6 +44,7 @@ + diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 13f523c..dc1ce71 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -15,6 +15,7 @@ using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; using Microsoft.EntityFrameworkCore; +using Prometheus; namespace Geekbot.net { @@ -32,6 +33,9 @@ namespace Geekbot.net private readonly RestApplication _applicationInfo; private readonly List _ignoredServers; + private readonly Counter _messageCounterPrometheus = + Metrics.CreateCounter("messages", "Number of discord messages", new CounterConfiguration() {LabelNames = new[] {"guild", "channel", "user"}}); + public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IReactionListener reactionListener, RestApplication applicationInfo) @@ -146,6 +150,8 @@ namespace Geekbot.net _messageCounterDatabaseContext.SaveChanges(); } + _messageCounterPrometheus.WithLabels(channel.Guild.Id.ToString(), channel.Id.ToString(), message.Author.Id.ToString()).Inc(); + if (message.Author.IsBot) return; _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); } diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index 444a60f..e16f644 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -72,5 +72,14 @@ namespace Geekbot.net.Lib [Option("api-port", Default = "12995", HelpText = "Port on which the WebApi listens")] public string ApiPort { get; set; } + + /************************************ + * Prometheus * + ************************************/ + [Option("prometheus-host", Default = "localhost", HelpText = "Host on which the Prometheus Metric Server listens")] + public string PrometheusHost { get; set; } + + [Option("prometheus-port", Default = "12991", HelpText = "Port on which the Prometheus Metric Server listens")] + public string PrometheusPort { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 4907431..bccc23f 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -24,6 +24,7 @@ using Geekbot.net.Lib.UserRepository; using Geekbot.net.WebApi; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Prometheus; using WikipediaApi; namespace Geekbot.net @@ -185,6 +186,8 @@ namespace Geekbot.net var webserver = _runParameters.DisableApi ? Task.Delay(10) : StartWebApi(); + StartPrometheusServer(); + _logger.Information(LogSource.Geekbot, "Done and ready for use"); await webserver; @@ -211,5 +214,13 @@ namespace Geekbot.net WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); return Task.CompletedTask; } + + private void StartPrometheusServer() + { + var port = int.Parse(_runParameters.PrometheusPort); + var server = new MetricServer(_runParameters.PrometheusHost, port); + server.Start(); + _logger.Information(LogSource.Geekbot, $"Prometheus Metric Server running on {_runParameters.PrometheusHost}:{_runParameters.PrometheusPort}"); + } } } \ No newline at end of file From 569715f124fe2be626c753a20bda6ec892c53819 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 18 Apr 2020 00:05:09 +0200 Subject: [PATCH 026/264] fix prometheus metric server startup --- Geekbot.net/Program.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index bccc23f..6830bba 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -184,10 +184,9 @@ namespace Geekbot.net _client.ReactionRemoved += handlers.ReactionRemoved; if (!_runParameters.InMemory) _client.MessageReceived += handlers.UpdateStats; - var webserver = _runParameters.DisableApi ? Task.Delay(10) : StartWebApi(); - StartPrometheusServer(); + var webserver = _runParameters.DisableApi ? Task.Delay(10) : StartWebApi(); _logger.Information(LogSource.Geekbot, "Done and ready for use"); await webserver; @@ -217,7 +216,7 @@ namespace Geekbot.net private void StartPrometheusServer() { - var port = int.Parse(_runParameters.PrometheusPort); + var port = _runParameters.PrometheusPort == "12991" ? 12991 : int.Parse(_runParameters.PrometheusPort); var server = new MetricServer(_runParameters.PrometheusHost, port); server.Start(); _logger.Information(LogSource.Geekbot, $"Prometheus Metric Server running on {_runParameters.PrometheusHost}:{_runParameters.PrometheusPort}"); From fc5ff87c8fd4880ba26f78c223aae35755589d35 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 19 Apr 2020 13:52:44 +0200 Subject: [PATCH 027/264] Only the ManageMessages is now required to delete a quote --- Geekbot.net/Commands/Utils/Quote/Quote.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index e9c4706..f568036 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -166,10 +166,8 @@ namespace Geekbot.net.Commands.Utils.Quote } [Command("remove")] - [RequireUserPermission(GuildPermission.KickMembers)] [RequireUserPermission(GuildPermission.ManageMessages)] - [RequireUserPermission(GuildPermission.ManageRoles)] - [Summary("Remove a quote (required mod permissions)")] + [Summary("Remove a quote (user needs the 'ManageMessages' permission)")] public async Task RemoveQuote([Summary("quote-ID")] int id) { try From c031d2bfb42ef5ecba58710f3453a0e58cf61884 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 7 May 2020 13:11:00 +0200 Subject: [PATCH 028/264] Remove Prometheus --- Geekbot.net/Handlers.cs | 11 +---------- Geekbot.net/Program.cs | 13 +------------ 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index dc1ce71..52cf937 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -15,8 +15,6 @@ using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; using Microsoft.EntityFrameworkCore; -using Prometheus; - namespace Geekbot.net { public class Handlers @@ -24,7 +22,6 @@ namespace Geekbot.net private readonly DatabaseContext _database; private readonly IDiscordClient _client; private readonly IGeekbotLogger _logger; - private readonly IAlmostRedis _redis; private readonly IServiceProvider _servicesProvider; private readonly CommandService _commands; private readonly IUserRepository _userRepository; @@ -33,10 +30,7 @@ namespace Geekbot.net private readonly RestApplication _applicationInfo; private readonly List _ignoredServers; - private readonly Counter _messageCounterPrometheus = - Metrics.CreateCounter("messages", "Number of discord messages", new CounterConfiguration() {LabelNames = new[] {"guild", "channel", "user"}}); - - public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, + public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IReactionListener reactionListener, RestApplication applicationInfo) { @@ -44,7 +38,6 @@ namespace Geekbot.net _messageCounterDatabaseContext = databaseInitializer.Initialize(); _client = client; _logger = logger; - _redis = redis; _servicesProvider = servicesProvider; _commands = commands; _userRepository = userRepository; @@ -150,8 +143,6 @@ namespace Geekbot.net _messageCounterDatabaseContext.SaveChanges(); } - _messageCounterPrometheus.WithLabels(channel.Guild.Id.ToString(), channel.Id.ToString(), message.Author.Id.ToString()).Inc(); - if (message.Author.IsBot) return; _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); } diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 6830bba..3bd5a8f 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -24,7 +24,6 @@ using Geekbot.net.Lib.UserRepository; using Geekbot.net.WebApi; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using Prometheus; using WikipediaApi; namespace Geekbot.net @@ -173,7 +172,7 @@ namespace Geekbot.net _servicesProvider = _services.BuildServiceProvider(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); + var handlers = new Handlers(_databaseInitializer, _client, _logger, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); _client.MessageReceived += handlers.RunCommand; _client.MessageDeleted += handlers.MessageDeleted; @@ -183,8 +182,6 @@ namespace Geekbot.net _client.ReactionAdded += handlers.ReactionAdded; _client.ReactionRemoved += handlers.ReactionRemoved; if (!_runParameters.InMemory) _client.MessageReceived += handlers.UpdateStats; - - StartPrometheusServer(); var webserver = _runParameters.DisableApi ? Task.Delay(10) : StartWebApi(); _logger.Information(LogSource.Geekbot, "Done and ready for use"); @@ -213,13 +210,5 @@ namespace Geekbot.net WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); return Task.CompletedTask; } - - private void StartPrometheusServer() - { - var port = _runParameters.PrometheusPort == "12991" ? 12991 : int.Parse(_runParameters.PrometheusPort); - var server = new MetricServer(_runParameters.PrometheusHost, port); - server.Start(); - _logger.Information(LogSource.Geekbot, $"Prometheus Metric Server running on {_runParameters.PrometheusHost}:{_runParameters.PrometheusPort}"); - } } } \ No newline at end of file From 5cf1248bf04df3b5a6c1fe8bb46a4019057904ad Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 11 May 2020 23:44:15 +0200 Subject: [PATCH 029/264] Add !quote stats (v1) --- Geekbot.net/Commands/Utils/Quote/Quote.cs | 48 ++++++++++++++++++- Geekbot.net/Lib/Localization/Translations.yml | 9 ++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index f568036..454ad9b 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Threading.Tasks; using Discord; @@ -192,6 +192,52 @@ namespace Geekbot.net.Commands.Utils.Quote } } + [Command("stats")] + [Summary("Show quote stats for this server")] + public async Task GetQuoteStatsForServer() + { + try + { + var transContext = await _translationHandler.GetGuildContext(Context); + var eb = new EmbedBuilder(); + eb.Author = new EmbedAuthorBuilder() + { + IconUrl = Context.Guild.IconUrl, + Name = $"{Context.Guild.Name} - {transContext.GetString("QuoteStats")}" + }; + + var totalQuotes = _database.Quotes.Count(row => row.GuildId == Context.Guild.Id.AsLong()); + if (totalQuotes == 0) + { + await ReplyAsync(transContext.GetString("NoQuotesFound")); + return; + } + eb.AddInlineField(transContext.GetString("TotalQuotes"), totalQuotes); + + var mostQuotedPerson = _database.Quotes + .Where(row => row.GuildId == Context.Guild.Id.AsLong()) + .GroupBy(row => row.UserId) + .Max(row => row.Key); + var user = Context.Client.GetUserAsync(mostQuotedPerson.AsUlong()).Result ?? new UserPolyfillDto {Username = "Unknown User"}; + eb.AddInlineField(transContext.GetString("MostQuotesPerson"), user); + + var quotesByYear = _database.Quotes + .Where(row => row.GuildId == Context.Guild.Id.AsLong()) + .GroupBy(row => row.Time.Year) + .Select(row => new { year = row.Key, amount = row.Count()}); + foreach (var year in quotesByYear) + { + eb.AddInlineField(year.year.ToString(), year.amount); + } + + await ReplyAsync("", false, eb.Build()); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } + private async Task GetLastMessageByUser(IUser user) { try diff --git a/Geekbot.net/Lib/Localization/Translations.yml b/Geekbot.net/Lib/Localization/Translations.yml index 5744741..a19a6f3 100644 --- a/Geekbot.net/Lib/Localization/Translations.yml +++ b/Geekbot.net/Lib/Localization/Translations.yml @@ -160,6 +160,15 @@ quote: NotFoundWithId: EN: "I couldn't find a quote with that ID :disappointed:" CHDE: "Ich chan kei quote finde mit därri ID :disappointed:" + QuoteStats: + EN: "Quote Stats" + CHDE: "Quote statistike" + TotalQuotes: + EN: "Total" + CHDE: "Total" + MostQuotesPerson: + EN: "Most quoted person" + CHDE: "Meist quoteti person" rank: InvalidType: EN: "Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`'" From 656393cc7b40654023ec44dbcde207d466e9f8fe Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 12 May 2020 00:04:20 +0200 Subject: [PATCH 030/264] '!quote stats' bug fixes --- Geekbot.net/Commands/Utils/Quote/Quote.cs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index 454ad9b..5c2bd3b 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -198,6 +198,7 @@ namespace Geekbot.net.Commands.Utils.Quote { try { + // setup var transContext = await _translationHandler.GetGuildContext(Context); var eb = new EmbedBuilder(); eb.Author = new EmbedAuthorBuilder() @@ -206,25 +207,33 @@ namespace Geekbot.net.Commands.Utils.Quote Name = $"{Context.Guild.Name} - {transContext.GetString("QuoteStats")}" }; + // gather data var totalQuotes = _database.Quotes.Count(row => row.GuildId == Context.Guild.Id.AsLong()); if (totalQuotes == 0) { + // no quotes, no stats, end of the road await ReplyAsync(transContext.GetString("NoQuotesFound")); return; } - eb.AddInlineField(transContext.GetString("TotalQuotes"), totalQuotes); - + var mostQuotedPerson = _database.Quotes .Where(row => row.GuildId == Context.Guild.Id.AsLong()) .GroupBy(row => row.UserId) - .Max(row => row.Key); - var user = Context.Client.GetUserAsync(mostQuotedPerson.AsUlong()).Result ?? new UserPolyfillDto {Username = "Unknown User"}; - eb.AddInlineField(transContext.GetString("MostQuotesPerson"), user); + .Select(row => new { userId = row.Key, amount = row.Count()}) + .OrderBy(row => row.amount) + .Last(); + var mostQuotedPersonUser = Context.Client.GetUserAsync(mostQuotedPerson.userId.AsUlong()).Result ?? new UserPolyfillDto {Username = "Unknown User"}; var quotesByYear = _database.Quotes .Where(row => row.GuildId == Context.Guild.Id.AsLong()) .GroupBy(row => row.Time.Year) - .Select(row => new { year = row.Key, amount = row.Count()}); + .Select(row => new { year = row.Key, amount = row.Count()}) + .OrderBy(row => row.year); + + // add data to the embed + eb.AddField(transContext.GetString("MostQuotesPerson"), $"{mostQuotedPersonUser.Username} ({mostQuotedPerson.amount})"); + eb.AddInlineField(transContext.GetString("TotalQuotes"), totalQuotes); + foreach (var year in quotesByYear) { eb.AddInlineField(year.year.ToString(), year.amount); From 2e501008df466b6fb2eda39dcd7bda6f823edaf3 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 21 May 2020 15:55:04 +0200 Subject: [PATCH 031/264] Remove !checkem --- Geekbot.net/Commands/Randomness/CheckEm.cs | 71 ------------ Geekbot.net/Geekbot.net.csproj | 3 - Geekbot.net/Lib/Media/IMediaProvider.cs | 1 - Geekbot.net/Lib/Media/MediaProvider.cs | 18 +-- Geekbot.net/Storage/checkEmPics | 122 --------------------- 5 files changed, 2 insertions(+), 213 deletions(-) delete mode 100644 Geekbot.net/Commands/Randomness/CheckEm.cs delete mode 100644 Geekbot.net/Storage/checkEmPics diff --git a/Geekbot.net/Commands/Randomness/CheckEm.cs b/Geekbot.net/Commands/Randomness/CheckEm.cs deleted file mode 100644 index 0596872..0000000 --- a/Geekbot.net/Commands/Randomness/CheckEm.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Media; - -namespace Geekbot.net.Commands.Randomness -{ - public class CheckEm : ModuleBase - { - private readonly IMediaProvider _checkEmImages; - private readonly IErrorHandler _errorHandler; - - public CheckEm(IMediaProvider mediaProvider, IErrorHandler errorHandler) - { - _checkEmImages = mediaProvider; - _errorHandler = errorHandler; - } - - [Command("checkem", RunMode = RunMode.Async)] - [Summary("Check for dubs")] - public async Task MuhDubs() - { - try - { - var number = new Random().Next(10000000, 99999999); - var dubtriqua = ""; - - var ns = GetIntArray(number); - if (ns[7] == ns[6]) - { - dubtriqua = "DUBS"; - if (ns[6] == ns[5]) - { - dubtriqua = "TRIPS"; - if (ns[5] == ns[4]) - dubtriqua = "QUADS"; - } - } - - var sb = new StringBuilder(); - sb.AppendLine($"Check em {Context.User.Mention}"); - sb.AppendLine($"**{number}**"); - if (!string.IsNullOrEmpty(dubtriqua)) - sb.AppendLine($":tada: {dubtriqua} :tada:"); - sb.AppendLine(_checkEmImages.GetCheckem()); - - await ReplyAsync(sb.ToString()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context); - } - } - - private int[] GetIntArray(int num) - { - var listOfInts = new List(); - while (num > 0) - { - listOfInts.Add(num % 10); - num /= 10; - } - - listOfInts.Reverse(); - return listOfInts.ToArray(); - } - } -} \ No newline at end of file diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index e50613a..baf326d 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -59,9 +59,6 @@ - - PreserveNewest - PreserveNewest diff --git a/Geekbot.net/Lib/Media/IMediaProvider.cs b/Geekbot.net/Lib/Media/IMediaProvider.cs index a646cea..33a0d7c 100644 --- a/Geekbot.net/Lib/Media/IMediaProvider.cs +++ b/Geekbot.net/Lib/Media/IMediaProvider.cs @@ -2,7 +2,6 @@ { public interface IMediaProvider { - string GetCheckem(); string GetPanda(); string GetCrossant(); string GetSquirrel(); diff --git a/Geekbot.net/Lib/Media/MediaProvider.cs b/Geekbot.net/Lib/Media/MediaProvider.cs index c88b696..f7ea9df 100644 --- a/Geekbot.net/Lib/Media/MediaProvider.cs +++ b/Geekbot.net/Lib/Media/MediaProvider.cs @@ -8,7 +8,6 @@ namespace Geekbot.net.Lib.Media { private readonly Random _random; private readonly IGeekbotLogger _logger; - private string[] _checkemImages; private string[] _pandaImages; private string[] _croissantImages; private string[] _squirrelImages; @@ -24,8 +23,7 @@ namespace Geekbot.net.Lib.Media _logger = logger; logger.Information(LogSource.Geekbot, "Loading Media Files"); - - LoadCheckem(); +; LoadPandas(); BakeCroissants(); LoadSquirrels(); @@ -35,13 +33,6 @@ namespace Geekbot.net.Lib.Media LoadFoxes(); LoadDab(); } - - private void LoadCheckem() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/checkEmPics")); - _checkemImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_checkemImages.Length} CheckEm Images"); - } private void LoadPandas() { @@ -98,12 +89,7 @@ namespace Geekbot.net.Lib.Media _dabImages = rawLinks.Split("\n"); _logger.Trace(LogSource.Geekbot, $"Loaded {_dabImages.Length} Dab Images"); } - - public string GetCheckem() - { - return _checkemImages[_random.Next(0, _checkemImages.Length)]; - } - + public string GetPanda() { return _pandaImages[_random.Next(0, _pandaImages.Length)]; diff --git a/Geekbot.net/Storage/checkEmPics b/Geekbot.net/Storage/checkEmPics deleted file mode 100644 index 03be23e..0000000 --- a/Geekbot.net/Storage/checkEmPics +++ /dev/null @@ -1,122 +0,0 @@ -http://s19.postimg.org/pcq2kwzoj/4cb.png -http://s19.postimg.org/cvetk0f4z/5_Dim_Dy6p.jpg -http://s19.postimg.org/5hzfl1v37/1310151998600.jpg -http://s19.postimg.org/53y3lgazn/1324181141954.jpg -http://s19.postimg.org/724rjg3hf/1392512742365.png -http://s19.postimg.org/3rgejkdk3/1393501296733.png -http://s19.postimg.org/a6ffg8k9v/1401667341503.jpg -http://s19.postimg.org/qiph5yylf/1419231572452.jpg -http://s19.postimg.org/fqwi4m8ir/1427600681401.png -http://s19.postimg.org/4c00zzw6b/1447813628974.png -http://s19.postimg.org/uuio8puw3/b5_3q_ycaaavxtf.jpg -http://s19.postimg.org/bghu913fn/check_em_by_boyboy99100_d57xp3y.png -http://s19.postimg.org/s1pgooujn/l_Hkppjs.jpg -http://s19.postimg.org/m08itft0j/checkem.jpg -https://old.postimg.org/image/6vx33rb1b/ -https://old.postimg.org/image/wxiaz1mov/ -https://old.postimg.org/image/azqfizx27/ -https://old.postimg.org/image/6iy2kbiu7/ -https://old.postimg.org/image/k8slt45y7/ -https://old.postimg.org/image/t7ruxmplr/ -https://old.postimg.org/image/ssbzqvean/ -https://old.postimg.org/image/kbchfy9lr/ -https://old.postimg.org/image/dl0lk9btr/ -https://old.postimg.org/image/e5k80oufz/ -https://old.postimg.org/image/er005baqn/ -https://old.postimg.org/image/bfk2uzcin/ -https://old.postimg.org/image/556fp0jkv/ -https://old.postimg.org/image/i0efbryu7/ -https://old.postimg.org/image/943n7u87z/ -https://old.postimg.org/image/xn5op5cm7/ -https://old.postimg.org/image/3l5p4d0kf/ -https://old.postimg.org/image/5boq5ui3j/ -https://old.postimg.org/image/ru082bqcf/ -https://old.postimg.org/image/ytea1oqan/ -https://old.postimg.org/image/vu7dekgtb/ -https://old.postimg.org/image/hl7qwi2an/ -https://old.postimg.org/image/5aescfg9r/ -https://old.postimg.org/image/9gzmrrfvj/ -https://old.postimg.org/image/50bv6tr1b/ -https://old.postimg.org/image/afkl7silb/ -https://old.postimg.org/image/nrdsgzllr/ -https://old.postimg.org/image/s32e5zsin/ -https://old.postimg.org/image/5sej60v8f/ -https://old.postimg.org/image/lgfqctau7/ -https://old.postimg.org/image/tn7q4e0wv/ -https://old.postimg.org/image/8612arz1b/ -https://old.postimg.org/image/w5tf52mn3/ -https://old.postimg.org/image/zdxwi48wv/ -https://old.postimg.org/image/lphwghd0f/ -https://old.postimg.org/image/uzu0k0nq7/ -https://old.postimg.org/image/3vqzsxjbz/ -https://old.postimg.org/image/5d7uqqyov/ -https://old.postimg.org/image/dntnyku8v/ -https://old.postimg.org/image/dsxf891jz/ -https://old.postimg.org/image/3nyrioizj/ -https://old.postimg.org/image/6zx2bzaqn/ -https://old.postimg.org/image/wu6v1raqn/ -https://old.postimg.org/image/hb9f4n2fz/ -https://old.postimg.org/image/p7yhqm3a7/ -https://old.postimg.org/image/oelvxzx9b/ -https://old.postimg.org/image/vcq03xvdr/ -https://old.postimg.org/image/b08t1yqlb/ -https://old.postimg.org/image/6yrpwayan/ -https://old.postimg.org/image/btleukwm7/ -https://old.postimg.org/image/62ztuldzz/ -https://old.postimg.org/image/w3iq9pxr3/ -https://old.postimg.org/image/byp6493xb/ -https://old.postimg.org/image/xp2lf9xcv/ -https://old.postimg.org/image/j9p9u49pb/ -https://old.postimg.org/image/hvxmytafz/ -https://old.postimg.org/image/5eqzbnfa7/ -https://old.postimg.org/image/do2uq290f/ -https://old.postimg.org/image/54o261q1r/ -https://old.postimg.org/image/94qm4jr4v/ -https://old.postimg.org/image/lee88y0pr/ -https://old.postimg.org/image/bncb58cv3/ -https://old.postimg.org/image/5246j7me7/ -https://old.postimg.org/image/4uby8ym1r/ -https://old.postimg.org/image/qn996tj4v/ -https://old.postimg.org/image/c1dn4twyn/ -https://old.postimg.org/image/6rd9ra23j/ -https://lehcark14.files.wordpress.com/2008/08/botan16.jpg -http://i.imgur.com/p9vALew.jpg -http://i.imgur.com/4a9l2Rm.png -http://i.imgur.com/RNtixMQ.jpg -https://pbs.twimg.com/media/Cro9aIGUEAAkXCP.jpg -http://s16.postimg.org/empvloimd/Check_em_Guts.png -https://s18.postimg.io/qgbhe7u09/1424491645996.gif -http://s19.postimg.org/hhemlt7xf/3eb.jpg -http://s19.postimg.org/cwsg6vo83/8aa.png -http://s19.postimg.org/rh9j1pj6r/28mohl4.png -http://s19.postimg.org/zba4n3qzn/86d.jpg -http://s19.postimg.org/cb3hart5v/2016_09_16_08_58_45.png -http://s19.postimg.org/m9ofx92lf/bb1.jpg -http://s19.postimg.org/maydqo4f7/e8b.jpg -http://s19.postimg.org/yqzoy5n4z/fbe.png -http://s19.postimg.org/xd822unvn/giphy.gif -http://s19.postimg.org/c4udlf9er/l_TU3eup.jpg -https://66.media.tumblr.com/cc893a0ee40d73d083da3df4bdaf45cc/tumblr_mx8psiFduG1t1g1k8o1_500.gif -http://i.imgur.com/swbXHSy.gif -http://img1.reactor.cc/pics/post/full/Anime-Touhou-Project-Yakumo-Yukari-%D0%A0%D0%B5%D0%BA%D1%83%D1%80%D1%81%D0%B8%D1%8F-1303807.jpeg -http://i.imgur.com/ftGLHE0.png -http://i.imgur.com/JELDhKQ.png -http://imgur.com/yBJound -http://i.imgur.com/f7gAVPJ.png -http://i.imgur.com/HxWyo2Z.jpg -http://i.imgur.com/8Eb9CxQ.png -http://i.imgur.com/kOECcjz.png -http://i.imgur.com/MJLu7oJ.jpg -http://i.imgur.com/itG3rPM.jpg -http://i.imgur.com/G83Go9t.jpg -http://i.imgur.com/jI2dBnU.jpg -http://i.imgur.com/FtALzg0.jpg -http://i.imgur.com/GwZpJEv.gif -http://i.imgur.com/TYGRD3B.gif -http://i.imgur.com/P6TxLS3.png -http://i.imgur.com/phTVTdn.jpg -http://i.imgur.com/thhR6UE.jpg -http://i.imgur.com/KbROufx.jpg -http://i.imgur.com/sQqWbcm.jpg -http://i.imgur.com/YYpis53.png -http://i.imgur.com/kwaRd54.gif \ No newline at end of file From 33b17b373f1a55e829d6b4bcb953e7a6384ffae3 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 30 May 2020 17:02:17 +0200 Subject: [PATCH 032/264] Remove all dependencies on redis --- Geekbot.net/Commands/Admin/Role.cs | 19 ++--- Geekbot.net/Commands/Games/Roll.cs | 23 +++-- Geekbot.net/Commands/User/Stats.cs | 5 +- Geekbot.net/Database/DatabaseContext.cs | 1 + .../Database/Models/ReactionListenerModel.cs | 22 +++++ Geekbot.net/Handlers.cs | 2 +- .../Lib/KvInMemoryStore/IKvInMemoryStore.cs | 9 ++ .../Lib/KvInMemoryStore/KvInMemoryStore.cs | 32 +++++++ .../Lib/ReactionListener/IReactionListener.cs | 3 +- .../Lib/ReactionListener/ReactionListener.cs | 85 +++++++++---------- Geekbot.net/Program.cs | 5 +- 11 files changed, 129 insertions(+), 77 deletions(-) create mode 100644 Geekbot.net/Database/Models/ReactionListenerModel.cs create mode 100644 Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs create mode 100644 Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs diff --git a/Geekbot.net/Commands/Admin/Role.cs b/Geekbot.net/Commands/Admin/Role.cs index b0df4bb..6d4557d 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/Geekbot.net/Commands/Admin/Role.cs @@ -170,23 +170,16 @@ namespace Geekbot.net.Commands.Admin [RequireUserPermission(GuildPermission.ManageRoles)] [Summary("Give a role by clicking on an emoji")] [Command("listen", RunMode = RunMode.Async)] - public async Task AddListener([Summary("message-ID")] string messageId, [Summary("Emoji")] string emoji, [Summary("@role")] IRole role) + public async Task AddListener([Summary("message-ID")] string messageIdStr, [Summary("Emoji")] string emoji, [Summary("@role")] IRole role) { try { - var message = (IUserMessage) await Context.Channel.GetMessageAsync(ulong.Parse(messageId)); - IEmote emote; - if (!emoji.StartsWith('<')) - { - var emo = new Emoji(emoji); - emote = emo; - } - else - { - emote = Emote.Parse(emoji); - } + var messageId = ulong.Parse(messageIdStr); + var message = (IUserMessage) await Context.Channel.GetMessageAsync(messageId); + var emote = _reactionListener.ConvertStringToEmote(emoji); + await message.AddReactionAsync(emote); - await _reactionListener.AddRoleToListener(messageId, emote, role); + await _reactionListener.AddRoleToListener(messageId, Context.Guild.Id, emoji, role); await Context.Message.DeleteAsync(); } catch (HttpException e) diff --git a/Geekbot.net/Commands/Games/Roll.cs b/Geekbot.net/Commands/Games/Roll.cs index dfecb13..076cf8f 100644 --- a/Geekbot.net/Commands/Games/Roll.cs +++ b/Geekbot.net/Commands/Games/Roll.cs @@ -4,26 +4,25 @@ using System.Threading.Tasks; using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Database.Models; -using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.KvInMemoryStore; using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.RandomNumberGenerator; -using StackExchange.Redis; namespace Geekbot.net.Commands.Games { public class Roll : ModuleBase { private readonly IErrorHandler _errorHandler; - private readonly IAlmostRedis _redis; + private readonly IKvInMemoryStore _kvInMemoryStore; private readonly ITranslationHandler _translation; private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Roll(IAlmostRedis redis, IErrorHandler errorHandler, ITranslationHandler translation, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) + public Roll(IKvInMemoryStore kvInMemoryStore,IErrorHandler errorHandler, ITranslationHandler translation, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) { - _redis = redis; + _kvInMemoryStore = kvInMemoryStore; _translation = translation; _database = database; _randomNumberGenerator = randomNumberGenerator; @@ -37,28 +36,28 @@ namespace Geekbot.net.Commands.Games try { var number = _randomNumberGenerator.Next(1, 100); - var guess = 1000; - int.TryParse(stuff, out guess); + int.TryParse(stuff, out var guess); var transContext = await _translation.GetGuildContext(Context); if (guess <= 100 && guess > 0) { - var prevRoll = _redis.Db.HashGet($"{Context.Guild.Id}:RollsPrevious2", Context.Message.Author.Id).ToString()?.Split('|'); - if (prevRoll?.Length == 2) + var kvKey = $"{Context.Guild.Id}:{Context.User.Id}:RollsPrevious"; + + var prevRoll = _kvInMemoryStore.Get(kvKey); + if (prevRoll > 0) { - if (prevRoll[0] == guess.ToString() && DateTime.Parse(prevRoll[1]) > DateTime.Now.AddDays(-1)) + if (prevRoll == guess) { await ReplyAsync(transContext.GetString("NoPrevGuess", Context.Message.Author.Mention)); return; } } - _redis.Db.HashSet($"{Context.Guild.Id}:RollsPrevious2", new[] {new HashEntry(Context.Message.Author.Id, $"{guess}|{DateTime.Now}")}); + _kvInMemoryStore.Set(kvKey, guess); await ReplyAsync(transContext.GetString("Rolled", Context.Message.Author.Mention, number, guess)); if (guess == number) { await ReplyAsync(transContext.GetString("Gratz", Context.Message.Author)); - _redis.Db.HashIncrement($"{Context.Guild.Id}:Rolls", Context.User.Id.ToString()); var user = await GetUser(Context.User.Id); user.Rolls += 1; _database.Rolls.Update(user); diff --git a/Geekbot.net/Commands/User/Stats.cs b/Geekbot.net/Commands/User/Stats.cs index 05ea324..08b69d2 100644 --- a/Geekbot.net/Commands/User/Stats.cs +++ b/Geekbot.net/Commands/User/Stats.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Database; -using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; @@ -16,12 +15,10 @@ namespace Geekbot.net.Commands.User { private readonly IErrorHandler _errorHandler; private readonly ILevelCalc _levelCalc; - private readonly IAlmostRedis _redis; private readonly DatabaseContext _database; - public Stats(IAlmostRedis redis, DatabaseContext database, IErrorHandler errorHandler, ILevelCalc levelCalc) + public Stats(DatabaseContext database, IErrorHandler errorHandler, ILevelCalc levelCalc) { - _redis = redis; _database = database; _errorHandler = errorHandler; _levelCalc = levelCalc; diff --git a/Geekbot.net/Database/DatabaseContext.cs b/Geekbot.net/Database/DatabaseContext.cs index cbfa30d..56c19f8 100644 --- a/Geekbot.net/Database/DatabaseContext.cs +++ b/Geekbot.net/Database/DatabaseContext.cs @@ -18,5 +18,6 @@ namespace Geekbot.net.Database public DbSet RoleSelfService { get; set; } public DbSet Polls { get; set; } public DbSet Cookies { get; set; } + public DbSet ReactionListeners { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Database/Models/ReactionListenerModel.cs b/Geekbot.net/Database/Models/ReactionListenerModel.cs new file mode 100644 index 0000000..05ab5b3 --- /dev/null +++ b/Geekbot.net/Database/Models/ReactionListenerModel.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; + +namespace Geekbot.net.Database.Models +{ + public class ReactionListenerModel + { + [Key] + public int Id { get; set; } + + [Required] + public long GuildId { get; set; } + + [Required] + public long MessageId { get; set; } + + [Required] + public long RoleId { get; set; } + + [Required] + public string Reaction { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index 52cf937..6f98041 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -9,12 +9,12 @@ using Discord.Rest; using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Database.Models; -using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; using Microsoft.EntityFrameworkCore; + namespace Geekbot.net { public class Handlers diff --git a/Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs b/Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs new file mode 100644 index 0000000..88f3863 --- /dev/null +++ b/Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs @@ -0,0 +1,9 @@ +namespace Geekbot.net.Lib.KvInMemoryStore +{ + public interface IKvInMemoryStore + { + public T Get(string key); + public void Set(string key, T value); + public void Remove(string key); + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs b/Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs new file mode 100644 index 0000000..33b7155 --- /dev/null +++ b/Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace Geekbot.net.Lib.KvInMemoryStore +{ + public class KvInInMemoryStore : IKvInMemoryStore + { + private readonly Dictionary _storage = new Dictionary(); + + public T Get(string key) + { + try + { + return (T) _storage[key]; + } + catch + { + return default; + } + } + + public void Set(string key, T value) + { + _storage.Remove(key); + _storage.Add(key, value); + } + + public void Remove(string key) + { + _storage.Remove(key); + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/ReactionListener/IReactionListener.cs b/Geekbot.net/Lib/ReactionListener/IReactionListener.cs index 792a516..b2ab9fb 100644 --- a/Geekbot.net/Lib/ReactionListener/IReactionListener.cs +++ b/Geekbot.net/Lib/ReactionListener/IReactionListener.cs @@ -7,8 +7,9 @@ namespace Geekbot.net.Lib.ReactionListener public interface IReactionListener { bool IsListener(ulong id); - Task AddRoleToListener(string messageId, IEmote emoji, IRole role); + Task AddRoleToListener(ulong messageId, ulong guildId, string emoji, IRole role); void RemoveRole(ISocketMessageChannel channel, SocketReaction reaction); void GiveRole(ISocketMessageChannel message, SocketReaction reaction); + IEmote ConvertStringToEmote(string emoji); } } \ No newline at end of file diff --git a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs index 2349028..4a9a08c 100644 --- a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs +++ b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs @@ -1,80 +1,66 @@ using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using Discord; using Discord.WebSocket; -using StackExchange.Redis; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; +using Geekbot.net.Lib.Extensions; namespace Geekbot.net.Lib.ReactionListener { public class ReactionListener : IReactionListener { - private readonly IDatabase _redis; - private Dictionary> _listener; + private readonly DatabaseContext _database; + private Dictionary> _listener; - public ReactionListener(IDatabase redis) + public ReactionListener(DatabaseContext database) { - _redis = redis; + _database = database; LoadListeners(); } private void LoadListeners() { - var ids = _redis.SetMembers("MessageIds"); - _listener = new Dictionary>(); - foreach (var id in ids) + _listener = new Dictionary>(); + foreach (var row in _database.ReactionListeners) { - var reactions = _redis.HashGetAll($"Messages:{id}"); - var messageId = id; - var emojiDict = new Dictionary(); - foreach (var r in reactions) + var messageId = row.MessageId.AsUlong(); + if (!_listener.ContainsKey(messageId)) { - IEmote emote; - if (!r.Name.ToString().StartsWith('<')) - { - var emo = new Emoji(r.Name); - emote = emo; - } - else - { - emote = Emote.Parse(r.Name); - } - emojiDict.Add(emote, ulong.Parse(r.Value)); + _listener.Add(messageId, new Dictionary()); } - _listener.Add(messageId, emojiDict); + + _listener[messageId].Add(ConvertStringToEmote(row.Reaction), row.RoleId.AsUlong()); } } public bool IsListener(ulong id) { - return _listener.ContainsKey(id.ToString()); + return _listener.ContainsKey(id); } - public Task AddRoleToListener(string messageId, IEmote emoji, IRole role) + public async Task AddRoleToListener(ulong messageId, ulong guildId, string emoji, IRole role) { - if (_redis.SetMembers("MessageIds").All(e => e.ToString() != messageId)) - { - _redis.SetAdd("MessageIds", messageId); - } - _redis.HashSet($"Messages:{messageId}", new[] {new HashEntry(emoji.ToString(), role.Id.ToString())}); - _redis.SetAdd("MessageIds", messageId); - if (_listener.ContainsKey(messageId)) - { - _listener[messageId].Add(emoji, role.Id); - return Task.CompletedTask; - } + var emote = ConvertStringToEmote(emoji); - var dict = new Dictionary + await _database.ReactionListeners.AddAsync(new ReactionListenerModel() { - {emoji, role.Id} - }; - _listener.Add(messageId, dict); - return Task.CompletedTask; + GuildId = guildId.AsLong(), + MessageId = messageId.AsLong(), + RoleId = role.Id.AsLong(), + Reaction = emoji + }); + + if (!_listener.ContainsKey(messageId)) + { + _listener.Add(messageId, new Dictionary()); + } + _listener[messageId].Add(emote, role.Id); } public async void RemoveRole(ISocketMessageChannel channel, SocketReaction reaction) { - var roleId = _listener[reaction.MessageId.ToString()][reaction.Emote]; + var roleId = _listener[reaction.MessageId][reaction.Emote]; var guild = (SocketGuildChannel) channel; var role = guild.Guild.GetRole(roleId); await ((IGuildUser) reaction.User.Value).RemoveRoleAsync(role); @@ -82,10 +68,19 @@ namespace Geekbot.net.Lib.ReactionListener public async void GiveRole(ISocketMessageChannel channel, SocketReaction reaction) { - var roleId = _listener[reaction.MessageId.ToString()][reaction.Emote]; + var roleId = _listener[reaction.MessageId][reaction.Emote]; var guild = (SocketGuildChannel) channel; var role = guild.Guild.GetRole(roleId); await ((IGuildUser) reaction.User.Value).AddRoleAsync(role); } + + public IEmote ConvertStringToEmote(string emoji) + { + if (!emoji.StartsWith('<')) + { + return new Emoji(emoji); + } + return Emote.Parse(emoji); + } } } \ No newline at end of file diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 3bd5a8f..389c051 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -14,6 +14,7 @@ using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Geekbot.net.Lib.Highscores; +using Geekbot.net.Lib.KvInMemoryStore; using Geekbot.net.Lib.Levels; using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Logger; @@ -125,6 +126,7 @@ namespace Geekbot.net var mtgManaConverter = new MtgManaConverter(); var wikipediaClient = new WikipediaClient(); var randomNumberGenerator = new RandomNumberGenerator(); + var kvMemoryStore = new KvInInMemoryStore(); _services.AddSingleton(_redis); _services.AddSingleton(_userRepository); @@ -137,6 +139,7 @@ namespace Geekbot.net _services.AddSingleton(mtgManaConverter); _services.AddSingleton(wikipediaClient); _services.AddSingleton(randomNumberGenerator); + _services.AddSingleton(kvMemoryStore); _services.AddSingleton(_globalSettings); _services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); _services.AddTransient(e => _databaseInitializer.Initialize()); @@ -164,7 +167,7 @@ namespace Geekbot.net _logger.Information(LogSource.Geekbot, "Registering Stuff"); var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); - var reactionListener = new ReactionListener(_redis.Db); + var reactionListener = new ReactionListener(_databaseInitializer.Initialize()); _services.AddSingleton(errorHandler); _services.AddSingleton(translationHandler); _services.AddSingleton(_client); From 46fee88f039bf796f54278298151b0b9aee82656 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 00:52:56 +0200 Subject: [PATCH 033/264] Add a migration script for role listeners --- Geekbot.net/Commands/Admin/Owner/Owner.cs | 79 ++++++++++++++++++- .../Lib/ReactionListener/ReactionListener.cs | 2 + 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/Geekbot.net/Commands/Admin/Owner/Owner.cs b/Geekbot.net/Commands/Admin/Owner/Owner.cs index 996d848..12f41a2 100644 --- a/Geekbot.net/Commands/Admin/Owner/Owner.cs +++ b/Geekbot.net/Commands/Admin/Owner/Owner.cs @@ -1,12 +1,16 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Geekbot.net.Lib.Logger; +using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; +using StackExchange.Redis; namespace Geekbot.net.Commands.Admin.Owner { @@ -17,16 +21,22 @@ namespace Geekbot.net.Commands.Admin.Owner private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; private readonly IGlobalSettings _globalSettings; + private readonly IDatabase _redis; + private readonly IReactionListener _reactionListener; private readonly IGeekbotLogger _logger; private readonly IUserRepository _userRepository; - public Owner(DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, IGlobalSettings globalSettings) + public Owner(DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, IGlobalSettings globalSettings, + IAlmostRedis redis, IReactionListener reactionListener + ) { _client = client; _logger = logger; _userRepository = userRepositry; _errorHandler = errorHandler; _globalSettings = globalSettings; + _redis = redis.Db; + _reactionListener = reactionListener; } [Command("youtubekey", RunMode = RunMode.Async)] @@ -122,5 +132,72 @@ namespace Geekbot.net.Commands.Admin.Owner await _errorHandler.HandleCommandException(e, Context); } } + + [Command("migrate_listeners", RunMode = RunMode.Async)] + public async Task MigrateListeners() + { + try + { + var messageIds = _redis.SetMembers("MessageIds"); + var connectedGuilds = _client.Guilds; + var messageGuildAssociation = new Dictionary(); + foreach (var messageIdUnparsed in messageIds) + { + var messageId = ulong.Parse(messageIdUnparsed); + var reactions = _redis.HashGetAll($"Messages:{messageIdUnparsed.ToString()}"); + + foreach (var reaction in reactions) + { + _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Starting"); + try + { + ulong guildId = 0; + IRole role = null; + + var roleId = ulong.Parse(reaction.Value); + if (messageGuildAssociation.ContainsKey(messageId)) + { + guildId = messageGuildAssociation[messageId]; + _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - known to be in {guildId}"); + role = _client.GetGuild(guildId).GetRole(roleId); + } + else + { + _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Attempting to find guild"); + IRole foundRole = null; + try + { + foreach (var guild in connectedGuilds) + { + foundRole = guild.GetRole(roleId); + if (foundRole != null) + { + role = _client.GetGuild(foundRole.Guild.Id).GetRole(ulong.Parse(reaction.Value)); + messageGuildAssociation.Add(messageId, foundRole.Guild.Id); + } + } + } catch { /* ignore */ } + + if (foundRole == null) + { + _logger.Warning(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Could not find guild for message"); + continue; + } + } + _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Found Role {roleId.ToString()}"); + await _reactionListener.AddRoleToListener(ulong.Parse(messageIdUnparsed), guildId, reaction.Name, role); + } + catch (Exception e) + { + _logger.Error(LogSource.Migration, $"Failed to migrate reaction for {messageIdUnparsed.ToString()}", e); + } + } + } + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs index 4a9a08c..bd335af 100644 --- a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs +++ b/Geekbot.net/Lib/ReactionListener/ReactionListener.cs @@ -11,6 +11,7 @@ namespace Geekbot.net.Lib.ReactionListener public class ReactionListener : IReactionListener { private readonly DatabaseContext _database; + // private Dictionary> _listener; public ReactionListener(DatabaseContext database) @@ -50,6 +51,7 @@ namespace Geekbot.net.Lib.ReactionListener RoleId = role.Id.AsLong(), Reaction = emoji }); + await _database.SaveChangesAsync(); if (!_listener.ContainsKey(messageId)) { From 520633c590a7e1f51794145e18b12f1e3730eedb Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 01:02:36 +0200 Subject: [PATCH 034/264] Remove all redis leftovers --- Geekbot.net/Commands/Admin/Owner/Owner.cs | 79 +-------------------- Geekbot.net/Geekbot.net.csproj | 1 - Geekbot.net/Lib/AlmostRedis/AlmostRedis.cs | 35 --------- Geekbot.net/Lib/AlmostRedis/IAlmostRedis.cs | 13 ---- Geekbot.net/Lib/GeekbotExitCode.cs | 2 +- Geekbot.net/Lib/Logger/LogSource.cs | 1 - Geekbot.net/Lib/RunParameters.cs | 13 ---- Geekbot.net/Program.cs | 14 ---- 8 files changed, 2 insertions(+), 156 deletions(-) delete mode 100644 Geekbot.net/Lib/AlmostRedis/AlmostRedis.cs delete mode 100644 Geekbot.net/Lib/AlmostRedis/IAlmostRedis.cs diff --git a/Geekbot.net/Commands/Admin/Owner/Owner.cs b/Geekbot.net/Commands/Admin/Owner/Owner.cs index 12f41a2..996d848 100644 --- a/Geekbot.net/Commands/Admin/Owner/Owner.cs +++ b/Geekbot.net/Commands/Admin/Owner/Owner.cs @@ -1,16 +1,12 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Geekbot.net.Lib.Logger; -using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; -using StackExchange.Redis; namespace Geekbot.net.Commands.Admin.Owner { @@ -21,22 +17,16 @@ namespace Geekbot.net.Commands.Admin.Owner private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; private readonly IGlobalSettings _globalSettings; - private readonly IDatabase _redis; - private readonly IReactionListener _reactionListener; private readonly IGeekbotLogger _logger; private readonly IUserRepository _userRepository; - public Owner(DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, IGlobalSettings globalSettings, - IAlmostRedis redis, IReactionListener reactionListener - ) + public Owner(DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, IGlobalSettings globalSettings) { _client = client; _logger = logger; _userRepository = userRepositry; _errorHandler = errorHandler; _globalSettings = globalSettings; - _redis = redis.Db; - _reactionListener = reactionListener; } [Command("youtubekey", RunMode = RunMode.Async)] @@ -132,72 +122,5 @@ namespace Geekbot.net.Commands.Admin.Owner await _errorHandler.HandleCommandException(e, Context); } } - - [Command("migrate_listeners", RunMode = RunMode.Async)] - public async Task MigrateListeners() - { - try - { - var messageIds = _redis.SetMembers("MessageIds"); - var connectedGuilds = _client.Guilds; - var messageGuildAssociation = new Dictionary(); - foreach (var messageIdUnparsed in messageIds) - { - var messageId = ulong.Parse(messageIdUnparsed); - var reactions = _redis.HashGetAll($"Messages:{messageIdUnparsed.ToString()}"); - - foreach (var reaction in reactions) - { - _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Starting"); - try - { - ulong guildId = 0; - IRole role = null; - - var roleId = ulong.Parse(reaction.Value); - if (messageGuildAssociation.ContainsKey(messageId)) - { - guildId = messageGuildAssociation[messageId]; - _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - known to be in {guildId}"); - role = _client.GetGuild(guildId).GetRole(roleId); - } - else - { - _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Attempting to find guild"); - IRole foundRole = null; - try - { - foreach (var guild in connectedGuilds) - { - foundRole = guild.GetRole(roleId); - if (foundRole != null) - { - role = _client.GetGuild(foundRole.Guild.Id).GetRole(ulong.Parse(reaction.Value)); - messageGuildAssociation.Add(messageId, foundRole.Guild.Id); - } - } - } catch { /* ignore */ } - - if (foundRole == null) - { - _logger.Warning(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Could not find guild for message"); - continue; - } - } - _logger.Information(LogSource.Migration, $"{messageIdUnparsed.ToString()} - Found Role {roleId.ToString()}"); - await _reactionListener.AddRoleToListener(ulong.Parse(messageIdUnparsed), guildId, reaction.Name, role); - } - catch (Exception e) - { - _logger.Error(LogSource.Migration, $"Failed to migrate reaction for {messageIdUnparsed.ToString()}", e); - } - } - } - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context); - } - } } } \ No newline at end of file diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index baf326d..32555e7 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -25,7 +25,6 @@ - diff --git a/Geekbot.net/Lib/AlmostRedis/AlmostRedis.cs b/Geekbot.net/Lib/AlmostRedis/AlmostRedis.cs deleted file mode 100644 index c6faf52..0000000 --- a/Geekbot.net/Lib/AlmostRedis/AlmostRedis.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Generic; -using Geekbot.net.Lib.Logger; -using StackExchange.Redis; - -namespace Geekbot.net.Lib.AlmostRedis -{ - // if anyone ever sees this, please come up with a better fucking name, i'd appriciate it - public class AlmostRedis : IAlmostRedis - { - private readonly GeekbotLogger _logger; - private readonly RunParameters _runParameters; - - public AlmostRedis(GeekbotLogger logger, RunParameters runParameters) - { - _logger = logger; - _runParameters = runParameters; - } - - public void Connect() - { - Connection = ConnectionMultiplexer.Connect($"{_runParameters.RedisHost}:{_runParameters.RedisPort}"); - Db = Connection.GetDatabase(int.Parse(_runParameters.RedisDatabase)); - _logger.Information(LogSource.Redis, $"Connected to Redis on {Connection.Configuration} at {Db.Database}"); - } - - public IDatabase Db { get; private set; } - - public ConnectionMultiplexer Connection { get; private set; } - - public IEnumerable GetAllKeys() - { - return Connection.GetServer($"{_runParameters.RedisHost}:{_runParameters.RedisPort}").Keys(int.Parse(_runParameters.RedisDatabase)); - } - } -} \ No newline at end of file diff --git a/Geekbot.net/Lib/AlmostRedis/IAlmostRedis.cs b/Geekbot.net/Lib/AlmostRedis/IAlmostRedis.cs deleted file mode 100644 index 549c49e..0000000 --- a/Geekbot.net/Lib/AlmostRedis/IAlmostRedis.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; -using StackExchange.Redis; - -namespace Geekbot.net.Lib.AlmostRedis -{ - public interface IAlmostRedis - { - void Connect(); - IDatabase Db { get; } - ConnectionMultiplexer Connection { get; } - IEnumerable GetAllKeys(); - } -} \ No newline at end of file diff --git a/Geekbot.net/Lib/GeekbotExitCode.cs b/Geekbot.net/Lib/GeekbotExitCode.cs index 130d435..4d91d18 100644 --- a/Geekbot.net/Lib/GeekbotExitCode.cs +++ b/Geekbot.net/Lib/GeekbotExitCode.cs @@ -10,7 +10,7 @@ TranslationsFailed = 201, // Dependent Services - RedisConnectionFailed = 301, + /* 301 not in use anymore (redis) */ DatabaseConnectionFailed = 302, // Discord Related diff --git a/Geekbot.net/Lib/Logger/LogSource.cs b/Geekbot.net/Lib/Logger/LogSource.cs index 7cd92ff..48ad7d0 100644 --- a/Geekbot.net/Lib/Logger/LogSource.cs +++ b/Geekbot.net/Lib/Logger/LogSource.cs @@ -10,7 +10,6 @@ namespace Geekbot.net.Lib.Logger Rest, Gateway, Discord, - Redis, Database, Message, UserRepository, diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index e16f644..e17825f 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -50,19 +50,6 @@ namespace Geekbot.net.Lib [Option("db-logging", Default = false, HelpText = "Enable database logging")] public bool DbLogging { get; set; } - /************************************ - * Redis * - ************************************/ - - [Option("redis-host", Default = "127.0.0.1", HelpText = "Set a redis host")] - public string RedisHost { get; set; } - - [Option("redis-port", Default = "6379", HelpText = "Set a redis port")] - public string RedisPort { get; set; } - - [Option("redis-database", Default = "6", HelpText = "Select a redis database (1-15)")] - public string RedisDatabase { get; set; } - /************************************ * WebApi * ************************************/ diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 389c051..d46df90 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -8,7 +8,6 @@ using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Lib; -using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; @@ -41,7 +40,6 @@ namespace Geekbot.net private GeekbotLogger _logger; private IUserRepository _userRepository; private RunParameters _runParameters; - private IAlmostRedis _redis; private static void Main(string[] args) { @@ -94,17 +92,6 @@ namespace Geekbot.net _globalSettings = new GlobalSettings(database); - try - { - _redis = new AlmostRedis(logger, runParameters); - _redis.Connect(); - } - catch (Exception e) - { - logger.Error(LogSource.Redis, "Redis Connection Failed", e); - Environment.Exit(GeekbotExitCode.RedisConnectionFailed.GetHashCode()); - } - _token = runParameters.Token ?? _globalSettings.GetKey("DiscordToken"); if (string.IsNullOrEmpty(_token)) { @@ -128,7 +115,6 @@ namespace Geekbot.net var randomNumberGenerator = new RandomNumberGenerator(); var kvMemoryStore = new KvInInMemoryStore(); - _services.AddSingleton(_redis); _services.AddSingleton(_userRepository); _services.AddSingleton(logger); _services.AddSingleton(levelCalc); From ff968a490f6b0ebf36235b861240e0245950c9b8 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 01:13:45 +0200 Subject: [PATCH 035/264] Cleanup some dead code and database models --- Geekbot.net/Database/DatabaseContext.cs | 2 -- Geekbot.net/Database/Models/GuildsModel.cs | 24 ----------------- Geekbot.net/Database/Models/PollModel.cs | 27 ------------------- .../Database/Models/PollQuestionModel.cs | 16 ----------- Geekbot.net/Lib/RunParameters.cs | 9 ------- 5 files changed, 78 deletions(-) delete mode 100644 Geekbot.net/Database/Models/GuildsModel.cs delete mode 100644 Geekbot.net/Database/Models/PollModel.cs delete mode 100644 Geekbot.net/Database/Models/PollQuestionModel.cs diff --git a/Geekbot.net/Database/DatabaseContext.cs b/Geekbot.net/Database/DatabaseContext.cs index 56c19f8..505486f 100644 --- a/Geekbot.net/Database/DatabaseContext.cs +++ b/Geekbot.net/Database/DatabaseContext.cs @@ -7,7 +7,6 @@ namespace Geekbot.net.Database { public DbSet Quotes { get; set; } public DbSet Users { get; set; } - public DbSet Guilds { get; set; } public DbSet GuildSettings { get; set; } public DbSet Karma { get; set; } public DbSet Ships { get; set; } @@ -16,7 +15,6 @@ namespace Geekbot.net.Database public DbSet Slaps { get; set; } public DbSet Globals { get; set; } public DbSet RoleSelfService { get; set; } - public DbSet Polls { get; set; } public DbSet Cookies { get; set; } public DbSet ReactionListeners { get; set; } } diff --git a/Geekbot.net/Database/Models/GuildsModel.cs b/Geekbot.net/Database/Models/GuildsModel.cs deleted file mode 100644 index b6347a6..0000000 --- a/Geekbot.net/Database/Models/GuildsModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; - -namespace Geekbot.net.Database.Models -{ - public class GuildsModel - { - [Key] - public int Id { get; set; } - - [Required] - public long GuildId { get; set; } - - [Required] - public string Name { get; set; } - - [Required] - public long Owner { get; set; } - - public string IconUrl { get; set; } - - public DateTimeOffset CreatedAt { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Database/Models/PollModel.cs b/Geekbot.net/Database/Models/PollModel.cs deleted file mode 100644 index 3b12410..0000000 --- a/Geekbot.net/Database/Models/PollModel.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace Geekbot.net.Database.Models -{ - public class PollModel - { - [Key] - public int Id { get; set; } - - [Required] - public long GuildId { get; set; } - - [Required] - public long ChannelId { get; set; } - - public string Question { get; set; } - - public long Creator { get; set; } - - public long MessageId { get; set; } - - public List Options { get; set; } - - public bool IsFinshed { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Database/Models/PollQuestionModel.cs b/Geekbot.net/Database/Models/PollQuestionModel.cs deleted file mode 100644 index e251fe2..0000000 --- a/Geekbot.net/Database/Models/PollQuestionModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Geekbot.net.Database.Models -{ - public class PollQuestionModel - { - [Key] - public int Id { get; set; } - - public int OptionId { get; set; } - - public string OptionText { get; set; } - - public int Votes { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index e17825f..e1386d3 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -59,14 +59,5 @@ namespace Geekbot.net.Lib [Option("api-port", Default = "12995", HelpText = "Port on which the WebApi listens")] public string ApiPort { get; set; } - - /************************************ - * Prometheus * - ************************************/ - [Option("prometheus-host", Default = "localhost", HelpText = "Host on which the Prometheus Metric Server listens")] - public string PrometheusHost { get; set; } - - [Option("prometheus-port", Default = "12991", HelpText = "Port on which the Prometheus Metric Server listens")] - public string PrometheusPort { get; set; } } } \ No newline at end of file From 3108a68407341a64b3ce3d07ef7419414ef35c3c Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 02:16:29 +0200 Subject: [PATCH 036/264] Dependency Upgrades --- Geekbot.net/Commands/Utils/Quote/Quote.cs | 2 +- Geekbot.net/Geekbot.net.csproj | 30 +++++++++---------- Geekbot.net/Lib/Extensions/DbSetExtensions.cs | 11 +++++++ Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs | 2 ++ Tests/Tests.csproj | 6 ++-- 5 files changed, 32 insertions(+), 19 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index 5c2bd3b..6288bef 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -252,7 +252,7 @@ namespace Geekbot.net.Commands.Utils.Quote try { var list = Context.Channel.GetMessagesAsync().Flatten(); - return await list.FirstOrDefault(msg => + return await list.FirstOrDefaultAsync(msg => msg.Author.Id == user.Id && msg.Embeds.Count == 0 && msg.Id != Context.Message.Id && diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 32555e7..0d39cae 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -20,28 +20,28 @@ true - - - - + + + + - - - - - - - - + + + + + + + + - - - + + + diff --git a/Geekbot.net/Lib/Extensions/DbSetExtensions.cs b/Geekbot.net/Lib/Extensions/DbSetExtensions.cs index c731fc0..e08b2d4 100644 --- a/Geekbot.net/Lib/Extensions/DbSetExtensions.cs +++ b/Geekbot.net/Lib/Extensions/DbSetExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; @@ -13,5 +14,15 @@ namespace Geekbot.net.Lib.Extensions var exists = predicate != null ? dbSet.Any(predicate) : dbSet.Any(); return !exists ? dbSet.Add(entity) : null; } + + // https://github.com/dotnet/efcore/issues/18124 + public static IAsyncEnumerable AsAsyncEnumerable(this Microsoft.EntityFrameworkCore.DbSet obj) where TEntity : class + { + return Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsAsyncEnumerable(obj); + } + public static IQueryable Where(this Microsoft.EntityFrameworkCore.DbSet obj, System.Linq.Expressions.Expression> predicate) where TEntity : class + { + return System.Linq.Queryable.Where(obj, predicate); + } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs b/Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs index 6d81581..32ea663 100644 --- a/Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs +++ b/Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Immutable; using System.Threading.Tasks; using Discord; @@ -11,6 +12,7 @@ namespace Geekbot.net.Lib.Polyfills public string Mention { get; set; } public IActivity Activity { get; } public UserStatus Status { get; set; } + public IImmutableSet ActiveClients { get; } public string AvatarId { get; set; } public string Discriminator { get; set; } public ushort DiscriminatorValue { get; set; } diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 235cc0b..345dacd 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -6,9 +6,9 @@ xUnit1026 - - - + + + From 6692b3bc778bdb90db6a737e44ecddeae1cd7431 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 02:17:15 +0200 Subject: [PATCH 037/264] Don't show a quote id when using '!quote make' --- Geekbot.net/Commands/Utils/Quote/Quote.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/Geekbot.net/Commands/Utils/Quote/Quote.cs index 6288bef..7af8a4c 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/Geekbot.net/Commands/Utils/Quote/Quote.cs @@ -270,7 +270,14 @@ namespace Geekbot.net.Commands.Utils.Quote var user = Context.Client.GetUserAsync(quote.UserId.AsUlong()).Result ?? new UserPolyfillDto { Username = "Unknown User" }; var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 167, 232)); - eb.Title = $"#{quote.InternalId} | {user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; + if (quote.InternalId == 0) + { + eb.Title = $"{user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; + } + else + { + eb.Title = $"#{quote.InternalId} | {user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; + } eb.Description = quote.Quote; eb.ThumbnailUrl = user.GetAvatarUrl(); if (quote.Image != null) eb.ImageUrl = quote.Image; @@ -289,9 +296,8 @@ namespace Geekbot.net.Commands.Utils.Quote image = null; } - var last = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())) - .OrderByDescending(e => e.InternalId).FirstOrDefault(); - var internalId = 1; + var last = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).OrderByDescending(e => e.InternalId).FirstOrDefault(); + var internalId = 0; if (last != null) internalId = last.InternalId + 1; return new QuoteModel() { From d91c21e607f4aeb7be3eee88106319b22914aef0 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 02:20:27 +0200 Subject: [PATCH 038/264] update readme --- readme.md | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/readme.md b/readme.md index 7d8544f..ffc320c 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -[![pipeline status](https://git.boerlage.me/open/Geekbot.net/badges/master/pipeline.svg)](https://git.boerlage.me/open/Geekbot.net/commits/master) +[![pipeline status](https://gitlab.com/dbgit/open/geekbot/badges/master/pipeline.svg)](https://gitlab.com/dbgit/open/geekbot/commits/master) # [Geekbot.net](https://geekbot.pizzaandcoffee.rocks/) @@ -8,22 +8,19 @@ You can invite Geekbot to your server with [this link](https://discordapp.com/oa ## Technologies -* DotNet Core 2 -* Redis +* DotNet Core 3.1 +* PostgreSQL * Discord.net ## Running -Make sure redis is running +You can start geekbot with: `dotnet run` -Run these commands +On your first run geekbot will ask for your bot token. -* `dotnet restore` -* `dotnet run` +You might need to pass some additional configuration (e.g. database credentials), these can be passed as commandline arguments. -On your first run geekbot will ask for your bot token, everything else is taken care of. - -For a list of launch options use `dotnet run -h` +For a list of commandline arguments use `dotnet run -- -h` ## Contributing From 8018d5e7501d09a32186a4fe5bd374ab9bb2b957 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 1 Jun 2020 15:22:41 +0200 Subject: [PATCH 039/264] Allow configuration to be passed as environment variables --- Geekbot.net/Lib/RunParameters.cs | 98 +++++++++++++++++++++----------- readme.md | 6 +- 2 files changed, 70 insertions(+), 34 deletions(-) diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index e1386d3..1ddbd46 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -1,4 +1,5 @@ -using CommandLine; +using System; +using CommandLine; namespace Geekbot.net.Lib { @@ -8,56 +9,89 @@ namespace Geekbot.net.Lib * General * ************************************/ - [Option('V', "verbose", Default = false, HelpText = "Logs everything.")] - public bool Verbose { get; set; } + [Option("token", HelpText = "Set a new bot token. By default it will use your previous bot token which was stored in the database (default: null) (env: TOKEN)")] + public string Token { get; set; } = ParamFallback("TOKEN"); - [Option('j', "log-json", Default = false, HelpText = "Logger outputs json")] - public bool LogJson { get; set; } + [Option('V', "verbose", HelpText = "Logs everything. (default: false) (env: LOG_VERBOSE)")] + public bool Verbose { get; set; } = ParamFallback("LOG_VERBOSE", false); - [Option('a', "disable-api", Default = false, HelpText = "Disables the web api")] - public bool DisableApi { get; set; } + [Option('j', "log-json", HelpText = "Logger outputs json (default: false ) (env: LOG_JSON)")] + public bool LogJson { get; set; } = ParamFallback("LOG_JSON", false); + + [Option('e', "expose-errors", HelpText = "Shows internal errors in the chat (default: false) (env: EXPOSE_ERRORS)")] + public bool ExposeErrors { get; set; } = ParamFallback("EXPOSE_ERRORS", false); - [Option('e', "expose-errors", Default = false, HelpText = "Shows internal errors in the chat")] - public bool ExposeErrors { get; set; } - - [Option("token", Default = null, HelpText = "Set a new bot token")] - public string Token { get; set; } - /************************************ * Database * ************************************/ - [Option("in-memory", Default = false, HelpText = "Uses the in-memory database instead of postgresql")] - public bool InMemory { get; set; } + [Option("in-memory", HelpText = "Uses the in-memory database instead of postgresql (default: false) (env: DB_INMEMORY)")] + public bool InMemory { get; set; } = ParamFallback("DB_INMEMORY", false); // Postresql connection - [Option("database", Default = "geekbot", HelpText = "Select a postgresql database")] - public string DbDatabase { get; set; } + [Option("database", HelpText = "Select a postgresql database (default: geekbot) (env: DB_DATABASE)")] + public string DbDatabase { get; set; } = ParamFallback("DB_DATABASE", "geekbot"); - [Option("db-host", Default = "localhost", HelpText = "Set a postgresql host (e.g. 127.0.0.1)")] - public string DbHost { get; set; } + [Option("db-host", HelpText = "Set a postgresql host (default: localhost) (env: DB_HOST)")] + public string DbHost { get; set; } = ParamFallback("DB_HOST", "localhost"); - [Option("db-port", Default = "5432", HelpText = "Set a postgresql host (e.g. 5432)")] - public string DbPort { get; set; } + [Option("db-port", HelpText = "Set a postgresql host (default: 5432) (env: DB_PORT)")] + public string DbPort { get; set; } = ParamFallback("DB_PORT", "5432"); - [Option("db-user", Default = "geekbot", HelpText = "Set a postgresql user")] - public string DbUser { get; set; } + [Option("db-user", HelpText = "Set a postgresql user (default: geekbot) (env: DB_USER)")] + public string DbUser { get; set; } = ParamFallback("DB_USER", "geekbot"); - [Option("db-password", Default = "", HelpText = "Set a posgresql password")] - public string DbPassword { get; set; } + [Option("db-password", HelpText = "Set a posgresql password (default: empty) (env: DB_PASSWORD)")] + public string DbPassword { get; set; } = ParamFallback("DB_PASSWORD", ""); // Logging - [Option("db-logging", Default = false, HelpText = "Enable database logging")] - public bool DbLogging { get; set; } + [Option("db-logging", HelpText = "Enable database logging (default: false) (env: DB_LOGGING)")] + public bool DbLogging { get; set; } = ParamFallback("DB_LOGGING", false); /************************************ * WebApi * ************************************/ - - [Option("api-host", Default = "localhost", HelpText = "Host on which the WebApi listens")] - public string ApiHost { get; set; } - [Option("api-port", Default = "12995", HelpText = "Port on which the WebApi listens")] - public string ApiPort { get; set; } + [Option('a', "disable-api", HelpText = "Disables the WebApi (default: false) (env: API_DISABLE)")] + public bool DisableApi { get; set; } = ParamFallback("API_DISABLE", false); + + [Option("api-host", HelpText = "Host on which the WebApi listens (default: localhost) (env: API_HOST)")] + public string ApiHost { get; set; } = ParamFallback("API_HOST", "localhost"); + + [Option("api-port", HelpText = "Port on which the WebApi listens (default: 12995) (env: API_PORT)")] + public string ApiPort { get; set; } = ParamFallback("API_PORT", "12995"); + + /************************************ + * Helper Functions * + ************************************/ + + private static string ParamFallback(string key, string defaultValue = null) + { + var envVar = GetEnvironmentVariable(key); + return !string.IsNullOrEmpty(envVar) ? envVar : defaultValue; + } + + private static bool ParamFallback(string key, bool defaultValue) + { + var envVar = GetEnvironmentVariable(key); + if (!string.IsNullOrEmpty(envVar)) + { + return envVar.ToLower() switch + { + "true" => true, + "1" => true, + "false" => false, + "0" => false, + _ => defaultValue + }; + } + + return defaultValue; + } + + private static string GetEnvironmentVariable(string name) + { + return Environment.GetEnvironmentVariable($"GEEKBOT_{name}"); + } } } \ No newline at end of file diff --git a/readme.md b/readme.md index ffc320c..c7f3f33 100644 --- a/readme.md +++ b/readme.md @@ -18,9 +18,11 @@ You can start geekbot with: `dotnet run` On your first run geekbot will ask for your bot token. -You might need to pass some additional configuration (e.g. database credentials), these can be passed as commandline arguments. +You might need to pass some additional configuration (e.g. database credentials), these can be passed as commandline arguments or environment variables. -For a list of commandline arguments use `dotnet run -- -h` +For a list of commandline arguments and environment variables use `dotnet run -- -h` + +All Environment Variables must be prefixed with `GEEKBOT_` ## Contributing From 0898e9b6bd9e6c135e951e0a1a0c89fbb6df00c6 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 14 Jun 2020 17:27:07 +0200 Subject: [PATCH 040/264] Add the timeout in !roll back --- Geekbot.net/Commands/Games/{ => Roll}/Roll.cs | 19 ++++++++++--------- .../Commands/Games/Roll/RollTimeout.cs | 10 ++++++++++ Geekbot.net/Lib/Localization/Translations.yml | 4 ++-- 3 files changed, 22 insertions(+), 11 deletions(-) rename Geekbot.net/Commands/Games/{ => Roll}/Roll.cs (83%) create mode 100644 Geekbot.net/Commands/Games/Roll/RollTimeout.cs diff --git a/Geekbot.net/Commands/Games/Roll.cs b/Geekbot.net/Commands/Games/Roll/Roll.cs similarity index 83% rename from Geekbot.net/Commands/Games/Roll.cs rename to Geekbot.net/Commands/Games/Roll/Roll.cs index 076cf8f..1c89f19 100644 --- a/Geekbot.net/Commands/Games/Roll.cs +++ b/Geekbot.net/Commands/Games/Roll/Roll.cs @@ -10,7 +10,7 @@ using Geekbot.net.Lib.KvInMemoryStore; using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.RandomNumberGenerator; -namespace Geekbot.net.Commands.Games +namespace Geekbot.net.Commands.Games.Roll { public class Roll : ModuleBase { @@ -42,17 +42,18 @@ namespace Geekbot.net.Commands.Games { var kvKey = $"{Context.Guild.Id}:{Context.User.Id}:RollsPrevious"; - var prevRoll = _kvInMemoryStore.Get(kvKey); - if (prevRoll > 0) + var prevRoll = _kvInMemoryStore.Get(kvKey); + + if (prevRoll?.LastGuess == guess && prevRoll?.GuessedOn.AddDays(1) > DateTime.Now) { - if (prevRoll == guess) - { - await ReplyAsync(transContext.GetString("NoPrevGuess", Context.Message.Author.Mention)); - return; - } + await ReplyAsync(transContext.GetString( + "NoPrevGuess", + Context.Message.Author.Mention, + transContext.FormatDateTimeAsRemaining(prevRoll.GuessedOn.AddDays(1)))); + return; } - _kvInMemoryStore.Set(kvKey, guess); + _kvInMemoryStore.Set(kvKey, new RollTimeout { LastGuess = guess, GuessedOn = DateTime.Now }); await ReplyAsync(transContext.GetString("Rolled", Context.Message.Author.Mention, number, guess)); if (guess == number) diff --git a/Geekbot.net/Commands/Games/Roll/RollTimeout.cs b/Geekbot.net/Commands/Games/Roll/RollTimeout.cs new file mode 100644 index 0000000..81a520f --- /dev/null +++ b/Geekbot.net/Commands/Games/Roll/RollTimeout.cs @@ -0,0 +1,10 @@ +using System; + +namespace Geekbot.net.Commands.Games.Roll +{ + public class RollTimeout + { + public int LastGuess { get; set; } + public DateTime GuessedOn { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/Localization/Translations.yml b/Geekbot.net/Lib/Localization/Translations.yml index a19a6f3..3c59977 100644 --- a/Geekbot.net/Lib/Localization/Translations.yml +++ b/Geekbot.net/Lib/Localization/Translations.yml @@ -83,8 +83,8 @@ roll: EN: "{0}, you rolled {1}" CHDE: "{0}, du hesch {1} grollt" NoPrevGuess: - EN: ":red_circle: {0}, you can't guess the same number again" - CHDE: ":red_circle: {0}, du chasch nid nomol es gliche rate" + EN: ":red_circle: {0}, you can't guess the same number again, guess another number or wait {1}" + CHDE: ":red_circle: {0}, du chasch nid nomol es gliche rate, rate öppis anders oder warte {1}" cookies: &cookiesAlias GetCookies: EN: "You got {0} cookies, there are now {1} cookies in you cookie jar" From 12199f4ad475554be327dada2e2369fd428ab9e7 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 18 Jun 2020 19:19:02 +0200 Subject: [PATCH 041/264] Add greetings in 299 languages --- .../Randomness/Greetings/GreetingDto.cs | 10 + .../Randomness/Greetings/GreetingProvider.cs | 1600 +++++++++++++++++ .../Randomness/Greetings/Greetings.cs | 50 + 3 files changed, 1660 insertions(+) create mode 100644 Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs create mode 100644 Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs create mode 100644 Geekbot.net/Commands/Randomness/Greetings/Greetings.cs diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs b/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs new file mode 100644 index 0000000..42792a5 --- /dev/null +++ b/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs @@ -0,0 +1,10 @@ +namespace Geekbot.net.Commands.Randomness.Greetings +{ + public class GreetingDto + { + public string Text { get; set; } + public string Language { get; set; } + public string Dialect { get; set; } = null; + public string Romanization { get; set; } = null; + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs b/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs new file mode 100644 index 0000000..52d8d18 --- /dev/null +++ b/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs @@ -0,0 +1,1600 @@ +using System.Collections.Generic; + +namespace Geekbot.net.Commands.Randomness.Greetings +{ + public class GreetingProvider + { + public static readonly List Greetings = new List + { + new GreetingDto() + { + Text = "Бзиа збаша", + Language = "Abkhaz", + Romanization = "Bzia zbaşa" + }, + new GreetingDto() + { + Text = "Фэсапщы", + Language = "Adyghe", + Romanization = "Fèsapŝy" + }, + new GreetingDto() + { + Text = "Haai", + Language = "Afrikaans" + }, + new GreetingDto() + { + Text = "Kamusta", + Language = "Aklan" + }, + new GreetingDto() + { + Text = "Fâla", + Language = "Albanian" + }, + new GreetingDto() + { + Text = "Ç'kemi", + Language = "Albanian" + }, + new GreetingDto() + { + Text = "Aang", + Language = "Aleut" + }, + new GreetingDto() + { + Text = "Hallo", + Language = "Alsatian" + }, + new GreetingDto() + { + Text = "Эзендер", + Language = "Altay", + Romanization = "Ezender" + }, + new GreetingDto() + { + Text = "ሰላም።", + Language = "Amharic", + Romanization = "sälam" + }, + new GreetingDto() + { + Text = "السلام عليكم", + Language = "Arabic", + Romanization = "as-salām 'alaykum" + }, + new GreetingDto() + { + Text = "Ola", + Language = "Aragonese" + }, + new GreetingDto() + { + Text = "Shl'am lak", + Language = "Aramaic" + }, + new GreetingDto() + { + Text = "Héébee", + Language = "Arapaho" + }, + new GreetingDto() + { + Text = "Բարեւ", + Language = "Armenian", + Romanization = "Parev" + }, + new GreetingDto() + { + Text = "Bunâ dzuâ", + Language = "Aromanian" + }, + new GreetingDto() + { + Text = "Werte", + Language = "Arrernte" + }, + new GreetingDto() + { + Text = "নমস্কাৰ", + Language = "Assamese", + Romanization = "নমস্কাৰ" + }, + new GreetingDto() + { + Text = "Hola", + Language = "Asturian" + }, + new GreetingDto() + { + Text = "Kwei", + Language = "Atikamekw" + }, + new GreetingDto() + { + Text = "Laphi!", + Language = "Aymara" + }, + new GreetingDto() + { + Text = "Salam", + Language = "Azerbaijani" + }, + new GreetingDto() + { + Text = "Swastyastu", + Language = "Balinese" + }, + new GreetingDto() + { + Text = "I ni ce", + Language = "Bambara" + }, + new GreetingDto() + { + Text = "Haku'", + Language = "Barbareño" + }, + new GreetingDto() + { + Text = "сәләм", + Language = "Bashkir", + Romanization = "sәlәm" + }, + new GreetingDto() + { + Text = "Kaixo", + Language = "Basque" + }, + new GreetingDto() + { + Text = "Horas", + Language = "Batak" + }, + new GreetingDto() + { + Text = "მარშიხ ვალ", + Language = "Batsbi", + Romanization = "Maršix val" + }, + new GreetingDto() + { + Text = "Seavus", + Language = "Bavarian" + }, + new GreetingDto() + { + Text = "Вітаю", + Language = "Belarusian", + Romanization = "Vіtaju" + }, + new GreetingDto() + { + Text = "Shani", + Language = "Bemba" + }, + new GreetingDto() + { + Text = "নমস্কার", + Language = "Bengali", + Romanization = "Nômôskar", + Dialect = "Hindus" + }, + new GreetingDto() + { + Text = "আসসালামু আলাইকুম", + Language = "Bengali", + Romanization = "Asôlamu alaikum", + Dialect = "Muslims" + }, + new GreetingDto() + { + Text = "प्रणाम", + Language = "Bhojpuri", + Romanization = "prannam" + }, + new GreetingDto() + { + Text = "Hello", + Language = "Bikol" + }, + new GreetingDto() + { + Text = "Halo", + Language = "Bislama" + }, + new GreetingDto() + { + Text = "Dobar dan", + Language = "Bosnian" + }, + new GreetingDto() + { + Text = "Salud", + Language = "Breton" + }, + new GreetingDto() + { + Text = "Здравейте", + Language = "Bulgarian" + }, + new GreetingDto() + { + Text = "မဂႆလာပၝ", + Language = "Burmese", + Romanization = "min-ga-la-ba" + }, + new GreetingDto() + { + Text = "Olá", + Language = "Cape Verdean Creole" + }, + new GreetingDto() + { + Text = "Hola", + Language = "Catalan" + }, + new GreetingDto() + { + Text = "Hello", + Language = "Cebuano" + }, + new GreetingDto() + { + Text = "Kopisanangan", + Language = "Central Dusun" + }, + new GreetingDto() + { + Text = "Que tal?", + Language = "Chabacano de Zamboanga" + }, + new GreetingDto() + { + Text = "Ola", + Language = "Chabacano de Cavite" + }, + new GreetingDto() + { + Text = "Håfa ådai", + Language = "Chamorro", + Dialect = "Guam" + }, + new GreetingDto() + { + Text = "Hafa Adai", + Language = "Chamorro", + Dialect = "North Marianas" + }, + new GreetingDto() + { + Text = "Салам", + Language = "Chechen", + Romanization = "Salam" + }, + new GreetingDto() + { + Text = "ᎣᏏᏲ", + Language = "Cherokee", + Romanization = "Osiyo" + }, + new GreetingDto() + { + Text = "Moni", + Language = "Chichewa" + }, + new GreetingDto() + { + Text = "你好", + Language = "Chinese", + Romanization = "nǐ hǎo", + Dialect = "Mandarin" + }, + new GreetingDto() + { + Text = "ʔédlánet’é", + Language = "Chipewyan" + }, + new GreetingDto() + { + Text = "Halito", + Language = "Choctaw" + }, + new GreetingDto() + { + Text = "Ran annim", + Language = "Chuukese" + }, + new GreetingDto() + { + Text = "Салам!", + Language = "Chuvash", + Romanization = "Salam!" + }, + new GreetingDto() + { + Text = "Guuten takh!", + Language = "Cimbrian" + }, + new GreetingDto() + { + Text = "Kopivosian", + Language = "Coastal Kadazan" + }, + new GreetingDto() + { + Text = "Marʉ́awe", + Language = "Comanche" + }, + new GreetingDto() + { + Text = "Dydh da", + Language = "Cornish" + }, + new GreetingDto() + { + Text = "Salute", + Language = "Corsican" + }, + new GreetingDto() + { + Text = "ᑕᓂᓯ", + Language = "Cree", + Romanization = "Tanisi" + }, + new GreetingDto() + { + Text = "Bok", + Language = "Croatian" + }, + new GreetingDto() + { + Text = "Sho'daache", + Language = "Crow" + }, + new GreetingDto() + { + Text = "Míyaxwe", + Language = "Cupeño" + }, + new GreetingDto() + { + Text = "Hello", + Language = "Cuyonon" + }, + new GreetingDto() + { + Text = "Ahoj", + Language = "Czech" + }, + new GreetingDto() + { + Text = "Hej", + Language = "Danish" + }, + new GreetingDto() + { + Text = "ااسال م عليكم", + Language = "Dari", + Romanization = "As-salâmo 'alaykom" + }, + new GreetingDto() + { + Text = "Misawa", + Language = "Dholuo" + }, + new GreetingDto() + { + Text = "Goededag", + Language = "Dutch" + }, + new GreetingDto() + { + Text = "སྐུ་གཟུགས་བཟང་པོ་ལགས།", + Language = "Dzongkha", + Romanization = "Kuzu zangpo la" + }, + new GreetingDto() + { + Text = "Mọkọm", + Language = "Efik" + }, + new GreetingDto() + { + Text = "Häj ą̊ dig!", + Language = "Elfdalian" + }, + new GreetingDto() + { + Text = "Hello", + Language = "English" + }, + new GreetingDto() + { + Text = "Tere", + Language = "Estonian" + }, + new GreetingDto() + { + Text = "Ola!", + Language = "Extremaduran" + }, + new GreetingDto() + { + Text = "Hallo", + Language = "Faroese" + }, + new GreetingDto() + { + Text = "Bula", + Language = "Fijian" + }, + new GreetingDto() + { + Text = "Hyvää päivää", + Language = "Finnish" + }, + new GreetingDto() + { + Text = "Bonjour", + Language = "French" + }, + new GreetingDto() + { + Text = "Guundach", + Language = "Frisian", + Dialect = "North Frisian" + }, + new GreetingDto() + { + Text = "Gouden Dai", + Language = "Frisian", + Dialect = "Saterland" + }, + new GreetingDto() + { + Text = "Goeie", + Language = "Frisian", + Dialect = "West Frisian" + }, + new GreetingDto() + { + Text = "Mandi", + Language = "Friulian" + }, + new GreetingDto() + { + Text = "Ola", + Language = "Galician" + }, + new GreetingDto() + { + Text = "सिवासौँळी", + Language = "Garhwali", + Romanization = "sivāsauṁḻī" + }, + new GreetingDto() + { + Text = "Buiti binafi", + Language = "Garifuna" + }, + new GreetingDto() + { + Text = "გამარჯობა", + Language = "Georgian", + Romanization = "gamarjoba" + }, + new GreetingDto() + { + Text = "Guten Tag", + Language = "German" + }, + new GreetingDto() + { + Text = "Χαῖρε", + Language = "Greek", + Romanization = "Khaĩre", + Dialect = "Ancient" + }, + new GreetingDto() + { + Text = "Γειά", + Language = "Greek", + Romanization = "Geiá", + Dialect = "Ancient" + }, + new GreetingDto() + { + Text = "something", + Language = "something" + }, + new GreetingDto() + { + Text = "Aluu", + Language = "Greenlandic" + }, + new GreetingDto() + { + Text = "નમસ્તે", + Language = "Gujarati", + Romanization = "namaste" + }, + new GreetingDto() + { + Text = "Bonjou", + Language = "Haitian Creole" + }, + new GreetingDto() + { + Text = "Sannu", + Language = "Hausa" + }, + new GreetingDto() + { + Text = "Aloha", + Language = "Hawaiian" + }, + new GreetingDto() + { + Text = "שלום", + Language = "Hebrew", + Romanization = "Shalom" + }, + new GreetingDto() + { + Text = "something", + Language = "something" + }, + new GreetingDto() + { + Text = "Tjike", + Language = "Herero" + }, + new GreetingDto() + { + Text = "Mono", + Language = "Himba" + }, + new GreetingDto() + { + Text = "नमस्ते", + Language = "Hindi", + Romanization = "namaste" + }, + new GreetingDto() + { + Text = "Nyob zoo", + Language = "Hmong", + Dialect = "White" + }, + new GreetingDto() + { + Text = "Jó napot kívánok", + Language = "Hungarian" + }, + new GreetingDto() + { + Text = "Góðan dag", + Language = "Icelandic" + }, + new GreetingDto() + { + Text = "Ndeewo", + Language = "Igbo" + }, + new GreetingDto() + { + Text = "Kablaaw", + Language = "Iloko" + }, + new GreetingDto() + { + Text = "Tiervâ", + Language = "Inari Saami" + }, + new GreetingDto() + { + Text = "Hi", + Language = "Indonesian" + }, + new GreetingDto() + { + Text = "ᐊᐃ", + Language = "Inuktitut", + Romanization = "Ai" + }, + new GreetingDto() + { + Text = "Haluu", + Language = "Iñupiaq" + }, + new GreetingDto() + { + Text = "Dia dhuit", + Language = "Irish" + }, + new GreetingDto() + { + Text = "Ciao", + Language = "Italian" + }, + new GreetingDto() + { + Text = "Míyaxwen", + Language = "Ivilyuat" + }, + new GreetingDto() + { + Text = "Ello", + Language = "Jamaican" + }, + new GreetingDto() + { + Text = "今日は", + Language = "Japanese", + Romanization = "konnichiwa" + }, + new GreetingDto() + { + Text = "ꦲꦭꦺꦴ", + Language = "Javanese", + Romanization = "Halo" + }, + new GreetingDto() + { + Text = "Puiznu", + Language = "Jenesch" + }, + new GreetingDto() + { + Text = "Salut", + Language = "Jèrriais" + }, + new GreetingDto() + { + Text = "Godaw", + Language = "Jutish" + }, + new GreetingDto() + { + Text = "Мендвт", + Language = "Kalmyk" + }, + new GreetingDto() + { + Text = "Tọi", + Language = "Kam" + }, + new GreetingDto() + { + Text = "ನಮಸ್ತೆ", + Language = "Kannada", + Romanization = "namaste" + }, + new GreetingDto() + { + Text = "Xsaqär", + Language = "Kaqchikel" + }, + new GreetingDto() + { + Text = "Ayukîi", + Language = "Karuk" + }, + new GreetingDto() + { + Text = "Witéj", + Language = "Kashubian" + }, + new GreetingDto() + { + Text = "असलामु अलैकुम", + Language = "Kashmiri", + Romanization = "asalāmu alaikuma" + }, + new GreetingDto() + { + Text = "Hagare'enaam", + Language = "Kawaiisu" + }, + new GreetingDto() + { + Text = "Сәлем", + Language = "Kazakh", + Romanization = "Sälem" + }, + new GreetingDto() + { + Text = "ជំរាបសួរ", + Language = "Khmer", + Romanization = "chôm rab suôr" + }, + new GreetingDto() + { + Text = "Halau", + Language = "Khoekhoe" + }, + new GreetingDto() + { + Text = "wĩmwega", + Language = "Kikuyu" + }, + new GreetingDto() + { + Text = "Muraho", + Language = "Kinyarwanda" + }, + new GreetingDto() + { + Text = "Ko na mauri", + Language = "Kiribati" + }, + new GreetingDto() + { + Text = "안녕하십니까", + Language = "Korean", + Romanization = "annyeong-hasimnikka" + }, + new GreetingDto() + { + Text = "Haawka", + Language = "Kumeyaay" + }, + new GreetingDto() + { + Text = "!kao", + Language = "Kung San" + }, + new GreetingDto() + { + Text = "Rojbash", + Language = "Kurdish", + Dialect = "Kurmanji" + }, + new GreetingDto() + { + Text = "Sillaw", + Language = "Kurdish", + Dialect = "Sorani" + }, + new GreetingDto() + { + Text = "Салам!", + Language = "Kyrgyz", + Romanization = "Salam!" + }, + new GreetingDto() + { + Text = "בוינוס דייאס", + Language = "Ladino", + Romanization = "Buenos diyas" + }, + new GreetingDto() + { + Text = "Hau", + Language = "Lakota Sioux" + }, + new GreetingDto() + { + Text = "ສະບາຍດີ", + Language = "Lao", + Romanization = "sába̖ai-di̖i" + }, + new GreetingDto() + { + Text = "Ave", + Language = "Latin" + }, + new GreetingDto() + { + Text = "Sveiki", + Language = "Latvian" + }, + new GreetingDto() + { + Text = "გეგაჯგინას", + Language = "Laz", + Romanization = "Gegacginas" + }, + new GreetingDto() + { + Text = "Салам алейкум", + Language = "Lezgi", + Romanization = "Salam alejkum" + }, + new GreetingDto() + { + Text = "Hallo", + Language = "Limburgish" + }, + new GreetingDto() + { + Text = "Mbote", + Language = "Lingala" + }, + new GreetingDto() + { + Text = "Labas", + Language = "Lithuanian" + }, + new GreetingDto() + { + Text = "Moin", + Language = "Low Saxon" + }, + new GreetingDto() + { + Text = "Lumela", + Language = "Lozi" + }, + new GreetingDto() + { + Text = "Gyebale ko", + Language = "Luganda" + }, + new GreetingDto() + { + Text = "Buoris", + Language = "Lule Sámi" + }, + new GreetingDto() + { + Text = "Mííyu", + Language = "Luiseño" + }, + new GreetingDto() + { + Text = "Moien", + Language = "Luxembourgish" + }, + new GreetingDto() + { + Text = "Здраво", + Language = "Macedonian", + Romanization = "Zdravo" + }, + new GreetingDto() + { + Text = "परनाम", + Language = "Magahi", + Romanization = "Pernaam" + }, + new GreetingDto() + { + Text = "प्रनाम", + Language = "Maithili", + Romanization = "Pranaam" + }, + new GreetingDto() + { + Text = "Manao ahoana", + Language = "Malagasy" + }, + new GreetingDto() + { + Text = "Selamat pagi", + Language = "Malay" + }, + new GreetingDto() + { + Text = "നമസ്തേ", + Language = "Malayalam", + Romanization = "namastē" + }, + new GreetingDto() + { + Text = "Jeeka, ma tzuula", + Language = "Mam" + }, + new GreetingDto() + { + Text = "Moghrey mie", + Language = "Gaelic", + Dialect = "Manx" + }, + new GreetingDto() + { + Text = "Assalaamu Alaikum", + Language = "Maldivian" + }, + new GreetingDto() + { + Text = "Ħello", + Language = "Maltese" + }, + new GreetingDto() + { + Text = "Kia ora", + Language = "Māori" + }, + new GreetingDto() + { + Text = "Mari mari", + Language = "Mapuche" + }, + new GreetingDto() + { + Text = "नमस्कार", + Language = "Marathi", + Romanization = "namaskāra" + }, + new GreetingDto() + { + Text = "Io̧kwe", + Language = "Marshallese" + }, + new GreetingDto() + { + Text = "Bonzur", + Language = "Mauritian Creole" + }, + new GreetingDto() + { + Text = "Gwe’", + Language = "Míkmaq" + }, + new GreetingDto() + { + Text = "ဟာဲ", + Language = "Mon", + Romanization = "hāai" + }, + new GreetingDto() + { + Text = "Ciau", + Language = "Monégasque" + }, + new GreetingDto() + { + Text = "Сайн уу", + Language = "Mongolian", + Romanization = "Sain uu" + }, + new GreetingDto() + { + Text = "Manahúú", + Language = "Mono" + }, + new GreetingDto() + { + Text = "Ne y windiga", + Language = "Mossi" + }, + new GreetingDto() + { + Text = "Niltze", + Language = "Nahuatl" + }, + new GreetingDto() + { + Text = "Ekamowir omo", + Language = "Nauruan" + }, + new GreetingDto() + { + Text = "Yá'át'ééh", + Language = "Navajo" + }, + new GreetingDto() + { + Text = "ज्वजलपा", + Language = "Newari", + Romanization = "jvajalapā" + }, + new GreetingDto() + { + Text = "Oraire ota?", + Language = "Nkore" + }, + new GreetingDto() + { + Text = "Salibonani", + Language = "Ndebele" + }, + new GreetingDto() + { + Text = "Lotjhani", + Language = "Southern Ndebele" + }, + new GreetingDto() + { + Text = "नमस्ते", + Language = "Nepali", + Romanization = "namaste" + }, + new GreetingDto() + { + Text = "Fakaalofa atu", + Language = "Niuean" + }, + new GreetingDto() + { + Text = "Салам!", + Language = "Nogai" + }, + new GreetingDto() + { + Text = "Bures", + Language = "Northern Sámi" + }, + new GreetingDto() + { + Text = "Dumêlang", + Language = "Northern Sotho" + }, + new GreetingDto() + { + Text = "Goddag", + Language = "Norwegian" + }, + new GreetingDto() + { + Text = "Hatʸu", + Language = "Northern Chumash" + }, + new GreetingDto() + { + Text = "Bonjorn", + Language = "Occitan" + }, + new GreetingDto() + { + Text = "Aniin", + Language = "Ojibwe" + }, + new GreetingDto() + { + Text = "今日拝なびら", + Language = "Okinawan", + Romanization = "chuu wuganabira" + }, + new GreetingDto() + { + Text = "Wes hāl", + Language = "Old English" + }, + new GreetingDto() + { + Text = "Ƿes hāl", + Language = "Old Prussian" + }, + new GreetingDto() + { + Text = "Ahó", + Language = "Omaha" + }, + new GreetingDto() + { + Text = "ନମସ୍କାର", + Language = "Oriya", + Romanization = "Namascāra" + }, + new GreetingDto() + { + Text = "Alii", + Language = "Palauan" + }, + new GreetingDto() + { + Text = "Bon dia", + Language = "Papiamento" + }, + new GreetingDto() + { + Text = "ښې چارې", + Language = "Pashto", + Romanization = "khe chare" + }, + new GreetingDto() + { + Text = "Gude Daag", + Language = "Pennsylvania Deitsch" + }, + new GreetingDto() + { + Text = "درود", + Language = "Persian", + Romanization = "dorood", + Dialect = "Farsi" + }, + new GreetingDto() + { + Text = "Bojour", + Language = "Picard" + }, + new GreetingDto() + { + Text = "Wai", + Language = "Pitjantjatjara" + }, + new GreetingDto() + { + Text = "Cześć", + Language = "Polish" + }, + new GreetingDto() + { + Text = "Olá", + Language = "Portuguese", + Dialect = "Protugal" + }, + new GreetingDto() + { + Text = "Oi", + Language = "Portuguese", + Dialect = "Brazilian" + }, + new GreetingDto() + { + Text = "ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ।", + Language = "Punjabi", + Romanization = "sat srī akāl" + }, + new GreetingDto() + { + Text = "Rimaykullayki", + Language = "Quechua" + }, + new GreetingDto() + { + Text = "'Iorana", + Language = "Rapa Nui" + }, + new GreetingDto() + { + Text = "Bonzour", + Language = "Réunion Creole" + }, + new GreetingDto() + { + Text = "Sastipe", + Language = "Romani" + }, + new GreetingDto() + { + Text = "Salut", + Language = "Romanian" + }, + new GreetingDto() + { + Text = "Ciao", + Language = "Romansh" + }, + new GreetingDto() + { + Text = "Привет", + Language = "Russian", + Romanization = "Privet" + }, + new GreetingDto() + { + Text = "Слава Исусу Христу", + Language = "Rusyn", + Dialect = "Slava Ysusu Chrystu" + }, + new GreetingDto() + { + Text = "бирибиэт", + Language = "Sakha", + Romanization = "biribiet" + }, + new GreetingDto() + { + Text = "Malō", + Language = "Samoan" + }, + new GreetingDto() + { + Text = "Bara mo", + Language = "Sango" + }, + new GreetingDto() + { + Text = "नमस्ते", + Language = "Sanskrit", + Romanization = "namaste" + }, + new GreetingDto() + { + Text = "Saludi", + Language = "Sardinian", + Dialect = "Campidanese" + }, + new GreetingDto() + { + Text = "Bone die", + Language = "Sardinian", + Dialect = "Logudorese" + }, + new GreetingDto() + { + Text = "Hullo", + Language = "Scots" + }, + new GreetingDto() + { + Text = "Halò", + Language = "Gaelic", + Dialect = "Scottish" + }, + new GreetingDto() + { + Text = "Здраво", + Language = "Serbian", + Dialect = "Zdravo" + }, + new GreetingDto() + { + Text = "Lumela", + Language = "Sesotho" + }, + new GreetingDto() + { + Text = "Mhoro", + Language = "Shona" + }, + new GreetingDto() + { + Text = "Ciau", + Language = "Sicilian" + }, + new GreetingDto() + { + Text = "سَلامُ", + Language = "Sindhi", + Romanization = "Salāmu" + }, + new GreetingDto() + { + Text = "ආයුඛෝවන්", + Language = "Sinhala", + Romanization = "āyubūvan" + }, + new GreetingDto() + { + Text = "Dobry den", + Language = "Slovak" + }, + new GreetingDto() + { + Text = "Pozdravljeni", + Language = "Slovenian" + }, + new GreetingDto() + { + Text = "Simi", + Language = "Solresol" + }, + new GreetingDto() + { + Text = "Salaam alaykum", + Language = "Somali" + }, + new GreetingDto() + { + Text = "Dobry źeń", + Language = "Sorbian", + Dialect = "Lower Sorbian" + }, + new GreetingDto() + { + Text = "Dobry dźeń", + Language = "Sorbian", + Dialect = "Upper Sorbian" + }, + new GreetingDto() + { + Text = "Buaregh", + Language = "Southern Sámi" + }, + new GreetingDto() + { + Text = "¡Hola!", + Language = "Spanish" + }, + new GreetingDto() + { + Text = "Hoj", + Language = "Stellingwarfs" + }, + new GreetingDto() + { + Text = "Sampurasun", + Language = "Sundanese" + }, + new GreetingDto() + { + Text = "Habari", + Language = "Swahili" + }, + new GreetingDto() + { + Text = "Sawubona", + Language = "Swazi" + }, + new GreetingDto() + { + Text = "God dag", + Language = "Swedish" + }, + new GreetingDto() + { + Text = "Grüezi", + Language = "Swiss German" + }, + new GreetingDto() + { + Text = "Салам", + Language = "Tabassaran", + Romanization = "Salam" + }, + new GreetingDto() + { + Text = "Musta?", + Language = "Tagalog" + }, + new GreetingDto() + { + Text = "'Ia ora na", + Language = "Tahitian" + }, + new GreetingDto() + { + Text = "Ассалому алейкум", + Language = "Tajik", + Romanization = "Assalomu alejkym" + }, + new GreetingDto() + { + Text = "வணக்கம்", + Language = "Tamil", + Romanization = "vaṇakkam" + }, + new GreetingDto() + { + Text = "Isänme", + Language = "Tatar" + }, + new GreetingDto() + { + Text = "నమస్కారం", + Language = "Telugu", + Romanization = "namaskārām" + }, + new GreetingDto() + { + Text = "Elo", + Language = "Tetum" + }, + new GreetingDto() + { + Text = "Miga", + Language = "Teribe" + }, + new GreetingDto() + { + Text = "สวัสดี", + Language = "Thai", + Romanization = "sà-wàt-dee" + }, + new GreetingDto() + { + Text = "བཀྲ་ཤིས་བདེ་ལེགས།", + Language = "Tibetan", + Romanization = "tashi delek" + }, + new GreetingDto() + { + Text = "ሰላም", + Language = "Tigrinya", + Romanization = "selam" + }, + new GreetingDto() + { + Text = "Tālofa", + Language = "Tokelauan" + }, + new GreetingDto() + { + Text = "Gude", + Language = "Tok Pisin" + }, + new GreetingDto() + { + Text = "Mālō e lelei", + Language = "Tongan" + }, + new GreetingDto() + { + Text = "Miiyiha", + Language = "Tongva", + Dialect = "Gabrielino" + }, + new GreetingDto() + { + Text = "Xewani", + Language = "Tsonga" + }, + new GreetingDto() + { + Text = "K'uxi", + Language = "Tsotsil" + }, + new GreetingDto() + { + Text = "Dumela", + Language = "Tswana" + }, + new GreetingDto() + { + Text = "АсаламугIалейкум!", + Language = "Tsez", + Romanization = "AsalamugIalejkum!" + }, + new GreetingDto() + { + Text = "Monile", + Language = "Tumbuka" + }, + new GreetingDto() + { + Text = "Merhaba", + Language = "Turkish" + }, + new GreetingDto() + { + Text = "Salam", + Language = "Turkmen" + }, + new GreetingDto() + { + Text = "Вітаю", + Language = "Ukrainian" + }, + new GreetingDto() + { + Text = "Сородэ", + Language = "Ulch", + Romanization = "Sorodè" + }, + new GreetingDto() + { + Text = "السلام علیکم", + Language = "Urdu", + Romanization = "āssālam 'alaykum" + }, + new GreetingDto() + { + Text = "ئەسسالامۇ ئەلەيكۇم", + Language = "Uyghur", + Romanization = "Ässalamu äläykum" + }, + new GreetingDto() + { + Text = "Assalomu Alaykum", + Language = "Uzbek" + }, + new GreetingDto() + { + Text = "I nhlikanhi", + Language = "Venda" + }, + new GreetingDto() + { + Text = "Ciao", + Language = "Venetian" + }, + new GreetingDto() + { + Text = "Tervhen", + Language = "Veps" + }, + new GreetingDto() + { + Text = "Chào anh", + Language = "Vietnamese" + }, + new GreetingDto() + { + Text = "Tereq", + Language = "Võro" + }, + new GreetingDto() + { + Text = "Bondjoû", + Language = "Walloon" + }, + new GreetingDto() + { + Text = "Ngurrju mayinpa", + Language = "Warlpiri" + }, + new GreetingDto() + { + Text = "Helô", + Language = "Welsh" + }, + new GreetingDto() + { + Text = "Hej", + Language = "Westrobothnian" + }, + new GreetingDto() + { + Text = "Na nga def", + Language = "Wolof" + }, + new GreetingDto() + { + Text = "Molo", + Language = "Xhosa" + }, + new GreetingDto() + { + Text = "Mogethin", + Language = "Yapese" + }, + new GreetingDto() + { + Text = "אַ גוטן טאָג", + Language = "Yiddish", + Romanization = "A gutn tog" + }, + new GreetingDto() + { + Text = "Ẹ n lẹ", + Language = "Yoruba" + }, + new GreetingDto() + { + Text = "Ba'ax ka wa'alik?", + Language = "Yucatec Maya" + }, + new GreetingDto() + { + Text = "Selam", + Language = "Zazaki" + }, + new GreetingDto() + { + Text = "Sawubona", + Language = "Zulu" + }, + new GreetingDto() + { + Text = "Saluton", + Language = "Esperanto" + }, + new GreetingDto() + { + Text = "Bon die!", + Language = "Interlingua" + }, + new GreetingDto() + { + Text = "nuqneH", + Language = "Klingon" + }, + new GreetingDto() + { + Text = "Aiya", + Language = "Quenya" + }, + new GreetingDto() + { + Text = "Glidö", + Language = "Volapük" + }, + new GreetingDto() + { + Text = "Saluto", + Language = "Ido" + } + }; + + public static readonly int GreetingCount = Greetings.Count; + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs new file mode 100644 index 0000000..83cdd63 --- /dev/null +++ b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs @@ -0,0 +1,50 @@ +using System; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Geekbot.net.Lib.ErrorHandling; +using Geekbot.net.Lib.Extensions; + +namespace Geekbot.net.Commands.Randomness.Greetings +{ + public class Greetings : ModuleBase + { + private readonly IErrorHandler _errorHandler; + + public Greetings(IErrorHandler errorHandler) + { + _errorHandler = errorHandler; + } + + [Command("hello", RunMode = RunMode.Async)] + [Alias("greeting")] + [Summary("Say hello to the bot and get a reply in a random language")] + public async Task GetGreeting() + { + try + { + var greeting = GreetingProvider.Greetings[new Random().Next(GreetingProvider.GreetingCount - 1)]; + + var eb = new EmbedBuilder(); + eb.Title = greeting.Text; + eb.AddInlineField("Language", greeting.Language); + + if (greeting.Dialect != null) + { + eb.AddInlineField("Dialect", greeting.Dialect); + } + + if (greeting.Romanization != null) + { + eb.AddInlineField("Romanization", greeting.Romanization); + } + + await ReplyAsync(string.Empty, false, eb.Build()); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } + } +} \ No newline at end of file From f7908c2a0c2a48ba2d0c73f654cf01a5884155a1 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 00:10:43 +0200 Subject: [PATCH 042/264] - Remove accidental leftover from the GreetingProvider - Add 2 additional aliases for !hello - Change Romanization to Roman in the !hello embed --- .../Commands/Randomness/Greetings/GreetingProvider.cs | 5 ----- Geekbot.net/Commands/Randomness/Greetings/Greetings.cs | 4 ++-- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs b/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs index 52d8d18..a15f32e 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs +++ b/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs @@ -507,11 +507,6 @@ namespace Geekbot.net.Commands.Randomness.Greetings Dialect = "Ancient" }, new GreetingDto() - { - Text = "something", - Language = "something" - }, - new GreetingDto() { Text = "Aluu", Language = "Greenlandic" diff --git a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs index 83cdd63..334b894 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs +++ b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs @@ -17,7 +17,7 @@ namespace Geekbot.net.Commands.Randomness.Greetings } [Command("hello", RunMode = RunMode.Async)] - [Alias("greeting")] + [Alias("greeting", "hi", "hallo")] [Summary("Say hello to the bot and get a reply in a random language")] public async Task GetGreeting() { @@ -36,7 +36,7 @@ namespace Geekbot.net.Commands.Randomness.Greetings if (greeting.Romanization != null) { - eb.AddInlineField("Romanization", greeting.Romanization); + eb.AddInlineField("Roman", greeting.Romanization); } await ReplyAsync(string.Empty, false, eb.Build()); From 83dc2c8e49350a3bcb1e3cc2cd8ca3ec1a81338b Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 03:34:37 +0200 Subject: [PATCH 043/264] Attempt to improve code quality with a fearless refactor - Completely refactor Program.cs - Split Handlers into separate files - Split up the command handler into multiple functions --- Geekbot.net/Handlers.cs | 280 ------------------ Geekbot.net/Handlers/CommandHandler.cs | 117 ++++++++ Geekbot.net/Handlers/MessageDeletedHandler.cs | 55 ++++ Geekbot.net/Handlers/ReactionHandler.cs | 33 +++ Geekbot.net/Handlers/StatsHandler.cs | 62 ++++ Geekbot.net/Handlers/UserHandler.cs | 96 ++++++ .../Lib/Logger/SimpleConextConverter.cs | 3 +- Geekbot.net/Program.cs | 223 +++++++------- 8 files changed, 488 insertions(+), 381 deletions(-) delete mode 100644 Geekbot.net/Handlers.cs create mode 100644 Geekbot.net/Handlers/CommandHandler.cs create mode 100644 Geekbot.net/Handlers/MessageDeletedHandler.cs create mode 100644 Geekbot.net/Handlers/ReactionHandler.cs create mode 100644 Geekbot.net/Handlers/StatsHandler.cs create mode 100644 Geekbot.net/Handlers/UserHandler.cs diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs deleted file mode 100644 index 6f98041..0000000 --- a/Geekbot.net/Handlers.cs +++ /dev/null @@ -1,280 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Discord; -using Discord.Commands; -using Discord.Rest; -using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Logger; -using Geekbot.net.Lib.ReactionListener; -using Geekbot.net.Lib.UserRepository; -using Microsoft.EntityFrameworkCore; - -namespace Geekbot.net -{ - public class Handlers - { - private readonly DatabaseContext _database; - private readonly IDiscordClient _client; - private readonly IGeekbotLogger _logger; - private readonly IServiceProvider _servicesProvider; - private readonly CommandService _commands; - private readonly IUserRepository _userRepository; - private readonly IReactionListener _reactionListener; - private readonly DatabaseContext _messageCounterDatabaseContext; - private readonly RestApplication _applicationInfo; - private readonly List _ignoredServers; - - public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, - IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, - IReactionListener reactionListener, RestApplication applicationInfo) - { - _database = databaseInitializer.Initialize(); - _messageCounterDatabaseContext = databaseInitializer.Initialize(); - _client = client; - _logger = logger; - _servicesProvider = servicesProvider; - _commands = commands; - _userRepository = userRepository; - _reactionListener = reactionListener; - _applicationInfo = applicationInfo; - // ToDo: create a clean solution for this... - _ignoredServers = new List() - { - 228623803201224704, // SwitzerLAN - 169844523181015040, // EEvent - 248531441548263425, // MYI - 110373943822540800 // Discord Bots - }; - } - - // - // Incoming Messages - // - - public Task RunCommand(SocketMessage messageParam) - { - try - { - if (!(messageParam is SocketUserMessage message)) return Task.CompletedTask; - if (message.Author.IsBot) return Task.CompletedTask; - var argPos = 0; - - var guildId = ((SocketGuildChannel) message.Channel).Guild.Id; - // Some guilds only wanted very specific functionally without any of the commands, a quick hack that solves that short term... - // ToDo: cleanup - if (_ignoredServers.Contains(guildId)) - { - if (message.Author.Id != _applicationInfo.Owner.Id) - { - return Task.CompletedTask; - } - } - - var lowCaseMsg = message.ToString().ToLower(); - if (lowCaseMsg.StartsWith("hui")) - { - var hasPing = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong()))?.Hui ?? false; - if (hasPing) - { - message.Channel.SendMessageAsync("hui!!!"); - return Task.CompletedTask; - } - } - - if (lowCaseMsg.StartsWith("ping ") || lowCaseMsg.Equals("ping")) - { - var hasPing = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong()))?.Ping ?? false; - if (hasPing) - { - message.Channel.SendMessageAsync("pong"); - return Task.CompletedTask; - } - } - - if (!(message.HasCharPrefix('!', ref argPos) || - message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask; - var context = new CommandContext(_client, message); - _commands.ExecuteAsync(context, argPos, _servicesProvider); - _logger.Information(LogSource.Command, - context.Message.Content.Split(" ")[0].Replace("!", ""), - SimpleConextConverter.ConvertContext(context)); - return Task.CompletedTask; - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Failed to Process Message", e); - return Task.CompletedTask; - } - } - - public async Task UpdateStats(SocketMessage message) - { - try - { - if (message == null) return; - if (message.Channel.Name.StartsWith('@')) - { - _logger.Information(LogSource.Message, $"[DM-Channel] {message.Content}", SimpleConextConverter.ConvertSocketMessage(message, true)); - return; - } - - var channel = (SocketGuildChannel) message.Channel; - - var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlRawAsync( - "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", - channel.Guild.Id.AsLong(), - message.Author.Id.AsLong() - ); - - if (rowId == 0) - { - _messageCounterDatabaseContext.Messages.Add(new MessagesModel - { - UserId = message.Author.Id.AsLong(), - GuildId = channel.Guild.Id.AsLong(), - MessageCount = 1 - }); - _messageCounterDatabaseContext.SaveChanges(); - } - - if (message.Author.IsBot) return; - _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); - } - catch (Exception e) - { - _logger.Error(LogSource.Message, "Could not process message stats", e); - } - } - - // - // User Stuff - // - - public async Task UserJoined(SocketGuildUser user) - { - try - { - var userRepoUpdate = _userRepository.Update(user); - _logger.Information(LogSource.Geekbot, $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})"); - - if (!user.IsBot) - { - var guildSettings = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId == user.Guild.Id.AsLong()); - var message = guildSettings?.WelcomeMessage; - if (string.IsNullOrEmpty(message)) return; - message = message.Replace("$user", user.Mention); - - var fallbackSender = new Func>(() => user.Guild.DefaultChannel.SendMessageAsync(message)); - if (guildSettings.WelcomeChannel != 0) - { - try - { - var target = await _client.GetChannelAsync(guildSettings.WelcomeChannel.AsUlong()); - var channel = target as ISocketMessageChannel; - await channel.SendMessageAsync(message); - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Failed to send welcome message to user defined welcome channel", e); - await fallbackSender(); - } - } - else - { - await fallbackSender(); - } - } - - await userRepoUpdate; - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Failed to send welcome message", e); - } - } - - public async Task UserUpdated(SocketUser oldUser, SocketUser newUser) - { - await _userRepository.Update(newUser); - } - - public async Task UserLeft(SocketGuildUser user) - { - try - { - var guild = _database.GuildSettings.FirstOrDefault(g => - g.GuildId.Equals(user.Guild.Id.AsLong())); - if (guild?.ShowLeave ?? false) - { - var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong()); - await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server"); - } - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Failed to send leave message", e); - } - - _logger.Information(LogSource.Geekbot, $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})"); - } - - // - // Message Stuff - // - - public async Task MessageDeleted(Cacheable message, ISocketMessageChannel channel) - { - try - { - var guildSocketData = ((IGuildChannel) channel).Guild; - var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildSocketData.Id.AsLong())); - if ((guild?.ShowDelete ?? false) && guild?.ModChannel != 0) - { - var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong()); - var sb = new StringBuilder(); - if (message.Value != null) - { - sb.AppendLine($"The following message from {message.Value.Author.Username}#{message.Value.Author.Discriminator} was deleted in <#{channel.Id}>"); - sb.AppendLine(message.Value.Content); - } - else - { - sb.AppendLine("Someone deleted a message, the message was not cached..."); - } - - await modChannelSocket.SendMessageAsync(sb.ToString()); - } - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Failed to send delete message...", e); - } - } - - // - // Reactions - // - - public Task ReactionAdded(Cacheable cacheable, ISocketMessageChannel socketMessageChannel, SocketReaction reaction) - { - if (reaction.User.Value.IsBot) return Task.CompletedTask; - if (!_reactionListener.IsListener(reaction.MessageId)) return Task.CompletedTask; - _reactionListener.GiveRole(socketMessageChannel, reaction); - return Task.CompletedTask; - } - - public Task ReactionRemoved(Cacheable cacheable, ISocketMessageChannel socketMessageChannel, SocketReaction reaction) - { - if (reaction.User.Value.IsBot) return Task.CompletedTask; - if (!_reactionListener.IsListener(reaction.MessageId)) return Task.CompletedTask; - _reactionListener.RemoveRole(socketMessageChannel, reaction); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Geekbot.net/Handlers/CommandHandler.cs b/Geekbot.net/Handlers/CommandHandler.cs new file mode 100644 index 0000000..5074ff2 --- /dev/null +++ b/Geekbot.net/Handlers/CommandHandler.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Discord.Rest; +using Discord.WebSocket; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; +using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.Logger; + +namespace Geekbot.net.Handlers +{ + public class CommandHandler + { + private readonly IDiscordClient _client; + private readonly IGeekbotLogger _logger; + private readonly IServiceProvider _servicesProvider; + private readonly CommandService _commands; + private readonly RestApplication _applicationInfo; + private readonly List _ignoredServers; + private readonly DatabaseContext _database; + + public CommandHandler(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, IServiceProvider servicesProvider, CommandService commands, RestApplication applicationInfo) + { + _database = database; + _client = client; + _logger = logger; + _servicesProvider = servicesProvider; + _commands = commands; + _applicationInfo = applicationInfo; + + // Some guilds only want very specific functionally without any of the commands, a quick hack that solves that "short term" + // ToDo: create a clean solution for this... + _ignoredServers = new List + { + 228623803201224704, // SwitzerLAN + 169844523181015040, // EEvent + 248531441548263425, // MYI + 110373943822540800 // Discord Bots + }; + } + + public Task RunCommand(SocketMessage messageParam) + { + try + { + if (!(messageParam is SocketUserMessage message)) return Task.CompletedTask; + if (message.Author.IsBot) return Task.CompletedTask; + + var guildId = ((SocketGuildChannel) message.Channel).Guild.Id; + if (IsIgnoredGuild(guildId, message.Author.Id)) return Task.CompletedTask; + + var lowCaseMsg = message.ToString().ToLower(); + if (ShouldHui(lowCaseMsg, guildId)) + { + message.Channel.SendMessageAsync("hui!!!"); + return Task.CompletedTask; + } + + if (ShouldPong(lowCaseMsg, guildId)) + { + message.Channel.SendMessageAsync("pong"); + return Task.CompletedTask; + } + + var argPos = 0; + if (!IsCommand(message, ref argPos)) return Task.CompletedTask; + + ExecuteCommand(message, argPos); + } + catch (Exception e) + { + _logger.Error(LogSource.Geekbot, "Failed to Process Message", e); + } + + return Task.CompletedTask; + } + + private void ExecuteCommand(IUserMessage message, int argPos) + { + var context = new CommandContext(_client, message); + _commands.ExecuteAsync(context, argPos, _servicesProvider); + _logger.Information(LogSource.Command, context.Message.Content.Split(" ")[0].Replace("!", ""), SimpleConextConverter.ConvertContext(context)); + } + + private bool IsIgnoredGuild(ulong guildId, ulong authorId) + { + if (!_ignoredServers.Contains(guildId)) return false; + return authorId == _applicationInfo.Owner.Id; + } + + private bool IsCommand(IUserMessage message, ref int argPos) + { + return message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos); + } + + private bool ShouldPong(string lowerCaseMessage, ulong guildId) + { + if (!lowerCaseMessage.StartsWith("ping ") && !lowerCaseMessage.Equals("ping")) return false; + return GetGuildSettings(guildId)?.Ping ?? false; + } + + private bool ShouldHui(string lowerCaseMessage, ulong guildId) + { + if (!lowerCaseMessage.StartsWith("hui")) return false; + return GetGuildSettings(guildId)?.Hui ?? false; + } + + private GuildSettingsModel GetGuildSettings(ulong guildId) + { + return _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong())); + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Handlers/MessageDeletedHandler.cs b/Geekbot.net/Handlers/MessageDeletedHandler.cs new file mode 100644 index 0000000..5595cff --- /dev/null +++ b/Geekbot.net/Handlers/MessageDeletedHandler.cs @@ -0,0 +1,55 @@ +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Discord; +using Discord.WebSocket; +using Geekbot.net.Database; +using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.Logger; + +namespace Geekbot.net.Handlers +{ + public class MessageDeletedHandler + { + private readonly DatabaseContext _database; + private readonly IGeekbotLogger _logger; + private readonly IDiscordClient _client; + + public MessageDeletedHandler(DatabaseContext database, IGeekbotLogger logger, IDiscordClient client) + { + _database = database; + _logger = logger; + _client = client; + } + + public async Task HandleMessageDeleted(Cacheable message, ISocketMessageChannel channel) + { + try + { + var guildSocketData = ((IGuildChannel) channel).Guild; + var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildSocketData.Id.AsLong())); + if ((guild?.ShowDelete ?? false) && guild?.ModChannel != 0) + { + var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong()); + var sb = new StringBuilder(); + if (message.Value != null) + { + sb.AppendLine($"The following message from {message.Value.Author.Username}#{message.Value.Author.Discriminator} was deleted in <#{channel.Id}>"); + sb.AppendLine(message.Value.Content); + } + else + { + sb.AppendLine("Someone deleted a message, the message was not cached..."); + } + + await modChannelSocket.SendMessageAsync(sb.ToString()); + } + } + catch (Exception e) + { + _logger.Error(LogSource.Geekbot, "Failed to send delete message...", e); + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Handlers/ReactionHandler.cs b/Geekbot.net/Handlers/ReactionHandler.cs new file mode 100644 index 0000000..e2355a8 --- /dev/null +++ b/Geekbot.net/Handlers/ReactionHandler.cs @@ -0,0 +1,33 @@ +using System.Threading.Tasks; +using Discord; +using Discord.WebSocket; +using Geekbot.net.Lib.ReactionListener; + +namespace Geekbot.net.Handlers +{ + public class ReactionHandler + { + private readonly IReactionListener _reactionListener; + + public ReactionHandler(IReactionListener reactionListener) + { + _reactionListener = reactionListener; + } + + public Task Added(Cacheable cacheable, ISocketMessageChannel socketMessageChannel, SocketReaction reaction) + { + if (reaction.User.Value.IsBot) return Task.CompletedTask; + if (!_reactionListener.IsListener(reaction.MessageId)) return Task.CompletedTask; + _reactionListener.GiveRole(socketMessageChannel, reaction); + return Task.CompletedTask; + } + + public Task Removed(Cacheable cacheable, ISocketMessageChannel socketMessageChannel, SocketReaction reaction) + { + if (reaction.User.Value.IsBot) return Task.CompletedTask; + if (!_reactionListener.IsListener(reaction.MessageId)) return Task.CompletedTask; + _reactionListener.RemoveRole(socketMessageChannel, reaction); + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Handlers/StatsHandler.cs b/Geekbot.net/Handlers/StatsHandler.cs new file mode 100644 index 0000000..56c0894 --- /dev/null +++ b/Geekbot.net/Handlers/StatsHandler.cs @@ -0,0 +1,62 @@ +using System; +using System.Threading.Tasks; +using Discord.WebSocket; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; +using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.Logger; +using Microsoft.EntityFrameworkCore; + +namespace Geekbot.net.Handlers +{ + public class StatsHandler + { + private readonly IGeekbotLogger _logger; + private readonly DatabaseContext _database; + + public StatsHandler(IGeekbotLogger logger, DatabaseContext database) + { + _logger = logger; + _database = database; + } + + public async Task UpdateStats(SocketMessage message) + { + try + { + if (message == null) return; + if (message.Channel.Name.StartsWith('@')) + { + _logger.Information(LogSource.Message, $"[DM-Channel] {message.Content}", SimpleConextConverter.ConvertSocketMessage(message, true)); + return; + } + + var channel = (SocketGuildChannel) message.Channel; + + var rowId = await _database.Database.ExecuteSqlRawAsync( + "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", + channel.Guild.Id.AsLong(), + message.Author.Id.AsLong() + ); + + if (rowId == 0) + { + await _database.Messages.AddAsync(new MessagesModel + { + UserId = message.Author.Id.AsLong(), + GuildId = channel.Guild.Id.AsLong(), + MessageCount = 1 + }); + await _database.SaveChangesAsync(); + } + + if (message.Author.IsBot) return; + _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); + } + catch (Exception e) + { + _logger.Error(LogSource.Message, "Could not process message stats", e); + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Handlers/UserHandler.cs b/Geekbot.net/Handlers/UserHandler.cs new file mode 100644 index 0000000..fb26d70 --- /dev/null +++ b/Geekbot.net/Handlers/UserHandler.cs @@ -0,0 +1,96 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Discord; +using Discord.Rest; +using Discord.WebSocket; +using Geekbot.net.Database; +using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.Logger; +using Geekbot.net.Lib.UserRepository; + +namespace Geekbot.net.Handlers +{ + public class UserHandler + { + private readonly IUserRepository _userRepository; + private readonly IGeekbotLogger _logger; + private readonly DatabaseContext _database; + private readonly IDiscordClient _client; + + public UserHandler(IUserRepository userRepository, IGeekbotLogger logger, DatabaseContext database, IDiscordClient client) + { + _userRepository = userRepository; + _logger = logger; + _database = database; + _client = client; + } + + public async Task Joined(SocketGuildUser user) + { + try + { + var userRepoUpdate = _userRepository.Update(user); + _logger.Information(LogSource.Geekbot, $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})"); + + if (!user.IsBot) + { + var guildSettings = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId == user.Guild.Id.AsLong()); + var message = guildSettings?.WelcomeMessage; + if (string.IsNullOrEmpty(message)) return; + message = message.Replace("$user", user.Mention); + + var fallbackSender = new Func>(() => user.Guild.DefaultChannel.SendMessageAsync(message)); + if (guildSettings.WelcomeChannel != 0) + { + try + { + var target = await _client.GetChannelAsync(guildSettings.WelcomeChannel.AsUlong()); + var channel = target as ISocketMessageChannel; + await channel.SendMessageAsync(message); + } + catch (Exception e) + { + _logger.Error(LogSource.Geekbot, "Failed to send welcome message to user defined welcome channel", e); + await fallbackSender(); + } + } + else + { + await fallbackSender(); + } + } + + await userRepoUpdate; + } + catch (Exception e) + { + _logger.Error(LogSource.Geekbot, "Failed to send welcome message", e); + } + } + + public async Task Updated(SocketUser oldUser, SocketUser newUser) + { + await _userRepository.Update(newUser); + } + + public async Task Left(SocketGuildUser user) + { + try + { + var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(user.Guild.Id.AsLong())); + if (guild?.ShowLeave ?? false) + { + var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong()); + await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server"); + } + } + catch (Exception e) + { + _logger.Error(LogSource.Geekbot, "Failed to send leave message", e); + } + + _logger.Information(LogSource.Geekbot, $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})"); + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/Logger/SimpleConextConverter.cs b/Geekbot.net/Lib/Logger/SimpleConextConverter.cs index d01da67..1eef12c 100644 --- a/Geekbot.net/Lib/Logger/SimpleConextConverter.cs +++ b/Geekbot.net/Lib/Logger/SimpleConextConverter.cs @@ -11,7 +11,7 @@ namespace Geekbot.net.Lib.Logger { Message = new MessageDto.MessageContent { - Content = context.Message.Content, + Content = context.Message.Content, // Only when an error occurs, including for diagnostic reason Id = context.Message.Id.ToString(), Attachments = context.Message.Attachments.Count, ChannelMentions = context.Message.MentionedChannelIds.Count, @@ -42,7 +42,6 @@ namespace Geekbot.net.Lib.Logger { Message = new MessageDto.MessageContent { - Content = message.Content, Id = message.Id.ToString(), Attachments = message.Attachments.Count, ChannelMentions = message.MentionedChannels.Count, diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index d46df90..262d830 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -7,6 +7,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Database; +using Geekbot.net.Handlers; using Geekbot.net.Lib; using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.Converters; @@ -34,12 +35,11 @@ namespace Geekbot.net private CommandService _commands; private DatabaseInitializer _databaseInitializer; private IGlobalSettings _globalSettings; - private IServiceCollection _services; private IServiceProvider _servicesProvider; - private string _token; private GeekbotLogger _logger; private IUserRepository _userRepository; private RunParameters _runParameters; + private IReactionListener _reactionListener; private static void Main(string[] args) { @@ -73,66 +73,25 @@ namespace Geekbot.net { _logger = logger; _runParameters = runParameters; - logger.Information(LogSource.Geekbot, "Initing Stuff"); - var discordLogger = new DiscordLogger(logger); - - _client = new DiscordSocketClient(new DiscordSocketConfig - { - LogLevel = LogSeverity.Verbose, - MessageCacheSize = 1000, - ExclusiveBulkDelete = true - }); - _client.Log += discordLogger.Log; - _commands = new CommandService(); - - _databaseInitializer = new DatabaseInitializer(runParameters, logger); - var database = _databaseInitializer.Initialize(); - database.Database.EnsureCreated(); - if(!_runParameters.InMemory) database.Database.Migrate(); + logger.Information(LogSource.Geekbot, "Connecting to Database"); + var database = ConnectToDatabase(); _globalSettings = new GlobalSettings(database); - - _token = runParameters.Token ?? _globalSettings.GetKey("DiscordToken"); - if (string.IsNullOrEmpty(_token)) - { - Console.Write("Your bot Token: "); - var newToken = Console.ReadLine(); - await _globalSettings.SetKey("DiscordToken", newToken); - await _globalSettings.SetKey("Game", "Ping Pong"); - _token = newToken; - } - - _services = new ServiceCollection(); - - _userRepository = new UserRepository(_databaseInitializer.Initialize(), logger); - var fortunes = new FortunesProvider(logger); - var mediaProvider = new MediaProvider(logger); - var malClient = new MalClient(_globalSettings, logger); - var levelCalc = new LevelCalc(); - var emojiConverter = new EmojiConverter(); - var mtgManaConverter = new MtgManaConverter(); - var wikipediaClient = new WikipediaClient(); - var randomNumberGenerator = new RandomNumberGenerator(); - var kvMemoryStore = new KvInInMemoryStore(); - - _services.AddSingleton(_userRepository); - _services.AddSingleton(logger); - _services.AddSingleton(levelCalc); - _services.AddSingleton(emojiConverter); - _services.AddSingleton(fortunes); - _services.AddSingleton(mediaProvider); - _services.AddSingleton(malClient); - _services.AddSingleton(mtgManaConverter); - _services.AddSingleton(wikipediaClient); - _services.AddSingleton(randomNumberGenerator); - _services.AddSingleton(kvMemoryStore); - _services.AddSingleton(_globalSettings); - _services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); - _services.AddTransient(e => _databaseInitializer.Initialize()); logger.Information(LogSource.Geekbot, "Connecting to Discord"); - + SetupDiscordClient(); await Login(); + _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); + await _client.SetGameAsync(_globalSettings.GetKey("Game")); + + _logger.Information(LogSource.Geekbot, "Loading Dependencies and Handlers"); + RegisterDependencies(); + await RegisterHandlers(); + + _logger.Information(LogSource.Api, "Starting Web API"); + StartWebApi(); + + _logger.Information(LogSource.Geekbot, "Done and ready for use"); await Task.Delay(-1); } @@ -141,42 +100,10 @@ namespace Geekbot.net { try { - await _client.LoginAsync(TokenType.Bot, _token); + var token = await GetToken(); + await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); - var isConneted = await IsConnected(); - if (isConneted) - { - var applicationInfo = await _client.GetApplicationInfoAsync(); - await _client.SetGameAsync(_globalSettings.GetKey("Game")); - _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); - - _logger.Information(LogSource.Geekbot, "Registering Stuff"); - var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); - var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); - var reactionListener = new ReactionListener(_databaseInitializer.Initialize()); - _services.AddSingleton(errorHandler); - _services.AddSingleton(translationHandler); - _services.AddSingleton(_client); - _services.AddSingleton(reactionListener); - _servicesProvider = _services.BuildServiceProvider(); - await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - - var handlers = new Handlers(_databaseInitializer, _client, _logger, _servicesProvider, _commands, _userRepository, reactionListener, applicationInfo); - - _client.MessageReceived += handlers.RunCommand; - _client.MessageDeleted += handlers.MessageDeleted; - _client.UserJoined += handlers.UserJoined; - _client.UserUpdated += handlers.UserUpdated; - _client.UserLeft += handlers.UserLeft; - _client.ReactionAdded += handlers.ReactionAdded; - _client.ReactionRemoved += handlers.ReactionRemoved; - if (!_runParameters.InMemory) _client.MessageReceived += handlers.UpdateStats; - - var webserver = _runParameters.DisableApi ? Task.Delay(10) : StartWebApi(); - _logger.Information(LogSource.Geekbot, "Done and ready for use"); - - await webserver; - } + while (!_client.ConnectionState.Equals(ConnectionState.Connected)) await Task.Delay(25); } catch (Exception e) { @@ -185,19 +112,117 @@ namespace Geekbot.net } } - private async Task IsConnected() + private DatabaseContext ConnectToDatabase() { - while (!_client.ConnectionState.Equals(ConnectionState.Connected)) - await Task.Delay(25); - return true; + _databaseInitializer = new DatabaseInitializer(_runParameters, _logger); + var database = _databaseInitializer.Initialize(); + database.Database.EnsureCreated(); + if(!_runParameters.InMemory) database.Database.Migrate(); + + return database; } - private Task StartWebApi() + private async Task GetToken() { - _logger.Information(LogSource.Api, "Starting Webserver"); + var token = _runParameters.Token ?? _globalSettings.GetKey("DiscordToken"); + if (string.IsNullOrEmpty(token)) + { + Console.Write("Your bot Token: "); + var newToken = Console.ReadLine(); + await _globalSettings.SetKey("DiscordToken", newToken); + await _globalSettings.SetKey("Game", "Ping Pong"); + token = newToken; + } + + return token; + } + + private void SetupDiscordClient() + { + _client = new DiscordSocketClient(new DiscordSocketConfig + { + LogLevel = LogSeverity.Verbose, + MessageCacheSize = 1000, + ExclusiveBulkDelete = true + }); + + var discordLogger = new DiscordLogger(_logger); + _client.Log += discordLogger.Log; + } + + private void RegisterDependencies() + { + var services = new ServiceCollection(); + + _userRepository = new UserRepository(_databaseInitializer.Initialize(), _logger); + _reactionListener = new ReactionListener(_databaseInitializer.Initialize()); + var fortunes = new FortunesProvider(_logger); + var mediaProvider = new MediaProvider(_logger); + var malClient = new MalClient(_globalSettings, _logger); + var levelCalc = new LevelCalc(); + var emojiConverter = new EmojiConverter(); + var mtgManaConverter = new MtgManaConverter(); + var wikipediaClient = new WikipediaClient(); + var randomNumberGenerator = new RandomNumberGenerator(); + var kvMemoryStore = new KvInInMemoryStore(); + var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); + var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); + + services.AddSingleton(_userRepository); + services.AddSingleton(_logger); + services.AddSingleton(levelCalc); + services.AddSingleton(emojiConverter); + services.AddSingleton(fortunes); + services.AddSingleton(mediaProvider); + services.AddSingleton(malClient); + services.AddSingleton(mtgManaConverter); + services.AddSingleton(wikipediaClient); + services.AddSingleton(randomNumberGenerator); + services.AddSingleton(kvMemoryStore); + services.AddSingleton(_globalSettings); + services.AddSingleton(errorHandler); + services.AddSingleton(translationHandler); + services.AddSingleton(_reactionListener); + services.AddSingleton(_client); + services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); + services.AddTransient(e => _databaseInitializer.Initialize()); + + _servicesProvider = services.BuildServiceProvider(); + } + + private async Task RegisterHandlers() + { + var applicationInfo = await _client.GetApplicationInfoAsync(); + + _commands = new CommandService(); + await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); + + var commandHandler = new CommandHandler(_databaseInitializer.Initialize(), _client, _logger, _servicesProvider, _commands, applicationInfo); + var userHandler = new UserHandler(_userRepository, _logger, _databaseInitializer.Initialize(), _client); + var reactionHandler = new ReactionHandler(_reactionListener); + var statsHandler = new StatsHandler(_logger, _databaseInitializer.Initialize()); + var messageDeletedHandler = new MessageDeletedHandler(_databaseInitializer.Initialize(), _logger, _client); + + _client.MessageReceived += commandHandler.RunCommand; + _client.MessageDeleted += messageDeletedHandler.HandleMessageDeleted; + _client.UserJoined += userHandler.Joined; + _client.UserUpdated += userHandler.Updated; + _client.UserLeft += userHandler.Left; + _client.ReactionAdded += reactionHandler.Added; + _client.ReactionRemoved += reactionHandler.Removed; + if (!_runParameters.InMemory) _client.MessageReceived += statsHandler.UpdateStats; + } + + private void StartWebApi() + { + if (_runParameters.DisableApi) + { + _logger.Warning(LogSource.Api, "Web API is disabled"); + return; + } + var highscoreManager = new HighscoreManager(_databaseInitializer.Initialize(), _userRepository); WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); - return Task.CompletedTask; } } } \ No newline at end of file From fb676e8918750ccaaad04cb6e2244d831626b0a5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 04:10:26 +0200 Subject: [PATCH 044/264] Add GuildSettingsManager to centrally manage guild settings --- Geekbot.net/Commands/Admin/Admin.cs | 107 ++++++------------ Geekbot.net/Handlers/CommandHandler.cs | 16 +-- .../GuildSettingsManager.cs | 68 +++++++++++ .../IGuildSettingsManager.cs | 11 ++ .../Lib/Localization/TranslationHandler.cs | 28 ++--- Geekbot.net/Program.cs | 8 +- 6 files changed, 138 insertions(+), 100 deletions(-) create mode 100644 Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs create mode 100644 Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs diff --git a/Geekbot.net/Commands/Admin/Admin.cs b/Geekbot.net/Commands/Admin/Admin.cs index 15b4df1..9120971 100644 --- a/Geekbot.net/Commands/Admin/Admin.cs +++ b/Geekbot.net/Commands/Admin/Admin.cs @@ -1,15 +1,13 @@ using System; -using System.Linq; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.GuildSettingsManager; using Geekbot.net.Lib.Localization; namespace Geekbot.net.Commands.Admin @@ -21,15 +19,14 @@ namespace Geekbot.net.Commands.Admin { private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; - private readonly DatabaseContext _database; + private readonly IGuildSettingsManager _guildSettingsManager; private readonly ITranslationHandler _translation; - public Admin(DatabaseContext database, DiscordSocketClient client, IErrorHandler errorHandler, - ITranslationHandler translationHandler) + public Admin(DiscordSocketClient client, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager, ITranslationHandler translationHandler) { - _database = database; _client = client; _errorHandler = errorHandler; + _guildSettingsManager = guildSettingsManager; _translation = translationHandler; } @@ -37,11 +34,10 @@ namespace Geekbot.net.Commands.Admin [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] public async Task SetWelcomeMessage([Remainder, Summary("message")] string welcomeMessage) { - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.WelcomeMessage = welcomeMessage; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); - + await _guildSettingsManager.UpdateSettings(guild); + var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention); await ReplyAsync($"Welcome message has been changed\r\nHere is an example of how it would look:\r\n{formatedMessage}"); } @@ -54,13 +50,12 @@ namespace Geekbot.net.Commands.Admin { var m = await channel.SendMessageAsync("..."); - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.WelcomeChannel = channel.Id.AsLong(); - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); - + await _guildSettingsManager.UpdateSettings(guild); + await m.DeleteAsync(); - + await ReplyAsync("Successfully saved the welcome channel"); } catch (Exception e) @@ -68,7 +63,7 @@ namespace Geekbot.net.Commands.Admin await _errorHandler.HandleCommandException(e, Context, "That channel doesn't seem to exist or i don't have write permissions"); } } - + [Command("modchannel", RunMode = RunMode.Async)] [Summary("Set a channel for moderation purposes")] public async Task SelectModChannel([Summary("#Channel")] ISocketMessageChannel channel) @@ -77,11 +72,10 @@ namespace Geekbot.net.Commands.Admin { var m = await channel.SendMessageAsync("verifying..."); - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.ModChannel = channel.Id.AsLong(); - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); - + await _guildSettingsManager.UpdateSettings(guild); + var sb = new StringBuilder(); sb.AppendLine("Successfully saved mod channel, you can now do the following"); sb.AppendLine("- `!admin showleave` - send message to mod channel when someone leaves"); @@ -100,13 +94,12 @@ namespace Geekbot.net.Commands.Admin { try { - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); var modChannel = await GetModChannel(guild.ModChannel.AsUlong()); if (modChannel == null) return; - + guild.ShowLeave = !guild.ShowLeave; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); + await _guildSettingsManager.UpdateSettings(guild); await modChannel.SendMessageAsync(guild.ShowLeave ? "Saved - now sending messages here when someone leaves" : "Saved - stopping sending messages here when someone leaves" @@ -124,13 +117,12 @@ namespace Geekbot.net.Commands.Admin { try { - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); var modChannel = await GetModChannel(guild.ModChannel.AsUlong()); if (modChannel == null) return; - + guild.ShowDelete = !guild.ShowDelete; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); + await _guildSettingsManager.UpdateSettings(guild); await modChannel.SendMessageAsync(guild.ShowDelete ? "Saved - now sending messages here when someone deletes a message" : "Saved - stopping sending messages here when someone deletes a message" @@ -152,11 +144,10 @@ namespace Geekbot.net.Commands.Admin var success = await _translation.SetLanguage(Context.Guild.Id, language); if (success) { - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.Language = language; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); - + await _guildSettingsManager.UpdateSettings(guild); + var transContext = await _translation.GetGuildContext(Context); await ReplyAsync(transContext.GetString("NewLanguageSet")); return; @@ -170,7 +161,7 @@ namespace Geekbot.net.Commands.Admin await _errorHandler.HandleCommandException(e, Context); } } - + [Command("wiki", RunMode = RunMode.Async)] [Summary("Change the wikipedia instance (use lang code in xx.wikipedia.org)")] public async Task SetWikiLanguage([Summary("language")] string languageRaw) @@ -178,11 +169,10 @@ namespace Geekbot.net.Commands.Admin try { var language = languageRaw.ToLower(); - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.WikiLang = language; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); - + await _guildSettingsManager.UpdateSettings(guild); + await ReplyAsync($"Now using the {language} wikipedia"); } catch (Exception e) @@ -190,17 +180,16 @@ namespace Geekbot.net.Commands.Admin await _errorHandler.HandleCommandException(e, Context); } } - + [Command("ping", RunMode = RunMode.Async)] [Summary("Enable the ping reply.")] public async Task TogglePing() { try { - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.Ping = !guild.Ping; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); + await _guildSettingsManager.UpdateSettings(guild); await ReplyAsync(guild.Ping ? "i will reply to ping now" : "No more pongs..."); } catch (Exception e) @@ -208,17 +197,16 @@ namespace Geekbot.net.Commands.Admin await _errorHandler.HandleCommandException(e, Context); } } - + [Command("hui", RunMode = RunMode.Async)] [Summary("Enable the ping reply.")] public async Task ToggleHui() { try { - var guild = await GetGuildSettings(Context.Guild.Id); + var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.Hui = !guild.Hui; - _database.GuildSettings.Update(guild); - await _database.SaveChangesAsync(); + await _guildSettingsManager.UpdateSettings(guild); await ReplyAsync(guild.Hui ? "i will reply to hui now" : "No more hui's..."); } catch (Exception e) @@ -227,41 +215,20 @@ namespace Geekbot.net.Commands.Admin } } - private async Task GetGuildSettings(ulong guildId) - { - var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); - if (guild != null) return guild; - Console.WriteLine("Adding non-exist Guild Settings to database"); - _database.GuildSettings.Add(new GuildSettingsModel() - { - GuildId = guildId.AsLong(), - Hui = false, - Ping = false, - Language = "EN", - ShowDelete = false, - ShowLeave = false, - WikiLang = "en" - }); - await _database.SaveChangesAsync(); - return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); - } - private async Task GetModChannel(ulong channelId) { try { - if(channelId == ulong.MinValue) throw new Exception(); + if (channelId == ulong.MinValue) throw new Exception(); var modChannel = (ISocketMessageChannel) _client.GetChannel(channelId); - if(modChannel == null) throw new Exception(); + if (modChannel == null) throw new Exception(); return modChannel; } catch { - await ReplyAsync( - "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); + await ReplyAsync("Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); return null; } } - } } \ No newline at end of file diff --git a/Geekbot.net/Handlers/CommandHandler.cs b/Geekbot.net/Handlers/CommandHandler.cs index 5074ff2..b811a8e 100644 --- a/Geekbot.net/Handlers/CommandHandler.cs +++ b/Geekbot.net/Handlers/CommandHandler.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; @@ -8,7 +7,7 @@ using Discord.Rest; using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.GuildSettingsManager; using Geekbot.net.Lib.Logger; namespace Geekbot.net.Handlers @@ -20,10 +19,12 @@ namespace Geekbot.net.Handlers private readonly IServiceProvider _servicesProvider; private readonly CommandService _commands; private readonly RestApplication _applicationInfo; + private readonly IGuildSettingsManager _guildSettingsManager; private readonly List _ignoredServers; private readonly DatabaseContext _database; - public CommandHandler(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, IServiceProvider servicesProvider, CommandService commands, RestApplication applicationInfo) + public CommandHandler(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, IServiceProvider servicesProvider, CommandService commands, RestApplication applicationInfo, + IGuildSettingsManager guildSettingsManager) { _database = database; _client = client; @@ -31,6 +32,7 @@ namespace Geekbot.net.Handlers _servicesProvider = servicesProvider; _commands = commands; _applicationInfo = applicationInfo; + _guildSettingsManager = guildSettingsManager; // Some guilds only want very specific functionally without any of the commands, a quick hack that solves that "short term" // ToDo: create a clean solution for this... @@ -68,14 +70,14 @@ namespace Geekbot.net.Handlers var argPos = 0; if (!IsCommand(message, ref argPos)) return Task.CompletedTask; - + ExecuteCommand(message, argPos); } catch (Exception e) { _logger.Error(LogSource.Geekbot, "Failed to Process Message", e); } - + return Task.CompletedTask; } @@ -102,7 +104,7 @@ namespace Geekbot.net.Handlers if (!lowerCaseMessage.StartsWith("ping ") && !lowerCaseMessage.Equals("ping")) return false; return GetGuildSettings(guildId)?.Ping ?? false; } - + private bool ShouldHui(string lowerCaseMessage, ulong guildId) { if (!lowerCaseMessage.StartsWith("hui")) return false; @@ -111,7 +113,7 @@ namespace Geekbot.net.Handlers private GuildSettingsModel GetGuildSettings(ulong guildId) { - return _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong())); + return _guildSettingsManager.GetSettings(guildId, false); } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs b/Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs new file mode 100644 index 0000000..bfa7556 --- /dev/null +++ b/Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; +using Geekbot.net.Lib.Extensions; + +namespace Geekbot.net.Lib.GuildSettingsManager +{ + public class GuildSettingsManager : IGuildSettingsManager + { + private readonly DatabaseContext _database; + private readonly Dictionary _settings; + + public GuildSettingsManager(DatabaseContext database) + { + _database = database; + _settings = new Dictionary(); + } + + public GuildSettingsModel GetSettings(ulong guildId, bool createIfNonExist = true) + { + return _settings.ContainsKey(guildId) ? _settings[guildId] : GetFromDatabase(guildId, createIfNonExist); + } + + public async Task UpdateSettings(GuildSettingsModel settings) + { + _database.GuildSettings.Update(settings); + if (_settings.ContainsKey(settings.GuildId.AsUlong())) + { + _settings[settings.GuildId.AsUlong()] = settings; + } + else + { + _settings.Add(settings.GuildId.AsUlong(), settings); + } + await _database.SaveChangesAsync(); + } + + private GuildSettingsModel GetFromDatabase(ulong guildId, bool createIfNonExist) + { + var settings = _database.GuildSettings.FirstOrDefault(guild => guild.GuildId.Equals(guildId.AsLong())); + if (createIfNonExist && settings == null) + { + settings = CreateSettings(guildId); + } + + _settings.Add(guildId, settings); + return settings; + } + + private GuildSettingsModel CreateSettings(ulong guildId) + { + _database.GuildSettings.Add(new GuildSettingsModel + { + GuildId = guildId.AsLong(), + Hui = false, + Ping = false, + Language = "EN", + ShowDelete = false, + ShowLeave = false, + WikiLang = "en" + }); + _database.SaveChanges(); + return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs b/Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs new file mode 100644 index 0000000..a45b263 --- /dev/null +++ b/Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using Geekbot.net.Database.Models; + +namespace Geekbot.net.Lib.GuildSettingsManager +{ + public interface IGuildSettingsManager + { + GuildSettingsModel GetSettings(ulong guildId, bool createIfNonExist = true); + Task UpdateSettings(GuildSettingsModel settings); + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/Localization/TranslationHandler.cs b/Geekbot.net/Lib/Localization/TranslationHandler.cs index a7a1a12..89ba632 100644 --- a/Geekbot.net/Lib/Localization/TranslationHandler.cs +++ b/Geekbot.net/Lib/Localization/TranslationHandler.cs @@ -4,9 +4,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.GuildSettingsManager; using Geekbot.net.Lib.Logger; using YamlDotNet.Core; using YamlDotNet.Serialization; @@ -15,15 +13,15 @@ namespace Geekbot.net.Lib.Localization { public class TranslationHandler : ITranslationHandler { - private readonly DatabaseContext _database; private readonly IGeekbotLogger _logger; + private readonly IGuildSettingsManager _guildSettingsManager; private readonly Dictionary _serverLanguages; private Dictionary>> _translations; - public TranslationHandler(DatabaseContext database, IGeekbotLogger logger) + public TranslationHandler(IGeekbotLogger logger, IGuildSettingsManager guildSettingsManager) { - _database = database; _logger = logger; + _guildSettingsManager = guildSettingsManager; _logger.Information(LogSource.Geekbot, "Loading Translations"); LoadTranslations(); _serverLanguages = new Dictionary(); @@ -107,7 +105,7 @@ namespace Geekbot.net.Lib.Localization } catch { - lang = (await GetGuild(guildId)).Language ?? "EN"; + lang = _guildSettingsManager.GetSettings(guildId, false)?.Language ?? "EN"; _serverLanguages[guildId] = lang; return lang; } @@ -178,9 +176,9 @@ namespace Geekbot.net.Lib.Localization try { if (!SupportedLanguages.Contains(language)) return false; - var guild = await GetGuild(guildId); + var guild = _guildSettingsManager.GetSettings(guildId); guild.Language = language; - _database.GuildSettings.Update(guild); + await _guildSettingsManager.UpdateSettings(guild); _serverLanguages[guildId] = language; return true; } @@ -192,17 +190,5 @@ namespace Geekbot.net.Lib.Localization } public List SupportedLanguages { get; private set; } - - private async Task GetGuild(ulong guildId) - { - var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); - if (guild != null) return guild; - _database.GuildSettings.Add(new GuildSettingsModel - { - GuildId = guildId.AsLong() - }); - await _database.SaveChangesAsync(); - return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); - } } } \ No newline at end of file diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 262d830..1299583 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -13,6 +13,7 @@ using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; +using Geekbot.net.Lib.GuildSettingsManager; using Geekbot.net.Lib.Highscores; using Geekbot.net.Lib.KvInMemoryStore; using Geekbot.net.Lib.Levels; @@ -40,6 +41,7 @@ namespace Geekbot.net private IUserRepository _userRepository; private RunParameters _runParameters; private IReactionListener _reactionListener; + private IGuildSettingsManager _guildSettingsManager; private static void Main(string[] args) { @@ -156,6 +158,7 @@ namespace Geekbot.net _userRepository = new UserRepository(_databaseInitializer.Initialize(), _logger); _reactionListener = new ReactionListener(_databaseInitializer.Initialize()); + _guildSettingsManager = new GuildSettingsManager(_databaseInitializer.Initialize()); var fortunes = new FortunesProvider(_logger); var mediaProvider = new MediaProvider(_logger); var malClient = new MalClient(_globalSettings, _logger); @@ -165,7 +168,7 @@ namespace Geekbot.net var wikipediaClient = new WikipediaClient(); var randomNumberGenerator = new RandomNumberGenerator(); var kvMemoryStore = new KvInInMemoryStore(); - var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger); + var translationHandler = new TranslationHandler(_logger, _guildSettingsManager); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); services.AddSingleton(_userRepository); @@ -183,6 +186,7 @@ namespace Geekbot.net services.AddSingleton(errorHandler); services.AddSingleton(translationHandler); services.AddSingleton(_reactionListener); + services.AddSingleton(_guildSettingsManager); services.AddSingleton(_client); services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); services.AddTransient(e => _databaseInitializer.Initialize()); @@ -197,7 +201,7 @@ namespace Geekbot.net _commands = new CommandService(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); - var commandHandler = new CommandHandler(_databaseInitializer.Initialize(), _client, _logger, _servicesProvider, _commands, applicationInfo); + var commandHandler = new CommandHandler(_databaseInitializer.Initialize(), _client, _logger, _servicesProvider, _commands, applicationInfo, _guildSettingsManager); var userHandler = new UserHandler(_userRepository, _logger, _databaseInitializer.Initialize(), _client); var reactionHandler = new ReactionHandler(_reactionListener); var statsHandler = new StatsHandler(_logger, _databaseInitializer.Initialize()); From 1ea851be22cff73ee85536a287f5f55fdf902de2 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 04:13:26 +0200 Subject: [PATCH 045/264] Release Geekbot 4.2 --- .gitlab-ci.yml | 6 +++--- Geekbot.net/Geekbot.net.csproj | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index cffe539..7b6b593 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -29,9 +29,9 @@ sentry: dependencies: - build script: - - sentry-cli releases new -p geekbot 4.1.0-${CI_COMMIT_SHA:0:8} - - sentry-cli releases set-commits --auto 4.1.0-${CI_COMMIT_SHA:0:8} - - sentry-cli releases deploys 4.1.0-${CI_COMMIT_SHA:0:8} new -e Production + - sentry-cli releases new -p geekbot 4.2.0-${CI_COMMIT_SHA:0:8} + - sentry-cli releases set-commits --auto 4.2.0-${CI_COMMIT_SHA:0:8} + - sentry-cli releases deploys 4.2.0-${CI_COMMIT_SHA:0:8} new -e Production deploy: stage: deploy diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 0d39cae..0d58104 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -4,7 +4,7 @@ netcoreapp3.1 win-x64;linux-x64 derp.ico - 4.1.0 + 4.2.0 $(VersionSuffix) $(Version)-$(VersionSuffix) $(Version)-DEV From 76bb645394d8cb447d8495b9334f06d20aa774c6 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 12:08:28 +0200 Subject: [PATCH 046/264] Inline MTG Emoji converter --- Geekbot.net/Geekbot.net.csproj | 3 -- .../Lib/Converters/MtgManaConverter.cs | 54 ++++++++++++++++++- Geekbot.net/Lib/Converters/MtgManaEmojis.json | 50 ----------------- 3 files changed, 52 insertions(+), 55 deletions(-) delete mode 100644 Geekbot.net/Lib/Converters/MtgManaEmojis.json diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 0d58104..b3f537e 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -82,9 +82,6 @@ PreserveNewest - - Always - PreserveNewest diff --git a/Geekbot.net/Lib/Converters/MtgManaConverter.cs b/Geekbot.net/Lib/Converters/MtgManaConverter.cs index 31a2db0..7e90df0 100644 --- a/Geekbot.net/Lib/Converters/MtgManaConverter.cs +++ b/Geekbot.net/Lib/Converters/MtgManaConverter.cs @@ -12,8 +12,57 @@ namespace Geekbot.net.Lib.Converters public MtgManaConverter() { // these emotes can be found at https://discord.gg/bz8HyA7 - var mtgEmojis = File.ReadAllText(Path.GetFullPath("./Lib/Converters/MtgManaEmojis.json")); - _manaDict = JsonSerializer.Deserialize>(mtgEmojis); + _manaDict = new Dictionary + { + {"{0}", "<:mtg_0:415216130043412482>"}, + {"{1}", "<:mtg_1:415216130253389835>"}, + {"{2}", "<:mtg_2:415216130031091713>"}, + {"{3}", "<:mtg_3:415216130467037194>"}, + {"{4}", "<:mtg_4:415216130026635295>"}, + {"{5}", "<:mtg_5:415216130492203008>"}, + {"{6}", "<:mtg_6:415216130458779658>"}, + {"{7}", "<:mtg_7:415216130190475265>"}, + {"{8}", "<:mtg_8:415216130517630986>"}, + {"{9}", "<:mtg_9:415216130500722689>"}, + {"{10", "<:mtg_10:415216130450391051>"}, + {"{11}", "<:mtg_11:415216130811101185>"}, + {"{12}", "<:mtg_12:415216130525888532>"}, + {"{13}", "<:mtg_13:415216130517631000>"}, + {"{14}", "<:mtg_14:415216130165178370>"}, + {"{15}", "<:mtg_15:415216130576089108>"}, + {"{16}", "<:mtg_16:415216130358247425>"}, + {"{17}", "<:mtg_17:415216130601517056>"}, + {"{18}", "<:mtg_18:415216130462842891>"}, + {"{19}", "<:mtg_19:415216130614099988>"}, + {"{20}", "<:mtg_20:415216130656043038>"}, + {"{W}", "<:mtg_white:415216131515744256>"}, + {"{U}", "<:mtg_blue:415216130521694209>"}, + {"{B}", "<:mtg_black:415216130873884683>"}, + {"{R}", "<:mtg_red:415216131322806272>"}, + {"{G}", "<:mtg_green:415216131180331009>"}, + {"{S}", "<:mtg_s:415216131293446144>"}, + {"{T}", "<:mtg_tap:415258392727257088>"}, + {"{C}", "<:mtg_colorless:415216130706374666>"}, + {"{2/W}", "<:mtg_2w:415216130446065664>"}, + {"{2/U}", "<:mtg_2u:415216130429550592>"}, + {"{2/B}", "<:mtg_2b:415216130160984065>"}, + {"{2/R}", "<:mtg_2r:415216130454716436>"}, + {"{2/G}", "<:mtg_2g:415216130420899840>"}, + {"{W/U}", "<:mtg_wu:415216130970484736>"}, + {"{W/B}", "<:mtg_wb:415216131222011914>"}, + {"{U/R}", "<:mtg_ur:415216130962096128>"}, + {"{U/B}", "<:mtg_ub:415216130865758218>"}, + {"{R/W}", "<:mtg_rw:415216130878210057>"}, + {"{G/W}", "<:mtg_gw:415216130567962646>"}, + {"{G/U}", "<:mtg_gu:415216130739666945>"}, + {"{B/R}", "<:mtg_br:415216130580283394>"}, + {"{B/G}", "<:mtg_bg:415216130781609994>"}, + {"{U/P}", "<:mtg_up:415216130861432842>"}, + {"{R/P}", "<:mtg_rp:415216130597322783>"}, + {"{G/P}", "<:mtg_gp:415216130760769546>"}, + {"{W/P}", "<:mtg_wp:415216131541041172>"}, + {"{B/P}", "<:mtg_bp:415216130664169482>"} + }; } public string ConvertMana(string mana) @@ -27,6 +76,7 @@ namespace Geekbot.net.Lib.Converters mana = mana.Replace(manaTypes.Value, m); } } + return mana; } } diff --git a/Geekbot.net/Lib/Converters/MtgManaEmojis.json b/Geekbot.net/Lib/Converters/MtgManaEmojis.json deleted file mode 100644 index 8ebe75b..0000000 --- a/Geekbot.net/Lib/Converters/MtgManaEmojis.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "{0}": "<:mtg_0:415216130043412482>", - "{1}": "<:mtg_1:415216130253389835>", - "{2}": "<:mtg_2:415216130031091713>", - "{3}": "<:mtg_3:415216130467037194>", - "{4}": "<:mtg_4:415216130026635295>", - "{5}": "<:mtg_5:415216130492203008>", - "{6}": "<:mtg_6:415216130458779658>", - "{7}": "<:mtg_7:415216130190475265>", - "{8}": "<:mtg_8:415216130517630986>", - "{9}": "<:mtg_9:415216130500722689>", - "{10": "<:mtg_10:415216130450391051>", - "{11}": "<:mtg_11:415216130811101185>", - "{12}": "<:mtg_12:415216130525888532>", - "{13}": "<:mtg_13:415216130517631000>", - "{14}": "<:mtg_14:415216130165178370>", - "{15}": "<:mtg_15:415216130576089108>", - "{16}": "<:mtg_16:415216130358247425>", - "{17}": "<:mtg_17:415216130601517056>", - "{18}": "<:mtg_18:415216130462842891>", - "{19}": "<:mtg_19:415216130614099988>", - "{20}": "<:mtg_20:415216130656043038>", - "{W}": "<:mtg_white:415216131515744256>", - "{U}": "<:mtg_blue:415216130521694209>", - "{B}": "<:mtg_black:415216130873884683>", - "{R}": "<:mtg_red:415216131322806272>", - "{G}": "<:mtg_green:415216131180331009>", - "{S}": "<:mtg_s:415216131293446144>", - "{T}": "<:mtg_tap:415258392727257088>", - "{C}": "<:mtg_colorless:415216130706374666>", - "{2/W}": "<:mtg_2w:415216130446065664>", - "{2/U}": "<:mtg_2u:415216130429550592>", - "{2/B}": "<:mtg_2b:415216130160984065>", - "{2/R}": "<:mtg_2r:415216130454716436>", - "{2/G}": "<:mtg_2g:415216130420899840>", - "{W/U}": "<:mtg_wu:415216130970484736>", - "{W/B}": "<:mtg_wb:415216131222011914>", - "{U/R}": "<:mtg_ur:415216130962096128>", - "{U/B}": "<:mtg_ub:415216130865758218>", - "{R/W}": "<:mtg_rw:415216130878210057>", - "{G/W}": "<:mtg_gw:415216130567962646>", - "{G/U}": "<:mtg_gu:415216130739666945>", - "{B/R}": "<:mtg_br:415216130580283394>", - "{B/G}": "<:mtg_bg:415216130781609994>", - "{U/P}": "<:mtg_up:415216130861432842>", - "{R/P}": "<:mtg_rp:415216130597322783>", - "{G/P}": "<:mtg_gp:415216130760769546>", - "{W/P}": "<:mtg_wp:415216131541041172>", - "{B/P}": "<:mtg_bp:415216130664169482>" -} \ No newline at end of file From e564e80849c5f425dac1c729120966de5a7dbcb4 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 12:15:17 +0200 Subject: [PATCH 047/264] Copy every file in storage by default instead of listing every single one --- Geekbot.net/Geekbot.net.csproj | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index b3f537e..23f331f 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -58,31 +58,7 @@ - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - + PreserveNewest From 9cc944fcc10d7fd284de89357c7a65ff2535dce0 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 12:28:22 +0200 Subject: [PATCH 048/264] Use a single message for !mtg and show a searching message when the command starts executing --- Geekbot.net/Commands/Integrations/MagicTheGathering.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs b/Geekbot.net/Commands/Integrations/MagicTheGathering.cs index 1075c46..f9e006c 100644 --- a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs +++ b/Geekbot.net/Commands/Integrations/MagicTheGathering.cs @@ -28,6 +28,8 @@ namespace Geekbot.net.Commands.Integrations { try { + var message = await Context.Channel.SendMessageAsync($":mag: Looking up\"{cardName}\", please wait..."); + var service = new CardService(); var result = service .Where(x => x.Name, cardName) @@ -37,7 +39,7 @@ namespace Geekbot.net.Commands.Integrations var card = result.All().Value.FirstOrDefault(); if (card == null) { - await ReplyAsync("I couldn't find that card..."); + await message.ModifyAsync(properties => properties.Content = ":red_circle: I couldn't find a card with that name..."); return; } @@ -65,7 +67,11 @@ namespace Geekbot.net.Commands.Integrations if (card.Legalities != null && card.Legalities.Count > 0) eb.AddField("Legality", string.Join(", ", card.Legalities.Select(e => e.Format))); - await ReplyAsync("", false, eb.Build()); + await message.ModifyAsync(properties => + { + properties.Content = string.Empty; + properties.Embed = eb.Build(); + }); } catch (Exception e) { From 4655424fb034adbf9f0c11c60a50565ddbe8afc4 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 12:40:17 +0200 Subject: [PATCH 049/264] Remove prometheus-net from the dependencies --- Geekbot.net/Geekbot.net.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 23f331f..8fc35f4 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -43,7 +43,6 @@ - From a0b1ec44f65ef39495755326f39fd278c04d906e Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 21:46:19 +0200 Subject: [PATCH 050/264] Make it possible to connect to the database with ssl enabled --- Geekbot.net/Database/DatabaseInitializer.cs | 4 +++- Geekbot.net/Database/SqlConnectionString.cs | 5 ++++- Geekbot.net/Lib/RunParameters.cs | 6 ++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Geekbot.net/Database/DatabaseInitializer.cs b/Geekbot.net/Database/DatabaseInitializer.cs index 582327f..637e7b8 100644 --- a/Geekbot.net/Database/DatabaseInitializer.cs +++ b/Geekbot.net/Database/DatabaseInitializer.cs @@ -35,7 +35,9 @@ namespace Geekbot.net.Database Port = _runParameters.DbPort, Database = _runParameters.DbDatabase, Username = _runParameters.DbUser, - Password = _runParameters.DbPassword + Password = _runParameters.DbPassword, + RequireSsl = _runParameters.DbSsl, + TrustServerCertificate = _runParameters.DbTrustCert }); } } diff --git a/Geekbot.net/Database/SqlConnectionString.cs b/Geekbot.net/Database/SqlConnectionString.cs index 3228a05..70346eb 100644 --- a/Geekbot.net/Database/SqlConnectionString.cs +++ b/Geekbot.net/Database/SqlConnectionString.cs @@ -7,10 +7,13 @@ public string Database { get; set; } public string Username { get; set; } public string Password { get; set; } + public bool RequireSsl { get; set; } + public bool TrustServerCertificate { get; set; } public override string ToString() { - return $"Server={Host};Port={Port};Database={Database};Uid={Username};Pwd={Password};"; + var sslMode = RequireSsl ? "Require" : "Prefer"; + return $"ApplicationName=Geekbot;Server={Host};Port={Port};Database={Database};Uid={Username};Pwd={Password};SSLMode={sslMode};TrustServerCertificate={TrustServerCertificate.ToString()};"; } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index 1ddbd46..8ebed67 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -43,6 +43,12 @@ namespace Geekbot.net.Lib [Option("db-password", HelpText = "Set a posgresql password (default: empty) (env: DB_PASSWORD)")] public string DbPassword { get; set; } = ParamFallback("DB_PASSWORD", ""); + + [Option("db-require-ssl", HelpText = "Require SSL to connect to the database (default: false) (env: DB_REQUIRE_SSL)")] + public bool DbSsl { get; set; } = ParamFallback("DB_REQUIRE_SSL", false); + + [Option("db-trust-cert", HelpText = "Trust the database certificate, regardless if it is valid (default: false) (env: DB_TRUST_CERT)")] + public bool DbTrustCert { get; set; } = ParamFallback("DB_TRUST_CERT", false); // Logging [Option("db-logging", HelpText = "Enable database logging (default: false) (env: DB_LOGGING)")] From e0f17d00ea90021e1864963de6a60938087cb8b9 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 22:19:26 +0200 Subject: [PATCH 051/264] Upgrade to .NET 5 --- .gitlab-ci.yml | 2 +- Geekbot.net/Geekbot.net.csproj | 3 +-- Tests/Tests.csproj | 2 +- WikipediaApi/WikipediaApi.csproj | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 7b6b593..d6f3e15 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,7 +10,7 @@ before_script: build: stage: build - image: mcr.microsoft.com/dotnet/core/sdk:3.1 + image: mcr.microsoft.com/dotnet/core/sdk:5.0-focal artifacts: expire_in: 1h paths: diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 8fc35f4..4e13438 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -1,7 +1,7 @@  Exe - netcoreapp3.1 + net5.0 win-x64;linux-x64 derp.ico 4.2.0 @@ -53,7 +53,6 @@ 4.3.0 - diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 345dacd..eaf88a3 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -1,6 +1,6 @@  - netcoreapp3.1 + net5.0 false NU1701 xUnit1026 diff --git a/WikipediaApi/WikipediaApi.csproj b/WikipediaApi/WikipediaApi.csproj index 24c20f7..e53e3c2 100644 --- a/WikipediaApi/WikipediaApi.csproj +++ b/WikipediaApi/WikipediaApi.csproj @@ -1,6 +1,6 @@  - netcoreapp3.1 + net5.0 From f23b8099f1b5687cf17b62dfe1a33c8f951d7e32 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 19 Jun 2020 22:20:05 +0200 Subject: [PATCH 052/264] Try to create a docker image --- .gitignore | 10 +-- .gitlab-ci.yml | 62 ++++++++++--------- Dockerfile | 6 +- .../Lib/Converters/MtgManaConverter.cs | 2 - 4 files changed, 38 insertions(+), 42 deletions(-) diff --git a/.gitignore b/.gitignore index fe7e3d4..5db124b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,6 @@ -Geekbot.net/bin -Geekbot.net/obj +*/bin/ +*/obj/ Geekbot.net/tmp/ -Tests/bin -Tests/obj -Backup/ .vs/ UpgradeLog.htm .idea @@ -12,5 +9,4 @@ Geekbot.net/Logs/* !/Geekbot.net/Logs/.keep Geekbot.net.sln.DotSettings.user Geekbot.net/temp/ -WikipediaApi/bin/ -WikipediaApi/obj/ +app \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index d6f3e15..86c6459 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,46 +1,40 @@ stages: - build - - ops + - docker - deploy + - ops -before_script: - - set -e - - set -u - - set -o pipefail - -build: +Build: stage: build image: mcr.microsoft.com/dotnet/core/sdk:5.0-focal artifacts: expire_in: 1h paths: - - Geekbot.net/Binaries/ + - app script: - dotnet restore - dotnet test Tests - - dotnet publish --version-suffix ${CI_COMMIT_SHA:0:8} --configuration Release -o ./Geekbot.net/Binaries ./Geekbot.net/ + - dotnet publish --version-suffix ${CI_COMMIT_SHA:0:8} -r linux-x64 -c Release -o ./app ./Geekbot.net/ -sentry: - stage: ops - image: getsentry/sentry-cli - allow_failure: true - only: - - master - dependencies: - - build - script: - - sentry-cli releases new -p geekbot 4.2.0-${CI_COMMIT_SHA:0:8} - - sentry-cli releases set-commits --auto 4.2.0-${CI_COMMIT_SHA:0:8} - - sentry-cli releases deploys 4.2.0-${CI_COMMIT_SHA:0:8} new -e Production +Package: + stage: docker + image: docker +# only: +# - master + services: + - docker:stable-dind + variables: + IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG + script: + - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY + - docker build -t $IMAGE_TAG . + - docker push $IMAGE_TAG -deploy: +Deploy: stage: deploy image: runebaas/rsync-ssh-git only: - master - dependencies: - - build - - sentry environment: name: Production url: https://discordapp.com/oauth2/authorize?client_id=171249478546882561&scope=bot&permissions=1416834054 @@ -54,13 +48,21 @@ deploy: - rsync -rav -e "ssh -p 65432" ./Geekbot.net/Binaries/* geekbot@$DEPIP:$DEPPATH - ssh -p 65432 geekbot@$DEPIP "sudo systemctl restart geekbot.service" -mirror: - stage: deploy +Sentry: + stage: ops + image: getsentry/sentry-cli + allow_failure: true + only: + - master + script: + - sentry-cli releases new -p geekbot 4.2.0-${CI_COMMIT_SHA:0:8} + - sentry-cli releases set-commits --auto 4.2.0-${CI_COMMIT_SHA:0:8} + - sentry-cli releases deploys 4.2.0-${CI_COMMIT_SHA:0:8} new -e Production + +Github Mirror: + stage: ops image: runebaas/rsync-ssh-git only: - master - dependencies: - - build - - sentry script: - git push https://runebaas:$TOKEN@github.com/pizzaandcoffee/Geekbot.net.git origin/master:master -f diff --git a/Dockerfile b/Dockerfile index 7594bec..822471d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ -FROM microsoft/dotnet:2.1-aspnetcore-runtime +FROM mcr.microsoft.com/dotnet/core/aspnet:5.0-focal -COPY Geekbot.net/Binaries /app/ +COPY ./app /app/ EXPOSE 12995/tcp WORKDIR /app -ENTRYPOINT ./run.sh +ENTRYPOINT ./Geekbot.net diff --git a/Geekbot.net/Lib/Converters/MtgManaConverter.cs b/Geekbot.net/Lib/Converters/MtgManaConverter.cs index 7e90df0..cfd893b 100644 --- a/Geekbot.net/Lib/Converters/MtgManaConverter.cs +++ b/Geekbot.net/Lib/Converters/MtgManaConverter.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; -using System.IO; using System.Text.RegularExpressions; -using Utf8Json; namespace Geekbot.net.Lib.Converters { From 3213e10b88ef131a53d7ad53cf2cf77e0e154d29 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 00:20:00 +0200 Subject: [PATCH 053/264] Add Sumologic and Sentry to the run parameters --- Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs | 6 +++--- Geekbot.net/Lib/Logger/GeekbotLogger.cs | 6 +++--- Geekbot.net/Lib/Logger/LoggerFactory.cs | 6 +++--- Geekbot.net/Lib/RunParameters.cs | 10 ++++++++++ Geekbot.net/Program.cs | 5 ++--- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs b/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs index 7c9d8ff..cda9129 100644 --- a/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs +++ b/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs @@ -18,13 +18,13 @@ namespace Geekbot.net.Lib.ErrorHandling private readonly IRavenClient _raven; private readonly bool _errorsInChat; - public ErrorHandler(IGeekbotLogger logger, ITranslationHandler translation, bool errorsInChat) + public ErrorHandler(IGeekbotLogger logger, ITranslationHandler translation, RunParameters runParameters) { _logger = logger; _translation = translation; - _errorsInChat = errorsInChat; + _errorsInChat = runParameters.ExposeErrors; - var sentryDsn = Environment.GetEnvironmentVariable("SENTRY"); + var sentryDsn = runParameters.SentryEndpoint; if (!string.IsNullOrEmpty(sentryDsn)) { _raven = new RavenClient(sentryDsn) { Release = Constants.BotVersion(), Environment = "Production" }; diff --git a/Geekbot.net/Lib/Logger/GeekbotLogger.cs b/Geekbot.net/Lib/Logger/GeekbotLogger.cs index 09a3ecb..e2a3714 100644 --- a/Geekbot.net/Lib/Logger/GeekbotLogger.cs +++ b/Geekbot.net/Lib/Logger/GeekbotLogger.cs @@ -9,10 +9,10 @@ namespace Geekbot.net.Lib.Logger private readonly NLog.Logger _logger; private readonly JsonSerializerSettings _serializerSettings; - public GeekbotLogger(RunParameters runParameters, bool sumologicActive) + public GeekbotLogger(RunParameters runParameters) { - _logAsJson = sumologicActive || runParameters.LogJson; - _logger = LoggerFactory.CreateNLog(runParameters, sumologicActive); + _logAsJson = !string.IsNullOrEmpty(runParameters.SumologicEndpoint) || runParameters.LogJson; + _logger = LoggerFactory.CreateNLog(runParameters); _serializerSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize, diff --git a/Geekbot.net/Lib/Logger/LoggerFactory.cs b/Geekbot.net/Lib/Logger/LoggerFactory.cs index b07bcda..e31686e 100644 --- a/Geekbot.net/Lib/Logger/LoggerFactory.cs +++ b/Geekbot.net/Lib/Logger/LoggerFactory.cs @@ -9,18 +9,18 @@ namespace Geekbot.net.Lib.Logger { public class LoggerFactory { - public static NLog.Logger CreateNLog(RunParameters runParameters, bool sumologicActive) + public static NLog.Logger CreateNLog(RunParameters runParameters) { var config = new LoggingConfiguration(); - if (sumologicActive) + if (!string.IsNullOrEmpty(runParameters.SumologicEndpoint)) { Console.WriteLine("Logging Geekbot Logs to Sumologic"); config.LoggingRules.Add( new LoggingRule("*", LogLevel.Debug, LogLevel.Fatal, new SumoLogicTarget() { - Url = Environment.GetEnvironmentVariable("GEEKBOT_SUMO"), + Url = runParameters.SumologicEndpoint, SourceName = "GeekbotLogger", Layout = "${message}", UseConsoleLog = false, diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index 8ebed67..bd8ce25 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -67,6 +67,16 @@ namespace Geekbot.net.Lib [Option("api-port", HelpText = "Port on which the WebApi listens (default: 12995) (env: API_PORT)")] public string ApiPort { get; set; } = ParamFallback("API_PORT", "12995"); + /************************************ + * Intergrations * + ************************************/ + + [Option("sumologic", HelpText = "Sumologic endpoint for logging (default: null) (env: SUMOLOGIC)")] + public string SumologicEndpoint { get; set; } = ParamFallback("SUMOLOGIC"); + + [Option("sentry", HelpText = "Sentry endpoint for error reporting (default: null) (env: SENTRY)")] + public string SentryEndpoint { get; set; } = ParamFallback("SENTRY"); + /************************************ * Helper Functions * ************************************/ diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 1299583..a5b0668 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -58,8 +58,7 @@ namespace Geekbot.net logo.AppendLine(@" \____|_____|_____|_|\_\____/ \___/ |_|"); logo.AppendLine($"Version {Constants.BotVersion()} ".PadRight(41, '=')); Console.WriteLine(logo.ToString()); - var sumologicActive = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GEEKBOT_SUMO")); - var logger = new GeekbotLogger(runParameters, sumologicActive); + var logger = new GeekbotLogger(runParameters); logger.Information(LogSource.Geekbot, "Starting..."); try { @@ -169,7 +168,7 @@ namespace Geekbot.net var randomNumberGenerator = new RandomNumberGenerator(); var kvMemoryStore = new KvInInMemoryStore(); var translationHandler = new TranslationHandler(_logger, _guildSettingsManager); - var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); + var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters); services.AddSingleton(_userRepository); services.AddSingleton(_logger); From a4b914d576fd3effdded6ad13c8fd3f3db30faf8 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 00:43:59 +0200 Subject: [PATCH 054/264] Use Ansible for deployment --- .deploy.yml | 37 +++++++++++++++++++++++++++++++++++++ .gitlab-ci.yml | 31 +++++++++++++++++-------------- 2 files changed, 54 insertions(+), 14 deletions(-) create mode 100644 .deploy.yml diff --git a/.deploy.yml b/.deploy.yml new file mode 100644 index 0000000..39e3233 --- /dev/null +++ b/.deploy.yml @@ -0,0 +1,37 @@ +--- +- name: Geekbot Deploy + hosts: all + remote_user: geekbot + vars: + ansible_port: 65432 + ansible_python_interpreter: /usr/bin/python3 + tasks: + - name: Login to Gitlab Docker Registry + docker_login: + registry_url: "{{ lookup('env', 'CI_REGISTRY') }}" + username: "{{ lookup('env', 'CI_REGISTRY_USER') }}" + password: "{{ lookup('env', 'CI_REGISTRY_PASSWORD') }}" + reauthorize: yes + - name: Replace Prod Container + docker_container: + name: GeekbotProd + image: "{{ lookup('env', 'IMAGE_TAG') }}" + recreate: yes + pull: yes + restart_policy: always + keep_volumes: no + ports: + - "12995:12995" + env: + GEEKBOT_DB_HOST: "{{ lookup('env', 'GEEKBOT_DB_HOST') }}" + GEEKBOT_DB_USER: "{{ lookup('env', 'GEEKBOT_DB_USER') }}" + GEEKBOT_DB_PASSWORD: "{{ lookup('env', 'GEEKBOT_DB_PASSWORD') }}" + GEEKBOT_DB_PORT: "{{ lookup('env', 'GEEKBOT_DB_PORT') }}" + GEEKBOT_DB_DATABASE: "{{ lookup('env', 'GEEKBOT_DB_DATABASE') }}" + GEEKBOT_DB_REQUIRE_SSL: "true" + GEEKBOT_DB_TRUST_CERT: "true" + GEEKBOT_SUMOLOCIG: "{{ lookup('env', 'GEEKBOT_SUMOLOCIG') }}" + GEEKBOT_SENTRY: "{{ lookup('env', 'GEEKBOT_SENTRY') }}" + - name: Cleanup Old Container + docker_prune: + images: yes diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 86c6459..6015b14 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,6 +4,8 @@ stages: - deploy - ops +.imageTag: &IMAGE_TAG $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG + Build: stage: build image: mcr.microsoft.com/dotnet/core/sdk:5.0-focal @@ -19,12 +21,13 @@ Build: Package: stage: docker image: docker -# only: -# - master + only: + - master + - docker services: - docker:stable-dind variables: - IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG + IMAGE_TAG: *IMAGE_TAG script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $IMAGE_TAG . @@ -32,21 +35,21 @@ Package: Deploy: stage: deploy - image: runebaas/rsync-ssh-git + image: ansible/ansible-runner only: - master - environment: - name: Production - url: https://discordapp.com/oauth2/authorize?client_id=171249478546882561&scope=bot&permissions=1416834054 + - docker + variables: + ANSIBLE_NOCOWS: 1 + IMAGE_TAG: *IMAGE_TAG before_script: - - eval $(ssh-agent -s) - - mkdir -p ~/.ssh - - '[[ -f /.dockerenv ]] && echo -e "Host *\n StrictHostKeyChecking no" > ~/.ssh/config' - - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null - - chmod 700 ~/.ssh + - mkdir /root/.ssh + - cp $SSH_PRIVATE_KEY /root/.ssh/id_ed25519 + - cp $SSH_PUBLIC_KEY /root/.ssh/id_ed25519.pub + - chmod -R 600 /root/.ssh + - ssh-keyscan -p 65432 $PROD_IP > /root/.ssh/known_hosts script: - - rsync -rav -e "ssh -p 65432" ./Geekbot.net/Binaries/* geekbot@$DEPIP:$DEPPATH - - ssh -p 65432 geekbot@$DEPIP "sudo systemctl restart geekbot.service" + - ansible-playbook -i $PROD_IP, .deploy.yml Sentry: stage: ops From d9f8e9a80ecb76b89c19fbfa2445cd789088754d Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:05:51 +0200 Subject: [PATCH 055/264] Add redshift (and DigitalOcean Managed DB) compatibility and start using a string building to create the sql connection string --- .deploy.yml | 1 + Geekbot.net/Database/DatabaseInitializer.cs | 3 ++- Geekbot.net/Database/SqlConnectionString.cs | 24 +++++++++++++++++++-- Geekbot.net/Lib/RunParameters.cs | 3 +++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/.deploy.yml b/.deploy.yml index 39e3233..fd2df00 100644 --- a/.deploy.yml +++ b/.deploy.yml @@ -32,6 +32,7 @@ GEEKBOT_DB_TRUST_CERT: "true" GEEKBOT_SUMOLOCIG: "{{ lookup('env', 'GEEKBOT_SUMOLOCIG') }}" GEEKBOT_SENTRY: "{{ lookup('env', 'GEEKBOT_SENTRY') }}" + GEEKBOT_DB_REDSHIFT_COMPAT: "true" - name: Cleanup Old Container docker_prune: images: yes diff --git a/Geekbot.net/Database/DatabaseInitializer.cs b/Geekbot.net/Database/DatabaseInitializer.cs index 637e7b8..9f60d8a 100644 --- a/Geekbot.net/Database/DatabaseInitializer.cs +++ b/Geekbot.net/Database/DatabaseInitializer.cs @@ -37,7 +37,8 @@ namespace Geekbot.net.Database Username = _runParameters.DbUser, Password = _runParameters.DbPassword, RequireSsl = _runParameters.DbSsl, - TrustServerCertificate = _runParameters.DbTrustCert + TrustServerCertificate = _runParameters.DbTrustCert, + RedshiftCompatibility = _runParameters.DbRedshiftCompatibility }); } } diff --git a/Geekbot.net/Database/SqlConnectionString.cs b/Geekbot.net/Database/SqlConnectionString.cs index 70346eb..61804cf 100644 --- a/Geekbot.net/Database/SqlConnectionString.cs +++ b/Geekbot.net/Database/SqlConnectionString.cs @@ -1,4 +1,6 @@ -namespace Geekbot.net.Database +using System.Text; + +namespace Geekbot.net.Database { public class SqlConnectionString { @@ -9,11 +11,29 @@ public string Password { get; set; } public bool RequireSsl { get; set; } public bool TrustServerCertificate { get; set; } + public bool RedshiftCompatibility { get; set; } public override string ToString() { + var sb = new StringBuilder(); + sb.Append("Application Name=Geekbot;"); + + sb.Append($"Host={Host};"); + sb.Append($"Port={Port};"); + sb.Append($"Database={Database};"); + sb.Append($"Username={Username};"); + sb.Append($"Password={Password};"); + var sslMode = RequireSsl ? "Require" : "Prefer"; - return $"ApplicationName=Geekbot;Server={Host};Port={Port};Database={Database};Uid={Username};Pwd={Password};SSLMode={sslMode};TrustServerCertificate={TrustServerCertificate.ToString()};"; + sb.Append($"SSL Mode={sslMode};"); + sb.Append($"Trust Server Certificate={TrustServerCertificate.ToString()};"); + + if (RedshiftCompatibility) + { + sb.Append("Server Compatibility Mode=Redshift"); + } + + return sb.ToString(); } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/RunParameters.cs b/Geekbot.net/Lib/RunParameters.cs index bd8ce25..eb8c078 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/Geekbot.net/Lib/RunParameters.cs @@ -49,6 +49,9 @@ namespace Geekbot.net.Lib [Option("db-trust-cert", HelpText = "Trust the database certificate, regardless if it is valid (default: false) (env: DB_TRUST_CERT)")] public bool DbTrustCert { get; set; } = ParamFallback("DB_TRUST_CERT", false); + + [Option("db-redshift-compat", HelpText = "Enable compatibility for AWS Redshift and DigitalOcean Managed Database (default: false) (env: DB_REDSHIFT_COMPAT)")] + public bool DbRedshiftCompatibility { get; set; } = ParamFallback("DB_REDSHIFT_COMPAT", false); // Logging [Option("db-logging", HelpText = "Enable database logging (default: false) (env: DB_LOGGING)")] From 56f788878ad83623da69daf6b13ebddb2e1336e5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:17:17 +0200 Subject: [PATCH 056/264] Fix Sumologic environment variable in docker --- .deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.deploy.yml b/.deploy.yml index fd2df00..cf0e485 100644 --- a/.deploy.yml +++ b/.deploy.yml @@ -30,7 +30,7 @@ GEEKBOT_DB_DATABASE: "{{ lookup('env', 'GEEKBOT_DB_DATABASE') }}" GEEKBOT_DB_REQUIRE_SSL: "true" GEEKBOT_DB_TRUST_CERT: "true" - GEEKBOT_SUMOLOCIG: "{{ lookup('env', 'GEEKBOT_SUMOLOCIG') }}" + GEEKBOT_SUMOLOGIC: "{{ lookup('env', 'GEEKBOT_SUMOLOCIG') }}" GEEKBOT_SENTRY: "{{ lookup('env', 'GEEKBOT_SENTRY') }}" GEEKBOT_DB_REDSHIFT_COMPAT: "true" - name: Cleanup Old Container From 619f63067c9f4726f06cda4982b4a800c34d38aa Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:23:27 +0200 Subject: [PATCH 057/264] Remove the ability the lookup username history for moderators --- Geekbot.net/Commands/Admin/Mod.cs | 25 +++---------------- Geekbot.net/Database/Models/UserModel.cs | 2 -- .../Database/Models/UserUsedNamesModel.cs | 15 ----------- .../Lib/UserRepository/UserRepository.cs | 5 ---- 4 files changed, 3 insertions(+), 44 deletions(-) delete mode 100644 Geekbot.net/Database/Models/UserUsedNamesModel.cs diff --git a/Geekbot.net/Commands/Admin/Mod.cs b/Geekbot.net/Commands/Admin/Mod.cs index f4beb54..b0114a8 100644 --- a/Geekbot.net/Commands/Admin/Mod.cs +++ b/Geekbot.net/Commands/Admin/Mod.cs @@ -1,12 +1,9 @@ using System; -using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Discord.WebSocket; using Geekbot.net.Lib.CommandPreconditions; using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.UserRepository; namespace Geekbot.net.Commands.Admin { @@ -17,15 +14,11 @@ namespace Geekbot.net.Commands.Admin [DisableInDirectMessage] public class Mod : ModuleBase { - private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; - private readonly IUserRepository _userRepository; - public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, DiscordSocketClient client) + public Mod(IErrorHandler errorHandler) { - _userRepository = userRepositry; _errorHandler = errorHandler; - _client = client; } [Command("namehistory", RunMode = RunMode.Async)] @@ -34,23 +27,11 @@ namespace Geekbot.net.Commands.Admin { try { - var userRepo = _userRepository.Get(user.Id); - if (userRepo?.UsedNames != null) - { - var sb = new StringBuilder(); - sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:"); - foreach (var name in userRepo.UsedNames) sb.AppendLine($"- `{name.Name}`"); - await ReplyAsync(sb.ToString()); - } - else - { - await ReplyAsync($"No name changes found for {user.Username}"); - } + await Context.Channel.SendMessageAsync("This command has been removed due to low usage and excessively high database usage"); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, - "I don't have enough permissions do that"); + await _errorHandler.HandleCommandException(e, Context); } } } diff --git a/Geekbot.net/Database/Models/UserModel.cs b/Geekbot.net/Database/Models/UserModel.cs index b9c60ca..43d3a9a 100644 --- a/Geekbot.net/Database/Models/UserModel.cs +++ b/Geekbot.net/Database/Models/UserModel.cs @@ -24,7 +24,5 @@ namespace Geekbot.net.Database.Models public bool IsBot { get; set; } public DateTimeOffset Joined { get; set; } - - public List UsedNames { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Database/Models/UserUsedNamesModel.cs b/Geekbot.net/Database/Models/UserUsedNamesModel.cs deleted file mode 100644 index 48ba873..0000000 --- a/Geekbot.net/Database/Models/UserUsedNamesModel.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; - -namespace Geekbot.net.Database.Models -{ - public class UserUsedNamesModel - { - [Key] - public int Id { get; set; } - - public string Name { get; set; } - - public DateTimeOffset FirstSeen { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Lib/UserRepository/UserRepository.cs b/Geekbot.net/Lib/UserRepository/UserRepository.cs index b27a0a2..41e8e73 100644 --- a/Geekbot.net/Lib/UserRepository/UserRepository.cs +++ b/Geekbot.net/Lib/UserRepository/UserRepository.cs @@ -37,11 +37,6 @@ namespace Geekbot.net.Lib.UserRepository savedUser.AvatarUrl = user.GetAvatarUrl() ?? ""; savedUser.IsBot = user.IsBot; savedUser.Joined = user.CreatedAt; - if (savedUser.UsedNames == null) savedUser.UsedNames = new List(); - if (!savedUser.UsedNames.Any(e => e.Name.Equals(user.Username))) - { - savedUser.UsedNames.Add(new UserUsedNamesModel { Name = user.Username, FirstSeen = DateTimeOffset.Now }); - } if (isNew) { From 8f41999015f90817e556b0c2958b28fa3fb48251 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:25:28 +0200 Subject: [PATCH 058/264] Expose the web api directly on port 80 --- .deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.deploy.yml b/.deploy.yml index cf0e485..e9915ba 100644 --- a/.deploy.yml +++ b/.deploy.yml @@ -21,7 +21,7 @@ restart_policy: always keep_volumes: no ports: - - "12995:12995" + - "80:12995" env: GEEKBOT_DB_HOST: "{{ lookup('env', 'GEEKBOT_DB_HOST') }}" GEEKBOT_DB_USER: "{{ lookup('env', 'GEEKBOT_DB_USER') }}" From 194bfd3d3b61c0a8ae4534fe742ef743a8cf32fe Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:27:08 +0200 Subject: [PATCH 059/264] remove traces of the docker branch from the ci file --- .gitlab-ci.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6015b14..2e22e02 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -23,7 +23,6 @@ Package: image: docker only: - master - - docker services: - docker:stable-dind variables: @@ -38,7 +37,6 @@ Deploy: image: ansible/ansible-runner only: - master - - docker variables: ANSIBLE_NOCOWS: 1 IMAGE_TAG: *IMAGE_TAG From 279a8975c91eb8c061d1320709617d31ffaf1fd5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:42:41 +0200 Subject: [PATCH 060/264] Expose web api on port 12995 again --- .deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.deploy.yml b/.deploy.yml index e9915ba..cf0e485 100644 --- a/.deploy.yml +++ b/.deploy.yml @@ -21,7 +21,7 @@ restart_policy: always keep_volumes: no ports: - - "80:12995" + - "12995:12995" env: GEEKBOT_DB_HOST: "{{ lookup('env', 'GEEKBOT_DB_HOST') }}" GEEKBOT_DB_USER: "{{ lookup('env', 'GEEKBOT_DB_USER') }}" From d7e313c9fa996cf008dae2721f892d4bad23ca30 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 20 Jun 2020 03:43:02 +0200 Subject: [PATCH 061/264] Update readme --- readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index c7f3f33..883e553 100644 --- a/readme.md +++ b/readme.md @@ -2,13 +2,13 @@ # [Geekbot.net](https://geekbot.pizzaandcoffee.rocks/) -A General Purpose Discord Bot written in DotNet Core. +A General Purpose Discord Bot written in C# You can invite Geekbot to your server with [this link](https://discordapp.com/oauth2/authorize?client_id=171249478546882561&scope=bot&permissions=1416834054) ## Technologies -* DotNet Core 3.1 +* .NET 5 * PostgreSQL * Discord.net From 6d449608671cb47c5705d65ad6f0f367d6b9801c Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 21 Jun 2020 03:33:05 +0200 Subject: [PATCH 062/264] Rewrite the !dice command from scratch --- Geekbot.net/Commands/Utils/Dice.cs | 107 ++++++++++++++++ Geekbot.net/Commands/Utils/Dice/Dice.cs | 116 ------------------ .../Commands/Utils/Dice/DiceTypeDto.cs | 10 -- Geekbot.net/Lib/DiceParser/DiceException.cs | 13 ++ Geekbot.net/Lib/DiceParser/DiceInput.cs | 11 ++ .../Lib/DiceParser/DiceInputOptions.cs | 7 ++ Geekbot.net/Lib/DiceParser/DiceParser.cs | 102 +++++++++++++++ .../Lib/DiceParser/DieAdvantageType.cs | 9 ++ Geekbot.net/Lib/DiceParser/DieResult.cs | 30 +++++ Geekbot.net/Lib/DiceParser/IDiceParser.cs | 7 ++ Geekbot.net/Lib/DiceParser/SingleDie.cs | 72 +++++++++++ Geekbot.net/Lib/Extensions/IntExtensions.cs | 15 +++ Geekbot.net/Program.cs | 3 + 13 files changed, 376 insertions(+), 126 deletions(-) create mode 100644 Geekbot.net/Commands/Utils/Dice.cs delete mode 100644 Geekbot.net/Commands/Utils/Dice/Dice.cs delete mode 100644 Geekbot.net/Commands/Utils/Dice/DiceTypeDto.cs create mode 100644 Geekbot.net/Lib/DiceParser/DiceException.cs create mode 100644 Geekbot.net/Lib/DiceParser/DiceInput.cs create mode 100644 Geekbot.net/Lib/DiceParser/DiceInputOptions.cs create mode 100644 Geekbot.net/Lib/DiceParser/DiceParser.cs create mode 100644 Geekbot.net/Lib/DiceParser/DieAdvantageType.cs create mode 100644 Geekbot.net/Lib/DiceParser/DieResult.cs create mode 100644 Geekbot.net/Lib/DiceParser/IDiceParser.cs create mode 100644 Geekbot.net/Lib/DiceParser/SingleDie.cs create mode 100644 Geekbot.net/Lib/Extensions/IntExtensions.cs diff --git a/Geekbot.net/Commands/Utils/Dice.cs b/Geekbot.net/Commands/Utils/Dice.cs new file mode 100644 index 0000000..f570271 --- /dev/null +++ b/Geekbot.net/Commands/Utils/Dice.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using Discord.Commands; +using Geekbot.net.Lib.DiceParser; +using Geekbot.net.Lib.ErrorHandling; + +namespace Geekbot.net.Commands.Utils +{ + public class Dice : ModuleBase + { + private readonly IErrorHandler _errorHandler; + private readonly IDiceParser _diceParser; + + public Dice(IErrorHandler errorHandler, IDiceParser diceParser) + { + _errorHandler = errorHandler; + _diceParser = diceParser; + } + + // ToDo: Separate representation and logic + // ToDo: Translate + [Command("dice", RunMode = RunMode.Async)] + [Summary("Roll a dice. (use '!dice help' for a manual)")] + public async Task RollCommand([Remainder] [Summary("input")] string diceInput = "1d20") + { + try + { + if (diceInput == "help") + { + await ShowDiceHelp(); + return; + } + + var parsed = _diceParser.Parse(diceInput); + + var sb = new StringBuilder(); + sb.AppendLine($"{Context.User.Mention} :game_die:"); + foreach (var die in parsed.Dice) + { + sb.AppendLine($"**{die.DiceName}**"); + var diceResultList = new List(); + var total = 0; + + foreach (var roll in die.Roll()) + { + diceResultList.Add(roll.ToString()); + total += roll.Result; + } + + sb.AppendLine(string.Join(" | ", diceResultList)); + + if (parsed.SkillModifier != 0) + { + sb.AppendLine($"Skill: {parsed.SkillModifier}"); + } + + if (parsed.Options.ShowTotal) + { + var totalLine = $"Total: {total}"; + if (parsed.SkillModifier > 0) + { + totalLine += ($" (+{parsed.SkillModifier} = {total + parsed.SkillModifier})"); + } + + if (parsed.SkillModifier < 0) + { + totalLine += ($" ({parsed.SkillModifier} = {total - parsed.SkillModifier})"); + } + + sb.AppendLine(totalLine); + } + } + + await Context.Channel.SendMessageAsync(sb.ToString()); + } + catch (DiceException e) + { + await Context.Channel.SendMessageAsync($"**:warning: {e.DiceName} is invalid:** {e.Message}"); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } + + private async Task ShowDiceHelp() + { + var sb = new StringBuilder(); + sb.AppendLine("**__Examples__**"); + sb.AppendLine("```"); + sb.AppendLine("'!dice' - throw a 1d20"); + sb.AppendLine("'!dice 1d12' - throw a 1d12"); + sb.AppendLine("'!dice +1d20' - throw with advantage"); + sb.AppendLine("'!dice -1d20' - throw with disadvantage"); + sb.AppendLine("'!dice 1d20 +2' - throw with a +2 skill bonus"); + sb.AppendLine("'!dice 1d20 -2' - throw with a -2 skill bonus"); + sb.AppendLine("'!dice 8d6' - throw ~~a fireball~~ a 8d6"); + sb.AppendLine("'!dice 8d6 total' - calculate the total"); + sb.AppendLine("'!dice 2d20 6d6 2d4 2d12' - drop your dice pouch"); + sb.AppendLine("```"); + + await Context.Channel.SendMessageAsync(sb.ToString()); + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Utils/Dice/Dice.cs b/Geekbot.net/Commands/Utils/Dice/Dice.cs deleted file mode 100644 index c335982..0000000 --- a/Geekbot.net/Commands/Utils/Dice/Dice.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Discord.Commands; -using Geekbot.net.Lib.RandomNumberGenerator; - -namespace Geekbot.net.Commands.Utils.Dice -{ - public class Dice : ModuleBase - { - private readonly IRandomNumberGenerator _randomNumberGenerator; - - public Dice(IRandomNumberGenerator randomNumberGenerator) - { - _randomNumberGenerator = randomNumberGenerator; - } - - [Command("dice", RunMode = RunMode.Async)] - [Summary("Roll a dice.")] - public async Task RollCommand([Remainder] [Summary("dice-type")] string diceType = "1d20") - { - var splitedDices = diceType.Split("+"); - var dices = new List(); - var mod = 0; - foreach (var i in splitedDices) - { - var dice = ToDice(i); - if (dice.Sides != 0 && dice.Times != 0) - { - dices.Add(dice); - } - else if (dice.Mod != 0) - { - if (mod != 0) - { - await ReplyAsync("You can only have one mod"); - return; - } - - mod = dice.Mod; - } - } - - if (!dices.Any()) - { - await ReplyAsync( - "That is not a valid dice, examples are: 1d20, 1d6, 2d6, 1d6+2, 1d6+2d8+1d20+6, etc..."); - return; - } - - - if (dices.Any(d => d.Times > 20)) - { - await ReplyAsync("You can't throw more than 20 dices"); - return; - } - - if (dices.Any(d => d.Sides > 144)) - { - await ReplyAsync("A dice can't have more than 144 sides"); - return; - } - - var rep = new StringBuilder(); - rep.AppendLine($":game_die: {Context.User.Mention}"); - rep.Append("**Result:** "); - var resultStrings = new List(); - var total = 0; - foreach (var dice in dices) - { - var results = new List(); - for (var i = 0; i < dice.Times; i++) - { - var roll = _randomNumberGenerator.Next(1, dice.Sides); - total += roll; - results.Add(roll); - } - - resultStrings.Add($"{dice.DiceType} ({string.Join(",", results)})"); - } - - rep.Append(string.Join(" + ", resultStrings)); - if (mod != 0) - { - rep.Append($" + {mod}"); - total += mod; - } - - rep.AppendLine(); - rep.AppendLine($"**Total:** {total}"); - await ReplyAsync(rep.ToString()); - } - - private DiceTypeDto ToDice(string dice) - { - var diceParts = dice.Split('d'); - if (diceParts.Length == 2 - && int.TryParse(diceParts[0], out var times) - && int.TryParse(diceParts[1], out var max)) - return new DiceTypeDto - { - DiceType = dice, - Times = times, - Sides = max - }; - if (dice.Length == 1 - && int.TryParse(diceParts[0], out var mod)) - return new DiceTypeDto - { - Mod = mod - }; - return new DiceTypeDto(); - } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Utils/Dice/DiceTypeDto.cs b/Geekbot.net/Commands/Utils/Dice/DiceTypeDto.cs deleted file mode 100644 index 5c54792..0000000 --- a/Geekbot.net/Commands/Utils/Dice/DiceTypeDto.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Geekbot.net.Commands.Utils.Dice -{ - internal class DiceTypeDto - { - public string DiceType { get; set; } - public int Times { get; set; } - public int Sides { get; set; } - public int Mod { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/DiceException.cs b/Geekbot.net/Lib/DiceParser/DiceException.cs new file mode 100644 index 0000000..d2a66ad --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/DiceException.cs @@ -0,0 +1,13 @@ +using System; + +namespace Geekbot.net.Lib.DiceParser +{ + public class DiceException : Exception + { + public DiceException(string message) : base(message) + { + } + + public string DiceName { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/DiceInput.cs b/Geekbot.net/Lib/DiceParser/DiceInput.cs new file mode 100644 index 0000000..baca42c --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/DiceInput.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace Geekbot.net.Lib.DiceParser +{ + public class DiceInput + { + public List Dice { get; set; } = new List(); + public DiceInputOptions Options { get; set; } = new DiceInputOptions(); + public int SkillModifier { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/DiceInputOptions.cs b/Geekbot.net/Lib/DiceParser/DiceInputOptions.cs new file mode 100644 index 0000000..41f2def --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/DiceInputOptions.cs @@ -0,0 +1,7 @@ +namespace Geekbot.net.Lib.DiceParser +{ + public struct DiceInputOptions + { + public bool ShowTotal { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/DiceParser.cs b/Geekbot.net/Lib/DiceParser/DiceParser.cs new file mode 100644 index 0000000..7f90865 --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/DiceParser.cs @@ -0,0 +1,102 @@ +using System; +using System.Linq; +using System.Text.RegularExpressions; +using Geekbot.net.Lib.RandomNumberGenerator; + +namespace Geekbot.net.Lib.DiceParser +{ + public class DiceParser : IDiceParser + { + private readonly IRandomNumberGenerator _randomNumberGenerator; + private readonly Regex _inputRegex; + private readonly Regex _singleDieRegex; + + public DiceParser(IRandomNumberGenerator randomNumberGenerator) + { + _randomNumberGenerator = randomNumberGenerator; + _inputRegex = new Regex( + @"((?\+\d+d\d+)|(?\-\d+d\d+)|(?\d+d\d+)|(?(total))|(?(\+|\-)\d+))\s", + RegexOptions.Compiled | RegexOptions.IgnoreCase, + new TimeSpan(0, 0, 2)); + _singleDieRegex = new Regex( + @"\d+d\d+", + RegexOptions.Compiled | RegexOptions.IgnoreCase, + new TimeSpan(0, 0, 0, 0, 500)); + } + + public DiceInput Parse(string input) + { + // adding a whitespace at the end, otherwise the parser might pickup on false items + var inputWithExtraWhitespace = $"{input} "; + + var matches = _inputRegex.Matches(inputWithExtraWhitespace); + var result = new DiceInput(); + var resultOptions = new DiceInputOptions(); + + foreach (Match match in matches) + { + foreach (Group matchGroup in match.Groups) + { + if (matchGroup.Success) + { + switch (matchGroup.Name) + { + case "DieNormal": + result.Dice.Add(Die(matchGroup.Value, DieAdvantageType.None)); + break; + case "DieAdvantage": + result.Dice.Add(Die(matchGroup.Value, DieAdvantageType.Advantage)); + break; + case "DieDisadvantage": + result.Dice.Add(Die(matchGroup.Value, DieAdvantageType.Disadvantage)); + break; + case "Keywords": + Keywords(matchGroup.Value, ref resultOptions); + break; + case "SkillModifer": + result.SkillModifier = SkillModifer(matchGroup.Value); + break; + } + } + } + } + + if (!result.Dice.Any()) + { + result.Dice.Add(new SingleDie(_randomNumberGenerator)); + } + + result.Options = resultOptions; + + return result; + } + + private SingleDie Die(string match, DieAdvantageType advantageType) + { + var x = _singleDieRegex.Match(match).Value.Split('d'); + var die = new SingleDie(_randomNumberGenerator) + { + Amount = int.Parse(x[0]), + Sides = int.Parse(x[1]), + AdvantageType = advantageType + }; + die.ValidateDie(); + return die; + } + + private int SkillModifer(string match) + { + return int.Parse(match); + } + + private void Keywords(string match, ref DiceInputOptions options) + { + switch (match) + { + case "total": + options.ShowTotal = true; + break; + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/DieAdvantageType.cs b/Geekbot.net/Lib/DiceParser/DieAdvantageType.cs new file mode 100644 index 0000000..91818cb --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/DieAdvantageType.cs @@ -0,0 +1,9 @@ +namespace Geekbot.net.Lib.DiceParser +{ + public enum DieAdvantageType + { + Advantage, + Disadvantage, + None + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/DieResult.cs b/Geekbot.net/Lib/DiceParser/DieResult.cs new file mode 100644 index 0000000..2f99fb6 --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/DieResult.cs @@ -0,0 +1,30 @@ +using System; + +namespace Geekbot.net.Lib.DiceParser +{ + public class DieResult + { + // public int Result { get; set; } + public int Roll1 { get; set; } + public int Roll2 { get; set; } + public DieAdvantageType AdvantageType { get; set; } + + public override string ToString() + { + return AdvantageType switch + { + DieAdvantageType.Advantage => Roll1 > Roll2 ? $"(**{Roll1}**, {Roll2})" : $"({Roll1}, **{Roll2}**)", + DieAdvantageType.Disadvantage => Roll1 < Roll2 ? $"(**{Roll1}**, {Roll2})" : $"({Roll1}, **{Roll2}**)", + _ => Result.ToString() + }; + } + + public int Result => AdvantageType switch + { + DieAdvantageType.None => Roll1, + DieAdvantageType.Advantage => Math.Max(Roll1, Roll2), + DieAdvantageType.Disadvantage => Math.Min(Roll1, Roll2), + _ => 0 + }; + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/IDiceParser.cs b/Geekbot.net/Lib/DiceParser/IDiceParser.cs new file mode 100644 index 0000000..608b379 --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/IDiceParser.cs @@ -0,0 +1,7 @@ +namespace Geekbot.net.Lib.DiceParser +{ + public interface IDiceParser + { + DiceInput Parse(string input); + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/DiceParser/SingleDie.cs b/Geekbot.net/Lib/DiceParser/SingleDie.cs new file mode 100644 index 0000000..24280d1 --- /dev/null +++ b/Geekbot.net/Lib/DiceParser/SingleDie.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.RandomNumberGenerator; + +namespace Geekbot.net.Lib.DiceParser +{ + public class SingleDie + { + private readonly IRandomNumberGenerator _random; + + public SingleDie(IRandomNumberGenerator random) + { + _random = random; + } + + public int Sides { get; set; } = 20; + public int Amount { get; set; } = 1; + public DieAdvantageType AdvantageType { get; set; } = DieAdvantageType.None; + + public string DiceName => AdvantageType switch + { + DieAdvantageType.Advantage => $"{Amount}d{Sides} (with advantage)", + DieAdvantageType.Disadvantage => $"{Amount}d{Sides} (with disadvantage)", + _ => $"{Amount}d{Sides}" + }; + + public List Roll() + { + var results = new List(); + + Amount.Times(() => + { + var result = new DieResult + { + Roll1 = _random.Next(1, Sides), + AdvantageType = AdvantageType + }; + + if (AdvantageType == DieAdvantageType.Advantage || AdvantageType == DieAdvantageType.Disadvantage) + { + result.Roll2 = _random.Next(1, Sides); + } + + results.Add(result); + }); + + return results; + } + + public void ValidateDie() + { + if (Amount < 1) + { + throw new DiceException("To few dice, must be a minimum of 1"); + } + if (Amount > 24) + { + throw new DiceException("To many dice, maximum allowed is 24") { DiceName = DiceName }; + } + + if (Sides < 2) + { + throw new DiceException("Die must have at least 2 sides") { DiceName = DiceName }; + } + + if (Sides > 144) + { + throw new DiceException("Die can not have more than 144 sides") { DiceName = DiceName }; + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Lib/Extensions/IntExtensions.cs b/Geekbot.net/Lib/Extensions/IntExtensions.cs new file mode 100644 index 0000000..ed0fc10 --- /dev/null +++ b/Geekbot.net/Lib/Extensions/IntExtensions.cs @@ -0,0 +1,15 @@ +using System; + +namespace Geekbot.net.Lib.Extensions +{ + public static class IntExtensions + { + public static void Times(this int count, Action action) + { + for (var i = 0; i < count; i++) + { + action(); + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index a5b0668..3d98ad9 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -11,6 +11,7 @@ using Geekbot.net.Handlers; using Geekbot.net.Lib; using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.Converters; +using Geekbot.net.Lib.DiceParser; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.GlobalSettings; using Geekbot.net.Lib.GuildSettingsManager; @@ -169,6 +170,7 @@ namespace Geekbot.net var kvMemoryStore = new KvInInMemoryStore(); var translationHandler = new TranslationHandler(_logger, _guildSettingsManager); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters); + var diceParser = new DiceParser(randomNumberGenerator); services.AddSingleton(_userRepository); services.AddSingleton(_logger); @@ -183,6 +185,7 @@ namespace Geekbot.net services.AddSingleton(kvMemoryStore); services.AddSingleton(_globalSettings); services.AddSingleton(errorHandler); + services.AddSingleton(diceParser); services.AddSingleton(translationHandler); services.AddSingleton(_reactionListener); services.AddSingleton(_guildSettingsManager); From acd1cee16cbdc2c695be7662cb929fc5da0f6581 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 21 Jun 2020 03:43:11 +0200 Subject: [PATCH 063/264] Reformat !dice help --- Geekbot.net/Commands/Utils/Dice.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Dice.cs b/Geekbot.net/Commands/Utils/Dice.cs index f570271..2cd2e19 100644 --- a/Geekbot.net/Commands/Utils/Dice.cs +++ b/Geekbot.net/Commands/Utils/Dice.cs @@ -90,15 +90,15 @@ namespace Geekbot.net.Commands.Utils var sb = new StringBuilder(); sb.AppendLine("**__Examples__**"); sb.AppendLine("```"); - sb.AppendLine("'!dice' - throw a 1d20"); - sb.AppendLine("'!dice 1d12' - throw a 1d12"); - sb.AppendLine("'!dice +1d20' - throw with advantage"); - sb.AppendLine("'!dice -1d20' - throw with disadvantage"); - sb.AppendLine("'!dice 1d20 +2' - throw with a +2 skill bonus"); - sb.AppendLine("'!dice 1d20 -2' - throw with a -2 skill bonus"); - sb.AppendLine("'!dice 8d6' - throw ~~a fireball~~ a 8d6"); - sb.AppendLine("'!dice 8d6 total' - calculate the total"); - sb.AppendLine("'!dice 2d20 6d6 2d4 2d12' - drop your dice pouch"); + sb.AppendLine("!dice - throw a 1d20"); + sb.AppendLine("!dice 1d12 - throw a 1d12"); + sb.AppendLine("!dice +1d20 - throw with advantage"); + sb.AppendLine("!dice -1d20 - throw with disadvantage"); + sb.AppendLine("!dice 1d20 +2 - throw with a +2 skill bonus"); + sb.AppendLine("!dice 1d20 -2 - throw with a -2 skill bonus"); + sb.AppendLine("!dice 8d6 - throw a fireball 🔥"); + sb.AppendLine("!dice 8d6 total - calculate the total"); + sb.AppendLine("!dice 2d20 6d6 2d12 - drop your dice pouch"); sb.AppendLine("```"); await Context.Channel.SendMessageAsync(sb.ToString()); From 859db4ebddc4322ab1745c8b7f5744574813b465 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 21 Jun 2020 15:49:18 +0200 Subject: [PATCH 064/264] Add some unit tests for the dice parser --- Tests/Lib/DiceParser/DiceParser.test.cs | 209 ++++++++++++++++++++++++ Tests/Lib/DiceParser/SingleDie.test.cs | 125 ++++++++++++++ 2 files changed, 334 insertions(+) create mode 100644 Tests/Lib/DiceParser/DiceParser.test.cs create mode 100644 Tests/Lib/DiceParser/SingleDie.test.cs diff --git a/Tests/Lib/DiceParser/DiceParser.test.cs b/Tests/Lib/DiceParser/DiceParser.test.cs new file mode 100644 index 0000000..48a362c --- /dev/null +++ b/Tests/Lib/DiceParser/DiceParser.test.cs @@ -0,0 +1,209 @@ +using System.Collections.Generic; +using System.Text.Json; +using Geekbot.net.Lib.DiceParser; +using Geekbot.net.Lib.RandomNumberGenerator; +using Xunit; +using YamlDotNet.Serialization; + +namespace Tests.Lib.DiceParser +{ + public class DiceParserTest + { + private static readonly RandomNumberGenerator _randomNumberGenerator = new RandomNumberGenerator(); + + public struct DiceParserTestDto + { + public string Input { get; set; } + public DiceInput Expected { get; set; } + } + + public static TestData DiceParserTestData => + new TestData + { + { + "Empty Input", + new DiceParserTestDto + { + Input = "", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 1, + Sides = 20, + AdvantageType = DieAdvantageType.None + } + } + } + } + }, + { + "Simple 1d20 input", + new DiceParserTestDto + { + Input = "1d20", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 1, + Sides = 20, + AdvantageType = DieAdvantageType.None + } + } + } + } + }, + { + "2d8 with advantage", + new DiceParserTestDto + { + Input = "+2d8", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 2, + Sides = 8, + AdvantageType = DieAdvantageType.Advantage + } + } + } + } + }, + { + "2d8 with disadvantage", + new DiceParserTestDto + { + Input = "-2d8", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 2, + Sides = 8, + AdvantageType = DieAdvantageType.Disadvantage + } + } + } + } + }, + { + "multiple dice", + new DiceParserTestDto + { + Input = "2d8 2d6", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 2, + Sides = 8 + }, + new SingleDie(_randomNumberGenerator) + { + Amount = 2, + Sides = 6 + } + } + } + } + }, + { + "with skill modifier, no dice", + new DiceParserTestDto + { + Input = "+2", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 1, + Sides = 20 + } + }, + SkillModifier = 2 + } + } + }, + { + "8d6 with total", + new DiceParserTestDto + { + Input = "8d6 total", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 8, + Sides = 6 + } + }, + Options = new DiceInputOptions + { + ShowTotal = true + } + } + } + }, + { + "All posibilities", + new DiceParserTestDto + { + Input = "2d20 +1d20 -1d20 +1 total", + Expected = new DiceInput() + { + Dice = new List + { + new SingleDie(_randomNumberGenerator) + { + Amount = 2, + Sides = 20 + }, + new SingleDie(_randomNumberGenerator) + { + Amount = 1, + Sides = 20, + AdvantageType = DieAdvantageType.Advantage + }, + new SingleDie(_randomNumberGenerator) + { + Amount = 1, + Sides = 20, + AdvantageType = DieAdvantageType.Disadvantage + }, + }, + Options = new DiceInputOptions + { + ShowTotal = true + }, + SkillModifier = 1 + } + } + }, + }; + + [Theory, MemberData(nameof(DiceParserTestData))] + public void DiceParserTestFunc(string testName, DiceParserTestDto testData) + { + var parser = new Geekbot.net.Lib.DiceParser.DiceParser(_randomNumberGenerator); + var result = parser.Parse(testData.Input); + + Assert.Equal(JsonSerializer.Serialize(result), JsonSerializer.Serialize(testData.Expected)); + } + } +} \ No newline at end of file diff --git a/Tests/Lib/DiceParser/SingleDie.test.cs b/Tests/Lib/DiceParser/SingleDie.test.cs new file mode 100644 index 0000000..2309f98 --- /dev/null +++ b/Tests/Lib/DiceParser/SingleDie.test.cs @@ -0,0 +1,125 @@ +using Geekbot.net.Lib.DiceParser; +using Geekbot.net.Lib.RandomNumberGenerator; +using Xunit; + +namespace Tests.Lib.DiceParser +{ + public class SingleDieTest + { + public struct SingleDieNameTestDto + { + public DieAdvantageType AdvantageType { get; set; } + public string Expected { get; set; } + } + + public static TestData SingleDieNameTestData => new TestData + { + { + "No advantage", + new SingleDieNameTestDto() + { + AdvantageType = DieAdvantageType.None, + Expected = "1d20" + } + }, + { + "With advantage", + new SingleDieNameTestDto() + { + AdvantageType = DieAdvantageType.Advantage, + Expected = "1d20 (with advantage)" + } + }, + { + "With disadvantage", + new SingleDieNameTestDto() + { + AdvantageType = DieAdvantageType.Disadvantage, + Expected = "1d20 (with disadvantage)" + } + } + }; + + [Theory, MemberData(nameof(SingleDieNameTestData))] + public void SingleDieNameTestFunc(string testName, SingleDieNameTestDto testData) + { + var die = new SingleDie(new RandomNumberGenerator()) {AdvantageType = testData.AdvantageType}; + Assert.Equal(die.DiceName, testData.Expected); + } + + public struct SingleDieValidationTestDto + { + public int Sides { get; set; } + public int Amount { get; set; } + public bool PassValidation { get; set; } + } + + public static TestData SingleDieValidationTestData => new TestData + { + { + "To many sides", + new SingleDieValidationTestDto() + { + Amount = 1, + Sides = 200, + PassValidation = false + } + }, + { + "To few sides", + new SingleDieValidationTestDto() + { + Amount = 1, + Sides = 1, + PassValidation = false + } + }, + { + "To many Dice", + new SingleDieValidationTestDto() + { + Amount = 200, + Sides = 20, + PassValidation = false + } + }, + { + "To few Dice", + new SingleDieValidationTestDto() + { + Amount = 0, + Sides = 20, + PassValidation = false + } + }, + { + "Correct Dice", + new SingleDieValidationTestDto() + { + Amount = 1, + Sides = 20, + PassValidation = true + } + } + }; + + [Theory, MemberData(nameof(SingleDieValidationTestData))] + public void SingleDieValidationTestFunc(string testName, SingleDieValidationTestDto testData) + { + var die = new SingleDie(new RandomNumberGenerator()) + { + Amount = testData.Amount, + Sides = testData.Sides + }; + + if (testData.PassValidation) + { + die.ValidateDie(); + } + else + { + Assert.Throws(() => die.ValidateDie()); + } + } + } +} \ No newline at end of file From cc227747295afb9eae1b1fd365d0d959b779c50d Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 21 Jun 2020 21:12:34 +0200 Subject: [PATCH 065/264] Make sure a die can actually land on its highest number --- Geekbot.net/Lib/DiceParser/SingleDie.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Geekbot.net/Lib/DiceParser/SingleDie.cs b/Geekbot.net/Lib/DiceParser/SingleDie.cs index 24280d1..582fe29 100644 --- a/Geekbot.net/Lib/DiceParser/SingleDie.cs +++ b/Geekbot.net/Lib/DiceParser/SingleDie.cs @@ -32,7 +32,7 @@ namespace Geekbot.net.Lib.DiceParser { var result = new DieResult { - Roll1 = _random.Next(1, Sides), + Roll1 = _random.Next(1, Sides + 1), AdvantageType = AdvantageType }; From 580a514ce5c648a72c3d4deda0eec8cf07c026b3 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 25 Jun 2020 15:12:41 +0200 Subject: [PATCH 066/264] Rework the media provider --- .../Commands/Randomness/RandomAnimals.cs | 24 ++-- Geekbot.net/Lib/Media/IMediaProvider.cs | 9 +- Geekbot.net/Lib/Media/MediaProvider.cs | 135 +++++------------- Geekbot.net/Lib/Media/MediaType.cs | 14 ++ Geekbot.net/Program.cs | 2 +- Geekbot.net/Storage/{pinguins => penguins} | 24 ++-- 6 files changed, 72 insertions(+), 136 deletions(-) create mode 100644 Geekbot.net/Lib/Media/MediaType.cs rename Geekbot.net/Storage/{pinguins => penguins} (99%) diff --git a/Geekbot.net/Commands/Randomness/RandomAnimals.cs b/Geekbot.net/Commands/Randomness/RandomAnimals.cs index 8562908..47b6ea6 100644 --- a/Geekbot.net/Commands/Randomness/RandomAnimals.cs +++ b/Geekbot.net/Commands/Randomness/RandomAnimals.cs @@ -18,7 +18,7 @@ namespace Geekbot.net.Commands.Randomness [Summary("Get a random panda image")] public async Task Panda() { - await ReplyAsync("", false, Eb(_mediaProvider.GetPanda())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Panda))); } [Command("croissant", RunMode = RunMode.Async)] @@ -26,50 +26,50 @@ namespace Geekbot.net.Commands.Randomness [Summary("Get a random croissant image")] public async Task Croissant() { - await ReplyAsync("", false, Eb(_mediaProvider.GetCrossant())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Croissant))); } [Command("pumpkin", RunMode = RunMode.Async)] [Summary("Get a random pumpkin image")] public async Task Pumpkin() { - await ReplyAsync("", false, Eb(_mediaProvider.GetPumpkin())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Pumpkin))); } [Command("squirrel", RunMode = RunMode.Async)] [Summary("Get a random squirrel image")] public async Task Squirrel() { - await ReplyAsync("", false, Eb(_mediaProvider.GetSquirrel())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Squirrel))); } [Command("turtle", RunMode = RunMode.Async)] [Summary("Get a random turtle image")] public async Task Turtle() { - await ReplyAsync("", false, Eb(_mediaProvider.GetTurtle())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Turtle))); } - [Command("pinguin", RunMode = RunMode.Async)] - [Alias("pingu")] - [Summary("Get a random pinguin image")] - public async Task Pinguin() + [Command("penguin", RunMode = RunMode.Async)] + [Alias("pengu")] + [Summary("Get a random penguin image")] + public async Task Penguin() { - await ReplyAsync("", false, Eb(_mediaProvider.GetPinguin())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Penguin))); } [Command("fox", RunMode = RunMode.Async)] [Summary("Get a random fox image")] public async Task Fox() { - await ReplyAsync("", false, Eb(_mediaProvider.GetFox())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Fox))); } [Command("dab", RunMode = RunMode.Async)] [Summary("Get a random dab image")] public async Task Dab() { - await ReplyAsync("", false, Eb(_mediaProvider.GetDab())); + await ReplyAsync("", false, Eb(_mediaProvider.GetMedia(MediaType.Dab))); } private static Embed Eb(string image) diff --git a/Geekbot.net/Lib/Media/IMediaProvider.cs b/Geekbot.net/Lib/Media/IMediaProvider.cs index 33a0d7c..63c0f41 100644 --- a/Geekbot.net/Lib/Media/IMediaProvider.cs +++ b/Geekbot.net/Lib/Media/IMediaProvider.cs @@ -2,13 +2,6 @@ { public interface IMediaProvider { - string GetPanda(); - string GetCrossant(); - string GetSquirrel(); - string GetPumpkin(); - string GetTurtle(); - string GetPinguin(); - string GetFox(); - string GetDab(); + string GetMedia(MediaType type); } } \ No newline at end of file diff --git a/Geekbot.net/Lib/Media/MediaProvider.cs b/Geekbot.net/Lib/Media/MediaProvider.cs index f7ea9df..45524de 100644 --- a/Geekbot.net/Lib/Media/MediaProvider.cs +++ b/Geekbot.net/Lib/Media/MediaProvider.cs @@ -1,133 +1,62 @@ using System; using System.IO; using Geekbot.net.Lib.Logger; +using Geekbot.net.Lib.RandomNumberGenerator; namespace Geekbot.net.Lib.Media { public class MediaProvider : IMediaProvider { - private readonly Random _random; + private readonly IRandomNumberGenerator _random; private readonly IGeekbotLogger _logger; private string[] _pandaImages; private string[] _croissantImages; private string[] _squirrelImages; private string[] _pumpkinImages; private string[] _turtlesImages; - private string[] _pinguinImages; + private string[] _penguinImages; private string[] _foxImages; private string[] _dabImages; - public MediaProvider(IGeekbotLogger logger) + public MediaProvider(IGeekbotLogger logger, IRandomNumberGenerator random) { - _random = new Random(); + _random = random; _logger = logger; logger.Information(LogSource.Geekbot, "Loading Media Files"); ; - LoadPandas(); - BakeCroissants(); - LoadSquirrels(); - LoadPumpkins(); - LoadTurtles(); - LoadPinguins(); - LoadFoxes(); - LoadDab(); - } - - private void LoadPandas() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pandas")); - _pandaImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_pandaImages.Length} Panda Images"); - } - - private void BakeCroissants() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/croissant")); - _croissantImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_croissantImages.Length} Croissant Images"); - } - - private void LoadSquirrels() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/squirrel")); - _squirrelImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_squirrelImages.Length} Squirrel Images"); - } - - private void LoadPumpkins() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pumpkin")); - _pumpkinImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_pumpkinImages.Length} Pumpkin Images"); - } - - private void LoadTurtles() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/turtles")); - _turtlesImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_turtlesImages.Length} Turtle Images"); - } - - private void LoadPinguins() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pinguins")); - _pinguinImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_pinguinImages.Length} Pinguin Images"); - } - - private void LoadFoxes() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/foxes")); - _foxImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_foxImages.Length} Foxes Images"); - } - - private void LoadDab() - { - var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/dab")); - _dabImages = rawLinks.Split("\n"); - _logger.Trace(LogSource.Geekbot, $"Loaded {_dabImages.Length} Dab Images"); + LoadMedia("./Storage/pandas", ref _pandaImages); + LoadMedia("./Storage/croissant", ref _croissantImages); + LoadMedia("./Storage/squirrel", ref _squirrelImages); + LoadMedia("./Storage/pumpkin", ref _pumpkinImages); + LoadMedia("./Storage/turtles", ref _turtlesImages); + LoadMedia("./Storage/penguins", ref _penguinImages); + LoadMedia("./Storage/foxes", ref _foxImages); + LoadMedia("./Storage/dab", ref _dabImages); } - public string GetPanda() + private void LoadMedia(string path, ref string[] storage) { - return _pandaImages[_random.Next(0, _pandaImages.Length)]; + var rawLinks = File.ReadAllText(Path.GetFullPath(path)); + storage = rawLinks.Split("\n"); + _logger.Trace(LogSource.Geekbot, $"Loaded {storage.Length} Images from ${path}"); } - - public string GetCrossant() + + public string GetMedia(MediaType type) { - return _croissantImages[_random.Next(0, _croissantImages.Length)]; - } - - public string GetSquirrel() - { - return _squirrelImages[_random.Next(0, _squirrelImages.Length)]; - } - - public string GetPumpkin() - { - return _pumpkinImages[_random.Next(0, _pumpkinImages.Length)]; - } - - public string GetTurtle() - { - return _turtlesImages[_random.Next(0, _turtlesImages.Length)]; - } - - public string GetPinguin() - { - return _pinguinImages[_random.Next(0, _pinguinImages.Length)]; - } - - public string GetFox() - { - return _foxImages[_random.Next(0, _foxImages.Length)]; - } - - public string GetDab() - { - return _dabImages[_random.Next(0, _dabImages.Length)]; + var collection = type switch + { + MediaType.Panda => _pandaImages, + MediaType.Croissant => _croissantImages, + MediaType.Squirrel => _squirrelImages, + MediaType.Pumpkin => _pumpkinImages, + MediaType.Turtle => _turtlesImages, + MediaType.Penguin => _penguinImages, + MediaType.Fox => _foxImages, + MediaType.Dab => _dabImages + }; + + return collection[_random.Next(0, collection.Length)]; } } } \ No newline at end of file diff --git a/Geekbot.net/Lib/Media/MediaType.cs b/Geekbot.net/Lib/Media/MediaType.cs new file mode 100644 index 0000000..aee317b --- /dev/null +++ b/Geekbot.net/Lib/Media/MediaType.cs @@ -0,0 +1,14 @@ +namespace Geekbot.net.Lib.Media +{ + public enum MediaType + { + Panda, + Croissant, + Squirrel, + Pumpkin, + Turtle, + Penguin, + Fox, + Dab + } +} \ No newline at end of file diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 3d98ad9..c96e2f5 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -160,13 +160,13 @@ namespace Geekbot.net _reactionListener = new ReactionListener(_databaseInitializer.Initialize()); _guildSettingsManager = new GuildSettingsManager(_databaseInitializer.Initialize()); var fortunes = new FortunesProvider(_logger); - var mediaProvider = new MediaProvider(_logger); var malClient = new MalClient(_globalSettings, _logger); var levelCalc = new LevelCalc(); var emojiConverter = new EmojiConverter(); var mtgManaConverter = new MtgManaConverter(); var wikipediaClient = new WikipediaClient(); var randomNumberGenerator = new RandomNumberGenerator(); + var mediaProvider = new MediaProvider(_logger, randomNumberGenerator); var kvMemoryStore = new KvInInMemoryStore(); var translationHandler = new TranslationHandler(_logger, _guildSettingsManager); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters); diff --git a/Geekbot.net/Storage/pinguins b/Geekbot.net/Storage/penguins similarity index 99% rename from Geekbot.net/Storage/pinguins rename to Geekbot.net/Storage/penguins index 631f9d0..d38d853 100644 --- a/Geekbot.net/Storage/pinguins +++ b/Geekbot.net/Storage/penguins @@ -1,13 +1,13 @@ -https://i.ytimg.com/vi/Qr6sULJnu2o/maxresdefault.jpg -https://www.apex-expeditions.com/wp-content/uploads/2015/08/newzealandSlider_Macquarie_ElephantSealKingPenguins_GRiehle_1366x601.jpg -https://www.birdlife.org/sites/default/files/styles/1600/public/slide.jpg?itok=HRhQfA1S -http://experimentexchange.com/wp-content/uploads/2016/07/penguins-fact.jpg -http://images.mentalfloss.com/sites/default/files/styles/mf_image_16x9/public/istock-511366776.jpg?itok=cWhdWNZ8&resize=1100x619 -https://www.thevaporplace.ch/media/catalog/product/cache/1/thumbnail/800x800/9df78eab33525d08d6e5fb8d27136e95/a/t/atopack_penguin-15.jpg -https://www.superfastbusiness.com/wp-content/uploads/2015/10/real-time-penguin-algorithm-featured.jpg -http://www.antarctica.gov.au/__data/assets/image/0011/147737/varieties/antarctic.jpg -https://vignette.wikia.nocookie.net/robloxcreepypasta/images/1/11/AAEAAQAAAAAAAAdkAAAAJDc3YzkyYjJhLTYyZjctNDY2Mi04M2VjLTg4NjY4ZjgwYzRmNg.png/revision/latest?cb=20180207200526 -https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR3xV0lhpZuhT8Nmm6LaITsppZ7VfWcWXuyu2cPHrlv_dt_M92K5g -http://goboiano.com/wp-content/uploads/2017/04/Penguin-Kemeno-Friends-Waifu.jpg -https://cdn.yoast.com/app/uploads/2015/10/Penguins_1200x628.png +https://i.ytimg.com/vi/Qr6sULJnu2o/maxresdefault.jpg +https://www.apex-expeditions.com/wp-content/uploads/2015/08/newzealandSlider_Macquarie_ElephantSealKingPenguins_GRiehle_1366x601.jpg +https://www.birdlife.org/sites/default/files/styles/1600/public/slide.jpg?itok=HRhQfA1S +http://experimentexchange.com/wp-content/uploads/2016/07/penguins-fact.jpg +http://images.mentalfloss.com/sites/default/files/styles/mf_image_16x9/public/istock-511366776.jpg?itok=cWhdWNZ8&resize=1100x619 +https://www.thevaporplace.ch/media/catalog/product/cache/1/thumbnail/800x800/9df78eab33525d08d6e5fb8d27136e95/a/t/atopack_penguin-15.jpg +https://www.superfastbusiness.com/wp-content/uploads/2015/10/real-time-penguin-algorithm-featured.jpg +http://www.antarctica.gov.au/__data/assets/image/0011/147737/varieties/antarctic.jpg +https://vignette.wikia.nocookie.net/robloxcreepypasta/images/1/11/AAEAAQAAAAAAAAdkAAAAJDc3YzkyYjJhLTYyZjctNDY2Mi04M2VjLTg4NjY4ZjgwYzRmNg.png/revision/latest?cb=20180207200526 +https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR3xV0lhpZuhT8Nmm6LaITsppZ7VfWcWXuyu2cPHrlv_dt_M92K5g +http://goboiano.com/wp-content/uploads/2017/04/Penguin-Kemeno-Friends-Waifu.jpg +https://cdn.yoast.com/app/uploads/2015/10/Penguins_1200x628.png https://images.justwatch.com/backdrop/8611153/s1440/pingu \ No newline at end of file From c94d73736d6bf5a70273cd2ed020bcc106da9123 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 30 Jun 2020 17:54:01 +0200 Subject: [PATCH 067/264] Use greetings.dev instead of hardcoded greetings --- .../Randomness/Greetings/GreetingBaseDto.cs | 11 + .../Randomness/Greetings/GreetingDto.cs | 8 +- .../Randomness/Greetings/GreetingProvider.cs | 1595 ----------------- .../Randomness/Greetings/Greetings.cs | 28 +- 4 files changed, 37 insertions(+), 1605 deletions(-) create mode 100644 Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs delete mode 100644 Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs b/Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs new file mode 100644 index 0000000..7f4e02f --- /dev/null +++ b/Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs @@ -0,0 +1,11 @@ +namespace Geekbot.net.Commands.Randomness.Greetings +{ + public class GreetingBaseDto + { + public string Language { get; set; } + public string LanguageNative { get; set; } + public string LanguageCode { get; set; } + public string Script { get; set; } + public GreetingDto Primary { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs b/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs index 42792a5..c967885 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs +++ b/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs @@ -2,9 +2,9 @@ namespace Geekbot.net.Commands.Randomness.Greetings { public class GreetingDto { - public string Text { get; set; } - public string Language { get; set; } - public string Dialect { get; set; } = null; - public string Romanization { get; set; } = null; + public string Text { get; set; } + public string Dialect { get; set; } + public string Romanization { get; set; } + public string[] Use { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs b/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs deleted file mode 100644 index a15f32e..0000000 --- a/Geekbot.net/Commands/Randomness/Greetings/GreetingProvider.cs +++ /dev/null @@ -1,1595 +0,0 @@ -using System.Collections.Generic; - -namespace Geekbot.net.Commands.Randomness.Greetings -{ - public class GreetingProvider - { - public static readonly List Greetings = new List - { - new GreetingDto() - { - Text = "Бзиа збаша", - Language = "Abkhaz", - Romanization = "Bzia zbaşa" - }, - new GreetingDto() - { - Text = "Фэсапщы", - Language = "Adyghe", - Romanization = "Fèsapŝy" - }, - new GreetingDto() - { - Text = "Haai", - Language = "Afrikaans" - }, - new GreetingDto() - { - Text = "Kamusta", - Language = "Aklan" - }, - new GreetingDto() - { - Text = "Fâla", - Language = "Albanian" - }, - new GreetingDto() - { - Text = "Ç'kemi", - Language = "Albanian" - }, - new GreetingDto() - { - Text = "Aang", - Language = "Aleut" - }, - new GreetingDto() - { - Text = "Hallo", - Language = "Alsatian" - }, - new GreetingDto() - { - Text = "Эзендер", - Language = "Altay", - Romanization = "Ezender" - }, - new GreetingDto() - { - Text = "ሰላም።", - Language = "Amharic", - Romanization = "sälam" - }, - new GreetingDto() - { - Text = "السلام عليكم", - Language = "Arabic", - Romanization = "as-salām 'alaykum" - }, - new GreetingDto() - { - Text = "Ola", - Language = "Aragonese" - }, - new GreetingDto() - { - Text = "Shl'am lak", - Language = "Aramaic" - }, - new GreetingDto() - { - Text = "Héébee", - Language = "Arapaho" - }, - new GreetingDto() - { - Text = "Բարեւ", - Language = "Armenian", - Romanization = "Parev" - }, - new GreetingDto() - { - Text = "Bunâ dzuâ", - Language = "Aromanian" - }, - new GreetingDto() - { - Text = "Werte", - Language = "Arrernte" - }, - new GreetingDto() - { - Text = "নমস্কাৰ", - Language = "Assamese", - Romanization = "নমস্কাৰ" - }, - new GreetingDto() - { - Text = "Hola", - Language = "Asturian" - }, - new GreetingDto() - { - Text = "Kwei", - Language = "Atikamekw" - }, - new GreetingDto() - { - Text = "Laphi!", - Language = "Aymara" - }, - new GreetingDto() - { - Text = "Salam", - Language = "Azerbaijani" - }, - new GreetingDto() - { - Text = "Swastyastu", - Language = "Balinese" - }, - new GreetingDto() - { - Text = "I ni ce", - Language = "Bambara" - }, - new GreetingDto() - { - Text = "Haku'", - Language = "Barbareño" - }, - new GreetingDto() - { - Text = "сәләм", - Language = "Bashkir", - Romanization = "sәlәm" - }, - new GreetingDto() - { - Text = "Kaixo", - Language = "Basque" - }, - new GreetingDto() - { - Text = "Horas", - Language = "Batak" - }, - new GreetingDto() - { - Text = "მარშიხ ვალ", - Language = "Batsbi", - Romanization = "Maršix val" - }, - new GreetingDto() - { - Text = "Seavus", - Language = "Bavarian" - }, - new GreetingDto() - { - Text = "Вітаю", - Language = "Belarusian", - Romanization = "Vіtaju" - }, - new GreetingDto() - { - Text = "Shani", - Language = "Bemba" - }, - new GreetingDto() - { - Text = "নমস্কার", - Language = "Bengali", - Romanization = "Nômôskar", - Dialect = "Hindus" - }, - new GreetingDto() - { - Text = "আসসালামু আলাইকুম", - Language = "Bengali", - Romanization = "Asôlamu alaikum", - Dialect = "Muslims" - }, - new GreetingDto() - { - Text = "प्रणाम", - Language = "Bhojpuri", - Romanization = "prannam" - }, - new GreetingDto() - { - Text = "Hello", - Language = "Bikol" - }, - new GreetingDto() - { - Text = "Halo", - Language = "Bislama" - }, - new GreetingDto() - { - Text = "Dobar dan", - Language = "Bosnian" - }, - new GreetingDto() - { - Text = "Salud", - Language = "Breton" - }, - new GreetingDto() - { - Text = "Здравейте", - Language = "Bulgarian" - }, - new GreetingDto() - { - Text = "မဂႆလာပၝ", - Language = "Burmese", - Romanization = "min-ga-la-ba" - }, - new GreetingDto() - { - Text = "Olá", - Language = "Cape Verdean Creole" - }, - new GreetingDto() - { - Text = "Hola", - Language = "Catalan" - }, - new GreetingDto() - { - Text = "Hello", - Language = "Cebuano" - }, - new GreetingDto() - { - Text = "Kopisanangan", - Language = "Central Dusun" - }, - new GreetingDto() - { - Text = "Que tal?", - Language = "Chabacano de Zamboanga" - }, - new GreetingDto() - { - Text = "Ola", - Language = "Chabacano de Cavite" - }, - new GreetingDto() - { - Text = "Håfa ådai", - Language = "Chamorro", - Dialect = "Guam" - }, - new GreetingDto() - { - Text = "Hafa Adai", - Language = "Chamorro", - Dialect = "North Marianas" - }, - new GreetingDto() - { - Text = "Салам", - Language = "Chechen", - Romanization = "Salam" - }, - new GreetingDto() - { - Text = "ᎣᏏᏲ", - Language = "Cherokee", - Romanization = "Osiyo" - }, - new GreetingDto() - { - Text = "Moni", - Language = "Chichewa" - }, - new GreetingDto() - { - Text = "你好", - Language = "Chinese", - Romanization = "nǐ hǎo", - Dialect = "Mandarin" - }, - new GreetingDto() - { - Text = "ʔédlánet’é", - Language = "Chipewyan" - }, - new GreetingDto() - { - Text = "Halito", - Language = "Choctaw" - }, - new GreetingDto() - { - Text = "Ran annim", - Language = "Chuukese" - }, - new GreetingDto() - { - Text = "Салам!", - Language = "Chuvash", - Romanization = "Salam!" - }, - new GreetingDto() - { - Text = "Guuten takh!", - Language = "Cimbrian" - }, - new GreetingDto() - { - Text = "Kopivosian", - Language = "Coastal Kadazan" - }, - new GreetingDto() - { - Text = "Marʉ́awe", - Language = "Comanche" - }, - new GreetingDto() - { - Text = "Dydh da", - Language = "Cornish" - }, - new GreetingDto() - { - Text = "Salute", - Language = "Corsican" - }, - new GreetingDto() - { - Text = "ᑕᓂᓯ", - Language = "Cree", - Romanization = "Tanisi" - }, - new GreetingDto() - { - Text = "Bok", - Language = "Croatian" - }, - new GreetingDto() - { - Text = "Sho'daache", - Language = "Crow" - }, - new GreetingDto() - { - Text = "Míyaxwe", - Language = "Cupeño" - }, - new GreetingDto() - { - Text = "Hello", - Language = "Cuyonon" - }, - new GreetingDto() - { - Text = "Ahoj", - Language = "Czech" - }, - new GreetingDto() - { - Text = "Hej", - Language = "Danish" - }, - new GreetingDto() - { - Text = "ااسال م عليكم", - Language = "Dari", - Romanization = "As-salâmo 'alaykom" - }, - new GreetingDto() - { - Text = "Misawa", - Language = "Dholuo" - }, - new GreetingDto() - { - Text = "Goededag", - Language = "Dutch" - }, - new GreetingDto() - { - Text = "སྐུ་གཟུགས་བཟང་པོ་ལགས།", - Language = "Dzongkha", - Romanization = "Kuzu zangpo la" - }, - new GreetingDto() - { - Text = "Mọkọm", - Language = "Efik" - }, - new GreetingDto() - { - Text = "Häj ą̊ dig!", - Language = "Elfdalian" - }, - new GreetingDto() - { - Text = "Hello", - Language = "English" - }, - new GreetingDto() - { - Text = "Tere", - Language = "Estonian" - }, - new GreetingDto() - { - Text = "Ola!", - Language = "Extremaduran" - }, - new GreetingDto() - { - Text = "Hallo", - Language = "Faroese" - }, - new GreetingDto() - { - Text = "Bula", - Language = "Fijian" - }, - new GreetingDto() - { - Text = "Hyvää päivää", - Language = "Finnish" - }, - new GreetingDto() - { - Text = "Bonjour", - Language = "French" - }, - new GreetingDto() - { - Text = "Guundach", - Language = "Frisian", - Dialect = "North Frisian" - }, - new GreetingDto() - { - Text = "Gouden Dai", - Language = "Frisian", - Dialect = "Saterland" - }, - new GreetingDto() - { - Text = "Goeie", - Language = "Frisian", - Dialect = "West Frisian" - }, - new GreetingDto() - { - Text = "Mandi", - Language = "Friulian" - }, - new GreetingDto() - { - Text = "Ola", - Language = "Galician" - }, - new GreetingDto() - { - Text = "सिवासौँळी", - Language = "Garhwali", - Romanization = "sivāsauṁḻī" - }, - new GreetingDto() - { - Text = "Buiti binafi", - Language = "Garifuna" - }, - new GreetingDto() - { - Text = "გამარჯობა", - Language = "Georgian", - Romanization = "gamarjoba" - }, - new GreetingDto() - { - Text = "Guten Tag", - Language = "German" - }, - new GreetingDto() - { - Text = "Χαῖρε", - Language = "Greek", - Romanization = "Khaĩre", - Dialect = "Ancient" - }, - new GreetingDto() - { - Text = "Γειά", - Language = "Greek", - Romanization = "Geiá", - Dialect = "Ancient" - }, - new GreetingDto() - { - Text = "Aluu", - Language = "Greenlandic" - }, - new GreetingDto() - { - Text = "નમસ્તે", - Language = "Gujarati", - Romanization = "namaste" - }, - new GreetingDto() - { - Text = "Bonjou", - Language = "Haitian Creole" - }, - new GreetingDto() - { - Text = "Sannu", - Language = "Hausa" - }, - new GreetingDto() - { - Text = "Aloha", - Language = "Hawaiian" - }, - new GreetingDto() - { - Text = "שלום", - Language = "Hebrew", - Romanization = "Shalom" - }, - new GreetingDto() - { - Text = "something", - Language = "something" - }, - new GreetingDto() - { - Text = "Tjike", - Language = "Herero" - }, - new GreetingDto() - { - Text = "Mono", - Language = "Himba" - }, - new GreetingDto() - { - Text = "नमस्ते", - Language = "Hindi", - Romanization = "namaste" - }, - new GreetingDto() - { - Text = "Nyob zoo", - Language = "Hmong", - Dialect = "White" - }, - new GreetingDto() - { - Text = "Jó napot kívánok", - Language = "Hungarian" - }, - new GreetingDto() - { - Text = "Góðan dag", - Language = "Icelandic" - }, - new GreetingDto() - { - Text = "Ndeewo", - Language = "Igbo" - }, - new GreetingDto() - { - Text = "Kablaaw", - Language = "Iloko" - }, - new GreetingDto() - { - Text = "Tiervâ", - Language = "Inari Saami" - }, - new GreetingDto() - { - Text = "Hi", - Language = "Indonesian" - }, - new GreetingDto() - { - Text = "ᐊᐃ", - Language = "Inuktitut", - Romanization = "Ai" - }, - new GreetingDto() - { - Text = "Haluu", - Language = "Iñupiaq" - }, - new GreetingDto() - { - Text = "Dia dhuit", - Language = "Irish" - }, - new GreetingDto() - { - Text = "Ciao", - Language = "Italian" - }, - new GreetingDto() - { - Text = "Míyaxwen", - Language = "Ivilyuat" - }, - new GreetingDto() - { - Text = "Ello", - Language = "Jamaican" - }, - new GreetingDto() - { - Text = "今日は", - Language = "Japanese", - Romanization = "konnichiwa" - }, - new GreetingDto() - { - Text = "ꦲꦭꦺꦴ", - Language = "Javanese", - Romanization = "Halo" - }, - new GreetingDto() - { - Text = "Puiznu", - Language = "Jenesch" - }, - new GreetingDto() - { - Text = "Salut", - Language = "Jèrriais" - }, - new GreetingDto() - { - Text = "Godaw", - Language = "Jutish" - }, - new GreetingDto() - { - Text = "Мендвт", - Language = "Kalmyk" - }, - new GreetingDto() - { - Text = "Tọi", - Language = "Kam" - }, - new GreetingDto() - { - Text = "ನಮಸ್ತೆ", - Language = "Kannada", - Romanization = "namaste" - }, - new GreetingDto() - { - Text = "Xsaqär", - Language = "Kaqchikel" - }, - new GreetingDto() - { - Text = "Ayukîi", - Language = "Karuk" - }, - new GreetingDto() - { - Text = "Witéj", - Language = "Kashubian" - }, - new GreetingDto() - { - Text = "असलामु अलैकुम", - Language = "Kashmiri", - Romanization = "asalāmu alaikuma" - }, - new GreetingDto() - { - Text = "Hagare'enaam", - Language = "Kawaiisu" - }, - new GreetingDto() - { - Text = "Сәлем", - Language = "Kazakh", - Romanization = "Sälem" - }, - new GreetingDto() - { - Text = "ជំរាបសួរ", - Language = "Khmer", - Romanization = "chôm rab suôr" - }, - new GreetingDto() - { - Text = "Halau", - Language = "Khoekhoe" - }, - new GreetingDto() - { - Text = "wĩmwega", - Language = "Kikuyu" - }, - new GreetingDto() - { - Text = "Muraho", - Language = "Kinyarwanda" - }, - new GreetingDto() - { - Text = "Ko na mauri", - Language = "Kiribati" - }, - new GreetingDto() - { - Text = "안녕하십니까", - Language = "Korean", - Romanization = "annyeong-hasimnikka" - }, - new GreetingDto() - { - Text = "Haawka", - Language = "Kumeyaay" - }, - new GreetingDto() - { - Text = "!kao", - Language = "Kung San" - }, - new GreetingDto() - { - Text = "Rojbash", - Language = "Kurdish", - Dialect = "Kurmanji" - }, - new GreetingDto() - { - Text = "Sillaw", - Language = "Kurdish", - Dialect = "Sorani" - }, - new GreetingDto() - { - Text = "Салам!", - Language = "Kyrgyz", - Romanization = "Salam!" - }, - new GreetingDto() - { - Text = "בוינוס דייאס", - Language = "Ladino", - Romanization = "Buenos diyas" - }, - new GreetingDto() - { - Text = "Hau", - Language = "Lakota Sioux" - }, - new GreetingDto() - { - Text = "ສະບາຍດີ", - Language = "Lao", - Romanization = "sába̖ai-di̖i" - }, - new GreetingDto() - { - Text = "Ave", - Language = "Latin" - }, - new GreetingDto() - { - Text = "Sveiki", - Language = "Latvian" - }, - new GreetingDto() - { - Text = "გეგაჯგინას", - Language = "Laz", - Romanization = "Gegacginas" - }, - new GreetingDto() - { - Text = "Салам алейкум", - Language = "Lezgi", - Romanization = "Salam alejkum" - }, - new GreetingDto() - { - Text = "Hallo", - Language = "Limburgish" - }, - new GreetingDto() - { - Text = "Mbote", - Language = "Lingala" - }, - new GreetingDto() - { - Text = "Labas", - Language = "Lithuanian" - }, - new GreetingDto() - { - Text = "Moin", - Language = "Low Saxon" - }, - new GreetingDto() - { - Text = "Lumela", - Language = "Lozi" - }, - new GreetingDto() - { - Text = "Gyebale ko", - Language = "Luganda" - }, - new GreetingDto() - { - Text = "Buoris", - Language = "Lule Sámi" - }, - new GreetingDto() - { - Text = "Mííyu", - Language = "Luiseño" - }, - new GreetingDto() - { - Text = "Moien", - Language = "Luxembourgish" - }, - new GreetingDto() - { - Text = "Здраво", - Language = "Macedonian", - Romanization = "Zdravo" - }, - new GreetingDto() - { - Text = "परनाम", - Language = "Magahi", - Romanization = "Pernaam" - }, - new GreetingDto() - { - Text = "प्रनाम", - Language = "Maithili", - Romanization = "Pranaam" - }, - new GreetingDto() - { - Text = "Manao ahoana", - Language = "Malagasy" - }, - new GreetingDto() - { - Text = "Selamat pagi", - Language = "Malay" - }, - new GreetingDto() - { - Text = "നമസ്തേ", - Language = "Malayalam", - Romanization = "namastē" - }, - new GreetingDto() - { - Text = "Jeeka, ma tzuula", - Language = "Mam" - }, - new GreetingDto() - { - Text = "Moghrey mie", - Language = "Gaelic", - Dialect = "Manx" - }, - new GreetingDto() - { - Text = "Assalaamu Alaikum", - Language = "Maldivian" - }, - new GreetingDto() - { - Text = "Ħello", - Language = "Maltese" - }, - new GreetingDto() - { - Text = "Kia ora", - Language = "Māori" - }, - new GreetingDto() - { - Text = "Mari mari", - Language = "Mapuche" - }, - new GreetingDto() - { - Text = "नमस्कार", - Language = "Marathi", - Romanization = "namaskāra" - }, - new GreetingDto() - { - Text = "Io̧kwe", - Language = "Marshallese" - }, - new GreetingDto() - { - Text = "Bonzur", - Language = "Mauritian Creole" - }, - new GreetingDto() - { - Text = "Gwe’", - Language = "Míkmaq" - }, - new GreetingDto() - { - Text = "ဟာဲ", - Language = "Mon", - Romanization = "hāai" - }, - new GreetingDto() - { - Text = "Ciau", - Language = "Monégasque" - }, - new GreetingDto() - { - Text = "Сайн уу", - Language = "Mongolian", - Romanization = "Sain uu" - }, - new GreetingDto() - { - Text = "Manahúú", - Language = "Mono" - }, - new GreetingDto() - { - Text = "Ne y windiga", - Language = "Mossi" - }, - new GreetingDto() - { - Text = "Niltze", - Language = "Nahuatl" - }, - new GreetingDto() - { - Text = "Ekamowir omo", - Language = "Nauruan" - }, - new GreetingDto() - { - Text = "Yá'át'ééh", - Language = "Navajo" - }, - new GreetingDto() - { - Text = "ज्वजलपा", - Language = "Newari", - Romanization = "jvajalapā" - }, - new GreetingDto() - { - Text = "Oraire ota?", - Language = "Nkore" - }, - new GreetingDto() - { - Text = "Salibonani", - Language = "Ndebele" - }, - new GreetingDto() - { - Text = "Lotjhani", - Language = "Southern Ndebele" - }, - new GreetingDto() - { - Text = "नमस्ते", - Language = "Nepali", - Romanization = "namaste" - }, - new GreetingDto() - { - Text = "Fakaalofa atu", - Language = "Niuean" - }, - new GreetingDto() - { - Text = "Салам!", - Language = "Nogai" - }, - new GreetingDto() - { - Text = "Bures", - Language = "Northern Sámi" - }, - new GreetingDto() - { - Text = "Dumêlang", - Language = "Northern Sotho" - }, - new GreetingDto() - { - Text = "Goddag", - Language = "Norwegian" - }, - new GreetingDto() - { - Text = "Hatʸu", - Language = "Northern Chumash" - }, - new GreetingDto() - { - Text = "Bonjorn", - Language = "Occitan" - }, - new GreetingDto() - { - Text = "Aniin", - Language = "Ojibwe" - }, - new GreetingDto() - { - Text = "今日拝なびら", - Language = "Okinawan", - Romanization = "chuu wuganabira" - }, - new GreetingDto() - { - Text = "Wes hāl", - Language = "Old English" - }, - new GreetingDto() - { - Text = "Ƿes hāl", - Language = "Old Prussian" - }, - new GreetingDto() - { - Text = "Ahó", - Language = "Omaha" - }, - new GreetingDto() - { - Text = "ନମସ୍କାର", - Language = "Oriya", - Romanization = "Namascāra" - }, - new GreetingDto() - { - Text = "Alii", - Language = "Palauan" - }, - new GreetingDto() - { - Text = "Bon dia", - Language = "Papiamento" - }, - new GreetingDto() - { - Text = "ښې چارې", - Language = "Pashto", - Romanization = "khe chare" - }, - new GreetingDto() - { - Text = "Gude Daag", - Language = "Pennsylvania Deitsch" - }, - new GreetingDto() - { - Text = "درود", - Language = "Persian", - Romanization = "dorood", - Dialect = "Farsi" - }, - new GreetingDto() - { - Text = "Bojour", - Language = "Picard" - }, - new GreetingDto() - { - Text = "Wai", - Language = "Pitjantjatjara" - }, - new GreetingDto() - { - Text = "Cześć", - Language = "Polish" - }, - new GreetingDto() - { - Text = "Olá", - Language = "Portuguese", - Dialect = "Protugal" - }, - new GreetingDto() - { - Text = "Oi", - Language = "Portuguese", - Dialect = "Brazilian" - }, - new GreetingDto() - { - Text = "ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ।", - Language = "Punjabi", - Romanization = "sat srī akāl" - }, - new GreetingDto() - { - Text = "Rimaykullayki", - Language = "Quechua" - }, - new GreetingDto() - { - Text = "'Iorana", - Language = "Rapa Nui" - }, - new GreetingDto() - { - Text = "Bonzour", - Language = "Réunion Creole" - }, - new GreetingDto() - { - Text = "Sastipe", - Language = "Romani" - }, - new GreetingDto() - { - Text = "Salut", - Language = "Romanian" - }, - new GreetingDto() - { - Text = "Ciao", - Language = "Romansh" - }, - new GreetingDto() - { - Text = "Привет", - Language = "Russian", - Romanization = "Privet" - }, - new GreetingDto() - { - Text = "Слава Исусу Христу", - Language = "Rusyn", - Dialect = "Slava Ysusu Chrystu" - }, - new GreetingDto() - { - Text = "бирибиэт", - Language = "Sakha", - Romanization = "biribiet" - }, - new GreetingDto() - { - Text = "Malō", - Language = "Samoan" - }, - new GreetingDto() - { - Text = "Bara mo", - Language = "Sango" - }, - new GreetingDto() - { - Text = "नमस्ते", - Language = "Sanskrit", - Romanization = "namaste" - }, - new GreetingDto() - { - Text = "Saludi", - Language = "Sardinian", - Dialect = "Campidanese" - }, - new GreetingDto() - { - Text = "Bone die", - Language = "Sardinian", - Dialect = "Logudorese" - }, - new GreetingDto() - { - Text = "Hullo", - Language = "Scots" - }, - new GreetingDto() - { - Text = "Halò", - Language = "Gaelic", - Dialect = "Scottish" - }, - new GreetingDto() - { - Text = "Здраво", - Language = "Serbian", - Dialect = "Zdravo" - }, - new GreetingDto() - { - Text = "Lumela", - Language = "Sesotho" - }, - new GreetingDto() - { - Text = "Mhoro", - Language = "Shona" - }, - new GreetingDto() - { - Text = "Ciau", - Language = "Sicilian" - }, - new GreetingDto() - { - Text = "سَلامُ", - Language = "Sindhi", - Romanization = "Salāmu" - }, - new GreetingDto() - { - Text = "ආයුඛෝවන්", - Language = "Sinhala", - Romanization = "āyubūvan" - }, - new GreetingDto() - { - Text = "Dobry den", - Language = "Slovak" - }, - new GreetingDto() - { - Text = "Pozdravljeni", - Language = "Slovenian" - }, - new GreetingDto() - { - Text = "Simi", - Language = "Solresol" - }, - new GreetingDto() - { - Text = "Salaam alaykum", - Language = "Somali" - }, - new GreetingDto() - { - Text = "Dobry źeń", - Language = "Sorbian", - Dialect = "Lower Sorbian" - }, - new GreetingDto() - { - Text = "Dobry dźeń", - Language = "Sorbian", - Dialect = "Upper Sorbian" - }, - new GreetingDto() - { - Text = "Buaregh", - Language = "Southern Sámi" - }, - new GreetingDto() - { - Text = "¡Hola!", - Language = "Spanish" - }, - new GreetingDto() - { - Text = "Hoj", - Language = "Stellingwarfs" - }, - new GreetingDto() - { - Text = "Sampurasun", - Language = "Sundanese" - }, - new GreetingDto() - { - Text = "Habari", - Language = "Swahili" - }, - new GreetingDto() - { - Text = "Sawubona", - Language = "Swazi" - }, - new GreetingDto() - { - Text = "God dag", - Language = "Swedish" - }, - new GreetingDto() - { - Text = "Grüezi", - Language = "Swiss German" - }, - new GreetingDto() - { - Text = "Салам", - Language = "Tabassaran", - Romanization = "Salam" - }, - new GreetingDto() - { - Text = "Musta?", - Language = "Tagalog" - }, - new GreetingDto() - { - Text = "'Ia ora na", - Language = "Tahitian" - }, - new GreetingDto() - { - Text = "Ассалому алейкум", - Language = "Tajik", - Romanization = "Assalomu alejkym" - }, - new GreetingDto() - { - Text = "வணக்கம்", - Language = "Tamil", - Romanization = "vaṇakkam" - }, - new GreetingDto() - { - Text = "Isänme", - Language = "Tatar" - }, - new GreetingDto() - { - Text = "నమస్కారం", - Language = "Telugu", - Romanization = "namaskārām" - }, - new GreetingDto() - { - Text = "Elo", - Language = "Tetum" - }, - new GreetingDto() - { - Text = "Miga", - Language = "Teribe" - }, - new GreetingDto() - { - Text = "สวัสดี", - Language = "Thai", - Romanization = "sà-wàt-dee" - }, - new GreetingDto() - { - Text = "བཀྲ་ཤིས་བདེ་ལེགས།", - Language = "Tibetan", - Romanization = "tashi delek" - }, - new GreetingDto() - { - Text = "ሰላም", - Language = "Tigrinya", - Romanization = "selam" - }, - new GreetingDto() - { - Text = "Tālofa", - Language = "Tokelauan" - }, - new GreetingDto() - { - Text = "Gude", - Language = "Tok Pisin" - }, - new GreetingDto() - { - Text = "Mālō e lelei", - Language = "Tongan" - }, - new GreetingDto() - { - Text = "Miiyiha", - Language = "Tongva", - Dialect = "Gabrielino" - }, - new GreetingDto() - { - Text = "Xewani", - Language = "Tsonga" - }, - new GreetingDto() - { - Text = "K'uxi", - Language = "Tsotsil" - }, - new GreetingDto() - { - Text = "Dumela", - Language = "Tswana" - }, - new GreetingDto() - { - Text = "АсаламугIалейкум!", - Language = "Tsez", - Romanization = "AsalamugIalejkum!" - }, - new GreetingDto() - { - Text = "Monile", - Language = "Tumbuka" - }, - new GreetingDto() - { - Text = "Merhaba", - Language = "Turkish" - }, - new GreetingDto() - { - Text = "Salam", - Language = "Turkmen" - }, - new GreetingDto() - { - Text = "Вітаю", - Language = "Ukrainian" - }, - new GreetingDto() - { - Text = "Сородэ", - Language = "Ulch", - Romanization = "Sorodè" - }, - new GreetingDto() - { - Text = "السلام علیکم", - Language = "Urdu", - Romanization = "āssālam 'alaykum" - }, - new GreetingDto() - { - Text = "ئەسسالامۇ ئەلەيكۇم", - Language = "Uyghur", - Romanization = "Ässalamu äläykum" - }, - new GreetingDto() - { - Text = "Assalomu Alaykum", - Language = "Uzbek" - }, - new GreetingDto() - { - Text = "I nhlikanhi", - Language = "Venda" - }, - new GreetingDto() - { - Text = "Ciao", - Language = "Venetian" - }, - new GreetingDto() - { - Text = "Tervhen", - Language = "Veps" - }, - new GreetingDto() - { - Text = "Chào anh", - Language = "Vietnamese" - }, - new GreetingDto() - { - Text = "Tereq", - Language = "Võro" - }, - new GreetingDto() - { - Text = "Bondjoû", - Language = "Walloon" - }, - new GreetingDto() - { - Text = "Ngurrju mayinpa", - Language = "Warlpiri" - }, - new GreetingDto() - { - Text = "Helô", - Language = "Welsh" - }, - new GreetingDto() - { - Text = "Hej", - Language = "Westrobothnian" - }, - new GreetingDto() - { - Text = "Na nga def", - Language = "Wolof" - }, - new GreetingDto() - { - Text = "Molo", - Language = "Xhosa" - }, - new GreetingDto() - { - Text = "Mogethin", - Language = "Yapese" - }, - new GreetingDto() - { - Text = "אַ גוטן טאָג", - Language = "Yiddish", - Romanization = "A gutn tog" - }, - new GreetingDto() - { - Text = "Ẹ n lẹ", - Language = "Yoruba" - }, - new GreetingDto() - { - Text = "Ba'ax ka wa'alik?", - Language = "Yucatec Maya" - }, - new GreetingDto() - { - Text = "Selam", - Language = "Zazaki" - }, - new GreetingDto() - { - Text = "Sawubona", - Language = "Zulu" - }, - new GreetingDto() - { - Text = "Saluton", - Language = "Esperanto" - }, - new GreetingDto() - { - Text = "Bon die!", - Language = "Interlingua" - }, - new GreetingDto() - { - Text = "nuqneH", - Language = "Klingon" - }, - new GreetingDto() - { - Text = "Aiya", - Language = "Quenya" - }, - new GreetingDto() - { - Text = "Glidö", - Language = "Volapük" - }, - new GreetingDto() - { - Text = "Saluto", - Language = "Ido" - } - }; - - public static readonly int GreetingCount = Greetings.Count; - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs index 334b894..c47bf2a 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs +++ b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs @@ -1,9 +1,12 @@ using System; +using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Commands.Randomness.Cat; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; +using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Greetings { @@ -23,20 +26,20 @@ namespace Geekbot.net.Commands.Randomness.Greetings { try { - var greeting = GreetingProvider.Greetings[new Random().Next(GreetingProvider.GreetingCount - 1)]; + var greeting = await GetRandomGreeting(); var eb = new EmbedBuilder(); - eb.Title = greeting.Text; + eb.Title = greeting.Primary.Text; eb.AddInlineField("Language", greeting.Language); - if (greeting.Dialect != null) + if (greeting.Primary.Dialect != null) { - eb.AddInlineField("Dialect", greeting.Dialect); + eb.AddInlineField("Dialect", greeting.Primary.Dialect); } - if (greeting.Romanization != null) + if (greeting.Primary.Romanization != null) { - eb.AddInlineField("Roman", greeting.Romanization); + eb.AddInlineField("Roman", greeting.Primary.Romanization); } await ReplyAsync(string.Empty, false, eb.Build()); @@ -46,5 +49,18 @@ namespace Geekbot.net.Commands.Randomness.Greetings await _errorHandler.HandleCommandException(e, Context); } } + + private async Task GetRandomGreeting() + { + using var client = new HttpClient + { + BaseAddress = new Uri("https://api.greetings.dev") + }; + var response = await client.GetAsync("/v1/greeting"); + response.EnsureSuccessStatusCode(); + + var stringResponse = await response.Content.ReadAsStringAsync(); + return JsonConvert.DeserializeObject(stringResponse); + } } } \ No newline at end of file From 0589b8e91b8cf00474f7fafabb8ca1f13740dd95 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 10 Jul 2020 22:32:42 +0200 Subject: [PATCH 068/264] Update EntityFrameworkCore and microsoft.extensions.* to .net5 preview 6 --- Geekbot.net/Geekbot.net.csproj | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 4e13438..969cc30 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -28,31 +28,27 @@ - - - - - - - - + + + + + + + + - + - - 4.3.0 - - - 4.3.0 - + + From ba0d116f3e4e70bdc1a10b9bd8e19e603bf9b774 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 15 Jul 2020 02:52:13 +0200 Subject: [PATCH 069/264] Add an abstraction for http calls --- .../UbranDictionary/UrbanDictionary.cs | 13 +----- Geekbot.net/Commands/Randomness/Cat/Cat.cs | 29 +++---------- .../Randomness/Chuck/ChuckNorrisJokes.cs | 14 ++----- .../Commands/Randomness/Dad/DadJokes.cs | 22 ++-------- Geekbot.net/Commands/Randomness/Dog/Dog.cs | 28 +++---------- .../Randomness/Greetings/Greetings.cs | 19 +-------- .../Commands/Randomness/Kanye/Kanye.cs | 22 ++-------- .../Commands/Utils/Changelog/Changelog.cs | 22 ++++------ Geekbot.net/Lib/HttpAbstractions.cs | 41 +++++++++++++++++++ 9 files changed, 75 insertions(+), 135 deletions(-) create mode 100644 Geekbot.net/Lib/HttpAbstractions.cs diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 1f33573..882caa5 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -1,12 +1,11 @@ using System; using System.Linq; -using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Integrations.UbranDictionary { @@ -25,15 +24,7 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary { try { - using var client = new HttpClient - { - BaseAddress = new Uri("https://api.urbandictionary.com") - }; - var response = await client.GetAsync($"/v0/define?term={word}"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var definitions = JsonConvert.DeserializeObject(stringResponse); + var definitions = await HttpAbstractions.Get(new Uri($"https://api.urbandictionary.com/v0/define?term={word}")); if (definitions.List.Count == 0) { await ReplyAsync("That word hasn't been defined..."); diff --git a/Geekbot.net/Commands/Randomness/Cat/Cat.cs b/Geekbot.net/Commands/Randomness/Cat/Cat.cs index 3ac0764..7cd7b19 100644 --- a/Geekbot.net/Commands/Randomness/Cat/Cat.cs +++ b/Geekbot.net/Commands/Randomness/Cat/Cat.cs @@ -1,10 +1,9 @@ using System; -using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Cat { @@ -23,28 +22,12 @@ namespace Geekbot.net.Commands.Randomness.Cat { try { - - try + var response = await HttpAbstractions.Get(new Uri("https://aws.random.cat/meow")); + var eb = new EmbedBuilder { - using var client = new HttpClient - { - BaseAddress = new Uri("https://aws.random.cat") - }; - var response = await client.GetAsync("/meow"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var catFile = JsonConvert.DeserializeObject(stringResponse); - var eb = new EmbedBuilder - { - ImageUrl = catFile.File - }; - await ReplyAsync("", false, eb.Build()); - } - catch - { - await ReplyAsync("Seems like the dog cought the cat (error occured)"); - } + ImageUrl = response.File + }; + await ReplyAsync("", false, eb.Build()); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs b/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs index 5c28a9a..95dcfd4 100644 --- a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs +++ b/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs @@ -1,10 +1,9 @@ using System; using System.Net.Http; -using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Chuck { @@ -25,15 +24,8 @@ namespace Geekbot.net.Commands.Randomness.Chuck { try { - using var client = new HttpClient(); - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - var response = await client.GetAsync("https://api.chucknorris.io/jokes/random"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.Value); + var response = await HttpAbstractions.Get(new Uri("https://api.chucknorris.io/jokes/random")); + await ReplyAsync(response.Value); } catch (HttpRequestException) { diff --git a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs b/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs index bcedd96..7aabff3 100644 --- a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs +++ b/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs @@ -1,10 +1,8 @@ using System; -using System.Net.Http; -using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Dad { @@ -23,22 +21,8 @@ namespace Geekbot.net.Commands.Randomness.Dad { try { - try - { - using var client = new HttpClient(); - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - var response = await client.GetAsync("https://icanhazdadjoke.com/"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.Joke); - } - catch (HttpRequestException) - { - await ReplyAsync("Api down..."); - } + var response = await HttpAbstractions.Get(new Uri("https://icanhazdadjoke.com/")); + await ReplyAsync(response.Joke); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Randomness/Dog/Dog.cs b/Geekbot.net/Commands/Randomness/Dog/Dog.cs index d7404c6..b3d603b 100644 --- a/Geekbot.net/Commands/Randomness/Dog/Dog.cs +++ b/Geekbot.net/Commands/Randomness/Dog/Dog.cs @@ -1,10 +1,9 @@ using System; -using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Dog { @@ -23,27 +22,12 @@ namespace Geekbot.net.Commands.Randomness.Dog { try { - try + var response = await HttpAbstractions.Get(new Uri("http://random.dog/woof.json")); + var eb = new EmbedBuilder { - using var client = new HttpClient - { - BaseAddress = new Uri("http://random.dog") - }; - var response = await client.GetAsync("/woof.json"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var dogFile = JsonConvert.DeserializeObject(stringResponse); - var eb = new EmbedBuilder - { - ImageUrl = dogFile.Url - }; - await ReplyAsync("", false, eb.Build()); - } - catch (HttpRequestException e) - { - await ReplyAsync($"Seems like the dog got lost (error occured)\r\n{e.Message}"); - } + ImageUrl = response.Url + }; + await ReplyAsync("", false, eb.Build()); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs index c47bf2a..85e9152 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs +++ b/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs @@ -1,12 +1,10 @@ using System; -using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Commands.Randomness.Cat; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Greetings { @@ -26,7 +24,7 @@ namespace Geekbot.net.Commands.Randomness.Greetings { try { - var greeting = await GetRandomGreeting(); + var greeting = await HttpAbstractions.Get(new Uri("https://api.greetings.dev/v1/greeting")); var eb = new EmbedBuilder(); eb.Title = greeting.Primary.Text; @@ -49,18 +47,5 @@ namespace Geekbot.net.Commands.Randomness.Greetings await _errorHandler.HandleCommandException(e, Context); } } - - private async Task GetRandomGreeting() - { - using var client = new HttpClient - { - BaseAddress = new Uri("https://api.greetings.dev") - }; - var response = await client.GetAsync("/v1/greeting"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(stringResponse); - } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs index 36f1d1a..2aca31d 100644 --- a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs +++ b/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs @@ -1,10 +1,8 @@ using System; -using System.Net.Http; -using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Randomness.Kanye { @@ -23,22 +21,8 @@ namespace Geekbot.net.Commands.Randomness.Kanye { try { - try - { - using var client = new HttpClient(); - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - var response = await client.GetAsync("https://api.kanye.rest/"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.Quote); - } - catch (HttpRequestException) - { - await ReplyAsync("Api down..."); - } + var response = await HttpAbstractions.Get(new Uri("https://api.kanye.rest/")); + await ReplyAsync(response.Quote); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs index 02981df..335ee3f 100644 --- a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs +++ b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs @@ -1,14 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net.Http; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.net.Lib; using Geekbot.net.Lib.ErrorHandling; -using Newtonsoft.Json; namespace Geekbot.net.Commands.Utils.Changelog { @@ -29,17 +28,14 @@ namespace Geekbot.net.Commands.Utils.Changelog { try { - using var client = new HttpClient - { - BaseAddress = new Uri("https://api.github.com") - }; - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", - "http://developer.github.com/v3/#user-agent-required"); - var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits"); - response.EnsureSuccessStatusCode(); - - var stringResponse = await response.Content.ReadAsStringAsync(); - var commits = JsonConvert.DeserializeObject>(stringResponse); + var commits = await HttpAbstractions.Get>( + new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits"), + new Dictionary() + { + { "User-Agent", "http://developer.github.com/v3/#user-agent-required" } + } + ); + var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 165, 102)); eb.WithAuthor(new EmbedAuthorBuilder diff --git a/Geekbot.net/Lib/HttpAbstractions.cs b/Geekbot.net/Lib/HttpAbstractions.cs new file mode 100644 index 0000000..cf609f6 --- /dev/null +++ b/Geekbot.net/Lib/HttpAbstractions.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace Geekbot.net.Lib +{ + public class HttpAbstractions + { + public static async Task Get(Uri location, Dictionary additionalHeaders = null) + { + using var client = new HttpClient + { + BaseAddress = location, + DefaultRequestHeaders = + { + Accept = + { + MediaTypeWithQualityHeaderValue.Parse("application/json") + } + } + }; + + if (additionalHeaders != null) + { + foreach (var (name, val) in additionalHeaders) + { + client.DefaultRequestHeaders.TryAddWithoutValidation(name, val); + } + } + + var response = await client.GetAsync(location.PathAndQuery); + response.EnsureSuccessStatusCode(); + + var stringResponse = await response.Content.ReadAsStringAsync(); + return JsonConvert.DeserializeObject(stringResponse); + } + } +} \ No newline at end of file From efed2f712048e904de30299d66477003cd1ac533 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 15 Jul 2020 03:09:43 +0200 Subject: [PATCH 070/264] Add the !corona command --- .../Commands/Utils/Corona/CoronaStats.cs | 67 +++++++++++++++++++ .../Commands/Utils/Corona/CoronaSummaryDto.cs | 9 +++ 2 files changed, 76 insertions(+) create mode 100644 Geekbot.net/Commands/Utils/Corona/CoronaStats.cs create mode 100644 Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs diff --git a/Geekbot.net/Commands/Utils/Corona/CoronaStats.cs b/Geekbot.net/Commands/Utils/Corona/CoronaStats.cs new file mode 100644 index 0000000..4be8195 --- /dev/null +++ b/Geekbot.net/Commands/Utils/Corona/CoronaStats.cs @@ -0,0 +1,67 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Geekbot.net.Lib; +using Geekbot.net.Lib.ErrorHandling; +using Geekbot.net.Lib.Extensions; + +namespace Geekbot.net.Commands.Utils.Corona +{ + public class CoronaStats : ModuleBase + { + private readonly IErrorHandler _errorHandler; + + public CoronaStats(IErrorHandler errorHandler) + { + _errorHandler = errorHandler; + } + + [Command("corona", RunMode = RunMode.Async)] + [Summary("Get the latest worldwide corona statistics")] + public async Task Summary() + { + try + { + var summary = await HttpAbstractions.Get(new Uri("https://api.covid19api.com/world/total")); + var activeCases = summary.TotalConfirmed - (summary.TotalRecovered + summary.TotalDeaths); + + string CalculatePercentage(decimal i) => (i / summary.TotalConfirmed).ToString("#0.##%"); + var activePercent = CalculatePercentage(activeCases); + var recoveredPercentage = CalculatePercentage(summary.TotalRecovered); + var deathsPercentage = CalculatePercentage(summary.TotalDeaths); + + var numberFormat = "#,#"; + var totalFormatted = summary.TotalConfirmed.ToString(numberFormat); + var activeFormatted = activeCases.ToString(numberFormat); + var recoveredFormatted = summary.TotalRecovered.ToString(numberFormat); + var deathsFormatted = summary.TotalDeaths.ToString(numberFormat); + + var eb = new EmbedBuilder + { + Author = new EmbedAuthorBuilder + { + Name = "Confirmed Corona Cases", + IconUrl = "https://www.redcross.org/content/dam/icons/disasters/virus/Virus-1000x1000-R-Pl.png" + }, + Footer = new EmbedFooterBuilder + { + Text = "Source: covid19api.com", + }, + Color = Color.Red + }; + eb.AddField("Total", totalFormatted); + eb.AddInlineField("Active", $"{activeFormatted} ({activePercent})"); + eb.AddInlineField("Recovered", $"{recoveredFormatted} ({recoveredPercentage})"); + eb.AddInlineField("Deaths", $"{deathsFormatted} ({deathsPercentage})"); + + await Context.Channel.SendMessageAsync(String.Empty, false, eb.Build()); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs b/Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs new file mode 100644 index 0000000..5639249 --- /dev/null +++ b/Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs @@ -0,0 +1,9 @@ +namespace Geekbot.net.Commands.Utils.Corona +{ + public class CoronaSummaryDto + { + public decimal TotalConfirmed { get; set; } + public decimal TotalDeaths { get; set; } + public decimal TotalRecovered { get; set; } + } +} \ No newline at end of file From 5e9cb8a4c18f739e00807511d8fa656591711956 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 15 Jul 2020 03:11:36 +0200 Subject: [PATCH 071/264] Make main async --- Geekbot.net/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index c96e2f5..689c170 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -44,7 +44,7 @@ namespace Geekbot.net private IReactionListener _reactionListener; private IGuildSettingsManager _guildSettingsManager; - private static void Main(string[] args) + private static async Task Main(string[] args) { RunParameters runParameters = null; Parser.Default.ParseArguments(args) @@ -63,7 +63,7 @@ namespace Geekbot.net logger.Information(LogSource.Geekbot, "Starting..."); try { - new Program().MainAsync(runParameters, logger).GetAwaiter().GetResult(); + await new Program().Start(runParameters, logger); } catch (Exception e) { @@ -71,7 +71,7 @@ namespace Geekbot.net } } - private async Task MainAsync(RunParameters runParameters, GeekbotLogger logger) + private async Task Start(RunParameters runParameters, GeekbotLogger logger) { _logger = logger; _runParameters = runParameters; From 4cd7ac1d799acac1b2866e9b064223ebcbb98c19 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 15 Jul 2020 17:10:50 +0200 Subject: [PATCH 072/264] Fix broken DM Channel support --- Geekbot.net/Handlers/CommandHandler.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Geekbot.net/Handlers/CommandHandler.cs b/Geekbot.net/Handlers/CommandHandler.cs index b811a8e..b6a3d9f 100644 --- a/Geekbot.net/Handlers/CommandHandler.cs +++ b/Geekbot.net/Handlers/CommandHandler.cs @@ -52,7 +52,12 @@ namespace Geekbot.net.Handlers if (!(messageParam is SocketUserMessage message)) return Task.CompletedTask; if (message.Author.IsBot) return Task.CompletedTask; - var guildId = ((SocketGuildChannel) message.Channel).Guild.Id; + ulong guildId = message.Author switch + { + SocketGuildUser user => user.Guild.Id, + _ => 0 // DM Channel + }; + if (IsIgnoredGuild(guildId, message.Author.Id)) return Task.CompletedTask; var lowCaseMsg = message.ToString().ToLower(); @@ -102,12 +107,14 @@ namespace Geekbot.net.Handlers private bool ShouldPong(string lowerCaseMessage, ulong guildId) { if (!lowerCaseMessage.StartsWith("ping ") && !lowerCaseMessage.Equals("ping")) return false; + if (guildId == 0) return true; return GetGuildSettings(guildId)?.Ping ?? false; } private bool ShouldHui(string lowerCaseMessage, ulong guildId) { if (!lowerCaseMessage.StartsWith("hui")) return false; + if (guildId == 0) return true; return GetGuildSettings(guildId)?.Hui ?? false; } From 77e912501df42181578c4b1187cb94354510aa84 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 22 Jul 2020 14:09:26 +0200 Subject: [PATCH 073/264] Upgrade to .NET5 preview 7 --- Geekbot.net/Geekbot.net.csproj | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 969cc30..37dc310 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -28,14 +28,14 @@ - - - - - - - - + + + + + + + + From fff232423264abed48ad3a4e1d93c09283d3d290 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 22 Jul 2020 14:17:08 +0200 Subject: [PATCH 074/264] Fix build warnings in MediaProvider.cs and TranslationHandler.cs --- .../Lib/Localization/TranslationHandler.cs | 8 +++---- Geekbot.net/Lib/Media/MediaProvider.cs | 21 ++++++++++--------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/Geekbot.net/Lib/Localization/TranslationHandler.cs b/Geekbot.net/Lib/Localization/TranslationHandler.cs index 89ba632..6166e6a 100644 --- a/Geekbot.net/Lib/Localization/TranslationHandler.cs +++ b/Geekbot.net/Lib/Localization/TranslationHandler.cs @@ -89,7 +89,7 @@ namespace Geekbot.net.Lib.Localization } } - private async Task GetServerLanguage(ulong guildId) + private Task GetServerLanguage(ulong guildId) { try { @@ -99,7 +99,7 @@ namespace Geekbot.net.Lib.Localization lang = _serverLanguages[guildId]; if (!string.IsNullOrEmpty(lang)) { - return lang; + return Task.FromResult(lang); } throw new Exception(); } @@ -107,13 +107,13 @@ namespace Geekbot.net.Lib.Localization { lang = _guildSettingsManager.GetSettings(guildId, false)?.Language ?? "EN"; _serverLanguages[guildId] = lang; - return lang; + return Task.FromResult(lang); } } catch (Exception e) { _logger.Error(LogSource.Geekbot, "Could not get guild language", e); - return "EN"; + return Task.FromResult("EN"); } } diff --git a/Geekbot.net/Lib/Media/MediaProvider.cs b/Geekbot.net/Lib/Media/MediaProvider.cs index 45524de..5a9a055 100644 --- a/Geekbot.net/Lib/Media/MediaProvider.cs +++ b/Geekbot.net/Lib/Media/MediaProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.RandomNumberGenerator; @@ -9,14 +10,14 @@ namespace Geekbot.net.Lib.Media { private readonly IRandomNumberGenerator _random; private readonly IGeekbotLogger _logger; - private string[] _pandaImages; - private string[] _croissantImages; - private string[] _squirrelImages; - private string[] _pumpkinImages; - private string[] _turtlesImages; - private string[] _penguinImages; - private string[] _foxImages; - private string[] _dabImages; + private readonly string[] _pandaImages; + private readonly string[] _croissantImages; + private readonly string[] _squirrelImages; + private readonly string[] _pumpkinImages; + private readonly string[] _turtlesImages; + private readonly string[] _penguinImages; + private readonly string[] _foxImages; + private readonly string[] _dabImages; public MediaProvider(IGeekbotLogger logger, IRandomNumberGenerator random) { @@ -24,7 +25,6 @@ namespace Geekbot.net.Lib.Media _logger = logger; logger.Information(LogSource.Geekbot, "Loading Media Files"); -; LoadMedia("./Storage/pandas", ref _pandaImages); LoadMedia("./Storage/croissant", ref _croissantImages); LoadMedia("./Storage/squirrel", ref _squirrelImages); @@ -53,7 +53,8 @@ namespace Geekbot.net.Lib.Media MediaType.Turtle => _turtlesImages, MediaType.Penguin => _penguinImages, MediaType.Fox => _foxImages, - MediaType.Dab => _dabImages + MediaType.Dab => _dabImages, + _ => new string[0] }; return collection[_random.Next(0, collection.Length)]; From 4659f793f55b689ad5df83987007a7827eccd9e5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 22 Jul 2020 14:32:47 +0200 Subject: [PATCH 075/264] Add !lmgtfy --- Geekbot.net/Commands/Utils/Lmgtfy.cs | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Geekbot.net/Commands/Utils/Lmgtfy.cs diff --git a/Geekbot.net/Commands/Utils/Lmgtfy.cs b/Geekbot.net/Commands/Utils/Lmgtfy.cs new file mode 100644 index 0000000..9976dad --- /dev/null +++ b/Geekbot.net/Commands/Utils/Lmgtfy.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading.Tasks; +using System.Web; +using Discord.Commands; +using Geekbot.net.Lib.ErrorHandling; + +namespace Geekbot.net.Commands.Utils +{ + public class Lmgtfy : ModuleBase + { + private readonly IErrorHandler _errorHandler; + + public Lmgtfy(IErrorHandler errorHandler) + { + _errorHandler = errorHandler; + } + + [Command("lmgtfy", RunMode = RunMode.Async)] + [Summary("Get a 'Let me google that for you' link")] + public async Task GetUrl([Remainder] [Summary("question")] string question) + { + try + { + var encoded = HttpUtility.UrlEncode(question).Replace("%20", "+"); + await Context.Channel.SendMessageAsync($""); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } + } +} \ No newline at end of file From 913b4a5f10c4dbbb62932d312e35c28839e721c5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 28 Jul 2020 22:14:22 +0200 Subject: [PATCH 076/264] Change the HttpAbstractions so that the caller can provide its own HttpClient instead of creating parameters for every HttpClient Option --- .../Commands/Utils/Changelog/Changelog.cs | 8 +--- Geekbot.net/Lib/HttpAbstractions.cs | 39 ++++++++++--------- 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs index 335ee3f..c217619 100644 --- a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs +++ b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs @@ -28,13 +28,7 @@ namespace Geekbot.net.Commands.Utils.Changelog { try { - var commits = await HttpAbstractions.Get>( - new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits"), - new Dictionary() - { - { "User-Agent", "http://developer.github.com/v3/#user-agent-required" } - } - ); + var commits = await HttpAbstractions.Get>(new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits")); var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 165, 102)); diff --git a/Geekbot.net/Lib/HttpAbstractions.cs b/Geekbot.net/Lib/HttpAbstractions.cs index cf609f6..2cde4cc 100644 --- a/Geekbot.net/Lib/HttpAbstractions.cs +++ b/Geekbot.net/Lib/HttpAbstractions.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; @@ -7,34 +6,36 @@ using Newtonsoft.Json; namespace Geekbot.net.Lib { - public class HttpAbstractions + public static class HttpAbstractions { - public static async Task Get(Uri location, Dictionary additionalHeaders = null) + public static HttpClient CreateDefaultClient() { - using var client = new HttpClient + var client = new HttpClient { - BaseAddress = location, DefaultRequestHeaders = { - Accept = - { - MediaTypeWithQualityHeaderValue.Parse("application/json") - } + Accept = {MediaTypeWithQualityHeaderValue.Parse("application/json")}, } }; + client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Geekbot/v0.0.0 (+https://geekbot.pizzaandcoffee.rocks/)"); - if (additionalHeaders != null) - { - foreach (var (name, val) in additionalHeaders) - { - client.DefaultRequestHeaders.TryAddWithoutValidation(name, val); - } - } - - var response = await client.GetAsync(location.PathAndQuery); + return client; + } + + public static async Task Get(Uri location, HttpClient httpClient = null, bool disposeClient = true) + { + httpClient ??= CreateDefaultClient(); + httpClient.BaseAddress = location; + + var response = await httpClient.GetAsync(location.PathAndQuery); response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); + + if (disposeClient) + { + httpClient.Dispose(); + } + return JsonConvert.DeserializeObject(stringResponse); } } From 9003d6249eb62e32302c4b38cf35b42905674cfb Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 28 Jul 2020 22:14:59 +0200 Subject: [PATCH 077/264] Add !mmr to get League of Legends MMR numbers --- .../Commands/Integrations/LolMmr/LolMmr.cs | 61 +++++++++++++++++++ .../Commands/Integrations/LolMmr/LolMmrDto.cs | 9 +++ .../Integrations/LolMmr/LolMrrInfoDto.cs | 11 ++++ 3 files changed, 81 insertions(+) create mode 100644 Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs create mode 100644 Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs create mode 100644 Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs diff --git a/Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs b/Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs new file mode 100644 index 0000000..5de7d63 --- /dev/null +++ b/Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs @@ -0,0 +1,61 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using System.Web; +using Discord.Commands; +using Geekbot.net.Lib; +using Geekbot.net.Lib.ErrorHandling; + +namespace Geekbot.net.Commands.Integrations.LolMmr +{ + public class LolMmr : ModuleBase + { + private readonly IErrorHandler _errorHandler; + + public LolMmr(IErrorHandler errorHandler) + { + _errorHandler = errorHandler; + } + + [Command("mmr", RunMode = RunMode.Async)] + [Summary("Get the League of Legends MMR for a specified summoner")] + public async Task GetMmr([Remainder] [Summary("summoner")] string summonerName) + { + try + { + LolMmrDto data; + try + { + var name = HttpUtility.UrlEncode(summonerName.ToLower()); + var httpClient = HttpAbstractions.CreateDefaultClient(); + // setting the user agent in accordance with the whatismymmr.com api rules + httpClient.DefaultRequestHeaders.Remove("User-Agent"); + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Linux:rocks.pizzaandcoffee.geekbot:v0.0.0"); + data = await HttpAbstractions.Get(new Uri($"https://euw.whatismymmr.com/api/v1/summoner?name={name}"), httpClient); + } + catch (HttpRequestException e) + { + if (e.StatusCode != HttpStatusCode.NotFound) throw e; + + await Context.Channel.SendMessageAsync("Player not found"); + return; + + } + + var sb = new StringBuilder(); + sb.AppendLine($"**MMR for {summonerName}**"); + sb.AppendLine($"Normal: {data.Normal.Avg}"); + sb.AppendLine($"Ranked: {data.Ranked.Avg}"); + sb.AppendLine($"ARAM: {data.ARAM.Avg}"); + + await Context.Channel.SendMessageAsync(sb.ToString()); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context); + } + } + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs b/Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs new file mode 100644 index 0000000..4a9887d --- /dev/null +++ b/Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs @@ -0,0 +1,9 @@ +namespace Geekbot.net.Commands.Integrations.LolMmr +{ + public class LolMmrDto + { + public LolMrrInfoDto Ranked { get; set; } + public LolMrrInfoDto Normal { get; set; } + public LolMrrInfoDto ARAM { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs b/Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs new file mode 100644 index 0000000..55804fd --- /dev/null +++ b/Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs @@ -0,0 +1,11 @@ +using System; +using Newtonsoft.Json; + +namespace Geekbot.net.Commands.Integrations.LolMmr +{ + public class LolMrrInfoDto + { + [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] + public decimal Avg { get; set; } = 0; + } +} \ No newline at end of file From 3813290f89ab7c2c9558318ee375fde18a16ca98 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Aug 2020 20:53:50 +0200 Subject: [PATCH 078/264] Simplefy version number during in CI pipeline --- .gitlab-ci.yml | 15 +++++++-------- Geekbot.net/Geekbot.net.csproj | 5 ++--- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 2e22e02..3d362ce 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,7 +4,9 @@ stages: - deploy - ops -.imageTag: &IMAGE_TAG $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG +variables: + VERSION: 4.2.0-$CI_COMMIT_SHORT_SHA + IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG Build: stage: build @@ -16,7 +18,7 @@ Build: script: - dotnet restore - dotnet test Tests - - dotnet publish --version-suffix ${CI_COMMIT_SHA:0:8} -r linux-x64 -c Release -o ./app ./Geekbot.net/ + - dotnet publish --version-suffix $VERSION -r linux-x64 -c Release -o ./app ./Geekbot.net/ Package: stage: docker @@ -25,8 +27,6 @@ Package: - master services: - docker:stable-dind - variables: - IMAGE_TAG: *IMAGE_TAG script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $IMAGE_TAG . @@ -39,7 +39,6 @@ Deploy: - master variables: ANSIBLE_NOCOWS: 1 - IMAGE_TAG: *IMAGE_TAG before_script: - mkdir /root/.ssh - cp $SSH_PRIVATE_KEY /root/.ssh/id_ed25519 @@ -56,9 +55,9 @@ Sentry: only: - master script: - - sentry-cli releases new -p geekbot 4.2.0-${CI_COMMIT_SHA:0:8} - - sentry-cli releases set-commits --auto 4.2.0-${CI_COMMIT_SHA:0:8} - - sentry-cli releases deploys 4.2.0-${CI_COMMIT_SHA:0:8} new -e Production + - sentry-cli releases new -p geekbot $VERSION + - sentry-cli releases set-commits --auto $VERSION + - sentry-cli releases deploys $VERSION new -e Production Github Mirror: stage: ops diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj index 37dc310..006e6cb 100755 --- a/Geekbot.net/Geekbot.net.csproj +++ b/Geekbot.net/Geekbot.net.csproj @@ -4,10 +4,9 @@ net5.0 win-x64;linux-x64 derp.ico - 4.2.0 $(VersionSuffix) - $(Version)-$(VersionSuffix) - $(Version)-DEV + $(VersionSuffix) + 0.0.0-DEV Pizza and Coffee Studios Pizza and Coffee Studios A Discord bot From c22d0cf9419c47dd9ccde2eb4a7245b233633644 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Aug 2020 21:09:27 +0200 Subject: [PATCH 079/264] Merge WikipediaApi into the main code base --- Geekbot.net.sln | 6 ------ Geekbot.net/Commands/Integrations/Wikipedia.cs | 4 ++-- .../Lib/WikipediaClient}/IWikipediaClient.cs | 4 ++-- .../Lib/WikipediaClient}/Page/PageApiUrls.cs | 2 +- .../Lib/WikipediaClient}/Page/PageContentUrlCollection.cs | 2 +- .../Lib/WikipediaClient}/Page/PageContentUrls.cs | 2 +- .../Lib/WikipediaClient}/Page/PageCoordinates.cs | 2 +- .../Lib/WikipediaClient}/Page/PageImage.cs | 2 +- .../Lib/WikipediaClient}/Page/PageNamespace.cs | 2 +- .../Lib/WikipediaClient}/Page/PagePreview.cs | 2 +- .../Lib/WikipediaClient}/Page/PageTitles.cs | 2 +- .../Lib/WikipediaClient}/Page/PageTypes.cs | 2 +- .../Lib/WikipediaClient}/WikipediaClient.cs | 4 ++-- Geekbot.net/Program.cs | 2 +- WikipediaApi/WikipediaApi.csproj | 8 -------- 15 files changed, 16 insertions(+), 30 deletions(-) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/IWikipediaClient.cs (63%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageApiUrls.cs (84%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageContentUrlCollection.cs (73%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageContentUrls.cs (79%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageCoordinates.cs (68%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageImage.cs (76%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageNamespace.cs (68%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PagePreview.cs (94%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageTitles.cs (76%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/Page/PageTypes.cs (84%) rename {WikipediaApi => Geekbot.net/Lib/WikipediaClient}/WikipediaClient.cs (87%) delete mode 100644 WikipediaApi/WikipediaApi.csproj diff --git a/Geekbot.net.sln b/Geekbot.net.sln index b542f25..5011ad4 100644 --- a/Geekbot.net.sln +++ b/Geekbot.net.sln @@ -7,8 +7,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Geekbot.net", "Geekbot.net/ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WikipediaApi", "WikipediaApi\WikipediaApi.csproj", "{1084D499-EF94-4834-9E6A-B2AD81B60078}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -23,10 +21,6 @@ Global {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Debug|Any CPU.Build.0 = Debug|Any CPU {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Release|Any CPU.ActiveCfg = Release|Any CPU {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Release|Any CPU.Build.0 = Release|Any CPU - {1084D499-EF94-4834-9E6A-B2AD81B60078}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1084D499-EF94-4834-9E6A-B2AD81B60078}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1084D499-EF94-4834-9E6A-B2AD81B60078}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1084D499-EF94-4834-9E6A-B2AD81B60078}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Geekbot.net/Commands/Integrations/Wikipedia.cs b/Geekbot.net/Commands/Integrations/Wikipedia.cs index 9124670..93f68fd 100644 --- a/Geekbot.net/Commands/Integrations/Wikipedia.cs +++ b/Geekbot.net/Commands/Integrations/Wikipedia.cs @@ -8,9 +8,9 @@ using Discord.Commands; using Geekbot.net.Database; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.WikipediaClient; +using Geekbot.net.Lib.WikipediaClient.Page; using HtmlAgilityPack; -using WikipediaApi; -using WikipediaApi.Page; namespace Geekbot.net.Commands.Integrations { diff --git a/WikipediaApi/IWikipediaClient.cs b/Geekbot.net/Lib/WikipediaClient/IWikipediaClient.cs similarity index 63% rename from WikipediaApi/IWikipediaClient.cs rename to Geekbot.net/Lib/WikipediaClient/IWikipediaClient.cs index 4d1dae9..c6cdf3d 100644 --- a/WikipediaApi/IWikipediaClient.cs +++ b/Geekbot.net/Lib/WikipediaClient/IWikipediaClient.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using WikipediaApi.Page; +using Geekbot.net.Lib.WikipediaClient.Page; -namespace WikipediaApi +namespace Geekbot.net.Lib.WikipediaClient { public interface IWikipediaClient { diff --git a/WikipediaApi/Page/PageApiUrls.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageApiUrls.cs similarity index 84% rename from WikipediaApi/Page/PageApiUrls.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageApiUrls.cs index 8a121be..803f4d7 100644 --- a/WikipediaApi/Page/PageApiUrls.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageApiUrls.cs @@ -1,6 +1,6 @@ using System; -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageApiUrls { diff --git a/WikipediaApi/Page/PageContentUrlCollection.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrlCollection.cs similarity index 73% rename from WikipediaApi/Page/PageContentUrlCollection.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageContentUrlCollection.cs index f6c680b..614aaa7 100644 --- a/WikipediaApi/Page/PageContentUrlCollection.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrlCollection.cs @@ -1,4 +1,4 @@ -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageContentUrlCollection { diff --git a/WikipediaApi/Page/PageContentUrls.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrls.cs similarity index 79% rename from WikipediaApi/Page/PageContentUrls.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageContentUrls.cs index 64a80dc..faf7bb5 100644 --- a/WikipediaApi/Page/PageContentUrls.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrls.cs @@ -1,6 +1,6 @@ using System; -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageContentUrls { diff --git a/WikipediaApi/Page/PageCoordinates.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageCoordinates.cs similarity index 68% rename from WikipediaApi/Page/PageCoordinates.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageCoordinates.cs index 7fa42ba..ce67f9b 100644 --- a/WikipediaApi/Page/PageCoordinates.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageCoordinates.cs @@ -1,4 +1,4 @@ -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageCoordinates { diff --git a/WikipediaApi/Page/PageImage.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageImage.cs similarity index 76% rename from WikipediaApi/Page/PageImage.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageImage.cs index 4a8b28d..cdcc2a9 100644 --- a/WikipediaApi/Page/PageImage.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageImage.cs @@ -1,6 +1,6 @@ using System; -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageImage { diff --git a/WikipediaApi/Page/PageNamespace.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageNamespace.cs similarity index 68% rename from WikipediaApi/Page/PageNamespace.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageNamespace.cs index 66600b6..798e6b9 100644 --- a/WikipediaApi/Page/PageNamespace.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageNamespace.cs @@ -1,4 +1,4 @@ -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageNamespace { diff --git a/WikipediaApi/Page/PagePreview.cs b/Geekbot.net/Lib/WikipediaClient/Page/PagePreview.cs similarity index 94% rename from WikipediaApi/Page/PagePreview.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PagePreview.cs index 8db9dad..37434d3 100644 --- a/WikipediaApi/Page/PagePreview.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PagePreview.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PagePreview { diff --git a/WikipediaApi/Page/PageTitles.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageTitles.cs similarity index 76% rename from WikipediaApi/Page/PageTitles.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageTitles.cs index 31a55b9..dcc2cea 100644 --- a/WikipediaApi/Page/PageTitles.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageTitles.cs @@ -1,4 +1,4 @@ -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public class PageTitles { diff --git a/WikipediaApi/Page/PageTypes.cs b/Geekbot.net/Lib/WikipediaClient/Page/PageTypes.cs similarity index 84% rename from WikipediaApi/Page/PageTypes.cs rename to Geekbot.net/Lib/WikipediaClient/Page/PageTypes.cs index a415d75..63cd4d2 100644 --- a/WikipediaApi/Page/PageTypes.cs +++ b/Geekbot.net/Lib/WikipediaClient/Page/PageTypes.cs @@ -1,6 +1,6 @@ using System.Runtime.Serialization; -namespace WikipediaApi.Page +namespace Geekbot.net.Lib.WikipediaClient.Page { public enum PageTypes { diff --git a/WikipediaApi/WikipediaClient.cs b/Geekbot.net/Lib/WikipediaClient/WikipediaClient.cs similarity index 87% rename from WikipediaApi/WikipediaClient.cs rename to Geekbot.net/Lib/WikipediaClient/WikipediaClient.cs index 6576f3d..ed4902a 100644 --- a/WikipediaApi/WikipediaClient.cs +++ b/Geekbot.net/Lib/WikipediaClient/WikipediaClient.cs @@ -1,9 +1,9 @@ using System.Net.Http; using System.Threading.Tasks; +using Geekbot.net.Lib.WikipediaClient.Page; using Newtonsoft.Json; -using WikipediaApi.Page; -namespace WikipediaApi +namespace Geekbot.net.Lib.WikipediaClient { public class WikipediaClient : IWikipediaClient { diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 689c170..5876c4a 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -24,10 +24,10 @@ using Geekbot.net.Lib.Media; using Geekbot.net.Lib.RandomNumberGenerator; using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.UserRepository; +using Geekbot.net.Lib.WikipediaClient; using Geekbot.net.WebApi; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using WikipediaApi; namespace Geekbot.net { diff --git a/WikipediaApi/WikipediaApi.csproj b/WikipediaApi/WikipediaApi.csproj deleted file mode 100644 index e53e3c2..0000000 --- a/WikipediaApi/WikipediaApi.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - net5.0 - - - - - \ No newline at end of file From 7b6dd2d2f907bb770a8c7a0361ae598c9ab47c32 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Aug 2020 21:17:02 +0200 Subject: [PATCH 080/264] Rename the clients namescape to MalClient, because that was the only thing in there, while other clients got their own namespaces --- Geekbot.net/Commands/Integrations/Mal.cs | 2 +- Geekbot.net/Lib/{Clients => MalClient}/IMalClient.cs | 2 +- Geekbot.net/Lib/{Clients => MalClient}/MalClient.cs | 2 +- Geekbot.net/Program.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename Geekbot.net/Lib/{Clients => MalClient}/IMalClient.cs (83%) rename Geekbot.net/Lib/{Clients => MalClient}/MalClient.cs (95%) diff --git a/Geekbot.net/Commands/Integrations/Mal.cs b/Geekbot.net/Commands/Integrations/Mal.cs index ecc91bf..f8aeb95 100644 --- a/Geekbot.net/Commands/Integrations/Mal.cs +++ b/Geekbot.net/Commands/Integrations/Mal.cs @@ -4,9 +4,9 @@ using System.Web; using System.Xml; using Discord; using Discord.Commands; -using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; +using Geekbot.net.Lib.MalClient; namespace Geekbot.net.Commands.Integrations { diff --git a/Geekbot.net/Lib/Clients/IMalClient.cs b/Geekbot.net/Lib/MalClient/IMalClient.cs similarity index 83% rename from Geekbot.net/Lib/Clients/IMalClient.cs rename to Geekbot.net/Lib/MalClient/IMalClient.cs index f59c511..6aaab05 100644 --- a/Geekbot.net/Lib/Clients/IMalClient.cs +++ b/Geekbot.net/Lib/MalClient/IMalClient.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using MyAnimeListSharp.Core; -namespace Geekbot.net.Lib.Clients +namespace Geekbot.net.Lib.MalClient { public interface IMalClient { diff --git a/Geekbot.net/Lib/Clients/MalClient.cs b/Geekbot.net/Lib/MalClient/MalClient.cs similarity index 95% rename from Geekbot.net/Lib/Clients/MalClient.cs rename to Geekbot.net/Lib/MalClient/MalClient.cs index 8e5d950..3f121ea 100644 --- a/Geekbot.net/Lib/Clients/MalClient.cs +++ b/Geekbot.net/Lib/MalClient/MalClient.cs @@ -5,7 +5,7 @@ using MyAnimeListSharp.Auth; using MyAnimeListSharp.Core; using MyAnimeListSharp.Facade.Async; -namespace Geekbot.net.Lib.Clients +namespace Geekbot.net.Lib.MalClient { public class MalClient : IMalClient { diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index 5876c4a..c55f390 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -9,7 +9,6 @@ using Discord.WebSocket; using Geekbot.net.Database; using Geekbot.net.Handlers; using Geekbot.net.Lib; -using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.DiceParser; using Geekbot.net.Lib.ErrorHandling; @@ -20,6 +19,7 @@ using Geekbot.net.Lib.KvInMemoryStore; using Geekbot.net.Lib.Levels; using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Logger; +using Geekbot.net.Lib.MalClient; using Geekbot.net.Lib.Media; using Geekbot.net.Lib.RandomNumberGenerator; using Geekbot.net.Lib.ReactionListener; From fc0af492addf933ae08aec4f953110e4be6bcad1 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Aug 2020 22:24:01 +0200 Subject: [PATCH 081/264] Split Geekbot.net into src/Bot, src/Core, and src/Web --- .gitignore | 14 ++-- Geekbot.net.sln | 24 +++++-- Geekbot.net/Geekbot.net.csproj | 64 ------------------ .../Converters/EmojiConverter.test.cs | 4 +- .../DiceParser/DiceParser.test.cs | 9 ++- .../DiceParser/SingleDie.test.cs | 6 +- Tests/{Lib => Core}/Levels/LevelCalc.test.cs | 5 +- .../TranslationGuildContext.test.cs | 4 +- .../Localization/Translations.test.cs | 4 +- Tests/Tests.csproj | 2 +- src/Bot/Bot.csproj | 43 ++++++++++++ .../Bot}/Commands/Admin/Admin.cs | 12 ++-- .../Bot}/Commands/Admin/Mod.cs | 6 +- .../Bot}/Commands/Admin/Owner/Owner.cs | 10 +-- .../Bot}/Commands/Admin/Role.cs | 16 ++--- .../Bot}/Commands/Games/Pokedex.cs | 6 +- .../Bot}/Commands/Games/Roll/Roll.cs | 16 ++--- .../Bot}/Commands/Games/Roll/RollTimeout.cs | 2 +- .../Commands/Integrations/LolMmr/LolMmr.cs | 6 +- .../Commands/Integrations/LolMmr/LolMmrDto.cs | 2 +- .../Integrations/LolMmr/LolMrrInfoDto.cs | 3 +- .../Integrations/MagicTheGathering.cs | 8 +-- .../Bot}/Commands/Integrations/Mal.cs | 8 +-- .../UbranDictionary/UrbanDictListItemDto.cs | 2 +- .../UbranDictionary/UrbanDictResponseDto.cs | 2 +- .../UbranDictionary/UrbanDictionary.cs | 8 +-- .../Bot}/Commands/Integrations/Wikipedia.cs | 12 ++-- .../Bot}/Commands/Integrations/Youtube.cs | 6 +- .../BenedictCumberbatchNameGenerator.cs | 6 +- .../Bot}/Commands/Randomness/Cat/Cat.cs | 6 +- .../Commands/Randomness/Cat/CatResponseDto.cs | 2 +- .../Chuck/ChuckNorrisJokeResponseDto.cs | 2 +- .../Randomness/Chuck/ChuckNorrisJokes.cs | 6 +- .../Randomness/Dad/DadJokeResponseDto.cs | 2 +- .../Bot}/Commands/Randomness/Dad/DadJokes.cs | 6 +- .../Bot}/Commands/Randomness/Dog/Dog.cs | 6 +- .../Commands/Randomness/Dog/DogResponseDto.cs | 2 +- .../Bot}/Commands/Randomness/EightBall.cs | 4 +- .../Bot}/Commands/Randomness/Fortune.cs | 4 +- .../Bot}/Commands/Randomness/Gdq.cs | 4 +- .../Randomness/Greetings/GreetingBaseDto.cs | 2 +- .../Randomness/Greetings/GreetingDto.cs | 2 +- .../Randomness/Greetings/Greetings.cs | 8 +-- .../Bot}/Commands/Randomness/Kanye/Kanye.cs | 6 +- .../Randomness/Kanye/KanyeResponseDto.cs | 2 +- .../Bot}/Commands/Randomness/RandomAnimals.cs | 4 +- .../Bot}/Commands/Randomness/Ship.cs | 14 ++-- .../Bot}/Commands/Randomness/Slap.cs | 10 +-- .../Bot}/Commands/Rpg/Cookies.cs | 16 ++--- .../Bot}/Commands/User/GuildInfo.cs | 12 ++-- .../Bot}/Commands/User/Karma.cs | 14 ++-- .../Bot}/Commands/User/Ranking/Rank.cs | 18 ++--- .../Bot}/Commands/User/Stats.cs | 12 ++-- .../Bot}/Commands/Utils/AvatarGetter.cs | 4 +- .../Commands/Utils/Changelog/Changelog.cs | 6 +- .../Utils/Changelog/CommitAuthorDto.cs | 2 +- .../Commands/Utils/Changelog/CommitDto.cs | 2 +- .../Commands/Utils/Changelog/CommitInfoDto.cs | 2 +- .../Bot}/Commands/Utils/Choose.cs | 6 +- .../Bot}/Commands/Utils/Corona/CoronaStats.cs | 9 ++- .../Commands/Utils/Corona/CoronaSummaryDto.cs | 2 +- .../Bot}/Commands/Utils/Dice.cs | 6 +- .../Bot}/Commands/Utils/Emojify.cs | 6 +- .../Bot}/Commands/Utils/Help.cs | 4 +- .../Bot}/Commands/Utils/Info.cs | 8 +-- .../Bot}/Commands/Utils/Lmgtfy.cs | 4 +- .../Bot}/Commands/Utils/Ping.cs | 2 +- .../Bot}/Commands/Utils/Quote/Quote.cs | 18 ++--- .../Commands/Utils/Quote/QuoteObjectDto.cs | 2 +- .../Bot}/Handlers/CommandHandler.cs | 10 +-- .../Bot}/Handlers/MessageDeletedHandler.cs | 8 +-- .../Bot}/Handlers/ReactionHandler.cs | 4 +- .../Bot}/Handlers/StatsHandler.cs | 10 +-- .../Bot}/Handlers/UserHandler.cs | 10 +-- {Geekbot.net => src/Bot}/Logs/.keep | 0 {Geekbot.net => src/Bot}/Program.cs | 42 ++++++------ {Geekbot.net => src/Bot}/Storage/croissant | 0 {Geekbot.net => src/Bot}/Storage/dab | 0 {Geekbot.net => src/Bot}/Storage/fortunes | 0 {Geekbot.net => src/Bot}/Storage/foxes | 0 {Geekbot.net => src/Bot}/Storage/pandas | 0 {Geekbot.net => src/Bot}/Storage/penguins | 0 {Geekbot.net => src/Bot}/Storage/pumpkin | 0 {Geekbot.net => src/Bot}/Storage/squirrel | 0 {Geekbot.net => src/Bot}/Storage/turtles | 0 {Geekbot.net => src/Bot}/derp.ico | Bin .../DisableInDirectMessageAttribute.cs | 2 +- {Geekbot.net/Lib => src/Core}/Constants.cs | 4 +- .../Core}/Converters/EmojiConverter.cs | 2 +- .../Core}/Converters/IEmojiConverter.cs | 2 +- .../Core}/Converters/IMtgManaConverter.cs | 2 +- .../Core}/Converters/MtgManaConverter.cs | 2 +- src/Core/Core.csproj | 40 +++++++++++ .../Core}/Database/DatabaseContext.cs | 4 +- .../Core}/Database/DatabaseInitializer.cs | 7 +- .../Core}/Database/InMemoryDatabase.cs | 2 +- .../LoggingAdapter/NpgsqlLoggingAdapter.cs | 5 +- .../NpgsqlLoggingProviderAdapter.cs | 5 +- .../Core}/Database/Models/CookiesModel.cs | 2 +- .../Core}/Database/Models/GlobalsModel.cs | 2 +- .../Database/Models/GuildSettingsModel.cs | 2 +- .../Core}/Database/Models/KarmaModel.cs | 2 +- .../Core}/Database/Models/MessagesModel.cs | 2 +- .../Core}/Database/Models/QuoteModel.cs | 2 +- .../Database/Models/ReactionListenerModel.cs | 2 +- .../Database/Models/RoleSelfServiceModel.cs | 2 +- .../Core}/Database/Models/RollsModel.cs | 2 +- .../Core}/Database/Models/ShipsModel.cs | 2 +- .../Core}/Database/Models/SlapsModel.cs | 2 +- .../Core}/Database/Models/UserModel.cs | 3 +- .../Core}/Database/SqlConnectionString.cs | 2 +- .../Core}/Database/SqlDatabase.cs | 2 +- .../Core}/DiceParser/DiceException.cs | 2 +- .../Lib => src/Core}/DiceParser/DiceInput.cs | 2 +- .../Core}/DiceParser/DiceInputOptions.cs | 2 +- .../Lib => src/Core}/DiceParser/DiceParser.cs | 4 +- .../Core}/DiceParser/DieAdvantageType.cs | 2 +- .../Lib => src/Core}/DiceParser/DieResult.cs | 2 +- .../Core}/DiceParser/IDiceParser.cs | 2 +- .../Lib => src/Core}/DiceParser/SingleDie.cs | 6 +- .../Core}/ErrorHandling/ErrorHandler.cs | 6 +- .../Core}/ErrorHandling/IErrorHandler.cs | 2 +- .../Core}/Extensions/DbSetExtensions.cs | 2 +- .../Extensions/EmbedBuilderExtensions.cs | 2 +- .../Core}/Extensions/IntExtensions.cs | 2 +- .../Core}/Extensions/LongExtensions.cs | 2 +- .../Core}/Extensions/StringExtensions.cs | 2 +- .../Core}/Extensions/UlongExtensions.cs | 2 +- .../Lib => src/Core}/GeekbotExitCode.cs | 2 +- .../Core}/GlobalSettings/GlobalSettings.cs | 6 +- .../Core}/GlobalSettings/IGlobalSettings.cs | 4 +- .../GuildSettingsManager.cs | 8 +-- .../IGuildSettingsManager.cs | 4 +- .../Highscores/HighscoreListEmptyException.cs | 2 +- .../Core}/Highscores/HighscoreManager.cs | 8 +-- .../Core}/Highscores/HighscoreTypes.cs | 2 +- .../Core}/Highscores/HighscoreUserDto.cs | 2 +- .../Core}/Highscores/IHighscoreManager.cs | 2 +- .../Lib => src/Core}/HttpAbstractions.cs | 2 +- .../Core}/KvInMemoryStore/IKvInMemoryStore.cs | 2 +- .../Core}/KvInMemoryStore/KvInMemoryStore.cs | 2 +- .../Lib => src/Core}/Levels/ILevelCalc.cs | 2 +- .../Lib => src/Core}/Levels/LevelCalc.cs | 2 +- .../Core}/Localization/ITranslationHandler.cs | 2 +- .../Localization/TranslationGuildContext.cs | 2 +- .../Core}/Localization/TranslationHandler.cs | 6 +- .../Core}/Localization/Translations.yml | 0 .../Lib => src/Core}/Logger/DiscordLogger.cs | 2 +- .../Lib => src/Core}/Logger/GeekbotLogger.cs | 2 +- .../Lib => src/Core}/Logger/IDiscordLogger.cs | 2 +- .../Lib => src/Core}/Logger/IGeekbotLogger.cs | 2 +- .../Lib => src/Core}/Logger/LogDto.cs | 2 +- .../Lib => src/Core}/Logger/LogSource.cs | 2 +- .../Lib => src/Core}/Logger/LoggerFactory.cs | 2 +- .../Lib => src/Core}/Logger/MessageDto.cs | 2 +- .../Core}/Logger/SimpleConextConverter.cs | 2 +- .../Lib => src/Core}/MalClient/IMalClient.cs | 2 +- .../Lib => src/Core}/MalClient/MalClient.cs | 6 +- .../Core}/Media/FortunesProvider.cs | 6 +- .../Core}/Media/IFortunesProvider.cs | 2 +- .../Lib => src/Core}/Media/IMediaProvider.cs | 2 +- .../Lib => src/Core}/Media/MediaProvider.cs | 10 ++- .../Lib => src/Core}/Media/MediaType.cs | 2 +- .../Core}/Polyfills/UserPolyfillDto.cs | 4 +- .../IRandomNumberGenerator.cs | 2 +- .../RandomNumberGenerator.cs | 2 +- .../ReactionListener/IReactionListener.cs | 2 +- .../ReactionListener/ReactionListener.cs | 8 +-- .../Lib => src/Core}/RunParameters.cs | 2 +- .../Core}/UserRepository/IUserRepository.cs | 4 +- .../Core}/UserRepository/UserRepository.cs | 11 ++- .../Core}/WikipediaClient/IWikipediaClient.cs | 4 +- .../Core}/WikipediaClient/Page/PageApiUrls.cs | 2 +- .../Page/PageContentUrlCollection.cs | 2 +- .../WikipediaClient/Page/PageContentUrls.cs | 2 +- .../WikipediaClient/Page/PageCoordinates.cs | 2 +- .../Core}/WikipediaClient/Page/PageImage.cs | 2 +- .../WikipediaClient/Page/PageNamespace.cs | 2 +- .../Core}/WikipediaClient/Page/PagePreview.cs | 2 +- .../Core}/WikipediaClient/Page/PageTitles.cs | 2 +- .../Core}/WikipediaClient/Page/PageTypes.cs | 2 +- .../Core}/WikipediaClient/WikipediaClient.cs | 4 +- {Geekbot.net/WebApi => src/Web}/ApiError.cs | 2 +- .../Callback/CallbackController.cs | 4 +- .../Callback/CallbackTokenResponseDto.cs | 2 +- .../Controllers/Commands/CommandController.cs | 2 +- .../Web}/Controllers/Commands/CommandDto.cs | 2 +- .../Controllers/Commands/CommandParamDto.cs | 2 +- .../Highscores/HighscoreController.cs | 4 +- .../HighscoreControllerPostBodyDto.cs | 4 +- .../HighscoreControllerReponseBody.cs | 4 +- .../Web}/Controllers/Status/ApiStatusDto.cs | 2 +- .../Controllers/Status/StatusController.cs | 4 +- .../Web}/Logging/AspLogProvider.cs | 4 +- .../WebApi => src/Web}/Logging/AspLogger.cs | 4 +- src/Web/Web.csproj | 26 +++++++ .../WebApi => src/Web}/WebApiStartup.cs | 16 ++--- 197 files changed, 542 insertions(+), 498 deletions(-) delete mode 100755 Geekbot.net/Geekbot.net.csproj rename Tests/{Lib => Core}/Converters/EmojiConverter.test.cs (94%) rename Tests/{Lib => Core}/DiceParser/DiceParser.test.cs (97%) rename Tests/{Lib => Core}/DiceParser/SingleDie.test.cs (97%) rename Tests/{Lib => Core}/Levels/LevelCalc.test.cs (91%) rename Tests/{Lib => Core}/Localization/TranslationGuildContext.test.cs (95%) rename Tests/{Lib => Core}/Localization/Translations.test.cs (91%) create mode 100644 src/Bot/Bot.csproj rename {Geekbot.net => src/Bot}/Commands/Admin/Admin.cs (95%) rename {Geekbot.net => src/Bot}/Commands/Admin/Mod.cs (87%) rename {Geekbot.net => src/Bot}/Commands/Admin/Owner/Owner.cs (93%) rename {Geekbot.net => src/Bot}/Commands/Admin/Role.cs (96%) rename {Geekbot.net => src/Bot}/Commands/Games/Pokedex.cs (93%) rename {Geekbot.net => src/Bot}/Commands/Games/Roll/Roll.cs (92%) rename {Geekbot.net => src/Bot}/Commands/Games/Roll/RollTimeout.cs (74%) rename {Geekbot.net => src/Bot}/Commands/Integrations/LolMmr/LolMmr.cs (92%) rename {Geekbot.net => src/Bot}/Commands/Integrations/LolMmr/LolMmrDto.cs (76%) rename {Geekbot.net => src/Bot}/Commands/Integrations/LolMmr/LolMrrInfoDto.cs (71%) rename {Geekbot.net => src/Bot}/Commands/Integrations/MagicTheGathering.cs (93%) rename {Geekbot.net => src/Bot}/Commands/Integrations/Mal.cs (94%) rename {Geekbot.net => src/Bot}/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs (81%) rename {Geekbot.net => src/Bot}/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs (73%) rename {Geekbot.net => src/Bot}/Commands/Integrations/UbranDictionary/UrbanDictionary.cs (91%) rename {Geekbot.net => src/Bot}/Commands/Integrations/Wikipedia.cs (92%) rename {Geekbot.net => src/Bot}/Commands/Integrations/Youtube.cs (91%) rename {Geekbot.net => src/Bot}/Commands/Randomness/BenedictCumberbatchNameGenerator.cs (95%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Cat/Cat.cs (86%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Cat/CatResponseDto.cs (62%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs (64%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Chuck/ChuckNorrisJokes.cs (87%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Dad/DadJokeResponseDto.cs (63%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Dad/DadJokes.cs (85%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Dog/Dog.cs (86%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Dog/DogResponseDto.cs (61%) rename {Geekbot.net => src/Bot}/Commands/Randomness/EightBall.cs (95%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Fortune.cs (83%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Gdq.cs (88%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Greetings/GreetingBaseDto.cs (84%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Greetings/GreetingDto.cs (80%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Greetings/Greetings.cs (90%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Kanye/Kanye.cs (87%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Kanye/KanyeResponseDto.cs (73%) rename {Geekbot.net => src/Bot}/Commands/Randomness/RandomAnimals.cs (97%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Ship.cs (91%) rename {Geekbot.net => src/Bot}/Commands/Randomness/Slap.cs (93%) rename {Geekbot.net => src/Bot}/Commands/Rpg/Cookies.cs (92%) rename {Geekbot.net => src/Bot}/Commands/User/GuildInfo.cs (87%) rename {Geekbot.net => src/Bot}/Commands/User/Karma.cs (95%) rename {Geekbot.net => src/Bot}/Commands/User/Ranking/Rank.cs (90%) rename {Geekbot.net => src/Bot}/Commands/User/Stats.cs (94%) rename {Geekbot.net => src/Bot}/Commands/Utils/AvatarGetter.cs (88%) rename {Geekbot.net => src/Bot}/Commands/Utils/Changelog/Changelog.cs (92%) rename {Geekbot.net => src/Bot}/Commands/Utils/Changelog/CommitAuthorDto.cs (77%) rename {Geekbot.net => src/Bot}/Commands/Utils/Changelog/CommitDto.cs (62%) rename {Geekbot.net => src/Bot}/Commands/Utils/Changelog/CommitInfoDto.cs (71%) rename {Geekbot.net => src/Bot}/Commands/Utils/Choose.cs (88%) rename {Geekbot.net => src/Bot}/Commands/Utils/Corona/CoronaStats.cs (94%) rename {Geekbot.net => src/Bot}/Commands/Utils/Corona/CoronaSummaryDto.cs (82%) rename {Geekbot.net => src/Bot}/Commands/Utils/Dice.cs (97%) rename {Geekbot.net => src/Bot}/Commands/Utils/Emojify.cs (88%) rename {Geekbot.net => src/Bot}/Commands/Utils/Help.cs (93%) rename {Geekbot.net => src/Bot}/Commands/Utils/Info.cs (92%) rename {Geekbot.net => src/Bot}/Commands/Utils/Lmgtfy.cs (92%) rename {Geekbot.net => src/Bot}/Commands/Utils/Ping.cs (89%) rename {Geekbot.net => src/Bot}/Commands/Utils/Quote/Quote.cs (97%) rename {Geekbot.net => src/Bot}/Commands/Utils/Quote/QuoteObjectDto.cs (81%) rename {Geekbot.net => src/Bot}/Handlers/CommandHandler.cs (96%) rename {Geekbot.net => src/Bot}/Handlers/MessageDeletedHandler.cs (93%) rename {Geekbot.net => src/Bot}/Handlers/ReactionHandler.cs (94%) rename {Geekbot.net => src/Bot}/Handlers/StatsHandler.cs (92%) rename {Geekbot.net => src/Bot}/Handlers/UserHandler.cs (95%) rename {Geekbot.net => src/Bot}/Logs/.keep (100%) mode change 100755 => 100644 rename {Geekbot.net => src/Bot}/Program.cs (91%) mode change 100755 => 100644 rename {Geekbot.net => src/Bot}/Storage/croissant (100%) rename {Geekbot.net => src/Bot}/Storage/dab (100%) rename {Geekbot.net => src/Bot}/Storage/fortunes (100%) rename {Geekbot.net => src/Bot}/Storage/foxes (100%) rename {Geekbot.net => src/Bot}/Storage/pandas (100%) rename {Geekbot.net => src/Bot}/Storage/penguins (100%) rename {Geekbot.net => src/Bot}/Storage/pumpkin (100%) rename {Geekbot.net => src/Bot}/Storage/squirrel (100%) rename {Geekbot.net => src/Bot}/Storage/turtles (100%) rename {Geekbot.net => src/Bot}/derp.ico (100%) rename {Geekbot.net/Lib => src/Core}/CommandPreconditions/DisableInDirectMessageAttribute.cs (92%) rename {Geekbot.net/Lib => src/Core}/Constants.cs (72%) rename {Geekbot.net/Lib => src/Core}/Converters/EmojiConverter.cs (96%) rename {Geekbot.net/Lib => src/Core}/Converters/IEmojiConverter.cs (74%) rename {Geekbot.net/Lib => src/Core}/Converters/IMtgManaConverter.cs (67%) rename {Geekbot.net/Lib => src/Core}/Converters/MtgManaConverter.cs (96%) create mode 100644 src/Core/Core.csproj rename {Geekbot.net => src/Core}/Database/DatabaseContext.cs (91%) rename {Geekbot.net => src/Core}/Database/DatabaseInitializer.cs (93%) rename {Geekbot.net => src/Core}/Database/InMemoryDatabase.cs (89%) rename {Geekbot.net => src/Core}/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs (93%) rename {Geekbot.net => src/Core}/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs (82%) rename {Geekbot.net => src/Core}/Database/Models/CookiesModel.cs (87%) rename {Geekbot.net => src/Core}/Database/Models/GlobalsModel.cs (85%) rename {Geekbot.net => src/Core}/Database/Models/GuildSettingsModel.cs (90%) rename {Geekbot.net => src/Core}/Database/Models/KarmaModel.cs (87%) rename {Geekbot.net => src/Core}/Database/Models/MessagesModel.cs (85%) rename {Geekbot.net => src/Core}/Database/Models/QuoteModel.cs (93%) rename {Geekbot.net => src/Core}/Database/Models/ReactionListenerModel.cs (91%) rename {Geekbot.net => src/Core}/Database/Models/RoleSelfServiceModel.cs (85%) rename {Geekbot.net => src/Core}/Database/Models/RollsModel.cs (85%) rename {Geekbot.net => src/Core}/Database/Models/ShipsModel.cs (84%) rename {Geekbot.net => src/Core}/Database/Models/SlapsModel.cs (86%) rename {Geekbot.net => src/Core}/Database/Models/UserModel.cs (84%) rename {Geekbot.net => src/Core}/Database/SqlConnectionString.cs (94%) rename {Geekbot.net => src/Core}/Database/SqlDatabase.cs (90%) rename {Geekbot.net/Lib => src/Core}/DiceParser/DiceException.cs (84%) rename {Geekbot.net/Lib => src/Core}/DiceParser/DiceInput.cs (88%) rename {Geekbot.net/Lib => src/Core}/DiceParser/DiceInputOptions.cs (71%) rename {Geekbot.net/Lib => src/Core}/DiceParser/DiceParser.cs (97%) rename {Geekbot.net/Lib => src/Core}/DiceParser/DieAdvantageType.cs (73%) rename {Geekbot.net/Lib => src/Core}/DiceParser/DieResult.cs (96%) rename {Geekbot.net/Lib => src/Core}/DiceParser/IDiceParser.cs (70%) rename {Geekbot.net/Lib => src/Core}/DiceParser/SingleDie.cs (94%) rename {Geekbot.net/Lib => src/Core}/ErrorHandling/ErrorHandler.cs (97%) rename {Geekbot.net/Lib => src/Core}/ErrorHandling/IErrorHandler.cs (86%) rename {Geekbot.net/Lib => src/Core}/Extensions/DbSetExtensions.cs (94%) rename {Geekbot.net/Lib => src/Core}/Extensions/EmbedBuilderExtensions.cs (86%) rename {Geekbot.net/Lib => src/Core}/Extensions/IntExtensions.cs (87%) rename {Geekbot.net/Lib => src/Core}/Extensions/LongExtensions.cs (79%) rename {Geekbot.net/Lib => src/Core}/Extensions/StringExtensions.cs (83%) rename {Geekbot.net/Lib => src/Core}/Extensions/UlongExtensions.cs (79%) rename {Geekbot.net/Lib => src/Core}/GeekbotExitCode.cs (88%) rename {Geekbot.net/Lib => src/Core}/GlobalSettings/GlobalSettings.cs (91%) rename {Geekbot.net/Lib => src/Core}/GlobalSettings/IGlobalSettings.cs (72%) rename {Geekbot.net/Lib => src/Core}/GuildSettingsManager/GuildSettingsManager.cs (93%) rename {Geekbot.net/Lib => src/Core}/GuildSettingsManager/IGuildSettingsManager.cs (73%) rename {Geekbot.net/Lib => src/Core}/Highscores/HighscoreListEmptyException.cs (86%) rename {Geekbot.net/Lib => src/Core}/Highscores/HighscoreManager.cs (93%) rename {Geekbot.net/Lib => src/Core}/Highscores/HighscoreTypes.cs (69%) rename {Geekbot.net/Lib => src/Core}/Highscores/HighscoreUserDto.cs (82%) rename {Geekbot.net/Lib => src/Core}/Highscores/IHighscoreManager.cs (89%) rename {Geekbot.net/Lib => src/Core}/HttpAbstractions.cs (97%) rename {Geekbot.net/Lib => src/Core}/KvInMemoryStore/IKvInMemoryStore.cs (80%) rename {Geekbot.net/Lib => src/Core}/KvInMemoryStore/KvInMemoryStore.cs (93%) rename {Geekbot.net/Lib => src/Core}/Levels/ILevelCalc.cs (67%) rename {Geekbot.net/Lib => src/Core}/Levels/LevelCalc.cs (95%) rename {Geekbot.net/Lib => src/Core}/Localization/ITranslationHandler.cs (91%) rename {Geekbot.net/Lib => src/Core}/Localization/TranslationGuildContext.cs (95%) rename {Geekbot.net/Lib => src/Core}/Localization/TranslationHandler.cs (96%) rename {Geekbot.net/Lib => src/Core}/Localization/Translations.yml (100%) rename {Geekbot.net/Lib => src/Core}/Logger/DiscordLogger.cs (95%) rename {Geekbot.net/Lib => src/Core}/Logger/GeekbotLogger.cs (96%) rename {Geekbot.net/Lib => src/Core}/Logger/IDiscordLogger.cs (76%) rename {Geekbot.net/Lib => src/Core}/Logger/IGeekbotLogger.cs (92%) rename {Geekbot.net/Lib => src/Core}/Logger/LogDto.cs (88%) rename {Geekbot.net/Lib => src/Core}/Logger/LogSource.cs (87%) rename {Geekbot.net/Lib => src/Core}/Logger/LoggerFactory.cs (98%) rename {Geekbot.net/Lib => src/Core}/Logger/MessageDto.cs (92%) rename {Geekbot.net/Lib => src/Core}/Logger/SimpleConextConverter.cs (96%) rename {Geekbot.net/Lib => src/Core}/MalClient/IMalClient.cs (83%) rename {Geekbot.net/Lib => src/Core}/MalClient/MalClient.cs (92%) rename {Geekbot.net/Lib => src/Core}/Media/FortunesProvider.cs (85%) rename {Geekbot.net/Lib => src/Core}/Media/IFortunesProvider.cs (68%) rename {Geekbot.net/Lib => src/Core}/Media/IMediaProvider.cs (69%) rename {Geekbot.net/Lib => src/Core}/Media/MediaProvider.cs (92%) rename {Geekbot.net/Lib => src/Core}/Media/MediaType.cs (84%) rename {Geekbot.net/Lib => src/Core}/Polyfills/UserPolyfillDto.cs (90%) rename {Geekbot.net/Lib => src/Core}/RandomNumberGenerator/IRandomNumberGenerator.cs (67%) rename {Geekbot.net/Lib => src/Core}/RandomNumberGenerator/RandomNumberGenerator.cs (92%) rename {Geekbot.net/Lib => src/Core}/ReactionListener/IReactionListener.cs (89%) rename {Geekbot.net/Lib => src/Core}/ReactionListener/ReactionListener.cs (92%) rename {Geekbot.net/Lib => src/Core}/RunParameters.cs (97%) rename {Geekbot.net/Lib => src/Core}/UserRepository/IUserRepository.cs (68%) rename {Geekbot.net/Lib => src/Core}/UserRepository/UserRepository.cs (88%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/IWikipediaClient.cs (63%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageApiUrls.cs (84%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageContentUrlCollection.cs (73%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageContentUrls.cs (79%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageCoordinates.cs (68%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageImage.cs (76%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageNamespace.cs (68%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PagePreview.cs (94%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageTitles.cs (76%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/Page/PageTypes.cs (84%) rename {Geekbot.net/Lib => src/Core}/WikipediaClient/WikipediaClient.cs (87%) rename {Geekbot.net/WebApi => src/Web}/ApiError.cs (70%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Callback/CallbackController.cs (96%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Callback/CallbackTokenResponseDto.cs (85%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Commands/CommandController.cs (93%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Commands/CommandDto.cs (83%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Commands/CommandParamDto.cs (74%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Highscores/HighscoreController.cs (92%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Highscores/HighscoreControllerPostBodyDto.cs (76%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Highscores/HighscoreControllerReponseBody.cs (66%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Status/ApiStatusDto.cs (75%) rename {Geekbot.net/WebApi => src/Web}/Controllers/Status/StatusController.cs (89%) rename {Geekbot.net/WebApi => src/Web}/Logging/AspLogProvider.cs (88%) rename {Geekbot.net/WebApi => src/Web}/Logging/AspLogger.cs (95%) create mode 100644 src/Web/Web.csproj rename {Geekbot.net/WebApi => src/Web}/WebApiStartup.cs (86%) diff --git a/.gitignore b/.gitignore index 5db124b..066c4b4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,10 @@ -*/bin/ -*/obj/ -Geekbot.net/tmp/ +/*/**/bin +/*/**/obj +src/Bot/tmp/ +src/Bot/Logs/* +!/src/Bot/Logs/.keep .vs/ -UpgradeLog.htm .idea .vscode -Geekbot.net/Logs/* -!/Geekbot.net/Logs/.keep Geekbot.net.sln.DotSettings.user -Geekbot.net/temp/ -app \ No newline at end of file +app diff --git a/Geekbot.net.sln b/Geekbot.net.sln index 5011ad4..5dc5e4b 100644 --- a/Geekbot.net.sln +++ b/Geekbot.net.sln @@ -3,24 +3,36 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Geekbot.net", "Geekbot.net/Geekbot.net.csproj", "{FDCB3D92-E7B5-47BB-A9B5-CFAEFA57CDB4}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "src\Core\Core.csproj", "{47671723-52A9-4668-BBC5-2BA76AE3B288}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Web", "src\Web\Web.csproj", "{0A63D5DC-6325-4F53-8ED2-9843239B76CC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bot", "src\Bot\Bot.csproj", "{DBF79896-9F7F-443D-B336-155E276DFF16}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FDCB3D92-E7B5-47BB-A9B5-CFAEFA57CDB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FDCB3D92-E7B5-47BB-A9B5-CFAEFA57CDB4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FDCB3D92-E7B5-47BB-A9B5-CFAEFA57CDB4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FDCB3D92-E7B5-47BB-A9B5-CFAEFA57CDB4}.Release|Any CPU.Build.0 = Release|Any CPU {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Debug|Any CPU.Build.0 = Debug|Any CPU {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Release|Any CPU.ActiveCfg = Release|Any CPU {4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}.Release|Any CPU.Build.0 = Release|Any CPU + {47671723-52A9-4668-BBC5-2BA76AE3B288}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47671723-52A9-4668-BBC5-2BA76AE3B288}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47671723-52A9-4668-BBC5-2BA76AE3B288}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47671723-52A9-4668-BBC5-2BA76AE3B288}.Release|Any CPU.Build.0 = Release|Any CPU + {0A63D5DC-6325-4F53-8ED2-9843239B76CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A63D5DC-6325-4F53-8ED2-9843239B76CC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A63D5DC-6325-4F53-8ED2-9843239B76CC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A63D5DC-6325-4F53-8ED2-9843239B76CC}.Release|Any CPU.Build.0 = Release|Any CPU + {DBF79896-9F7F-443D-B336-155E276DFF16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DBF79896-9F7F-443D-B336-155E276DFF16}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DBF79896-9F7F-443D-B336-155E276DFF16}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DBF79896-9F7F-443D-B336-155E276DFF16}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Geekbot.net/Geekbot.net.csproj b/Geekbot.net/Geekbot.net.csproj deleted file mode 100755 index 006e6cb..0000000 --- a/Geekbot.net/Geekbot.net.csproj +++ /dev/null @@ -1,64 +0,0 @@ - - - Exe - net5.0 - win-x64;linux-x64 - derp.ico - $(VersionSuffix) - $(VersionSuffix) - 0.0.0-DEV - Pizza and Coffee Studios - Pizza and Coffee Studios - A Discord bot - https://github.com/pizzaandcoffee/Geekbot.net - NU1701 - git - https://geekbot.pizzaandcoffee.rocks - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - Always - - - - - - \ No newline at end of file diff --git a/Tests/Lib/Converters/EmojiConverter.test.cs b/Tests/Core/Converters/EmojiConverter.test.cs similarity index 94% rename from Tests/Lib/Converters/EmojiConverter.test.cs rename to Tests/Core/Converters/EmojiConverter.test.cs index ad37824..f58d669 100644 --- a/Tests/Lib/Converters/EmojiConverter.test.cs +++ b/Tests/Core/Converters/EmojiConverter.test.cs @@ -1,7 +1,7 @@ -using Geekbot.net.Lib.Converters; +using Geekbot.Core.Converters; using Xunit; -namespace Tests.Lib.Converters +namespace Tests.Core.Converters { public class EmojiConverterTest { diff --git a/Tests/Lib/DiceParser/DiceParser.test.cs b/Tests/Core/DiceParser/DiceParser.test.cs similarity index 97% rename from Tests/Lib/DiceParser/DiceParser.test.cs rename to Tests/Core/DiceParser/DiceParser.test.cs index 48a362c..8a9163a 100644 --- a/Tests/Lib/DiceParser/DiceParser.test.cs +++ b/Tests/Core/DiceParser/DiceParser.test.cs @@ -1,11 +1,10 @@ using System.Collections.Generic; using System.Text.Json; -using Geekbot.net.Lib.DiceParser; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.DiceParser; +using Geekbot.Core.RandomNumberGenerator; using Xunit; -using YamlDotNet.Serialization; -namespace Tests.Lib.DiceParser +namespace Tests.Core.DiceParser { public class DiceParserTest { @@ -200,7 +199,7 @@ namespace Tests.Lib.DiceParser [Theory, MemberData(nameof(DiceParserTestData))] public void DiceParserTestFunc(string testName, DiceParserTestDto testData) { - var parser = new Geekbot.net.Lib.DiceParser.DiceParser(_randomNumberGenerator); + var parser = new Geekbot.Core.DiceParser.DiceParser(_randomNumberGenerator); var result = parser.Parse(testData.Input); Assert.Equal(JsonSerializer.Serialize(result), JsonSerializer.Serialize(testData.Expected)); diff --git a/Tests/Lib/DiceParser/SingleDie.test.cs b/Tests/Core/DiceParser/SingleDie.test.cs similarity index 97% rename from Tests/Lib/DiceParser/SingleDie.test.cs rename to Tests/Core/DiceParser/SingleDie.test.cs index 2309f98..813a33b 100644 --- a/Tests/Lib/DiceParser/SingleDie.test.cs +++ b/Tests/Core/DiceParser/SingleDie.test.cs @@ -1,8 +1,8 @@ -using Geekbot.net.Lib.DiceParser; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.DiceParser; +using Geekbot.Core.RandomNumberGenerator; using Xunit; -namespace Tests.Lib.DiceParser +namespace Tests.Core.DiceParser { public class SingleDieTest { diff --git a/Tests/Lib/Levels/LevelCalc.test.cs b/Tests/Core/Levels/LevelCalc.test.cs similarity index 91% rename from Tests/Lib/Levels/LevelCalc.test.cs rename to Tests/Core/Levels/LevelCalc.test.cs index 9b4b97c..02db6f5 100644 --- a/Tests/Lib/Levels/LevelCalc.test.cs +++ b/Tests/Core/Levels/LevelCalc.test.cs @@ -1,8 +1,7 @@ -using System.Collections.Generic; -using Geekbot.net.Lib.Levels; +using Geekbot.Core.Levels; using Xunit; -namespace Tests.Lib.Levels +namespace Tests.Core.Levels { public class LevelCalcTest { diff --git a/Tests/Lib/Localization/TranslationGuildContext.test.cs b/Tests/Core/Localization/TranslationGuildContext.test.cs similarity index 95% rename from Tests/Lib/Localization/TranslationGuildContext.test.cs rename to Tests/Core/Localization/TranslationGuildContext.test.cs index aeea0e1..4aaca16 100644 --- a/Tests/Lib/Localization/TranslationGuildContext.test.cs +++ b/Tests/Core/Localization/TranslationGuildContext.test.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; -using Geekbot.net.Lib.Localization; +using Geekbot.Core.Localization; using Moq; using Xunit; -namespace Tests.Lib.Localization +namespace Tests.Core.Localization { public class TranslationGuildContext_test { diff --git a/Tests/Lib/Localization/Translations.test.cs b/Tests/Core/Localization/Translations.test.cs similarity index 91% rename from Tests/Lib/Localization/Translations.test.cs rename to Tests/Core/Localization/Translations.test.cs index 736ed83..d8a0879 100644 --- a/Tests/Lib/Localization/Translations.test.cs +++ b/Tests/Core/Localization/Translations.test.cs @@ -6,7 +6,7 @@ using Xunit; using YamlDotNet.Core; using YamlDotNet.Serialization; -namespace Tests.Lib.Localization +namespace Tests.Core.Localization { public class Translations_test { @@ -14,7 +14,7 @@ namespace Tests.Lib.Localization public void TranslationsYamlIsValid() { // Read the file - var translationFile = File.ReadAllText(Path.GetFullPath("./../../../../Geekbot.net/Lib/Localization/Translations.yml")); + var translationFile = File.ReadAllText(Path.GetFullPath("./../../../../src/Core/Localization/Translations.yml")); // Deserialize var input = new StringReader(translationFile); diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index eaf88a3..b8d1fc4 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -15,6 +15,6 @@ - + \ No newline at end of file diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj new file mode 100644 index 0000000..c7889ae --- /dev/null +++ b/src/Bot/Bot.csproj @@ -0,0 +1,43 @@ + + + Exe + net5.0 + win-x64;linux-x64 + derp.ico + $(VersionSuffix) + Geekbot.Bot + Geekbot + $(VersionSuffix) + 0.0.0-DEV + Pizza and Coffee Studios + Pizza and Coffee Studios + A Discord bot + https://github.com/pizzaandcoffee/Geekbot.net + NU1701 + git + https://geekbot.pizzaandcoffee.rocks + + + true + + + + + + + + + + + + + + + PreserveNewest + + + + + + + diff --git a/Geekbot.net/Commands/Admin/Admin.cs b/src/Bot/Commands/Admin/Admin.cs similarity index 95% rename from Geekbot.net/Commands/Admin/Admin.cs rename to src/Bot/Commands/Admin/Admin.cs index 9120971..f6c4210 100644 --- a/Geekbot.net/Commands/Admin/Admin.cs +++ b/src/Bot/Commands/Admin/Admin.cs @@ -4,13 +4,13 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.GuildSettingsManager; -using Geekbot.net.Lib.Localization; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; +using Geekbot.Core.Localization; -namespace Geekbot.net.Commands.Admin +namespace Geekbot.Bot.Commands.Admin { [Group("admin")] [RequireUserPermission(GuildPermission.Administrator)] diff --git a/Geekbot.net/Commands/Admin/Mod.cs b/src/Bot/Commands/Admin/Mod.cs similarity index 87% rename from Geekbot.net/Commands/Admin/Mod.cs rename to src/Bot/Commands/Admin/Mod.cs index b0114a8..b642680 100644 --- a/Geekbot.net/Commands/Admin/Mod.cs +++ b/src/Bot/Commands/Admin/Mod.cs @@ -2,10 +2,10 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Admin +namespace Geekbot.Bot.Commands.Admin { [Group("mod")] [RequireUserPermission(GuildPermission.KickMembers)] diff --git a/Geekbot.net/Commands/Admin/Owner/Owner.cs b/src/Bot/Commands/Admin/Owner/Owner.cs similarity index 93% rename from Geekbot.net/Commands/Admin/Owner/Owner.cs rename to src/Bot/Commands/Admin/Owner/Owner.cs index 996d848..5fa3976 100644 --- a/Geekbot.net/Commands/Admin/Owner/Owner.cs +++ b/src/Bot/Commands/Admin/Owner/Owner.cs @@ -3,12 +3,12 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.GlobalSettings; -using Geekbot.net.Lib.Logger; -using Geekbot.net.Lib.UserRepository; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.GlobalSettings; +using Geekbot.Core.Logger; +using Geekbot.Core.UserRepository; -namespace Geekbot.net.Commands.Admin.Owner +namespace Geekbot.Bot.Commands.Admin.Owner { [Group("owner")] [RequireOwner] diff --git a/Geekbot.net/Commands/Admin/Role.cs b/src/Bot/Commands/Admin/Role.cs similarity index 96% rename from Geekbot.net/Commands/Admin/Role.cs rename to src/Bot/Commands/Admin/Role.cs index 6d4557d..e997fa8 100644 --- a/Geekbot.net/Commands/Admin/Role.cs +++ b/src/Bot/Commands/Admin/Role.cs @@ -5,15 +5,15 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.Net; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.ReactionListener; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Localization; +using Geekbot.Core.ReactionListener; -namespace Geekbot.net.Commands.Admin +namespace Geekbot.Bot.Commands.Admin { [Group("role")] [DisableInDirectMessage] diff --git a/Geekbot.net/Commands/Games/Pokedex.cs b/src/Bot/Commands/Games/Pokedex.cs similarity index 93% rename from Geekbot.net/Commands/Games/Pokedex.cs rename to src/Bot/Commands/Games/Pokedex.cs index a0d2ae0..426761c 100644 --- a/Geekbot.net/Commands/Games/Pokedex.cs +++ b/src/Bot/Commands/Games/Pokedex.cs @@ -3,11 +3,11 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; using PokeAPI; -namespace Geekbot.net.Commands.Games +namespace Geekbot.Bot.Commands.Games { public class Pokedex : ModuleBase { diff --git a/Geekbot.net/Commands/Games/Roll/Roll.cs b/src/Bot/Commands/Games/Roll/Roll.cs similarity index 92% rename from Geekbot.net/Commands/Games/Roll/Roll.cs rename to src/Bot/Commands/Games/Roll/Roll.cs index 1c89f19..6241ba1 100644 --- a/Geekbot.net/Commands/Games/Roll/Roll.cs +++ b/src/Bot/Commands/Games/Roll/Roll.cs @@ -2,15 +2,15 @@ using System.Linq; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.KvInMemoryStore; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.KvInMemoryStore; +using Geekbot.Core.Localization; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Commands.Games.Roll +namespace Geekbot.Bot.Commands.Games.Roll { public class Roll : ModuleBase { diff --git a/Geekbot.net/Commands/Games/Roll/RollTimeout.cs b/src/Bot/Commands/Games/Roll/RollTimeout.cs similarity index 74% rename from Geekbot.net/Commands/Games/Roll/RollTimeout.cs rename to src/Bot/Commands/Games/Roll/RollTimeout.cs index 81a520f..c53101a 100644 --- a/Geekbot.net/Commands/Games/Roll/RollTimeout.cs +++ b/src/Bot/Commands/Games/Roll/RollTimeout.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Commands.Games.Roll +namespace Geekbot.Bot.Commands.Games.Roll { public class RollTimeout { diff --git a/Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs b/src/Bot/Commands/Integrations/LolMmr/LolMmr.cs similarity index 92% rename from Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs rename to src/Bot/Commands/Integrations/LolMmr/LolMmr.cs index 5de7d63..4e75034 100644 --- a/Geekbot.net/Commands/Integrations/LolMmr/LolMmr.cs +++ b/src/Bot/Commands/Integrations/LolMmr/LolMmr.cs @@ -5,10 +5,10 @@ using System.Text; using System.Threading.Tasks; using System.Web; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Integrations.LolMmr +namespace Geekbot.Bot.Commands.Integrations.LolMmr { public class LolMmr : ModuleBase { diff --git a/Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs b/src/Bot/Commands/Integrations/LolMmr/LolMmrDto.cs similarity index 76% rename from Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs rename to src/Bot/Commands/Integrations/LolMmr/LolMmrDto.cs index 4a9887d..51d4c85 100644 --- a/Geekbot.net/Commands/Integrations/LolMmr/LolMmrDto.cs +++ b/src/Bot/Commands/Integrations/LolMmr/LolMmrDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Integrations.LolMmr +namespace Geekbot.Bot.Commands.Integrations.LolMmr { public class LolMmrDto { diff --git a/Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs b/src/Bot/Commands/Integrations/LolMmr/LolMrrInfoDto.cs similarity index 71% rename from Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs rename to src/Bot/Commands/Integrations/LolMmr/LolMrrInfoDto.cs index 55804fd..18b096a 100644 --- a/Geekbot.net/Commands/Integrations/LolMmr/LolMrrInfoDto.cs +++ b/src/Bot/Commands/Integrations/LolMmr/LolMrrInfoDto.cs @@ -1,7 +1,6 @@ -using System; using Newtonsoft.Json; -namespace Geekbot.net.Commands.Integrations.LolMmr +namespace Geekbot.Bot.Commands.Integrations.LolMmr { public class LolMrrInfoDto { diff --git a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs b/src/Bot/Commands/Integrations/MagicTheGathering.cs similarity index 93% rename from Geekbot.net/Commands/Integrations/MagicTheGathering.cs rename to src/Bot/Commands/Integrations/MagicTheGathering.cs index f9e006c..66a87fe 100644 --- a/Geekbot.net/Commands/Integrations/MagicTheGathering.cs +++ b/src/Bot/Commands/Integrations/MagicTheGathering.cs @@ -4,12 +4,12 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib.Converters; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core.Converters; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; using MtgApiManager.Lib.Service; -namespace Geekbot.net.Commands.Integrations +namespace Geekbot.Bot.Commands.Integrations { public class MagicTheGathering : ModuleBase { diff --git a/Geekbot.net/Commands/Integrations/Mal.cs b/src/Bot/Commands/Integrations/Mal.cs similarity index 94% rename from Geekbot.net/Commands/Integrations/Mal.cs rename to src/Bot/Commands/Integrations/Mal.cs index f8aeb95..ae30493 100644 --- a/Geekbot.net/Commands/Integrations/Mal.cs +++ b/src/Bot/Commands/Integrations/Mal.cs @@ -4,11 +4,11 @@ using System.Web; using System.Xml; using Discord; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.MalClient; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.MalClient; -namespace Geekbot.net.Commands.Integrations +namespace Geekbot.Bot.Commands.Integrations { public class Mal : ModuleBase { diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs similarity index 81% rename from Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs rename to src/Bot/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs index e98885b..0aee35f 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs +++ b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictListItemDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Integrations.UbranDictionary +namespace Geekbot.Bot.Commands.Integrations.UbranDictionary { internal class UrbanListItemDto { diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs similarity index 73% rename from Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs rename to src/Bot/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs index 2c3e014..1846601 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs +++ b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictResponseDto.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Geekbot.net.Commands.Integrations.UbranDictionary +namespace Geekbot.Bot.Commands.Integrations.UbranDictionary { internal class UrbanResponseDto { diff --git a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs similarity index 91% rename from Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs rename to src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 882caa5..bc1f478 100644 --- a/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -3,11 +3,11 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Commands.Integrations.UbranDictionary +namespace Geekbot.Bot.Commands.Integrations.UbranDictionary { public class UrbanDictionary : ModuleBase { diff --git a/Geekbot.net/Commands/Integrations/Wikipedia.cs b/src/Bot/Commands/Integrations/Wikipedia.cs similarity index 92% rename from Geekbot.net/Commands/Integrations/Wikipedia.cs rename to src/Bot/Commands/Integrations/Wikipedia.cs index 93f68fd..709f974 100644 --- a/Geekbot.net/Commands/Integrations/Wikipedia.cs +++ b/src/Bot/Commands/Integrations/Wikipedia.cs @@ -5,14 +5,14 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.WikipediaClient; -using Geekbot.net.Lib.WikipediaClient.Page; +using Geekbot.Core.Database; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.WikipediaClient; +using Geekbot.Core.WikipediaClient.Page; using HtmlAgilityPack; -namespace Geekbot.net.Commands.Integrations +namespace Geekbot.Bot.Commands.Integrations { public class Wikipedia : ModuleBase { diff --git a/Geekbot.net/Commands/Integrations/Youtube.cs b/src/Bot/Commands/Integrations/Youtube.cs similarity index 91% rename from Geekbot.net/Commands/Integrations/Youtube.cs rename to src/Bot/Commands/Integrations/Youtube.cs index 1672bab..60ebdaa 100644 --- a/Geekbot.net/Commands/Integrations/Youtube.cs +++ b/src/Bot/Commands/Integrations/Youtube.cs @@ -1,12 +1,12 @@ using System; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.GlobalSettings; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.GlobalSettings; using Google.Apis.Services; using Google.Apis.YouTube.v3; -namespace Geekbot.net.Commands.Integrations +namespace Geekbot.Bot.Commands.Integrations { public class Youtube : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs b/src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs similarity index 95% rename from Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs rename to src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs index 838dff2..995c921 100644 --- a/Geekbot.net/Commands/Randomness/BenedictCumberbatchNameGenerator.cs +++ b/src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs @@ -2,10 +2,10 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class BenedictCumberbatchNameGenerator : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Cat/Cat.cs b/src/Bot/Commands/Randomness/Cat/Cat.cs similarity index 86% rename from Geekbot.net/Commands/Randomness/Cat/Cat.cs rename to src/Bot/Commands/Randomness/Cat/Cat.cs index 7cd7b19..7bd7e57 100644 --- a/Geekbot.net/Commands/Randomness/Cat/Cat.cs +++ b/src/Bot/Commands/Randomness/Cat/Cat.cs @@ -2,10 +2,10 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness.Cat +namespace Geekbot.Bot.Commands.Randomness.Cat { public class Cat : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Cat/CatResponseDto.cs b/src/Bot/Commands/Randomness/Cat/CatResponseDto.cs similarity index 62% rename from Geekbot.net/Commands/Randomness/Cat/CatResponseDto.cs rename to src/Bot/Commands/Randomness/Cat/CatResponseDto.cs index 05ebf2b..febb66f 100644 --- a/Geekbot.net/Commands/Randomness/Cat/CatResponseDto.cs +++ b/src/Bot/Commands/Randomness/Cat/CatResponseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Cat +namespace Geekbot.Bot.Commands.Randomness.Cat { internal class CatResponseDto { diff --git a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs b/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs similarity index 64% rename from Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs rename to src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs index 8d513b8..99d9493 100644 --- a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs +++ b/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokeResponseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Chuck +namespace Geekbot.Bot.Commands.Randomness.Chuck { internal class ChuckNorrisJokeResponseDto { diff --git a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs b/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs similarity index 87% rename from Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs rename to src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs index 95dcfd4..be328b4 100644 --- a/Geekbot.net/Commands/Randomness/Chuck/ChuckNorrisJokes.cs +++ b/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs @@ -2,10 +2,10 @@ using System.Net.Http; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness.Chuck +namespace Geekbot.Bot.Commands.Randomness.Chuck { public class ChuckNorrisJokes : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Dad/DadJokeResponseDto.cs b/src/Bot/Commands/Randomness/Dad/DadJokeResponseDto.cs similarity index 63% rename from Geekbot.net/Commands/Randomness/Dad/DadJokeResponseDto.cs rename to src/Bot/Commands/Randomness/Dad/DadJokeResponseDto.cs index 262eee9..2d72bdd 100644 --- a/Geekbot.net/Commands/Randomness/Dad/DadJokeResponseDto.cs +++ b/src/Bot/Commands/Randomness/Dad/DadJokeResponseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Dad +namespace Geekbot.Bot.Commands.Randomness.Dad { internal class DadJokeResponseDto { diff --git a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs b/src/Bot/Commands/Randomness/Dad/DadJokes.cs similarity index 85% rename from Geekbot.net/Commands/Randomness/Dad/DadJokes.cs rename to src/Bot/Commands/Randomness/Dad/DadJokes.cs index 7aabff3..136650c 100644 --- a/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs +++ b/src/Bot/Commands/Randomness/Dad/DadJokes.cs @@ -1,10 +1,10 @@ using System; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness.Dad +namespace Geekbot.Bot.Commands.Randomness.Dad { public class DadJokes : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Dog/Dog.cs b/src/Bot/Commands/Randomness/Dog/Dog.cs similarity index 86% rename from Geekbot.net/Commands/Randomness/Dog/Dog.cs rename to src/Bot/Commands/Randomness/Dog/Dog.cs index b3d603b..2a8a3f1 100644 --- a/Geekbot.net/Commands/Randomness/Dog/Dog.cs +++ b/src/Bot/Commands/Randomness/Dog/Dog.cs @@ -2,10 +2,10 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness.Dog +namespace Geekbot.Bot.Commands.Randomness.Dog { public class Dog : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Dog/DogResponseDto.cs b/src/Bot/Commands/Randomness/Dog/DogResponseDto.cs similarity index 61% rename from Geekbot.net/Commands/Randomness/Dog/DogResponseDto.cs rename to src/Bot/Commands/Randomness/Dog/DogResponseDto.cs index 1fc1a82..473c1ce 100644 --- a/Geekbot.net/Commands/Randomness/Dog/DogResponseDto.cs +++ b/src/Bot/Commands/Randomness/Dog/DogResponseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Dog +namespace Geekbot.Bot.Commands.Randomness.Dog { internal class DogResponseDto { diff --git a/Geekbot.net/Commands/Randomness/EightBall.cs b/src/Bot/Commands/Randomness/EightBall.cs similarity index 95% rename from Geekbot.net/Commands/Randomness/EightBall.cs rename to src/Bot/Commands/Randomness/EightBall.cs index d07451d..e1a3a71 100644 --- a/Geekbot.net/Commands/Randomness/EightBall.cs +++ b/src/Bot/Commands/Randomness/EightBall.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class EightBall : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Fortune.cs b/src/Bot/Commands/Randomness/Fortune.cs similarity index 83% rename from Geekbot.net/Commands/Randomness/Fortune.cs rename to src/Bot/Commands/Randomness/Fortune.cs index d4f6b5f..cc31536 100644 --- a/Geekbot.net/Commands/Randomness/Fortune.cs +++ b/src/Bot/Commands/Randomness/Fortune.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.Media; +using Geekbot.Core.Media; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class Fortune : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Gdq.cs b/src/Bot/Commands/Randomness/Gdq.cs similarity index 88% rename from Geekbot.net/Commands/Randomness/Gdq.cs rename to src/Bot/Commands/Randomness/Gdq.cs index 4c16bed..c6d9fa8 100644 --- a/Geekbot.net/Commands/Randomness/Gdq.cs +++ b/src/Bot/Commands/Randomness/Gdq.cs @@ -2,9 +2,9 @@ using System.Net; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class Gdq : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs b/src/Bot/Commands/Randomness/Greetings/GreetingBaseDto.cs similarity index 84% rename from Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs rename to src/Bot/Commands/Randomness/Greetings/GreetingBaseDto.cs index 7f4e02f..ae0274b 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/GreetingBaseDto.cs +++ b/src/Bot/Commands/Randomness/Greetings/GreetingBaseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Greetings +namespace Geekbot.Bot.Commands.Randomness.Greetings { public class GreetingBaseDto { diff --git a/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs b/src/Bot/Commands/Randomness/Greetings/GreetingDto.cs similarity index 80% rename from Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs rename to src/Bot/Commands/Randomness/Greetings/GreetingDto.cs index c967885..679e544 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/GreetingDto.cs +++ b/src/Bot/Commands/Randomness/Greetings/GreetingDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Greetings +namespace Geekbot.Bot.Commands.Randomness.Greetings { public class GreetingDto { diff --git a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs b/src/Bot/Commands/Randomness/Greetings/Greetings.cs similarity index 90% rename from Geekbot.net/Commands/Randomness/Greetings/Greetings.cs rename to src/Bot/Commands/Randomness/Greetings/Greetings.cs index 85e9152..cd69010 100644 --- a/Geekbot.net/Commands/Randomness/Greetings/Greetings.cs +++ b/src/Bot/Commands/Randomness/Greetings/Greetings.cs @@ -2,11 +2,11 @@ using System; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Commands.Randomness.Greetings +namespace Geekbot.Bot.Commands.Randomness.Greetings { public class Greetings : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs b/src/Bot/Commands/Randomness/Kanye/Kanye.cs similarity index 87% rename from Geekbot.net/Commands/Randomness/Kanye/Kanye.cs rename to src/Bot/Commands/Randomness/Kanye/Kanye.cs index 2aca31d..6ad67cb 100644 --- a/Geekbot.net/Commands/Randomness/Kanye/Kanye.cs +++ b/src/Bot/Commands/Randomness/Kanye/Kanye.cs @@ -1,10 +1,10 @@ using System; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Randomness.Kanye +namespace Geekbot.Bot.Commands.Randomness.Kanye { public class Kanye : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Kanye/KanyeResponseDto.cs b/src/Bot/Commands/Randomness/Kanye/KanyeResponseDto.cs similarity index 73% rename from Geekbot.net/Commands/Randomness/Kanye/KanyeResponseDto.cs rename to src/Bot/Commands/Randomness/Kanye/KanyeResponseDto.cs index ff74f37..8ca248e 100644 --- a/Geekbot.net/Commands/Randomness/Kanye/KanyeResponseDto.cs +++ b/src/Bot/Commands/Randomness/Kanye/KanyeResponseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Randomness.Kanye +namespace Geekbot.Bot.Commands.Randomness.Kanye { public class KanyeResponseDto { diff --git a/Geekbot.net/Commands/Randomness/RandomAnimals.cs b/src/Bot/Commands/Randomness/RandomAnimals.cs similarity index 97% rename from Geekbot.net/Commands/Randomness/RandomAnimals.cs rename to src/Bot/Commands/Randomness/RandomAnimals.cs index 47b6ea6..b9c1bdd 100644 --- a/Geekbot.net/Commands/Randomness/RandomAnimals.cs +++ b/src/Bot/Commands/Randomness/RandomAnimals.cs @@ -1,9 +1,9 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib.Media; +using Geekbot.Core.Media; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class RandomAnimals : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Ship.cs b/src/Bot/Commands/Randomness/Ship.cs similarity index 91% rename from Geekbot.net/Commands/Randomness/Ship.cs rename to src/Bot/Commands/Randomness/Ship.cs index d5386d4..d5d9eea 100644 --- a/Geekbot.net/Commands/Randomness/Ship.cs +++ b/src/Bot/Commands/Randomness/Ship.cs @@ -3,14 +3,14 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Localization; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class Ship : ModuleBase { diff --git a/Geekbot.net/Commands/Randomness/Slap.cs b/src/Bot/Commands/Randomness/Slap.cs similarity index 93% rename from Geekbot.net/Commands/Randomness/Slap.cs rename to src/Bot/Commands/Randomness/Slap.cs index 20e83c3..b512e73 100644 --- a/Geekbot.net/Commands/Randomness/Slap.cs +++ b/src/Bot/Commands/Randomness/Slap.cs @@ -4,12 +4,12 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Commands.Randomness +namespace Geekbot.Bot.Commands.Randomness { public class Slap : ModuleBase { diff --git a/Geekbot.net/Commands/Rpg/Cookies.cs b/src/Bot/Commands/Rpg/Cookies.cs similarity index 92% rename from Geekbot.net/Commands/Rpg/Cookies.cs rename to src/Bot/Commands/Rpg/Cookies.cs index b1a2d7d..f581105 100644 --- a/Geekbot.net/Commands/Rpg/Cookies.cs +++ b/src/Bot/Commands/Rpg/Cookies.cs @@ -3,15 +3,15 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Localization; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Commands.Rpg +namespace Geekbot.Bot.Commands.Rpg { [DisableInDirectMessage] [Group("cookies")] diff --git a/Geekbot.net/Commands/User/GuildInfo.cs b/src/Bot/Commands/User/GuildInfo.cs similarity index 87% rename from Geekbot.net/Commands/User/GuildInfo.cs rename to src/Bot/Commands/User/GuildInfo.cs index 6c8b941..c596186 100644 --- a/Geekbot.net/Commands/User/GuildInfo.cs +++ b/src/Bot/Commands/User/GuildInfo.cs @@ -3,13 +3,13 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Levels; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Levels; -namespace Geekbot.net.Commands.User +namespace Geekbot.Bot.Commands.User { public class GuildInfo : ModuleBase { diff --git a/Geekbot.net/Commands/User/Karma.cs b/src/Bot/Commands/User/Karma.cs similarity index 95% rename from Geekbot.net/Commands/User/Karma.cs rename to src/Bot/Commands/User/Karma.cs index bf85c91..3efc381 100644 --- a/Geekbot.net/Commands/User/Karma.cs +++ b/src/Bot/Commands/User/Karma.cs @@ -3,14 +3,14 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Localization; -namespace Geekbot.net.Commands.User +namespace Geekbot.Bot.Commands.User { [DisableInDirectMessage] public class Karma : ModuleBase diff --git a/Geekbot.net/Commands/User/Ranking/Rank.cs b/src/Bot/Commands/User/Ranking/Rank.cs similarity index 90% rename from Geekbot.net/Commands/User/Ranking/Rank.cs rename to src/Bot/Commands/User/Ranking/Rank.cs index 9021b4e..ae1bec9 100644 --- a/Geekbot.net/Commands/User/Ranking/Rank.cs +++ b/src/Bot/Commands/User/Ranking/Rank.cs @@ -4,16 +4,16 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.Converters; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Highscores; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.UserRepository; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Converters; +using Geekbot.Core.Database; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Highscores; +using Geekbot.Core.Localization; +using Geekbot.Core.UserRepository; -namespace Geekbot.net.Commands.User.Ranking +namespace Geekbot.Bot.Commands.User.Ranking { public class Rank : ModuleBase { diff --git a/Geekbot.net/Commands/User/Stats.cs b/src/Bot/Commands/User/Stats.cs similarity index 94% rename from Geekbot.net/Commands/User/Stats.cs rename to src/Bot/Commands/User/Stats.cs index 08b69d2..70f6247 100644 --- a/Geekbot.net/Commands/User/Stats.cs +++ b/src/Bot/Commands/User/Stats.cs @@ -3,13 +3,13 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Levels; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Levels; -namespace Geekbot.net.Commands.User +namespace Geekbot.Bot.Commands.User { public class Stats : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/AvatarGetter.cs b/src/Bot/Commands/Utils/AvatarGetter.cs similarity index 88% rename from Geekbot.net/Commands/Utils/AvatarGetter.cs rename to src/Bot/Commands/Utils/AvatarGetter.cs index 142b3e3..6585a75 100644 --- a/Geekbot.net/Commands/Utils/AvatarGetter.cs +++ b/src/Bot/Commands/Utils/AvatarGetter.cs @@ -2,9 +2,9 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class AvatarGetter : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs b/src/Bot/Commands/Utils/Changelog/Changelog.cs similarity index 92% rename from Geekbot.net/Commands/Utils/Changelog/Changelog.cs rename to src/Bot/Commands/Utils/Changelog/Changelog.cs index c217619..92d5ddd 100644 --- a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs +++ b/src/Bot/Commands/Utils/Changelog/Changelog.cs @@ -6,10 +6,10 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Utils.Changelog +namespace Geekbot.Bot.Commands.Utils.Changelog { public class Changelog : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Changelog/CommitAuthorDto.cs b/src/Bot/Commands/Utils/Changelog/CommitAuthorDto.cs similarity index 77% rename from Geekbot.net/Commands/Utils/Changelog/CommitAuthorDto.cs rename to src/Bot/Commands/Utils/Changelog/CommitAuthorDto.cs index 8debd77..7cabece 100644 --- a/Geekbot.net/Commands/Utils/Changelog/CommitAuthorDto.cs +++ b/src/Bot/Commands/Utils/Changelog/CommitAuthorDto.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Commands.Utils.Changelog +namespace Geekbot.Bot.Commands.Utils.Changelog { public class CommitAuthorDto { diff --git a/Geekbot.net/Commands/Utils/Changelog/CommitDto.cs b/src/Bot/Commands/Utils/Changelog/CommitDto.cs similarity index 62% rename from Geekbot.net/Commands/Utils/Changelog/CommitDto.cs rename to src/Bot/Commands/Utils/Changelog/CommitDto.cs index 3379697..a534730 100644 --- a/Geekbot.net/Commands/Utils/Changelog/CommitDto.cs +++ b/src/Bot/Commands/Utils/Changelog/CommitDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Utils.Changelog +namespace Geekbot.Bot.Commands.Utils.Changelog { public class CommitDto { diff --git a/Geekbot.net/Commands/Utils/Changelog/CommitInfoDto.cs b/src/Bot/Commands/Utils/Changelog/CommitInfoDto.cs similarity index 71% rename from Geekbot.net/Commands/Utils/Changelog/CommitInfoDto.cs rename to src/Bot/Commands/Utils/Changelog/CommitInfoDto.cs index 9008343..d6f806e 100644 --- a/Geekbot.net/Commands/Utils/Changelog/CommitInfoDto.cs +++ b/src/Bot/Commands/Utils/Changelog/CommitInfoDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Utils.Changelog +namespace Geekbot.Bot.Commands.Utils.Changelog { public class CommitInfoDto { diff --git a/Geekbot.net/Commands/Utils/Choose.cs b/src/Bot/Commands/Utils/Choose.cs similarity index 88% rename from Geekbot.net/Commands/Utils/Choose.cs rename to src/Bot/Commands/Utils/Choose.cs index 62069bd..d245bd2 100644 --- a/Geekbot.net/Commands/Utils/Choose.cs +++ b/src/Bot/Commands/Utils/Choose.cs @@ -1,10 +1,10 @@ using System; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Localization; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Localization; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Choose : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Corona/CoronaStats.cs b/src/Bot/Commands/Utils/Corona/CoronaStats.cs similarity index 94% rename from Geekbot.net/Commands/Utils/Corona/CoronaStats.cs rename to src/Bot/Commands/Utils/Corona/CoronaStats.cs index 4be8195..3f9f3ea 100644 --- a/Geekbot.net/Commands/Utils/Corona/CoronaStats.cs +++ b/src/Bot/Commands/Utils/Corona/CoronaStats.cs @@ -1,13 +1,12 @@ using System; -using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Commands.Utils.Corona +namespace Geekbot.Bot.Commands.Utils.Corona { public class CoronaStats : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs b/src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs similarity index 82% rename from Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs rename to src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs index 5639249..3f6a820 100644 --- a/Geekbot.net/Commands/Utils/Corona/CoronaSummaryDto.cs +++ b/src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Commands.Utils.Corona +namespace Geekbot.Bot.Commands.Utils.Corona { public class CoronaSummaryDto { diff --git a/Geekbot.net/Commands/Utils/Dice.cs b/src/Bot/Commands/Utils/Dice.cs similarity index 97% rename from Geekbot.net/Commands/Utils/Dice.cs rename to src/Bot/Commands/Utils/Dice.cs index 2cd2e19..0668493 100644 --- a/Geekbot.net/Commands/Utils/Dice.cs +++ b/src/Bot/Commands/Utils/Dice.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.DiceParser; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.DiceParser; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Dice : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Emojify.cs b/src/Bot/Commands/Utils/Emojify.cs similarity index 88% rename from Geekbot.net/Commands/Utils/Emojify.cs rename to src/Bot/Commands/Utils/Emojify.cs index 5355aff..c8328ee 100644 --- a/Geekbot.net/Commands/Utils/Emojify.cs +++ b/src/Bot/Commands/Utils/Emojify.cs @@ -1,10 +1,10 @@ using System; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.Converters; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.Converters; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Emojify : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Help.cs b/src/Bot/Commands/Utils/Help.cs similarity index 93% rename from Geekbot.net/Commands/Utils/Help.cs rename to src/Bot/Commands/Utils/Help.cs index a6f0084..58630fe 100644 --- a/Geekbot.net/Commands/Utils/Help.cs +++ b/src/Bot/Commands/Utils/Help.cs @@ -3,9 +3,9 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Help : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Info.cs b/src/Bot/Commands/Utils/Info.cs similarity index 92% rename from Geekbot.net/Commands/Utils/Info.cs rename to src/Bot/Commands/Utils/Info.cs index b1d5403..663dd07 100644 --- a/Geekbot.net/Commands/Utils/Info.cs +++ b/src/Bot/Commands/Utils/Info.cs @@ -5,11 +5,11 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Lib; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Info : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Lmgtfy.cs b/src/Bot/Commands/Utils/Lmgtfy.cs similarity index 92% rename from Geekbot.net/Commands/Utils/Lmgtfy.cs rename to src/Bot/Commands/Utils/Lmgtfy.cs index 9976dad..6063cf9 100644 --- a/Geekbot.net/Commands/Utils/Lmgtfy.cs +++ b/src/Bot/Commands/Utils/Lmgtfy.cs @@ -2,9 +2,9 @@ using System; using System.Threading.Tasks; using System.Web; using Discord.Commands; -using Geekbot.net.Lib.ErrorHandling; +using Geekbot.Core.ErrorHandling; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Lmgtfy : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Ping.cs b/src/Bot/Commands/Utils/Ping.cs similarity index 89% rename from Geekbot.net/Commands/Utils/Ping.cs rename to src/Bot/Commands/Utils/Ping.cs index 18cf9cb..d4faa53 100644 --- a/Geekbot.net/Commands/Utils/Ping.cs +++ b/src/Bot/Commands/Utils/Ping.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using Discord.Commands; -namespace Geekbot.net.Commands.Utils +namespace Geekbot.Bot.Commands.Utils { public class Ping : ModuleBase { diff --git a/Geekbot.net/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs similarity index 97% rename from Geekbot.net/Commands/Utils/Quote/Quote.cs rename to src/Bot/Commands/Utils/Quote/Quote.cs index 7af8a4c..4022753 100644 --- a/Geekbot.net/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -3,16 +3,16 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.CommandPreconditions; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.Polyfills; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.Localization; +using Geekbot.Core.Polyfills; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Commands.Utils.Quote +namespace Geekbot.Bot.Commands.Utils.Quote { [Group("quote")] [DisableInDirectMessage] diff --git a/Geekbot.net/Commands/Utils/Quote/QuoteObjectDto.cs b/src/Bot/Commands/Utils/Quote/QuoteObjectDto.cs similarity index 81% rename from Geekbot.net/Commands/Utils/Quote/QuoteObjectDto.cs rename to src/Bot/Commands/Utils/Quote/QuoteObjectDto.cs index a37ff76..32b65cf 100644 --- a/Geekbot.net/Commands/Utils/Quote/QuoteObjectDto.cs +++ b/src/Bot/Commands/Utils/Quote/QuoteObjectDto.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Commands.Utils.Quote +namespace Geekbot.Bot.Commands.Utils.Quote { internal class QuoteObjectDto { diff --git a/Geekbot.net/Handlers/CommandHandler.cs b/src/Bot/Handlers/CommandHandler.cs similarity index 96% rename from Geekbot.net/Handlers/CommandHandler.cs rename to src/Bot/Handlers/CommandHandler.cs index b6a3d9f..52e9a52 100644 --- a/Geekbot.net/Handlers/CommandHandler.cs +++ b/src/Bot/Handlers/CommandHandler.cs @@ -5,12 +5,12 @@ using Discord; using Discord.Commands; using Discord.Rest; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.GuildSettingsManager; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.GuildSettingsManager; +using Geekbot.Core.Logger; -namespace Geekbot.net.Handlers +namespace Geekbot.Bot.Handlers { public class CommandHandler { diff --git a/Geekbot.net/Handlers/MessageDeletedHandler.cs b/src/Bot/Handlers/MessageDeletedHandler.cs similarity index 93% rename from Geekbot.net/Handlers/MessageDeletedHandler.cs rename to src/Bot/Handlers/MessageDeletedHandler.cs index 5595cff..d0377f7 100644 --- a/Geekbot.net/Handlers/MessageDeletedHandler.cs +++ b/src/Bot/Handlers/MessageDeletedHandler.cs @@ -4,11 +4,11 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Database; +using Geekbot.Core.Extensions; +using Geekbot.Core.Logger; -namespace Geekbot.net.Handlers +namespace Geekbot.Bot.Handlers { public class MessageDeletedHandler { diff --git a/Geekbot.net/Handlers/ReactionHandler.cs b/src/Bot/Handlers/ReactionHandler.cs similarity index 94% rename from Geekbot.net/Handlers/ReactionHandler.cs rename to src/Bot/Handlers/ReactionHandler.cs index e2355a8..66af3e8 100644 --- a/Geekbot.net/Handlers/ReactionHandler.cs +++ b/src/Bot/Handlers/ReactionHandler.cs @@ -1,9 +1,9 @@ using System.Threading.Tasks; using Discord; using Discord.WebSocket; -using Geekbot.net.Lib.ReactionListener; +using Geekbot.Core.ReactionListener; -namespace Geekbot.net.Handlers +namespace Geekbot.Bot.Handlers { public class ReactionHandler { diff --git a/Geekbot.net/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs similarity index 92% rename from Geekbot.net/Handlers/StatsHandler.cs rename to src/Bot/Handlers/StatsHandler.cs index 56c0894..197bbb8 100644 --- a/Geekbot.net/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -1,13 +1,13 @@ using System; using System.Threading.Tasks; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.Extensions; +using Geekbot.Core.Logger; using Microsoft.EntityFrameworkCore; -namespace Geekbot.net.Handlers +namespace Geekbot.Bot.Handlers { public class StatsHandler { diff --git a/Geekbot.net/Handlers/UserHandler.cs b/src/Bot/Handlers/UserHandler.cs similarity index 95% rename from Geekbot.net/Handlers/UserHandler.cs rename to src/Bot/Handlers/UserHandler.cs index fb26d70..a22d0e1 100644 --- a/Geekbot.net/Handlers/UserHandler.cs +++ b/src/Bot/Handlers/UserHandler.cs @@ -4,12 +4,12 @@ using System.Threading.Tasks; using Discord; using Discord.Rest; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Logger; -using Geekbot.net.Lib.UserRepository; +using Geekbot.Core.Database; +using Geekbot.Core.Extensions; +using Geekbot.Core.Logger; +using Geekbot.Core.UserRepository; -namespace Geekbot.net.Handlers +namespace Geekbot.Bot.Handlers { public class UserHandler { diff --git a/Geekbot.net/Logs/.keep b/src/Bot/Logs/.keep old mode 100755 new mode 100644 similarity index 100% rename from Geekbot.net/Logs/.keep rename to src/Bot/Logs/.keep diff --git a/Geekbot.net/Program.cs b/src/Bot/Program.cs old mode 100755 new mode 100644 similarity index 91% rename from Geekbot.net/Program.cs rename to src/Bot/Program.cs index c55f390..04b1450 --- a/Geekbot.net/Program.cs +++ b/src/Bot/Program.cs @@ -6,30 +6,30 @@ using CommandLine; using Discord; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Handlers; -using Geekbot.net.Lib; -using Geekbot.net.Lib.Converters; -using Geekbot.net.Lib.DiceParser; -using Geekbot.net.Lib.ErrorHandling; -using Geekbot.net.Lib.GlobalSettings; -using Geekbot.net.Lib.GuildSettingsManager; -using Geekbot.net.Lib.Highscores; -using Geekbot.net.Lib.KvInMemoryStore; -using Geekbot.net.Lib.Levels; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.Logger; -using Geekbot.net.Lib.MalClient; -using Geekbot.net.Lib.Media; -using Geekbot.net.Lib.RandomNumberGenerator; -using Geekbot.net.Lib.ReactionListener; -using Geekbot.net.Lib.UserRepository; -using Geekbot.net.Lib.WikipediaClient; -using Geekbot.net.WebApi; +using Geekbot.Bot.Handlers; +using Geekbot.Core; +using Geekbot.Core.Converters; +using Geekbot.Core.Database; +using Geekbot.Core.DiceParser; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.GlobalSettings; +using Geekbot.Core.GuildSettingsManager; +using Geekbot.Core.Highscores; +using Geekbot.Core.KvInMemoryStore; +using Geekbot.Core.Levels; +using Geekbot.Core.Localization; +using Geekbot.Core.Logger; +using Geekbot.Core.MalClient; +using Geekbot.Core.Media; +using Geekbot.Core.RandomNumberGenerator; +using Geekbot.Core.ReactionListener; +using Geekbot.Core.UserRepository; +using Geekbot.Core.WikipediaClient; +using Geekbot.Web; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -namespace Geekbot.net +namespace Geekbot.Bot { internal class Program { diff --git a/Geekbot.net/Storage/croissant b/src/Bot/Storage/croissant similarity index 100% rename from Geekbot.net/Storage/croissant rename to src/Bot/Storage/croissant diff --git a/Geekbot.net/Storage/dab b/src/Bot/Storage/dab similarity index 100% rename from Geekbot.net/Storage/dab rename to src/Bot/Storage/dab diff --git a/Geekbot.net/Storage/fortunes b/src/Bot/Storage/fortunes similarity index 100% rename from Geekbot.net/Storage/fortunes rename to src/Bot/Storage/fortunes diff --git a/Geekbot.net/Storage/foxes b/src/Bot/Storage/foxes similarity index 100% rename from Geekbot.net/Storage/foxes rename to src/Bot/Storage/foxes diff --git a/Geekbot.net/Storage/pandas b/src/Bot/Storage/pandas similarity index 100% rename from Geekbot.net/Storage/pandas rename to src/Bot/Storage/pandas diff --git a/Geekbot.net/Storage/penguins b/src/Bot/Storage/penguins similarity index 100% rename from Geekbot.net/Storage/penguins rename to src/Bot/Storage/penguins diff --git a/Geekbot.net/Storage/pumpkin b/src/Bot/Storage/pumpkin similarity index 100% rename from Geekbot.net/Storage/pumpkin rename to src/Bot/Storage/pumpkin diff --git a/Geekbot.net/Storage/squirrel b/src/Bot/Storage/squirrel similarity index 100% rename from Geekbot.net/Storage/squirrel rename to src/Bot/Storage/squirrel diff --git a/Geekbot.net/Storage/turtles b/src/Bot/Storage/turtles similarity index 100% rename from Geekbot.net/Storage/turtles rename to src/Bot/Storage/turtles diff --git a/Geekbot.net/derp.ico b/src/Bot/derp.ico similarity index 100% rename from Geekbot.net/derp.ico rename to src/Bot/derp.ico diff --git a/Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs b/src/Core/CommandPreconditions/DisableInDirectMessageAttribute.cs similarity index 92% rename from Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs rename to src/Core/CommandPreconditions/DisableInDirectMessageAttribute.cs index 2bb5cfd..835e0b3 100644 --- a/Geekbot.net/Lib/CommandPreconditions/DisableInDirectMessageAttribute.cs +++ b/src/Core/CommandPreconditions/DisableInDirectMessageAttribute.cs @@ -2,7 +2,7 @@ using System; using System.Threading.Tasks; using Discord.Commands; -namespace Geekbot.net.Lib.CommandPreconditions +namespace Geekbot.Core.CommandPreconditions { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class DisableInDirectMessageAttribute : PreconditionAttribute diff --git a/Geekbot.net/Lib/Constants.cs b/src/Core/Constants.cs similarity index 72% rename from Geekbot.net/Lib/Constants.cs rename to src/Core/Constants.cs index 4abee4e..4dd08b9 100644 --- a/Geekbot.net/Lib/Constants.cs +++ b/src/Core/Constants.cs @@ -1,6 +1,6 @@ using System.Reflection; -namespace Geekbot.net.Lib +namespace Geekbot.Core { public static class Constants { @@ -8,7 +8,7 @@ namespace Geekbot.net.Lib public static string BotVersion() { - return typeof(Program).Assembly.GetCustomAttribute().InformationalVersion; + return typeof(Constants).Assembly.GetCustomAttribute().InformationalVersion; } public static string LibraryVersion() diff --git a/Geekbot.net/Lib/Converters/EmojiConverter.cs b/src/Core/Converters/EmojiConverter.cs similarity index 96% rename from Geekbot.net/Lib/Converters/EmojiConverter.cs rename to src/Core/Converters/EmojiConverter.cs index 06f1aa8..327aab8 100644 --- a/Geekbot.net/Lib/Converters/EmojiConverter.cs +++ b/src/Core/Converters/EmojiConverter.cs @@ -1,7 +1,7 @@ using System.Collections; using System.Text; -namespace Geekbot.net.Lib.Converters +namespace Geekbot.Core.Converters { public class EmojiConverter : IEmojiConverter { diff --git a/Geekbot.net/Lib/Converters/IEmojiConverter.cs b/src/Core/Converters/IEmojiConverter.cs similarity index 74% rename from Geekbot.net/Lib/Converters/IEmojiConverter.cs rename to src/Core/Converters/IEmojiConverter.cs index b0f666f..79ca0a7 100644 --- a/Geekbot.net/Lib/Converters/IEmojiConverter.cs +++ b/src/Core/Converters/IEmojiConverter.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Converters +namespace Geekbot.Core.Converters { public interface IEmojiConverter { diff --git a/Geekbot.net/Lib/Converters/IMtgManaConverter.cs b/src/Core/Converters/IMtgManaConverter.cs similarity index 67% rename from Geekbot.net/Lib/Converters/IMtgManaConverter.cs rename to src/Core/Converters/IMtgManaConverter.cs index d558f09..0dd3034 100644 --- a/Geekbot.net/Lib/Converters/IMtgManaConverter.cs +++ b/src/Core/Converters/IMtgManaConverter.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Converters +namespace Geekbot.Core.Converters { public interface IMtgManaConverter { diff --git a/Geekbot.net/Lib/Converters/MtgManaConverter.cs b/src/Core/Converters/MtgManaConverter.cs similarity index 96% rename from Geekbot.net/Lib/Converters/MtgManaConverter.cs rename to src/Core/Converters/MtgManaConverter.cs index cfd893b..aa6b74c 100644 --- a/Geekbot.net/Lib/Converters/MtgManaConverter.cs +++ b/src/Core/Converters/MtgManaConverter.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Text.RegularExpressions; -namespace Geekbot.net.Lib.Converters +namespace Geekbot.Core.Converters { public class MtgManaConverter : IMtgManaConverter { diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj new file mode 100644 index 0000000..fcbce09 --- /dev/null +++ b/src/Core/Core.csproj @@ -0,0 +1,40 @@ + + + + net5.0 + $(VersionSuffix) + $(VersionSuffix) + 0.0.0-DEV + Geekbot.Core + Geekbot.Core + NU1701 + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + diff --git a/Geekbot.net/Database/DatabaseContext.cs b/src/Core/Database/DatabaseContext.cs similarity index 91% rename from Geekbot.net/Database/DatabaseContext.cs rename to src/Core/Database/DatabaseContext.cs index 505486f..93d46d3 100644 --- a/Geekbot.net/Database/DatabaseContext.cs +++ b/src/Core/Database/DatabaseContext.cs @@ -1,7 +1,7 @@ -using Geekbot.net.Database.Models; +using Geekbot.Core.Database.Models; using Microsoft.EntityFrameworkCore; -namespace Geekbot.net.Database +namespace Geekbot.Core.Database { public class DatabaseContext : DbContext { diff --git a/Geekbot.net/Database/DatabaseInitializer.cs b/src/Core/Database/DatabaseInitializer.cs similarity index 93% rename from Geekbot.net/Database/DatabaseInitializer.cs rename to src/Core/Database/DatabaseInitializer.cs index 9f60d8a..37f07bc 100644 --- a/Geekbot.net/Database/DatabaseInitializer.cs +++ b/src/Core/Database/DatabaseInitializer.cs @@ -1,10 +1,9 @@ using System; -using Geekbot.net.Database.LoggingAdapter; -using Geekbot.net.Lib; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Database.LoggingAdapter; +using Geekbot.Core.Logger; using Npgsql.Logging; -namespace Geekbot.net.Database +namespace Geekbot.Core.Database { public class DatabaseInitializer { diff --git a/Geekbot.net/Database/InMemoryDatabase.cs b/src/Core/Database/InMemoryDatabase.cs similarity index 89% rename from Geekbot.net/Database/InMemoryDatabase.cs rename to src/Core/Database/InMemoryDatabase.cs index 2b2cfd0..1077aea 100644 --- a/Geekbot.net/Database/InMemoryDatabase.cs +++ b/src/Core/Database/InMemoryDatabase.cs @@ -1,6 +1,6 @@ using Microsoft.EntityFrameworkCore; -namespace Geekbot.net.Database +namespace Geekbot.Core.Database { public class InMemoryDatabase : DatabaseContext { diff --git a/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs b/src/Core/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs similarity index 93% rename from Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs rename to src/Core/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs index ceebd56..8a46c0d 100644 --- a/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs +++ b/src/Core/Database/LoggingAdapter/NpgsqlLoggingAdapter.cs @@ -1,10 +1,9 @@ using System; -using Geekbot.net.Lib; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Logger; using Npgsql.Logging; using LogLevel = NLog.LogLevel; -namespace Geekbot.net.Database.LoggingAdapter +namespace Geekbot.Core.Database.LoggingAdapter { public class NpgsqlLoggingAdapter : NpgsqlLogger { diff --git a/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs b/src/Core/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs similarity index 82% rename from Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs rename to src/Core/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs index efe82a3..c4f76d7 100644 --- a/Geekbot.net/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs +++ b/src/Core/Database/LoggingAdapter/NpgsqlLoggingProviderAdapter.cs @@ -1,8 +1,7 @@ -using Geekbot.net.Lib; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Logger; using Npgsql.Logging; -namespace Geekbot.net.Database.LoggingAdapter +namespace Geekbot.Core.Database.LoggingAdapter { public class NpgsqlLoggingProviderAdapter : INpgsqlLoggingProvider { diff --git a/Geekbot.net/Database/Models/CookiesModel.cs b/src/Core/Database/Models/CookiesModel.cs similarity index 87% rename from Geekbot.net/Database/Models/CookiesModel.cs rename to src/Core/Database/Models/CookiesModel.cs index 228f3b0..6ec71f9 100644 --- a/Geekbot.net/Database/Models/CookiesModel.cs +++ b/src/Core/Database/Models/CookiesModel.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class CookiesModel { diff --git a/Geekbot.net/Database/Models/GlobalsModel.cs b/src/Core/Database/Models/GlobalsModel.cs similarity index 85% rename from Geekbot.net/Database/Models/GlobalsModel.cs rename to src/Core/Database/Models/GlobalsModel.cs index 63261fc..af084f9 100644 --- a/Geekbot.net/Database/Models/GlobalsModel.cs +++ b/src/Core/Database/Models/GlobalsModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class GlobalsModel { diff --git a/Geekbot.net/Database/Models/GuildSettingsModel.cs b/src/Core/Database/Models/GuildSettingsModel.cs similarity index 90% rename from Geekbot.net/Database/Models/GuildSettingsModel.cs rename to src/Core/Database/Models/GuildSettingsModel.cs index ebb6dc4..80655f7 100644 --- a/Geekbot.net/Database/Models/GuildSettingsModel.cs +++ b/src/Core/Database/Models/GuildSettingsModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class GuildSettingsModel { diff --git a/Geekbot.net/Database/Models/KarmaModel.cs b/src/Core/Database/Models/KarmaModel.cs similarity index 87% rename from Geekbot.net/Database/Models/KarmaModel.cs rename to src/Core/Database/Models/KarmaModel.cs index 7d5f533..2ec64f0 100644 --- a/Geekbot.net/Database/Models/KarmaModel.cs +++ b/src/Core/Database/Models/KarmaModel.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class KarmaModel { diff --git a/Geekbot.net/Database/Models/MessagesModel.cs b/src/Core/Database/Models/MessagesModel.cs similarity index 85% rename from Geekbot.net/Database/Models/MessagesModel.cs rename to src/Core/Database/Models/MessagesModel.cs index 31332e8..87731d8 100644 --- a/Geekbot.net/Database/Models/MessagesModel.cs +++ b/src/Core/Database/Models/MessagesModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class MessagesModel { diff --git a/Geekbot.net/Database/Models/QuoteModel.cs b/src/Core/Database/Models/QuoteModel.cs similarity index 93% rename from Geekbot.net/Database/Models/QuoteModel.cs rename to src/Core/Database/Models/QuoteModel.cs index 98e8b21..3d356d2 100644 --- a/Geekbot.net/Database/Models/QuoteModel.cs +++ b/src/Core/Database/Models/QuoteModel.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class QuoteModel { diff --git a/Geekbot.net/Database/Models/ReactionListenerModel.cs b/src/Core/Database/Models/ReactionListenerModel.cs similarity index 91% rename from Geekbot.net/Database/Models/ReactionListenerModel.cs rename to src/Core/Database/Models/ReactionListenerModel.cs index 05ab5b3..5ec28be 100644 --- a/Geekbot.net/Database/Models/ReactionListenerModel.cs +++ b/src/Core/Database/Models/ReactionListenerModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class ReactionListenerModel { diff --git a/Geekbot.net/Database/Models/RoleSelfServiceModel.cs b/src/Core/Database/Models/RoleSelfServiceModel.cs similarity index 85% rename from Geekbot.net/Database/Models/RoleSelfServiceModel.cs rename to src/Core/Database/Models/RoleSelfServiceModel.cs index de8c341..4aa92c4 100644 --- a/Geekbot.net/Database/Models/RoleSelfServiceModel.cs +++ b/src/Core/Database/Models/RoleSelfServiceModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class RoleSelfServiceModel { diff --git a/Geekbot.net/Database/Models/RollsModel.cs b/src/Core/Database/Models/RollsModel.cs similarity index 85% rename from Geekbot.net/Database/Models/RollsModel.cs rename to src/Core/Database/Models/RollsModel.cs index de9b82e..aa6613d 100644 --- a/Geekbot.net/Database/Models/RollsModel.cs +++ b/src/Core/Database/Models/RollsModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class RollsModel { diff --git a/Geekbot.net/Database/Models/ShipsModel.cs b/src/Core/Database/Models/ShipsModel.cs similarity index 84% rename from Geekbot.net/Database/Models/ShipsModel.cs rename to src/Core/Database/Models/ShipsModel.cs index d8156b0..23cf367 100644 --- a/Geekbot.net/Database/Models/ShipsModel.cs +++ b/src/Core/Database/Models/ShipsModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class ShipsModel { diff --git a/Geekbot.net/Database/Models/SlapsModel.cs b/src/Core/Database/Models/SlapsModel.cs similarity index 86% rename from Geekbot.net/Database/Models/SlapsModel.cs rename to src/Core/Database/Models/SlapsModel.cs index 6c402aa..09026c8 100644 --- a/Geekbot.net/Database/Models/SlapsModel.cs +++ b/src/Core/Database/Models/SlapsModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class SlapsModel { diff --git a/Geekbot.net/Database/Models/UserModel.cs b/src/Core/Database/Models/UserModel.cs similarity index 84% rename from Geekbot.net/Database/Models/UserModel.cs rename to src/Core/Database/Models/UserModel.cs index 43d3a9a..aa6281d 100644 --- a/Geekbot.net/Database/Models/UserModel.cs +++ b/src/Core/Database/Models/UserModel.cs @@ -1,8 +1,7 @@ using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -namespace Geekbot.net.Database.Models +namespace Geekbot.Core.Database.Models { public class UserModel { diff --git a/Geekbot.net/Database/SqlConnectionString.cs b/src/Core/Database/SqlConnectionString.cs similarity index 94% rename from Geekbot.net/Database/SqlConnectionString.cs rename to src/Core/Database/SqlConnectionString.cs index 61804cf..ca2858d 100644 --- a/Geekbot.net/Database/SqlConnectionString.cs +++ b/src/Core/Database/SqlConnectionString.cs @@ -1,6 +1,6 @@ using System.Text; -namespace Geekbot.net.Database +namespace Geekbot.Core.Database { public class SqlConnectionString { diff --git a/Geekbot.net/Database/SqlDatabase.cs b/src/Core/Database/SqlDatabase.cs similarity index 90% rename from Geekbot.net/Database/SqlDatabase.cs rename to src/Core/Database/SqlDatabase.cs index e6d03d4..8a4d195 100644 --- a/Geekbot.net/Database/SqlDatabase.cs +++ b/src/Core/Database/SqlDatabase.cs @@ -1,6 +1,6 @@ using Microsoft.EntityFrameworkCore; -namespace Geekbot.net.Database +namespace Geekbot.Core.Database { public class SqlDatabase : DatabaseContext { diff --git a/Geekbot.net/Lib/DiceParser/DiceException.cs b/src/Core/DiceParser/DiceException.cs similarity index 84% rename from Geekbot.net/Lib/DiceParser/DiceException.cs rename to src/Core/DiceParser/DiceException.cs index d2a66ad..6c6c29c 100644 --- a/Geekbot.net/Lib/DiceParser/DiceException.cs +++ b/src/Core/DiceParser/DiceException.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public class DiceException : Exception { diff --git a/Geekbot.net/Lib/DiceParser/DiceInput.cs b/src/Core/DiceParser/DiceInput.cs similarity index 88% rename from Geekbot.net/Lib/DiceParser/DiceInput.cs rename to src/Core/DiceParser/DiceInput.cs index baca42c..60f0bd2 100644 --- a/Geekbot.net/Lib/DiceParser/DiceInput.cs +++ b/src/Core/DiceParser/DiceInput.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public class DiceInput { diff --git a/Geekbot.net/Lib/DiceParser/DiceInputOptions.cs b/src/Core/DiceParser/DiceInputOptions.cs similarity index 71% rename from Geekbot.net/Lib/DiceParser/DiceInputOptions.cs rename to src/Core/DiceParser/DiceInputOptions.cs index 41f2def..5606a5e 100644 --- a/Geekbot.net/Lib/DiceParser/DiceInputOptions.cs +++ b/src/Core/DiceParser/DiceInputOptions.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public struct DiceInputOptions { diff --git a/Geekbot.net/Lib/DiceParser/DiceParser.cs b/src/Core/DiceParser/DiceParser.cs similarity index 97% rename from Geekbot.net/Lib/DiceParser/DiceParser.cs rename to src/Core/DiceParser/DiceParser.cs index 7f90865..b0f6a88 100644 --- a/Geekbot.net/Lib/DiceParser/DiceParser.cs +++ b/src/Core/DiceParser/DiceParser.cs @@ -1,9 +1,9 @@ using System; using System.Linq; using System.Text.RegularExpressions; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public class DiceParser : IDiceParser { diff --git a/Geekbot.net/Lib/DiceParser/DieAdvantageType.cs b/src/Core/DiceParser/DieAdvantageType.cs similarity index 73% rename from Geekbot.net/Lib/DiceParser/DieAdvantageType.cs rename to src/Core/DiceParser/DieAdvantageType.cs index 91818cb..9bd7486 100644 --- a/Geekbot.net/Lib/DiceParser/DieAdvantageType.cs +++ b/src/Core/DiceParser/DieAdvantageType.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public enum DieAdvantageType { diff --git a/Geekbot.net/Lib/DiceParser/DieResult.cs b/src/Core/DiceParser/DieResult.cs similarity index 96% rename from Geekbot.net/Lib/DiceParser/DieResult.cs rename to src/Core/DiceParser/DieResult.cs index 2f99fb6..aa309c0 100644 --- a/Geekbot.net/Lib/DiceParser/DieResult.cs +++ b/src/Core/DiceParser/DieResult.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public class DieResult { diff --git a/Geekbot.net/Lib/DiceParser/IDiceParser.cs b/src/Core/DiceParser/IDiceParser.cs similarity index 70% rename from Geekbot.net/Lib/DiceParser/IDiceParser.cs rename to src/Core/DiceParser/IDiceParser.cs index 608b379..ab1ebd3 100644 --- a/Geekbot.net/Lib/DiceParser/IDiceParser.cs +++ b/src/Core/DiceParser/IDiceParser.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public interface IDiceParser { diff --git a/Geekbot.net/Lib/DiceParser/SingleDie.cs b/src/Core/DiceParser/SingleDie.cs similarity index 94% rename from Geekbot.net/Lib/DiceParser/SingleDie.cs rename to src/Core/DiceParser/SingleDie.cs index 582fe29..f13dbcd 100644 --- a/Geekbot.net/Lib/DiceParser/SingleDie.cs +++ b/src/Core/DiceParser/SingleDie.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.RandomNumberGenerator; +using Geekbot.Core.Extensions; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Lib.DiceParser +namespace Geekbot.Core.DiceParser { public class SingleDie { diff --git a/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs b/src/Core/ErrorHandling/ErrorHandler.cs similarity index 97% rename from Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs rename to src/Core/ErrorHandling/ErrorHandler.cs index cda9129..02402f2 100644 --- a/Geekbot.net/Lib/ErrorHandling/ErrorHandler.cs +++ b/src/Core/ErrorHandling/ErrorHandler.cs @@ -3,13 +3,13 @@ using System.Net; using System.Threading.Tasks; using Discord.Commands; using Discord.Net; -using Geekbot.net.Lib.Localization; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Localization; +using Geekbot.Core.Logger; using SharpRaven; using SharpRaven.Data; using Exception = System.Exception; -namespace Geekbot.net.Lib.ErrorHandling +namespace Geekbot.Core.ErrorHandling { public class ErrorHandler : IErrorHandler { diff --git a/Geekbot.net/Lib/ErrorHandling/IErrorHandler.cs b/src/Core/ErrorHandling/IErrorHandler.cs similarity index 86% rename from Geekbot.net/Lib/ErrorHandling/IErrorHandler.cs rename to src/Core/ErrorHandling/IErrorHandler.cs index 05e0d8e..c012b82 100644 --- a/Geekbot.net/Lib/ErrorHandling/IErrorHandler.cs +++ b/src/Core/ErrorHandling/IErrorHandler.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using Discord.Commands; using Discord.Net; -namespace Geekbot.net.Lib.ErrorHandling +namespace Geekbot.Core.ErrorHandling { public interface IErrorHandler { diff --git a/Geekbot.net/Lib/Extensions/DbSetExtensions.cs b/src/Core/Extensions/DbSetExtensions.cs similarity index 94% rename from Geekbot.net/Lib/Extensions/DbSetExtensions.cs rename to src/Core/Extensions/DbSetExtensions.cs index e08b2d4..3ccffe9 100644 --- a/Geekbot.net/Lib/Extensions/DbSetExtensions.cs +++ b/src/Core/Extensions/DbSetExtensions.cs @@ -5,7 +5,7 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace Geekbot.net.Lib.Extensions +namespace Geekbot.Core.Extensions { public static class DbSetExtensions { diff --git a/Geekbot.net/Lib/Extensions/EmbedBuilderExtensions.cs b/src/Core/Extensions/EmbedBuilderExtensions.cs similarity index 86% rename from Geekbot.net/Lib/Extensions/EmbedBuilderExtensions.cs rename to src/Core/Extensions/EmbedBuilderExtensions.cs index 246be44..c546306 100644 --- a/Geekbot.net/Lib/Extensions/EmbedBuilderExtensions.cs +++ b/src/Core/Extensions/EmbedBuilderExtensions.cs @@ -1,6 +1,6 @@ using Discord; -namespace Geekbot.net.Lib.Extensions +namespace Geekbot.Core.Extensions { public static class EmbedBuilderExtensions { diff --git a/Geekbot.net/Lib/Extensions/IntExtensions.cs b/src/Core/Extensions/IntExtensions.cs similarity index 87% rename from Geekbot.net/Lib/Extensions/IntExtensions.cs rename to src/Core/Extensions/IntExtensions.cs index ed0fc10..dac03e7 100644 --- a/Geekbot.net/Lib/Extensions/IntExtensions.cs +++ b/src/Core/Extensions/IntExtensions.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.Extensions +namespace Geekbot.Core.Extensions { public static class IntExtensions { diff --git a/Geekbot.net/Lib/Extensions/LongExtensions.cs b/src/Core/Extensions/LongExtensions.cs similarity index 79% rename from Geekbot.net/Lib/Extensions/LongExtensions.cs rename to src/Core/Extensions/LongExtensions.cs index 1bcdd9b..087910e 100644 --- a/Geekbot.net/Lib/Extensions/LongExtensions.cs +++ b/src/Core/Extensions/LongExtensions.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.Extensions +namespace Geekbot.Core.Extensions { public static class LongExtensions { diff --git a/Geekbot.net/Lib/Extensions/StringExtensions.cs b/src/Core/Extensions/StringExtensions.cs similarity index 83% rename from Geekbot.net/Lib/Extensions/StringExtensions.cs rename to src/Core/Extensions/StringExtensions.cs index 9ec1dfe..9affad1 100644 --- a/Geekbot.net/Lib/Extensions/StringExtensions.cs +++ b/src/Core/Extensions/StringExtensions.cs @@ -1,6 +1,6 @@ using System.Linq; -namespace Geekbot.net.Lib.Extensions +namespace Geekbot.Core.Extensions { public static class StringExtensions { diff --git a/Geekbot.net/Lib/Extensions/UlongExtensions.cs b/src/Core/Extensions/UlongExtensions.cs similarity index 79% rename from Geekbot.net/Lib/Extensions/UlongExtensions.cs rename to src/Core/Extensions/UlongExtensions.cs index 8fa2a67..295f317 100644 --- a/Geekbot.net/Lib/Extensions/UlongExtensions.cs +++ b/src/Core/Extensions/UlongExtensions.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.Extensions +namespace Geekbot.Core.Extensions { public static class UlongExtensions { diff --git a/Geekbot.net/Lib/GeekbotExitCode.cs b/src/Core/GeekbotExitCode.cs similarity index 88% rename from Geekbot.net/Lib/GeekbotExitCode.cs rename to src/Core/GeekbotExitCode.cs index 4d91d18..5598f48 100644 --- a/Geekbot.net/Lib/GeekbotExitCode.cs +++ b/src/Core/GeekbotExitCode.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib +namespace Geekbot.Core { public enum GeekbotExitCode { diff --git a/Geekbot.net/Lib/GlobalSettings/GlobalSettings.cs b/src/Core/GlobalSettings/GlobalSettings.cs similarity index 91% rename from Geekbot.net/Lib/GlobalSettings/GlobalSettings.cs rename to src/Core/GlobalSettings/GlobalSettings.cs index 685a1e5..a000f8b 100644 --- a/Geekbot.net/Lib/GlobalSettings/GlobalSettings.cs +++ b/src/Core/GlobalSettings/GlobalSettings.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; -namespace Geekbot.net.Lib.GlobalSettings +namespace Geekbot.Core.GlobalSettings { public class GlobalSettings : IGlobalSettings { diff --git a/Geekbot.net/Lib/GlobalSettings/IGlobalSettings.cs b/src/Core/GlobalSettings/IGlobalSettings.cs similarity index 72% rename from Geekbot.net/Lib/GlobalSettings/IGlobalSettings.cs rename to src/Core/GlobalSettings/IGlobalSettings.cs index 4833215..082b3dc 100644 --- a/Geekbot.net/Lib/GlobalSettings/IGlobalSettings.cs +++ b/src/Core/GlobalSettings/IGlobalSettings.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using Geekbot.net.Database.Models; +using Geekbot.Core.Database.Models; -namespace Geekbot.net.Lib.GlobalSettings +namespace Geekbot.Core.GlobalSettings { public interface IGlobalSettings { diff --git a/Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs b/src/Core/GuildSettingsManager/GuildSettingsManager.cs similarity index 93% rename from Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs rename to src/Core/GuildSettingsManager/GuildSettingsManager.cs index bfa7556..565563f 100644 --- a/Geekbot.net/Lib/GuildSettingsManager/GuildSettingsManager.cs +++ b/src/Core/GuildSettingsManager/GuildSettingsManager.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Lib.GuildSettingsManager +namespace Geekbot.Core.GuildSettingsManager { public class GuildSettingsManager : IGuildSettingsManager { diff --git a/Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs b/src/Core/GuildSettingsManager/IGuildSettingsManager.cs similarity index 73% rename from Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs rename to src/Core/GuildSettingsManager/IGuildSettingsManager.cs index a45b263..d34eb73 100644 --- a/Geekbot.net/Lib/GuildSettingsManager/IGuildSettingsManager.cs +++ b/src/Core/GuildSettingsManager/IGuildSettingsManager.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using Geekbot.net.Database.Models; +using Geekbot.Core.Database.Models; -namespace Geekbot.net.Lib.GuildSettingsManager +namespace Geekbot.Core.GuildSettingsManager { public interface IGuildSettingsManager { diff --git a/Geekbot.net/Lib/Highscores/HighscoreListEmptyException.cs b/src/Core/Highscores/HighscoreListEmptyException.cs similarity index 86% rename from Geekbot.net/Lib/Highscores/HighscoreListEmptyException.cs rename to src/Core/Highscores/HighscoreListEmptyException.cs index 8c05ca9..5fc08ee 100644 --- a/Geekbot.net/Lib/Highscores/HighscoreListEmptyException.cs +++ b/src/Core/Highscores/HighscoreListEmptyException.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.Highscores +namespace Geekbot.Core.Highscores { public class HighscoreListEmptyException : Exception { diff --git a/Geekbot.net/Lib/Highscores/HighscoreManager.cs b/src/Core/Highscores/HighscoreManager.cs similarity index 93% rename from Geekbot.net/Lib/Highscores/HighscoreManager.cs rename to src/Core/Highscores/HighscoreManager.cs index 8218532..ac8580b 100644 --- a/Geekbot.net/Lib/Highscores/HighscoreManager.cs +++ b/src/Core/Highscores/HighscoreManager.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; -using Geekbot.net.Database; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.UserRepository; +using Geekbot.Core.Database; +using Geekbot.Core.Extensions; +using Geekbot.Core.UserRepository; -namespace Geekbot.net.Lib.Highscores +namespace Geekbot.Core.Highscores { public class HighscoreManager : IHighscoreManager { diff --git a/Geekbot.net/Lib/Highscores/HighscoreTypes.cs b/src/Core/Highscores/HighscoreTypes.cs similarity index 69% rename from Geekbot.net/Lib/Highscores/HighscoreTypes.cs rename to src/Core/Highscores/HighscoreTypes.cs index adf5698..b577642 100644 --- a/Geekbot.net/Lib/Highscores/HighscoreTypes.cs +++ b/src/Core/Highscores/HighscoreTypes.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Highscores +namespace Geekbot.Core.Highscores { public enum HighscoreTypes { diff --git a/Geekbot.net/Lib/Highscores/HighscoreUserDto.cs b/src/Core/Highscores/HighscoreUserDto.cs similarity index 82% rename from Geekbot.net/Lib/Highscores/HighscoreUserDto.cs rename to src/Core/Highscores/HighscoreUserDto.cs index 7abb352..58e1897 100644 --- a/Geekbot.net/Lib/Highscores/HighscoreUserDto.cs +++ b/src/Core/Highscores/HighscoreUserDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Highscores +namespace Geekbot.Core.Highscores { public class HighscoreUserDto { diff --git a/Geekbot.net/Lib/Highscores/IHighscoreManager.cs b/src/Core/Highscores/IHighscoreManager.cs similarity index 89% rename from Geekbot.net/Lib/Highscores/IHighscoreManager.cs rename to src/Core/Highscores/IHighscoreManager.cs index a09b07e..83ba2da 100644 --- a/Geekbot.net/Lib/Highscores/IHighscoreManager.cs +++ b/src/Core/Highscores/IHighscoreManager.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Geekbot.net.Lib.Highscores +namespace Geekbot.Core.Highscores { public interface IHighscoreManager { diff --git a/Geekbot.net/Lib/HttpAbstractions.cs b/src/Core/HttpAbstractions.cs similarity index 97% rename from Geekbot.net/Lib/HttpAbstractions.cs rename to src/Core/HttpAbstractions.cs index 2cde4cc..4fa287b 100644 --- a/Geekbot.net/Lib/HttpAbstractions.cs +++ b/src/Core/HttpAbstractions.cs @@ -4,7 +4,7 @@ using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; -namespace Geekbot.net.Lib +namespace Geekbot.Core { public static class HttpAbstractions { diff --git a/Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs b/src/Core/KvInMemoryStore/IKvInMemoryStore.cs similarity index 80% rename from Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs rename to src/Core/KvInMemoryStore/IKvInMemoryStore.cs index 88f3863..6281f4b 100644 --- a/Geekbot.net/Lib/KvInMemoryStore/IKvInMemoryStore.cs +++ b/src/Core/KvInMemoryStore/IKvInMemoryStore.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.KvInMemoryStore +namespace Geekbot.Core.KvInMemoryStore { public interface IKvInMemoryStore { diff --git a/Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs b/src/Core/KvInMemoryStore/KvInMemoryStore.cs similarity index 93% rename from Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs rename to src/Core/KvInMemoryStore/KvInMemoryStore.cs index 33b7155..4a50546 100644 --- a/Geekbot.net/Lib/KvInMemoryStore/KvInMemoryStore.cs +++ b/src/Core/KvInMemoryStore/KvInMemoryStore.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Geekbot.net.Lib.KvInMemoryStore +namespace Geekbot.Core.KvInMemoryStore { public class KvInInMemoryStore : IKvInMemoryStore { diff --git a/Geekbot.net/Lib/Levels/ILevelCalc.cs b/src/Core/Levels/ILevelCalc.cs similarity index 67% rename from Geekbot.net/Lib/Levels/ILevelCalc.cs rename to src/Core/Levels/ILevelCalc.cs index cc488e7..17413e6 100644 --- a/Geekbot.net/Lib/Levels/ILevelCalc.cs +++ b/src/Core/Levels/ILevelCalc.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Levels +namespace Geekbot.Core.Levels { public interface ILevelCalc { diff --git a/Geekbot.net/Lib/Levels/LevelCalc.cs b/src/Core/Levels/LevelCalc.cs similarity index 95% rename from Geekbot.net/Lib/Levels/LevelCalc.cs rename to src/Core/Levels/LevelCalc.cs index 74747b7..8203f97 100644 --- a/Geekbot.net/Lib/Levels/LevelCalc.cs +++ b/src/Core/Levels/LevelCalc.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; -namespace Geekbot.net.Lib.Levels +namespace Geekbot.Core.Levels { public class LevelCalc : ILevelCalc { diff --git a/Geekbot.net/Lib/Localization/ITranslationHandler.cs b/src/Core/Localization/ITranslationHandler.cs similarity index 91% rename from Geekbot.net/Lib/Localization/ITranslationHandler.cs rename to src/Core/Localization/ITranslationHandler.cs index 9cd0680..74b3e88 100644 --- a/Geekbot.net/Lib/Localization/ITranslationHandler.cs +++ b/src/Core/Localization/ITranslationHandler.cs @@ -2,7 +2,7 @@ using System.Threading.Tasks; using Discord.Commands; -namespace Geekbot.net.Lib.Localization +namespace Geekbot.Core.Localization { public interface ITranslationHandler { diff --git a/Geekbot.net/Lib/Localization/TranslationGuildContext.cs b/src/Core/Localization/TranslationGuildContext.cs similarity index 95% rename from Geekbot.net/Lib/Localization/TranslationGuildContext.cs rename to src/Core/Localization/TranslationGuildContext.cs index fb65aa6..25685da 100644 --- a/Geekbot.net/Lib/Localization/TranslationGuildContext.cs +++ b/src/Core/Localization/TranslationGuildContext.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using System.Threading.Tasks; -namespace Geekbot.net.Lib.Localization +namespace Geekbot.Core.Localization { public class TranslationGuildContext { diff --git a/Geekbot.net/Lib/Localization/TranslationHandler.cs b/src/Core/Localization/TranslationHandler.cs similarity index 96% rename from Geekbot.net/Lib/Localization/TranslationHandler.cs rename to src/Core/Localization/TranslationHandler.cs index 6166e6a..e38d9a1 100644 --- a/Geekbot.net/Lib/Localization/TranslationHandler.cs +++ b/src/Core/Localization/TranslationHandler.cs @@ -4,12 +4,12 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using Discord.Commands; -using Geekbot.net.Lib.GuildSettingsManager; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.GuildSettingsManager; +using Geekbot.Core.Logger; using YamlDotNet.Core; using YamlDotNet.Serialization; -namespace Geekbot.net.Lib.Localization +namespace Geekbot.Core.Localization { public class TranslationHandler : ITranslationHandler { diff --git a/Geekbot.net/Lib/Localization/Translations.yml b/src/Core/Localization/Translations.yml similarity index 100% rename from Geekbot.net/Lib/Localization/Translations.yml rename to src/Core/Localization/Translations.yml diff --git a/Geekbot.net/Lib/Logger/DiscordLogger.cs b/src/Core/Logger/DiscordLogger.cs similarity index 95% rename from Geekbot.net/Lib/Logger/DiscordLogger.cs rename to src/Core/Logger/DiscordLogger.cs index 688e26b..f6fb95a 100644 --- a/Geekbot.net/Lib/Logger/DiscordLogger.cs +++ b/src/Core/Logger/DiscordLogger.cs @@ -2,7 +2,7 @@ using System.Threading.Tasks; using Discord; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public class DiscordLogger : IDiscordLogger { diff --git a/Geekbot.net/Lib/Logger/GeekbotLogger.cs b/src/Core/Logger/GeekbotLogger.cs similarity index 96% rename from Geekbot.net/Lib/Logger/GeekbotLogger.cs rename to src/Core/Logger/GeekbotLogger.cs index e2a3714..8d4a8eb 100644 --- a/Geekbot.net/Lib/Logger/GeekbotLogger.cs +++ b/src/Core/Logger/GeekbotLogger.cs @@ -1,7 +1,7 @@ using System; using Newtonsoft.Json; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public class GeekbotLogger : IGeekbotLogger { diff --git a/Geekbot.net/Lib/Logger/IDiscordLogger.cs b/src/Core/Logger/IDiscordLogger.cs similarity index 76% rename from Geekbot.net/Lib/Logger/IDiscordLogger.cs rename to src/Core/Logger/IDiscordLogger.cs index fdc8c7f..c127e0c 100644 --- a/Geekbot.net/Lib/Logger/IDiscordLogger.cs +++ b/src/Core/Logger/IDiscordLogger.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using Discord; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public interface IDiscordLogger { diff --git a/Geekbot.net/Lib/Logger/IGeekbotLogger.cs b/src/Core/Logger/IGeekbotLogger.cs similarity index 92% rename from Geekbot.net/Lib/Logger/IGeekbotLogger.cs rename to src/Core/Logger/IGeekbotLogger.cs index 944524a..1363629 100644 --- a/Geekbot.net/Lib/Logger/IGeekbotLogger.cs +++ b/src/Core/Logger/IGeekbotLogger.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public interface IGeekbotLogger { diff --git a/Geekbot.net/Lib/Logger/LogDto.cs b/src/Core/Logger/LogDto.cs similarity index 88% rename from Geekbot.net/Lib/Logger/LogDto.cs rename to src/Core/Logger/LogDto.cs index 8ccfcdf..9db0c65 100644 --- a/Geekbot.net/Lib/Logger/LogDto.cs +++ b/src/Core/Logger/LogDto.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public class GeekbotLoggerObject { diff --git a/Geekbot.net/Lib/Logger/LogSource.cs b/src/Core/Logger/LogSource.cs similarity index 87% rename from Geekbot.net/Lib/Logger/LogSource.cs rename to src/Core/Logger/LogSource.cs index 48ad7d0..4518327 100644 --- a/Geekbot.net/Lib/Logger/LogSource.cs +++ b/src/Core/Logger/LogSource.cs @@ -1,7 +1,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { [JsonConverter(typeof(StringEnumConverter))] public enum LogSource diff --git a/Geekbot.net/Lib/Logger/LoggerFactory.cs b/src/Core/Logger/LoggerFactory.cs similarity index 98% rename from Geekbot.net/Lib/Logger/LoggerFactory.cs rename to src/Core/Logger/LoggerFactory.cs index e31686e..bc129fc 100644 --- a/Geekbot.net/Lib/Logger/LoggerFactory.cs +++ b/src/Core/Logger/LoggerFactory.cs @@ -5,7 +5,7 @@ using NLog.Config; using NLog.Targets; using SumoLogic.Logging.NLog; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public class LoggerFactory { diff --git a/Geekbot.net/Lib/Logger/MessageDto.cs b/src/Core/Logger/MessageDto.cs similarity index 92% rename from Geekbot.net/Lib/Logger/MessageDto.cs rename to src/Core/Logger/MessageDto.cs index 011acf3..039024e 100644 --- a/Geekbot.net/Lib/Logger/MessageDto.cs +++ b/src/Core/Logger/MessageDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public class MessageDto { diff --git a/Geekbot.net/Lib/Logger/SimpleConextConverter.cs b/src/Core/Logger/SimpleConextConverter.cs similarity index 96% rename from Geekbot.net/Lib/Logger/SimpleConextConverter.cs rename to src/Core/Logger/SimpleConextConverter.cs index 1eef12c..23cee40 100644 --- a/Geekbot.net/Lib/Logger/SimpleConextConverter.cs +++ b/src/Core/Logger/SimpleConextConverter.cs @@ -1,7 +1,7 @@ using Discord.Commands; using Discord.WebSocket; -namespace Geekbot.net.Lib.Logger +namespace Geekbot.Core.Logger { public class SimpleConextConverter { diff --git a/Geekbot.net/Lib/MalClient/IMalClient.cs b/src/Core/MalClient/IMalClient.cs similarity index 83% rename from Geekbot.net/Lib/MalClient/IMalClient.cs rename to src/Core/MalClient/IMalClient.cs index 6aaab05..70851c1 100644 --- a/Geekbot.net/Lib/MalClient/IMalClient.cs +++ b/src/Core/MalClient/IMalClient.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using MyAnimeListSharp.Core; -namespace Geekbot.net.Lib.MalClient +namespace Geekbot.Core.MalClient { public interface IMalClient { diff --git a/Geekbot.net/Lib/MalClient/MalClient.cs b/src/Core/MalClient/MalClient.cs similarity index 92% rename from Geekbot.net/Lib/MalClient/MalClient.cs rename to src/Core/MalClient/MalClient.cs index 3f121ea..3f5f165 100644 --- a/Geekbot.net/Lib/MalClient/MalClient.cs +++ b/src/Core/MalClient/MalClient.cs @@ -1,11 +1,11 @@ using System.Threading.Tasks; -using Geekbot.net.Lib.GlobalSettings; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.GlobalSettings; +using Geekbot.Core.Logger; using MyAnimeListSharp.Auth; using MyAnimeListSharp.Core; using MyAnimeListSharp.Facade.Async; -namespace Geekbot.net.Lib.MalClient +namespace Geekbot.Core.MalClient { public class MalClient : IMalClient { diff --git a/Geekbot.net/Lib/Media/FortunesProvider.cs b/src/Core/Media/FortunesProvider.cs similarity index 85% rename from Geekbot.net/Lib/Media/FortunesProvider.cs rename to src/Core/Media/FortunesProvider.cs index 56b5ed6..1b0d87a 100644 --- a/Geekbot.net/Lib/Media/FortunesProvider.cs +++ b/src/Core/Media/FortunesProvider.cs @@ -1,10 +1,10 @@ using System; using System.IO; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Logger; -namespace Geekbot.net.Lib.Media +namespace Geekbot.Core.Media { - internal class FortunesProvider : IFortunesProvider + public class FortunesProvider : IFortunesProvider { private readonly string[] _fortuneArray; private readonly int _totalFortunes; diff --git a/Geekbot.net/Lib/Media/IFortunesProvider.cs b/src/Core/Media/IFortunesProvider.cs similarity index 68% rename from Geekbot.net/Lib/Media/IFortunesProvider.cs rename to src/Core/Media/IFortunesProvider.cs index c82e45c..a4ef0d9 100644 --- a/Geekbot.net/Lib/Media/IFortunesProvider.cs +++ b/src/Core/Media/IFortunesProvider.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Media +namespace Geekbot.Core.Media { public interface IFortunesProvider { diff --git a/Geekbot.net/Lib/Media/IMediaProvider.cs b/src/Core/Media/IMediaProvider.cs similarity index 69% rename from Geekbot.net/Lib/Media/IMediaProvider.cs rename to src/Core/Media/IMediaProvider.cs index 63c0f41..03e32cf 100644 --- a/Geekbot.net/Lib/Media/IMediaProvider.cs +++ b/src/Core/Media/IMediaProvider.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Media +namespace Geekbot.Core.Media { public interface IMediaProvider { diff --git a/Geekbot.net/Lib/Media/MediaProvider.cs b/src/Core/Media/MediaProvider.cs similarity index 92% rename from Geekbot.net/Lib/Media/MediaProvider.cs rename to src/Core/Media/MediaProvider.cs index 5a9a055..4c72ee0 100644 --- a/Geekbot.net/Lib/Media/MediaProvider.cs +++ b/src/Core/Media/MediaProvider.cs @@ -1,10 +1,8 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Geekbot.net.Lib.Logger; -using Geekbot.net.Lib.RandomNumberGenerator; +using System.IO; +using Geekbot.Core.Logger; +using Geekbot.Core.RandomNumberGenerator; -namespace Geekbot.net.Lib.Media +namespace Geekbot.Core.Media { public class MediaProvider : IMediaProvider { diff --git a/Geekbot.net/Lib/Media/MediaType.cs b/src/Core/Media/MediaType.cs similarity index 84% rename from Geekbot.net/Lib/Media/MediaType.cs rename to src/Core/Media/MediaType.cs index aee317b..fa30164 100644 --- a/Geekbot.net/Lib/Media/MediaType.cs +++ b/src/Core/Media/MediaType.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.Media +namespace Geekbot.Core.Media { public enum MediaType { diff --git a/Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs b/src/Core/Polyfills/UserPolyfillDto.cs similarity index 90% rename from Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs rename to src/Core/Polyfills/UserPolyfillDto.cs index 32ea663..3a8f43f 100644 --- a/Geekbot.net/Lib/Polyfills/UserPolyfillDto.cs +++ b/src/Core/Polyfills/UserPolyfillDto.cs @@ -3,9 +3,9 @@ using System.Collections.Immutable; using System.Threading.Tasks; using Discord; -namespace Geekbot.net.Lib.Polyfills +namespace Geekbot.Core.Polyfills { - internal class UserPolyfillDto : IUser + public class UserPolyfillDto : IUser { public ulong Id { get; set; } public DateTimeOffset CreatedAt { get; set; } diff --git a/Geekbot.net/Lib/RandomNumberGenerator/IRandomNumberGenerator.cs b/src/Core/RandomNumberGenerator/IRandomNumberGenerator.cs similarity index 67% rename from Geekbot.net/Lib/RandomNumberGenerator/IRandomNumberGenerator.cs rename to src/Core/RandomNumberGenerator/IRandomNumberGenerator.cs index 32c6285..f817248 100644 --- a/Geekbot.net/Lib/RandomNumberGenerator/IRandomNumberGenerator.cs +++ b/src/Core/RandomNumberGenerator/IRandomNumberGenerator.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.RandomNumberGenerator +namespace Geekbot.Core.RandomNumberGenerator { public interface IRandomNumberGenerator { diff --git a/Geekbot.net/Lib/RandomNumberGenerator/RandomNumberGenerator.cs b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs similarity index 92% rename from Geekbot.net/Lib/RandomNumberGenerator/RandomNumberGenerator.cs rename to src/Core/RandomNumberGenerator/RandomNumberGenerator.cs index 79b4620..63381b5 100644 --- a/Geekbot.net/Lib/RandomNumberGenerator/RandomNumberGenerator.cs +++ b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs @@ -1,7 +1,7 @@ using System; using System.Security.Cryptography; -namespace Geekbot.net.Lib.RandomNumberGenerator +namespace Geekbot.Core.RandomNumberGenerator { public class RandomNumberGenerator : IRandomNumberGenerator { diff --git a/Geekbot.net/Lib/ReactionListener/IReactionListener.cs b/src/Core/ReactionListener/IReactionListener.cs similarity index 89% rename from Geekbot.net/Lib/ReactionListener/IReactionListener.cs rename to src/Core/ReactionListener/IReactionListener.cs index b2ab9fb..4909d68 100644 --- a/Geekbot.net/Lib/ReactionListener/IReactionListener.cs +++ b/src/Core/ReactionListener/IReactionListener.cs @@ -2,7 +2,7 @@ using Discord; using Discord.WebSocket; -namespace Geekbot.net.Lib.ReactionListener +namespace Geekbot.Core.ReactionListener { public interface IReactionListener { diff --git a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs b/src/Core/ReactionListener/ReactionListener.cs similarity index 92% rename from Geekbot.net/Lib/ReactionListener/ReactionListener.cs rename to src/Core/ReactionListener/ReactionListener.cs index bd335af..84367c9 100644 --- a/Geekbot.net/Lib/ReactionListener/ReactionListener.cs +++ b/src/Core/ReactionListener/ReactionListener.cs @@ -2,11 +2,11 @@ using System.Threading.Tasks; using Discord; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.Extensions; -namespace Geekbot.net.Lib.ReactionListener +namespace Geekbot.Core.ReactionListener { public class ReactionListener : IReactionListener { diff --git a/Geekbot.net/Lib/RunParameters.cs b/src/Core/RunParameters.cs similarity index 97% rename from Geekbot.net/Lib/RunParameters.cs rename to src/Core/RunParameters.cs index eb8c078..3210587 100644 --- a/Geekbot.net/Lib/RunParameters.cs +++ b/src/Core/RunParameters.cs @@ -1,7 +1,7 @@ using System; using CommandLine; -namespace Geekbot.net.Lib +namespace Geekbot.Core { public class RunParameters { diff --git a/Geekbot.net/Lib/UserRepository/IUserRepository.cs b/src/Core/UserRepository/IUserRepository.cs similarity index 68% rename from Geekbot.net/Lib/UserRepository/IUserRepository.cs rename to src/Core/UserRepository/IUserRepository.cs index b2f9a1f..32598f6 100644 --- a/Geekbot.net/Lib/UserRepository/IUserRepository.cs +++ b/src/Core/UserRepository/IUserRepository.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; using Discord.WebSocket; -using Geekbot.net.Database.Models; +using Geekbot.Core.Database.Models; -namespace Geekbot.net.Lib.UserRepository +namespace Geekbot.Core.UserRepository { public interface IUserRepository { diff --git a/Geekbot.net/Lib/UserRepository/UserRepository.cs b/src/Core/UserRepository/UserRepository.cs similarity index 88% rename from Geekbot.net/Lib/UserRepository/UserRepository.cs rename to src/Core/UserRepository/UserRepository.cs index 41e8e73..94d5df4 100644 --- a/Geekbot.net/Lib/UserRepository/UserRepository.cs +++ b/src/Core/UserRepository/UserRepository.cs @@ -1,14 +1,13 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Database.Models; -using Geekbot.net.Lib.Extensions; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.Extensions; +using Geekbot.Core.Logger; -namespace Geekbot.net.Lib.UserRepository +namespace Geekbot.Core.UserRepository { public class UserRepository : IUserRepository { diff --git a/Geekbot.net/Lib/WikipediaClient/IWikipediaClient.cs b/src/Core/WikipediaClient/IWikipediaClient.cs similarity index 63% rename from Geekbot.net/Lib/WikipediaClient/IWikipediaClient.cs rename to src/Core/WikipediaClient/IWikipediaClient.cs index c6cdf3d..fdb1ae1 100644 --- a/Geekbot.net/Lib/WikipediaClient/IWikipediaClient.cs +++ b/src/Core/WikipediaClient/IWikipediaClient.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using Geekbot.net.Lib.WikipediaClient.Page; +using Geekbot.Core.WikipediaClient.Page; -namespace Geekbot.net.Lib.WikipediaClient +namespace Geekbot.Core.WikipediaClient { public interface IWikipediaClient { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageApiUrls.cs b/src/Core/WikipediaClient/Page/PageApiUrls.cs similarity index 84% rename from Geekbot.net/Lib/WikipediaClient/Page/PageApiUrls.cs rename to src/Core/WikipediaClient/Page/PageApiUrls.cs index 803f4d7..6e3a1b6 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageApiUrls.cs +++ b/src/Core/WikipediaClient/Page/PageApiUrls.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageApiUrls { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrlCollection.cs b/src/Core/WikipediaClient/Page/PageContentUrlCollection.cs similarity index 73% rename from Geekbot.net/Lib/WikipediaClient/Page/PageContentUrlCollection.cs rename to src/Core/WikipediaClient/Page/PageContentUrlCollection.cs index 614aaa7..3b567a7 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrlCollection.cs +++ b/src/Core/WikipediaClient/Page/PageContentUrlCollection.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageContentUrlCollection { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrls.cs b/src/Core/WikipediaClient/Page/PageContentUrls.cs similarity index 79% rename from Geekbot.net/Lib/WikipediaClient/Page/PageContentUrls.cs rename to src/Core/WikipediaClient/Page/PageContentUrls.cs index faf7bb5..ca30b43 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageContentUrls.cs +++ b/src/Core/WikipediaClient/Page/PageContentUrls.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageContentUrls { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageCoordinates.cs b/src/Core/WikipediaClient/Page/PageCoordinates.cs similarity index 68% rename from Geekbot.net/Lib/WikipediaClient/Page/PageCoordinates.cs rename to src/Core/WikipediaClient/Page/PageCoordinates.cs index ce67f9b..52c31a4 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageCoordinates.cs +++ b/src/Core/WikipediaClient/Page/PageCoordinates.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageCoordinates { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageImage.cs b/src/Core/WikipediaClient/Page/PageImage.cs similarity index 76% rename from Geekbot.net/Lib/WikipediaClient/Page/PageImage.cs rename to src/Core/WikipediaClient/Page/PageImage.cs index cdcc2a9..8c4fb82 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageImage.cs +++ b/src/Core/WikipediaClient/Page/PageImage.cs @@ -1,6 +1,6 @@ using System; -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageImage { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageNamespace.cs b/src/Core/WikipediaClient/Page/PageNamespace.cs similarity index 68% rename from Geekbot.net/Lib/WikipediaClient/Page/PageNamespace.cs rename to src/Core/WikipediaClient/Page/PageNamespace.cs index 798e6b9..0691ac3 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageNamespace.cs +++ b/src/Core/WikipediaClient/Page/PageNamespace.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageNamespace { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PagePreview.cs b/src/Core/WikipediaClient/Page/PagePreview.cs similarity index 94% rename from Geekbot.net/Lib/WikipediaClient/Page/PagePreview.cs rename to src/Core/WikipediaClient/Page/PagePreview.cs index 37434d3..1c1749d 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PagePreview.cs +++ b/src/Core/WikipediaClient/Page/PagePreview.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PagePreview { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageTitles.cs b/src/Core/WikipediaClient/Page/PageTitles.cs similarity index 76% rename from Geekbot.net/Lib/WikipediaClient/Page/PageTitles.cs rename to src/Core/WikipediaClient/Page/PageTitles.cs index dcc2cea..ad83b27 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageTitles.cs +++ b/src/Core/WikipediaClient/Page/PageTitles.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public class PageTitles { diff --git a/Geekbot.net/Lib/WikipediaClient/Page/PageTypes.cs b/src/Core/WikipediaClient/Page/PageTypes.cs similarity index 84% rename from Geekbot.net/Lib/WikipediaClient/Page/PageTypes.cs rename to src/Core/WikipediaClient/Page/PageTypes.cs index 63cd4d2..8bc9f64 100644 --- a/Geekbot.net/Lib/WikipediaClient/Page/PageTypes.cs +++ b/src/Core/WikipediaClient/Page/PageTypes.cs @@ -1,6 +1,6 @@ using System.Runtime.Serialization; -namespace Geekbot.net.Lib.WikipediaClient.Page +namespace Geekbot.Core.WikipediaClient.Page { public enum PageTypes { diff --git a/Geekbot.net/Lib/WikipediaClient/WikipediaClient.cs b/src/Core/WikipediaClient/WikipediaClient.cs similarity index 87% rename from Geekbot.net/Lib/WikipediaClient/WikipediaClient.cs rename to src/Core/WikipediaClient/WikipediaClient.cs index ed4902a..f577d92 100644 --- a/Geekbot.net/Lib/WikipediaClient/WikipediaClient.cs +++ b/src/Core/WikipediaClient/WikipediaClient.cs @@ -1,9 +1,9 @@ using System.Net.Http; using System.Threading.Tasks; -using Geekbot.net.Lib.WikipediaClient.Page; +using Geekbot.Core.WikipediaClient.Page; using Newtonsoft.Json; -namespace Geekbot.net.Lib.WikipediaClient +namespace Geekbot.Core.WikipediaClient { public class WikipediaClient : IWikipediaClient { diff --git a/Geekbot.net/WebApi/ApiError.cs b/src/Web/ApiError.cs similarity index 70% rename from Geekbot.net/WebApi/ApiError.cs rename to src/Web/ApiError.cs index 182518e..3708d2c 100644 --- a/Geekbot.net/WebApi/ApiError.cs +++ b/src/Web/ApiError.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.WebApi +namespace Geekbot.Web { public class ApiError { diff --git a/Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs b/src/Web/Controllers/Callback/CallbackController.cs similarity index 96% rename from Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs rename to src/Web/Controllers/Callback/CallbackController.cs index 78fb38d..b3927bc 100644 --- a/Geekbot.net/WebApi/Controllers/Callback/CallbackController.cs +++ b/src/Web/Controllers/Callback/CallbackController.cs @@ -4,11 +4,11 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Discord.WebSocket; -using Geekbot.net.Lib.GlobalSettings; +using Geekbot.Core.GlobalSettings; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -namespace Geekbot.net.WebApi.Controllers.Callback +namespace Geekbot.Web.Controllers.Callback { public class CallbackController : Controller { diff --git a/Geekbot.net/WebApi/Controllers/Callback/CallbackTokenResponseDto.cs b/src/Web/Controllers/Callback/CallbackTokenResponseDto.cs similarity index 85% rename from Geekbot.net/WebApi/Controllers/Callback/CallbackTokenResponseDto.cs rename to src/Web/Controllers/Callback/CallbackTokenResponseDto.cs index 3c81592..37d2c32 100644 --- a/Geekbot.net/WebApi/Controllers/Callback/CallbackTokenResponseDto.cs +++ b/src/Web/Controllers/Callback/CallbackTokenResponseDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.WebApi.Controllers.Callback +namespace Geekbot.Web.Controllers.Callback { public class CallbackTokenResponseDto { diff --git a/Geekbot.net/WebApi/Controllers/Commands/CommandController.cs b/src/Web/Controllers/Commands/CommandController.cs similarity index 93% rename from Geekbot.net/WebApi/Controllers/Commands/CommandController.cs rename to src/Web/Controllers/Commands/CommandController.cs index 74f6e3c..e6c73e3 100644 --- a/Geekbot.net/WebApi/Controllers/Commands/CommandController.cs +++ b/src/Web/Controllers/Commands/CommandController.cs @@ -3,7 +3,7 @@ using Discord.Commands; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; -namespace Geekbot.net.WebApi.Controllers.Commands +namespace Geekbot.Web.Controllers.Commands { [EnableCors("AllowSpecificOrigin")] public class CommandController : Controller diff --git a/Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs b/src/Web/Controllers/Commands/CommandDto.cs similarity index 83% rename from Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs rename to src/Web/Controllers/Commands/CommandDto.cs index 981d0f2..7183a75 100644 --- a/Geekbot.net/WebApi/Controllers/Commands/CommandDto.cs +++ b/src/Web/Controllers/Commands/CommandDto.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Geekbot.net.WebApi.Controllers.Commands +namespace Geekbot.Web.Controllers.Commands { public class CommandDto { diff --git a/Geekbot.net/WebApi/Controllers/Commands/CommandParamDto.cs b/src/Web/Controllers/Commands/CommandParamDto.cs similarity index 74% rename from Geekbot.net/WebApi/Controllers/Commands/CommandParamDto.cs rename to src/Web/Controllers/Commands/CommandParamDto.cs index 5f7519d..77c9da6 100644 --- a/Geekbot.net/WebApi/Controllers/Commands/CommandParamDto.cs +++ b/src/Web/Controllers/Commands/CommandParamDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.WebApi.Controllers.Commands +namespace Geekbot.Web.Controllers.Commands { public class CommandParamDto { diff --git a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreController.cs b/src/Web/Controllers/Highscores/HighscoreController.cs similarity index 92% rename from Geekbot.net/WebApi/Controllers/Highscores/HighscoreController.cs rename to src/Web/Controllers/Highscores/HighscoreController.cs index 3cccb0e..e990431 100644 --- a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreController.cs +++ b/src/Web/Controllers/Highscores/HighscoreController.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; -using Geekbot.net.Lib.Highscores; +using Geekbot.Core.Highscores; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; -namespace Geekbot.net.WebApi.Controllers.Highscores +namespace Geekbot.Web.Controllers.Highscores { [EnableCors("AllowSpecificOrigin")] public class HighscoreController : Controller diff --git a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs b/src/Web/Controllers/Highscores/HighscoreControllerPostBodyDto.cs similarity index 76% rename from Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs rename to src/Web/Controllers/Highscores/HighscoreControllerPostBodyDto.cs index 6e7aec3..c3fe6a8 100644 --- a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerPostBodyDto.cs +++ b/src/Web/Controllers/Highscores/HighscoreControllerPostBodyDto.cs @@ -1,7 +1,7 @@ using System.ComponentModel.DataAnnotations; -using Geekbot.net.Lib.Highscores; +using Geekbot.Core.Highscores; -namespace Geekbot.net.WebApi.Controllers.Highscores +namespace Geekbot.Web.Controllers.Highscores { public class HighscoreControllerPostBodyDto { diff --git a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerReponseBody.cs b/src/Web/Controllers/Highscores/HighscoreControllerReponseBody.cs similarity index 66% rename from Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerReponseBody.cs rename to src/Web/Controllers/Highscores/HighscoreControllerReponseBody.cs index 0e59880..3cea17f 100644 --- a/Geekbot.net/WebApi/Controllers/Highscores/HighscoreControllerReponseBody.cs +++ b/src/Web/Controllers/Highscores/HighscoreControllerReponseBody.cs @@ -1,6 +1,6 @@ -using Geekbot.net.Lib.Highscores; +using Geekbot.Core.Highscores; -namespace Geekbot.net.WebApi.Controllers.Highscores +namespace Geekbot.Web.Controllers.Highscores { public class HighscoreControllerReponseBody { diff --git a/Geekbot.net/WebApi/Controllers/Status/ApiStatusDto.cs b/src/Web/Controllers/Status/ApiStatusDto.cs similarity index 75% rename from Geekbot.net/WebApi/Controllers/Status/ApiStatusDto.cs rename to src/Web/Controllers/Status/ApiStatusDto.cs index 0d5e6ad..cb2e5c7 100644 --- a/Geekbot.net/WebApi/Controllers/Status/ApiStatusDto.cs +++ b/src/Web/Controllers/Status/ApiStatusDto.cs @@ -1,4 +1,4 @@ -namespace Geekbot.net.WebApi.Controllers.Status +namespace Geekbot.Web.Controllers.Status { public class ApiStatusDto { diff --git a/Geekbot.net/WebApi/Controllers/Status/StatusController.cs b/src/Web/Controllers/Status/StatusController.cs similarity index 89% rename from Geekbot.net/WebApi/Controllers/Status/StatusController.cs rename to src/Web/Controllers/Status/StatusController.cs index c437e64..881462a 100644 --- a/Geekbot.net/WebApi/Controllers/Status/StatusController.cs +++ b/src/Web/Controllers/Status/StatusController.cs @@ -1,9 +1,9 @@ using System.Globalization; -using Geekbot.net.Lib; +using Geekbot.Core; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; -namespace Geekbot.net.WebApi.Controllers.Status +namespace Geekbot.Web.Controllers.Status { [EnableCors("AllowSpecificOrigin")] public class StatusController : Controller diff --git a/Geekbot.net/WebApi/Logging/AspLogProvider.cs b/src/Web/Logging/AspLogProvider.cs similarity index 88% rename from Geekbot.net/WebApi/Logging/AspLogProvider.cs rename to src/Web/Logging/AspLogProvider.cs index d35872d..25fdace 100644 --- a/Geekbot.net/WebApi/Logging/AspLogProvider.cs +++ b/src/Web/Logging/AspLogProvider.cs @@ -1,8 +1,8 @@ using System.Collections.Concurrent; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Logger; using Microsoft.Extensions.Logging; -namespace Geekbot.net.WebApi.Logging +namespace Geekbot.Web.Logging { public class AspLogProvider : ILoggerProvider { diff --git a/Geekbot.net/WebApi/Logging/AspLogger.cs b/src/Web/Logging/AspLogger.cs similarity index 95% rename from Geekbot.net/WebApi/Logging/AspLogger.cs rename to src/Web/Logging/AspLogger.cs index 5899b26..c18a7f3 100644 --- a/Geekbot.net/WebApi/Logging/AspLogger.cs +++ b/src/Web/Logging/AspLogger.cs @@ -1,8 +1,8 @@ using System; -using Geekbot.net.Lib.Logger; +using Geekbot.Core.Logger; using Microsoft.Extensions.Logging; -namespace Geekbot.net.WebApi.Logging +namespace Geekbot.Web.Logging { public class AspLogger : ILogger { diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj new file mode 100644 index 0000000..429165b --- /dev/null +++ b/src/Web/Web.csproj @@ -0,0 +1,26 @@ + + + + net5.0 + $(VersionSuffix) + $(VersionSuffix) + 0.0.0-DEV + Geekbot.Web + Geekbot.Web + NU1701 + + + + + + + + + + + + + + + + diff --git a/Geekbot.net/WebApi/WebApiStartup.cs b/src/Web/WebApiStartup.cs similarity index 86% rename from Geekbot.net/WebApi/WebApiStartup.cs rename to src/Web/WebApiStartup.cs index 7d3adc9..9aeedf9 100644 --- a/Geekbot.net/WebApi/WebApiStartup.cs +++ b/src/Web/WebApiStartup.cs @@ -2,19 +2,19 @@ using System.Reflection; using Discord.Commands; using Discord.WebSocket; -using Geekbot.net.Database; -using Geekbot.net.Lib; -using Geekbot.net.Lib.GlobalSettings; -using Geekbot.net.Lib.Highscores; -using Geekbot.net.Lib.Logger; -using Geekbot.net.WebApi.Logging; +using Geekbot.Core; +using Geekbot.Core.Database; +using Geekbot.Core.GlobalSettings; +using Geekbot.Core.Highscores; +using Geekbot.Core.Logger; +using Geekbot.Web.Logging; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace Geekbot.net.WebApi +namespace Geekbot.Web { public static class WebApiStartup { @@ -51,7 +51,7 @@ namespace Geekbot.net.WebApi logging.SetMinimumLevel(LogLevel.Debug); logging.AddProvider(new AspLogProvider(logger)); }) - .UseSetting(WebHostDefaults.ApplicationKey, typeof(Program).GetTypeInfo().Assembly.FullName) + .UseSetting(WebHostDefaults.ApplicationKey, typeof(WebApiStartup).GetTypeInfo().Assembly.FullName) .Build().Run(); } } From 61ce14a61df972b644bcc214fb3ceae7cb4ef996 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 8 Aug 2020 22:33:02 +0200 Subject: [PATCH 082/264] Change .gitlab-ci and dockerfile to fit the new project structure --- .gitlab-ci.yml | 4 ++-- Dockerfile | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3d362ce..410e380 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -5,7 +5,7 @@ stages: - ops variables: - VERSION: 4.2.0-$CI_COMMIT_SHORT_SHA + VERSION: 4.3.0-$CI_COMMIT_SHORT_SHA IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG Build: @@ -18,7 +18,7 @@ Build: script: - dotnet restore - dotnet test Tests - - dotnet publish --version-suffix $VERSION -r linux-x64 -c Release -o ./app ./Geekbot.net/ + - dotnet publish --version-suffix $VERSION -r linux-x64 -c Release -o ./app ./src/Bot/ Package: stage: docker diff --git a/Dockerfile b/Dockerfile index 822471d..479dd40 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,4 +4,4 @@ COPY ./app /app/ EXPOSE 12995/tcp WORKDIR /app -ENTRYPOINT ./Geekbot.net +ENTRYPOINT ./Geekbot From 97ad54df9e34c24638310158c941040827fc2250 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 17:22:18 +0200 Subject: [PATCH 083/264] Rename the folder Tests to tests --- Geekbot.net.sln | 2 +- {Tests => tests}/Core/Converters/EmojiConverter.test.cs | 0 {Tests => tests}/Core/DiceParser/DiceParser.test.cs | 0 {Tests => tests}/Core/DiceParser/SingleDie.test.cs | 0 {Tests => tests}/Core/Levels/LevelCalc.test.cs | 0 .../Core/Localization/TranslationGuildContext.test.cs | 0 {Tests => tests}/Core/Localization/Translations.test.cs | 0 {Tests => tests}/TestData.cs | 0 {Tests => tests}/Tests.csproj | 0 9 files changed, 1 insertion(+), 1 deletion(-) rename {Tests => tests}/Core/Converters/EmojiConverter.test.cs (100%) rename {Tests => tests}/Core/DiceParser/DiceParser.test.cs (100%) rename {Tests => tests}/Core/DiceParser/SingleDie.test.cs (100%) rename {Tests => tests}/Core/Levels/LevelCalc.test.cs (100%) rename {Tests => tests}/Core/Localization/TranslationGuildContext.test.cs (100%) rename {Tests => tests}/Core/Localization/Translations.test.cs (100%) rename {Tests => tests}/TestData.cs (100%) rename {Tests => tests}/Tests.csproj (100%) diff --git a/Geekbot.net.sln b/Geekbot.net.sln index 5dc5e4b..4a5b912 100644 --- a/Geekbot.net.sln +++ b/Geekbot.net.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "tests\Tests.csproj", "{4CAF5F02-EFFE-4FDA-BD44-EEADDBA9600E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "src\Core\Core.csproj", "{47671723-52A9-4668-BBC5-2BA76AE3B288}" EndProject diff --git a/Tests/Core/Converters/EmojiConverter.test.cs b/tests/Core/Converters/EmojiConverter.test.cs similarity index 100% rename from Tests/Core/Converters/EmojiConverter.test.cs rename to tests/Core/Converters/EmojiConverter.test.cs diff --git a/Tests/Core/DiceParser/DiceParser.test.cs b/tests/Core/DiceParser/DiceParser.test.cs similarity index 100% rename from Tests/Core/DiceParser/DiceParser.test.cs rename to tests/Core/DiceParser/DiceParser.test.cs diff --git a/Tests/Core/DiceParser/SingleDie.test.cs b/tests/Core/DiceParser/SingleDie.test.cs similarity index 100% rename from Tests/Core/DiceParser/SingleDie.test.cs rename to tests/Core/DiceParser/SingleDie.test.cs diff --git a/Tests/Core/Levels/LevelCalc.test.cs b/tests/Core/Levels/LevelCalc.test.cs similarity index 100% rename from Tests/Core/Levels/LevelCalc.test.cs rename to tests/Core/Levels/LevelCalc.test.cs diff --git a/Tests/Core/Localization/TranslationGuildContext.test.cs b/tests/Core/Localization/TranslationGuildContext.test.cs similarity index 100% rename from Tests/Core/Localization/TranslationGuildContext.test.cs rename to tests/Core/Localization/TranslationGuildContext.test.cs diff --git a/Tests/Core/Localization/Translations.test.cs b/tests/Core/Localization/Translations.test.cs similarity index 100% rename from Tests/Core/Localization/Translations.test.cs rename to tests/Core/Localization/Translations.test.cs diff --git a/Tests/TestData.cs b/tests/TestData.cs similarity index 100% rename from Tests/TestData.cs rename to tests/TestData.cs diff --git a/Tests/Tests.csproj b/tests/Tests.csproj similarity index 100% rename from Tests/Tests.csproj rename to tests/Tests.csproj From bd117e25956b5a5e4f822c42793014600182d59f Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 17:42:33 +0200 Subject: [PATCH 084/264] Fix Translations file path --- src/Core/Localization/TranslationHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/Localization/TranslationHandler.cs b/src/Core/Localization/TranslationHandler.cs index e38d9a1..c7d35e9 100644 --- a/src/Core/Localization/TranslationHandler.cs +++ b/src/Core/Localization/TranslationHandler.cs @@ -32,7 +32,7 @@ namespace Geekbot.Core.Localization try { // Read the file - var translationFile = File.ReadAllText(Path.GetFullPath("./Lib/Localization/Translations.yml")); + var translationFile = File.ReadAllText(Path.GetFullPath("./Localization/Translations.yml")); // Deserialize var input = new StringReader(translationFile); From d68ce459ef5e9e54af3aff113c46df483ea98aa2 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 17:47:28 +0200 Subject: [PATCH 085/264] Fix CI Pipeline: tests should be executed from the tests folder (with a lowercase t) --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 410e380..8efd1d1 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -17,7 +17,7 @@ Build: - app script: - dotnet restore - - dotnet test Tests + - dotnet test tests - dotnet publish --version-suffix $VERSION -r linux-x64 -c Release -o ./app ./src/Bot/ Package: From 7942308059ada47dbd14cff9a7b630d00c624344 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 18:22:09 +0200 Subject: [PATCH 086/264] Alias "!quote save" with "!quote add" --- src/Bot/Commands/Utils/Quote/Quote.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 4022753..9fe1431 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -58,9 +58,10 @@ namespace Geekbot.Bot.Commands.Utils.Quote } } - [Command("save")] - [Summary("Save a quote from the last sent message by @user")] - public async Task SaveQuote([Summary("@someone")] IUser user) + [Command("add")] + [Alias("save")] + [Summary("Add a quote from the last sent message by @user")] + public async Task AddQuote([Summary("@someone")] IUser user) { try { @@ -94,9 +95,10 @@ namespace Geekbot.Bot.Commands.Utils.Quote } } - [Command("save")] - [Summary("Save a quote from a message id")] - public async Task SaveQuote([Summary("message-ID")] ulong messageId) + [Command("add")] + [Alias("save")] + [Summary("Add a quote from a message id")] + public async Task AddQuote([Summary("message-ID")] ulong messageId) { try { From ad086a5e0c43d0b7d1181e29d10b5d1e190f6d8e Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 19:51:56 +0200 Subject: [PATCH 087/264] Make it possible to create quotes from message links --- src/Bot/Commands/Utils/Quote/MessageLink.cs | 47 ++++++++++ src/Bot/Commands/Utils/Quote/Quote.cs | 95 ++++++++++++++++++++- src/Core/Localization/Translations.yml | 6 ++ 3 files changed, 146 insertions(+), 2 deletions(-) create mode 100644 src/Bot/Commands/Utils/Quote/MessageLink.cs diff --git a/src/Bot/Commands/Utils/Quote/MessageLink.cs b/src/Bot/Commands/Utils/Quote/MessageLink.cs new file mode 100644 index 0000000..d789d15 --- /dev/null +++ b/src/Bot/Commands/Utils/Quote/MessageLink.cs @@ -0,0 +1,47 @@ +using System; +using System.Data; +using System.Text.RegularExpressions; + +namespace Geekbot.Bot.Commands.Utils.Quote +{ + public class MessageLink + { + public readonly static Regex re = new Regex( + @"https:\/\/(canary|ptb)?.discord(app)?.com\/channels\/(?\d{16,20})\/(?\d{16,20})\/(?\d{16,20})", + RegexOptions.Compiled | RegexOptions.IgnoreCase, + new TimeSpan(0, 0, 2)); + + public ulong GuildId { get; set; } + public ulong ChannelId { get; set; } + public ulong MessageId { get; set; } + + public MessageLink(string url) + { + var matches = re.Matches(url); + + foreach (Match match in matches) + { + foreach (Group matchGroup in match.Groups) + { + switch (matchGroup.Name) + { + case "GuildId": + GuildId = ulong.Parse(matchGroup.Value); + break; + case "ChannelId": + ChannelId = ulong.Parse(matchGroup.Value); + break; + case "MessageId": + MessageId = ulong.Parse(matchGroup.Value); + break; + } + } + } + } + + public static bool IsValid(string link) + { + return re.IsMatch(link); + } + } +} \ No newline at end of file diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 9fe1431..1e49a84 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -82,7 +82,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote if (lastMessage == null) return; var quote = CreateQuoteObject(lastMessage); - _database.Quotes.Add(quote); + await _database.Quotes.AddAsync(quote); await _database.SaveChangesAsync(); var embed = QuoteBuilder(quote); @@ -117,7 +117,61 @@ namespace Geekbot.Bot.Commands.Utils.Quote } var quote = CreateQuoteObject(message); - _database.Quotes.Add(quote); + await _database.Quotes.AddAsync(quote); + await _database.SaveChangesAsync(); + + var embed = QuoteBuilder(quote); + await ReplyAsync(transContext.GetString("QuoteAdded"), false, embed.Build()); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context, + "I couldn't find a message with that id :disappointed:"); + } + } + + [Command("add")] + [Alias("save")] + [Summary("Add a quote from a message link")] + public async Task AddQuote([Summary("message-link")] string messageLink) + { + try + { + var transContext = await _translationHandler.GetGuildContext(Context); + + if (!MessageLink.IsValid(messageLink)) + { + await ReplyAsync(transContext.GetString("NotAValidMessageLink")); + return; + } + + var link = new MessageLink(messageLink); + if (link.GuildId != Context.Guild.Id) + { + await ReplyAsync(transContext.GetString("OnlyQuoteFromSameServer")); + return; + } + + var channel = link.ChannelId == Context.Channel.Id + ? Context.Channel + : await Context.Guild.GetTextChannelAsync(link.ChannelId); + + var message = await channel.GetMessageAsync(link.MessageId); + + if (message.Author.Id == Context.Message.Author.Id) + { + await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); + return; + } + + if (message.Author.IsBot) + { + await ReplyAsync(transContext.GetString("CannotQuoteBots")); + return; + } + + var quote = CreateQuoteObject(message); + await _database.Quotes.AddAsync(quote); await _database.SaveChangesAsync(); var embed = QuoteBuilder(quote); @@ -167,6 +221,43 @@ namespace Geekbot.Bot.Commands.Utils.Quote } } + [Command("make")] + [Summary("Create a quote from a message link")] + public async Task ReturnSpecifiedQuote([Summary("message-link")] string messageLink) + { + try + { + var transContext = await _translationHandler.GetGuildContext(Context); + + if (!MessageLink.IsValid(messageLink)) + { + await ReplyAsync(transContext.GetString("NotAValidMessageLink")); + return; + } + + var link = new MessageLink(messageLink); + if (link.GuildId != Context.Guild.Id) + { + await ReplyAsync(transContext.GetString("OnlyQuoteFromSameServer")); + return; + } + + var channel = link.ChannelId == Context.Channel.Id + ? Context.Channel + : await Context.Guild.GetTextChannelAsync(link.ChannelId); + + var message = await channel.GetMessageAsync(link.MessageId); + var quote = CreateQuoteObject(message); + var embed = QuoteBuilder(quote); + await ReplyAsync("", false, embed.Build()); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context, + "I couldn't find that message :disappointed:"); + } + } + [Command("remove")] [RequireUserPermission(GuildPermission.ManageMessages)] [Summary("Remove a quote (user needs the 'ManageMessages' permission)")] diff --git a/src/Core/Localization/Translations.yml b/src/Core/Localization/Translations.yml index 3c59977..fbb55bf 100644 --- a/src/Core/Localization/Translations.yml +++ b/src/Core/Localization/Translations.yml @@ -169,6 +169,12 @@ quote: MostQuotesPerson: EN: "Most quoted person" CHDE: "Meist quoteti person" + NotAValidMessageLink: + EN: "That is not a valid message link" + CHDE: "Das isch kei korrete nachrichtelink" + OnlyQuoteFromSameServer: + EN: "You can only quote messages from the same server" + CHDE: "Du chasch numme nachrichte vom gliche server quote" rank: InvalidType: EN: "Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`'" From 726ee77ed4fb3e1fb6933ba2d421be96aaba0888 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 20:04:54 +0200 Subject: [PATCH 088/264] Fix bug where message links from discord stable would be considered invalid --- src/Bot/Commands/Utils/Quote/MessageLink.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Bot/Commands/Utils/Quote/MessageLink.cs b/src/Bot/Commands/Utils/Quote/MessageLink.cs index d789d15..dff1273 100644 --- a/src/Bot/Commands/Utils/Quote/MessageLink.cs +++ b/src/Bot/Commands/Utils/Quote/MessageLink.cs @@ -7,7 +7,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote public class MessageLink { public readonly static Regex re = new Regex( - @"https:\/\/(canary|ptb)?.discord(app)?.com\/channels\/(?\d{16,20})\/(?\d{16,20})\/(?\d{16,20})", + @"https:\/\/((canary|ptb)\.)?discord(app)?.com\/channels\/(?\d{16,20})\/(?\d{16,20})\/(?\d{16,20})", RegexOptions.Compiled | RegexOptions.IgnoreCase, new TimeSpan(0, 0, 2)); From 187fd6a04f95c59044c9369de4ef145576d64982 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 13 Aug 2020 22:46:53 +0200 Subject: [PATCH 089/264] Remove code duplication from !quote --- src/Bot/Commands/Utils/Quote/Quote.cs | 288 ++++++++++---------------- 1 file changed, 109 insertions(+), 179 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 1e49a84..a731273 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; @@ -22,6 +23,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; private readonly ITranslationHandler _translationHandler; + private readonly bool _isDev; public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translationHandler) { @@ -29,6 +31,8 @@ namespace Geekbot.Bot.Commands.Utils.Quote _database = database; _randomNumberGenerator = randomNumberGenerator; _translationHandler = translationHandler; + // to remove restrictions when developing + _isDev = Constants.BotVersion() == "0.0.0-DEV"; } [Command] @@ -63,36 +67,15 @@ namespace Geekbot.Bot.Commands.Utils.Quote [Summary("Add a quote from the last sent message by @user")] public async Task AddQuote([Summary("@someone")] IUser user) { - try - { - var transContext = await _translationHandler.GetGuildContext(Context); - if (user.Id == Context.Message.Author.Id) - { - await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); - return; - } - - if (user.IsBot) - { - await ReplyAsync(transContext.GetString("CannotQuoteBots")); - return; - } - - var lastMessage = await GetLastMessageByUser(user); - if (lastMessage == null) return; - - var quote = CreateQuoteObject(lastMessage); - await _database.Quotes.AddAsync(quote); - await _database.SaveChangesAsync(); - - var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("QuoteAdded"), false, embed.Build()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context, - "I counldn't find a quote from that user :disappointed:"); - } + await QuoteFromMention(user, true); + } + + [Command("make")] + [Alias("preview")] + [Summary("Preview a quote from the last sent message by @user")] + public async Task ReturnSpecifiedQuote([Summary("@someone")] IUser user) + { + await QuoteFromMention(user, false); } [Command("add")] @@ -100,34 +83,15 @@ namespace Geekbot.Bot.Commands.Utils.Quote [Summary("Add a quote from a message id")] public async Task AddQuote([Summary("message-ID")] ulong messageId) { - try - { - var transContext = await _translationHandler.GetGuildContext(Context); - var message = await Context.Channel.GetMessageAsync(messageId); - if (message.Author.Id == Context.Message.Author.Id) - { - await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); - return; - } - - if (message.Author.IsBot) - { - await ReplyAsync(transContext.GetString("CannotQuoteBots")); - return; - } - - var quote = CreateQuoteObject(message); - await _database.Quotes.AddAsync(quote); - await _database.SaveChangesAsync(); - - var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("QuoteAdded"), false, embed.Build()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context, - "I couldn't find a message with that id :disappointed:"); - } + await QuoteFromMessageId(messageId, true); + } + + [Command("make")] + [Alias("preview")] + [Summary("Preview a quote from a message id")] + public async Task ReturnSpecifiedQuote([Summary("message-ID")] ulong messageId) + { + await QuoteFromMessageId(messageId, false); } [Command("add")] @@ -135,127 +99,15 @@ namespace Geekbot.Bot.Commands.Utils.Quote [Summary("Add a quote from a message link")] public async Task AddQuote([Summary("message-link")] string messageLink) { - try - { - var transContext = await _translationHandler.GetGuildContext(Context); - - if (!MessageLink.IsValid(messageLink)) - { - await ReplyAsync(transContext.GetString("NotAValidMessageLink")); - return; - } - - var link = new MessageLink(messageLink); - if (link.GuildId != Context.Guild.Id) - { - await ReplyAsync(transContext.GetString("OnlyQuoteFromSameServer")); - return; - } - - var channel = link.ChannelId == Context.Channel.Id - ? Context.Channel - : await Context.Guild.GetTextChannelAsync(link.ChannelId); - - var message = await channel.GetMessageAsync(link.MessageId); - - if (message.Author.Id == Context.Message.Author.Id) - { - await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); - return; - } - - if (message.Author.IsBot) - { - await ReplyAsync(transContext.GetString("CannotQuoteBots")); - return; - } - - var quote = CreateQuoteObject(message); - await _database.Quotes.AddAsync(quote); - await _database.SaveChangesAsync(); - - var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("QuoteAdded"), false, embed.Build()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context, - "I couldn't find a message with that id :disappointed:"); - } - } - - [Command("make")] - [Summary("Create a quote from the last sent message by @user")] - public async Task ReturnSpecifiedQuote([Summary("@someone")] IUser user) - { - try - { - var lastMessage = await GetLastMessageByUser(user); - if (lastMessage == null) return; - var quote = CreateQuoteObject(lastMessage); - var embed = QuoteBuilder(quote); - await ReplyAsync("", false, embed.Build()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context, - "I counldn't find a quote from that user :disappointed:"); - } - } - - [Command("make")] - [Summary("Create a quote from a message id")] - public async Task ReturnSpecifiedQuote([Summary("message-ID")] ulong messageId) - { - try - { - var message = await Context.Channel.GetMessageAsync(messageId); - var quote = CreateQuoteObject(message); - var embed = QuoteBuilder(quote); - await ReplyAsync("", false, embed.Build()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context, - "I couldn't find a message with that id :disappointed:"); - } + await QuoteFromMessageLink(messageLink, true); } [Command("make")] - [Summary("Create a quote from a message link")] + [Alias("preview")] + [Summary("Preview a quote from a message link")] public async Task ReturnSpecifiedQuote([Summary("message-link")] string messageLink) { - try - { - var transContext = await _translationHandler.GetGuildContext(Context); - - if (!MessageLink.IsValid(messageLink)) - { - await ReplyAsync(transContext.GetString("NotAValidMessageLink")); - return; - } - - var link = new MessageLink(messageLink); - if (link.GuildId != Context.Guild.Id) - { - await ReplyAsync(transContext.GetString("OnlyQuoteFromSameServer")); - return; - } - - var channel = link.ChannelId == Context.Channel.Id - ? Context.Channel - : await Context.Guild.GetTextChannelAsync(link.ChannelId); - - var message = await channel.GetMessageAsync(link.MessageId); - var quote = CreateQuoteObject(message); - var embed = QuoteBuilder(quote); - await ReplyAsync("", false, embed.Build()); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context, - "I couldn't find that message :disappointed:"); - } + await QuoteFromMessageLink(messageLink, false); } [Command("remove")] @@ -340,22 +192,100 @@ namespace Geekbot.Bot.Commands.Utils.Quote } } - private async Task GetLastMessageByUser(IUser user) + private async Task QuoteFromMention(IUser user, bool saveToDb) { try { + var transContext = await _translationHandler.GetGuildContext(Context); + var list = Context.Channel.GetMessagesAsync().Flatten(); - return await list.FirstOrDefaultAsync(msg => + var message = await list.FirstOrDefaultAsync(msg => msg.Author.Id == user.Id && msg.Embeds.Count == 0 && msg.Id != Context.Message.Id && !msg.Content.ToLower().StartsWith("!")); + if (message == null) return; + + await ProcessQuote(message, saveToDb, transContext); } - catch + catch (Exception e) { - await ReplyAsync($"No quoteable message have been sent by {user.Username} in this channel"); - return null; + await _errorHandler.HandleCommandException(e, Context, $"No quoteable messages have been sent by {user.Username} in this channel"); } + + } + + private async Task QuoteFromMessageId(ulong messageId, bool saveToDb) + { + try + { + var transContext = await _translationHandler.GetGuildContext(Context); + var message = await Context.Channel.GetMessageAsync(messageId); + + await ProcessQuote(message, saveToDb, transContext); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); + } + } + + private async Task QuoteFromMessageLink(string messageLink, bool saveToDb) + { + try + { + var transContext = await _translationHandler.GetGuildContext(Context); + + if (!MessageLink.IsValid(messageLink)) + { + await ReplyAsync(transContext.GetString("NotAValidMessageLink")); + return; + } + + var link = new MessageLink(messageLink); + if (link.GuildId != Context.Guild.Id) + { + await ReplyAsync(transContext.GetString("OnlyQuoteFromSameServer")); + return; + } + + var channel = link.ChannelId == Context.Channel.Id + ? Context.Channel + : await Context.Guild.GetTextChannelAsync(link.ChannelId); + + var message = await channel.GetMessageAsync(link.MessageId); + + await ProcessQuote(message, saveToDb, transContext); + } + catch (Exception e) + { + await _errorHandler.HandleCommandException(e, Context, "I couldn't find that message :disappointed:"); + } + } + + private async Task ProcessQuote(IMessage message, bool saveToDb, TranslationGuildContext transContext) + { + if (message.Author.Id == Context.Message.Author.Id && saveToDb && !_isDev) + { + await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); + return; + } + + if (message.Author.IsBot && saveToDb && !_isDev) + { + await ReplyAsync(transContext.GetString("CannotQuoteBots")); + return; + } + + var quote = CreateQuoteObject(message); + if (saveToDb) + { + await _database.Quotes.AddAsync(quote); + await _database.SaveChangesAsync(); + } + + var embed = QuoteBuilder(quote); + await ReplyAsync(saveToDb ? transContext.GetString("QuoteAdded") : string.Empty, false, embed.Build()); } private EmbedBuilder QuoteBuilder(QuoteModel quote) From 12388fd7d04faff06c43371c922df337b5a4dead Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 14 Aug 2020 00:12:14 +0200 Subject: [PATCH 090/264] Curate Media Files --- src/Bot/Storage/croissant | 13 +++---------- src/Bot/Storage/foxes | 31 +++++++++++-------------------- src/Bot/Storage/pandas | 5 +++-- src/Bot/Storage/penguins | 22 ++++++++++++---------- src/Bot/Storage/pumpkin | 23 +++++++---------------- src/Bot/Storage/squirrel | 28 ++++------------------------ src/Bot/Storage/turtles | 13 ++++++------- 7 files changed, 46 insertions(+), 89 deletions(-) diff --git a/src/Bot/Storage/croissant b/src/Bot/Storage/croissant index 281b790..6b4897f 100644 --- a/src/Bot/Storage/croissant +++ b/src/Bot/Storage/croissant @@ -3,15 +3,8 @@ http://www.bakespace.com/images/large/5d79070cf21b2f33c3a1dd4336cb27d2.jpeg http://food.fnr.sndimg.com/content/dam/images/food/fullset/2015/5/7/1/SD1B43_croissants-recipe_s4x3.jpg.rend.hgtvcom.616.462.suffix/1431052139248.jpeg http://img.taste.com.au/u-Bwjfm_/taste/2016/11/mini-croissants-with-3-fillings-14692-1.jpeg https://media.newyorker.com/photos/590974702179605b11ad8096/16:9/w_1200,h_630,c_limit/Gopnik-TheMurkyMeaningsofStraightenedOutCroissants.jpg -http://bt.static-redmouse.ch/sites/bielertagblatt.ch/files/styles/bt_article_showroom_landscape/hash/84/c9/84c9aed08415265911ec05c46d25d3ef.jpg?itok=hP5PnHaT -https://www.dermann.at/wp-content/uploads/Schokocroissant_HPBild_1400x900px.jpeg -https://www.bettybossi.ch/static/rezepte/x/bb_bkxx060101_0360a_x.jpg -http://www.engel-beck.ch/uploads/pics/tete-de-moine-gipfel-.jpg https://storage.cpstatic.ch/storage/og_image/laugengipfel--425319.jpg -https://www.backhaus-kutzer.de/fileadmin/templates/Resources/Public/img/produkte/suesses-gebaeck/Milchhoernchen.png -https://www.kuechengoetter.de/uploads/media/1000x524/00/36390-vanillekipferl-0.jpg?v=1-0 https://c1.staticflickr.com/3/2835/10874180753_2b2916e3ce_b.jpg -http://www.mistercool.ch/wp-content/uploads/2017/02/Gipfel-mit-Cerealien-7168.png -https://scontent-sea1-1.cdninstagram.com/t51.2885-15/s480x480/e35/c40.0.999.999/15099604_105396696611384_2866237281000226816_n.jpg?ig_cache_key=MTM4MzQxOTU1MDc5NjUxNzcwMA%3D%3D.2.c -http://www.lecrobag.de/wp-content/uploads/2014/03/Wurst_2014_l.jpg -https://www.thecookierookie.com/wp-content/uploads/2017/02/sheet-pan-chocolate-croissants-collage1.jpeg \ No newline at end of file +https://www.spatz-dessert.ch/image_upload/Laugengipfel.jpg +http://www.baeckerei-meier.ch/images/p005_1_03.png +http://i.huffpost.com/gen/1278175/thumbs/o-CROISSANT-facebook.jpg \ No newline at end of file diff --git a/src/Bot/Storage/foxes b/src/Bot/Storage/foxes index 020c1cf..52fd9d2 100644 --- a/src/Bot/Storage/foxes +++ b/src/Bot/Storage/foxes @@ -1,29 +1,20 @@ https://i.ytimg.com/vi/qF6OOGuT_hI/maxresdefault.jpg -https://www.hd-wallpapersdownload.com/script/bulk-upload/desktop-funny-fox-wallpaper.jpg -http://moziru.com/images/drawn-fox-funny-18.jpg https://static.tumblr.com/bb34d8f163098ad1daafcffbdbb03975/rk23uap/Nwwp0rmi2/tumblr_static_tumblr_static__640.jpg -https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoHUFOnZ3wJ2kT1skNdztFXXSvpU8bEoGS1alNZiuyLXvGJhcY -http://childrenstorytales.com/wp-content/uploads/2011/03/how-to-draw-a-red-fox-in-the-snow.jpg https://www.popsci.com/sites/popsci.com/files/styles/1000_1x_/public/import/2013/images/2013/09/redfoxyawn.jpg?itok=yRkSVe8T https://hdqwalls.com/wallpapers/wild-fox-art.jpg -https://ae01.alicdn.com/kf/HTB1Q9dpLpXXXXbhXpXXq6xXFXXXl/new-cute-fox-toy-lifelike-soft-long-yellow-fox-doll-gift-about-73cm.jpg_640x640.jpg https://i.imgur.com/ktK9yXX.jpg -https://res.cloudinary.com/teepublic/image/private/s--yTx2ncFA--/t_Preview/b_rgb:c8e0ec,c_limit,f_auto,h_313,q_90,w_313/v1506478249/production/designs/1932607_0 http://4.bp.blogspot.com/-Hz-o_KYj3Xk/Vlm2mwbztjI/AAAAAAAA8Ss/jbH5ovjmC9A/s1600/ScreenShot5502.jpg -https://i.pinimg.com/originals/1e/d5/2f/1ed52f70873a95ac02fa074e48edfb71.jpg -https://i.imgur.com/2vCrtap.jpg -https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSfukWGu_IBaDeJOMBqOhVAwsDfqEPw0BFpCn5_-Iyr_xjd7zi9 -https://cdn.pixabay.com/photo/2017/01/31/18/36/animal-2026297_960_720.png -https://i.pinimg.com/originals/e2/63/67/e26367a0844633b2a697b0a9d69e8cc9.jpg -https://i.ebayimg.com/images/g/BvkAAOSwqxdTqrip/s-l300.jpg -https://res.cloudinary.com/teepublic/image/private/s--1R53bger--/t_Preview/b_rgb:eae0c7,c_limit,f_jpg,h_630,q_90,w_630/v1481013120/production/designs/914528_1.jpg -https://i.pinimg.com/originals/97/fe/69/97fe698462afde7b4209ccefeecbce71.jpg -https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6G0ch6g-wG1TuDJ6BbkOFelMNnkgFXC6CxOw7qSNjoFkx-BCe https://wallpaperscraft.com/image/fox_forest_grass_117190_540x960.jpg -https://image.freepik.com/free-vector/cartoon-flat-illustration-funny-cute-fox_6317-1174.jpg https://orig00.deviantart.net/2feb/f/2013/137/a/f/fox_and_curious_squirrel_by_tamarar-d65ju8d.jpg -https://res.cloudinary.com/teepublic/image/private/s--dICeNmBx--/t_Preview/b_rgb:6e2229,c_limit,f_jpg,h_630,q_90,w_630/v1505243196/production/designs/1890493_1.jpg -https://vignette.wikia.nocookie.net/puppyinmypocketfanon/images/4/49/L-Baby-Fox.jpg/revision/latest?cb=20130421001806 -http://7-themes.com/data_images/out/69/7009194-fox-puppy.jpg http://www.tehcute.com/pics/201401/little-fox-big.jpg -https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR6QXB1APLdUsyzO39kPvhnC9cOvcwzEtsxown9QjWilWppia2mwg \ No newline at end of file +https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR6QXB1APLdUsyzO39kPvhnC9cOvcwzEtsxown9QjWilWppia2mwg +https://www.wildlifeaid.org.uk/wp-content/uploads/2016/03/FP9_July09.jpg +https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Vulpes_vulpes_ssp_fulvus_6568085.jpg/1200px-Vulpes_vulpes_ssp_fulvus_6568085.jpg +http://images.hellogiggles.com/uploads/2017/06/10023347/fox1.jpg +https://i.ytimg.com/vi/mtroFou8Xb4/maxresdefault.jpg +http://wallpapers-best.com/uploads/posts/2015-09/20_fox.jpg +https://www.whats-your-sign.com/wp-content/uploads/2018/02/RedFoxSymbolism4.jpg +https://cdn.zmescience.com/wp-content/uploads/2016/09/8505162700_11394c3f6a_b.jpg +http://wallpapers-best.com/uploads/posts/2015-09/18_fox.jpg +https://s.abcnews.com/images/General/red-fox-new-jersey-gty-jt-191119_hpMain_16x9_992.jpg +https://i.ytimg.com/vi/ClNRWL_9L8s/maxresdefault.jpg \ No newline at end of file diff --git a/src/Bot/Storage/pandas b/src/Bot/Storage/pandas index 9d5046c..6c6d725 100644 --- a/src/Bot/Storage/pandas +++ b/src/Bot/Storage/pandas @@ -4,8 +4,9 @@ https://nationalzoo.si.edu/sites/default/files/styles/slide_1400x700/public/supp https://media4.s-nbcnews.com/j/newscms/2016_36/1685951/ss-160826-twip-05_8cf6d4cb83758449fd400c7c3d71aa1f.nbcnews-ux-2880-1000.jpg https://ichef-1.bbci.co.uk/news/660/cpsprodpb/169F6/production/_91026629_gettyimages-519508400.jpg https://cdn.history.com/sites/2/2017/03/GettyImages-157278376.jpg -https://www.pandasinternational.org/wptemp/wp-content/uploads/2012/10/slider1.jpg https://tctechcrunch2011.files.wordpress.com/2015/11/panda.jpg http://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2016/08/departments/panda-mania-12.jpg http://animals.sandiegozoo.org/sites/default/files/2016-09/panda1_10.jpg -http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/A-G/giant-panda-eating.adapt.945.1.jpg \ No newline at end of file +http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/A-G/giant-panda-eating.adapt.945.1.jpg +https://static.independent.co.uk/s3fs-public/thumbnails/image/2015/10/08/15/Hong-Kong-pandas.jpg +https://3sn4dm1qd6i72l8a4r2ig7fl-wpengine.netdna-ssl.com/wp-content/uploads/2016/11/panda_lunlun_ZA_2083-b.jpg \ No newline at end of file diff --git a/src/Bot/Storage/penguins b/src/Bot/Storage/penguins index d38d853..95aa70d 100644 --- a/src/Bot/Storage/penguins +++ b/src/Bot/Storage/penguins @@ -1,13 +1,15 @@ -https://i.ytimg.com/vi/Qr6sULJnu2o/maxresdefault.jpg -https://www.apex-expeditions.com/wp-content/uploads/2015/08/newzealandSlider_Macquarie_ElephantSealKingPenguins_GRiehle_1366x601.jpg https://www.birdlife.org/sites/default/files/styles/1600/public/slide.jpg?itok=HRhQfA1S http://experimentexchange.com/wp-content/uploads/2016/07/penguins-fact.jpg -http://images.mentalfloss.com/sites/default/files/styles/mf_image_16x9/public/istock-511366776.jpg?itok=cWhdWNZ8&resize=1100x619 -https://www.thevaporplace.ch/media/catalog/product/cache/1/thumbnail/800x800/9df78eab33525d08d6e5fb8d27136e95/a/t/atopack_penguin-15.jpg -https://www.superfastbusiness.com/wp-content/uploads/2015/10/real-time-penguin-algorithm-featured.jpg http://www.antarctica.gov.au/__data/assets/image/0011/147737/varieties/antarctic.jpg -https://vignette.wikia.nocookie.net/robloxcreepypasta/images/1/11/AAEAAQAAAAAAAAdkAAAAJDc3YzkyYjJhLTYyZjctNDY2Mi04M2VjLTg4NjY4ZjgwYzRmNg.png/revision/latest?cb=20180207200526 -https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR3xV0lhpZuhT8Nmm6LaITsppZ7VfWcWXuyu2cPHrlv_dt_M92K5g -http://goboiano.com/wp-content/uploads/2017/04/Penguin-Kemeno-Friends-Waifu.jpg -https://cdn.yoast.com/app/uploads/2015/10/Penguins_1200x628.png -https://images.justwatch.com/backdrop/8611153/s1440/pingu \ No newline at end of file +https://images.justwatch.com/backdrop/8611153/s1440/pingu +http://4.bp.blogspot.com/-VhmPPCcZnwA/TWR303DSAuI/AAAAAAAAABU/eSSokmd376s/s1600/2-Penguins-penguins-4234010-1280-1024.jpg +https://media.glamour.com/photos/56959e35d9dab9ff41b308a0/master/pass/inspired-2015-02-gentoo-penguin-main.jpg +https://indiansciencejournal.files.wordpress.com/2012/04/emperor-penguin-credit-british-antarctic-survey.jpg +https://fthmb.tqn.com/7cd9Q3LSapEShHq2mKvQgSPr_tc=/2250x1500/filters:fill(auto,1)/149267744-56a008755f9b58eba4ae8f46.jpg +https://blogs.voanews.com/science-world/files/2014/07/11240219084_941dfbf66e_b.jpg +https://blogs.biomedcentral.com/bmcseriesblog/wp-content/uploads/sites/9/2015/11/IMG_5391-2.jpg +https://i2-prod.mirror.co.uk/incoming/article11682518.ece/ALTERNATES/s615/Emperor-penguins-on-ice.jpg +https://www.gannett-cdn.com/presto/2019/04/15/PPHX/8dfe0433-c22c-4458-9ba8-3aab866774f8-Penguins5cad7bfd107a4.jpg?crop=5759,3224,x0,y0&width=3200&height=1680&fit=bounds +http://4.bp.blogspot.com/_FNQgkfCwYxs/S82jBAxMVEI/AAAAAAAAAns/_3lAuJhUfcs/s1600/311785583_af8f2d1ea7_o.jpg +http://wallsdesk.com/wp-content/uploads/2017/01/Pictures-of-Penguin-.jpg +http://2.bp.blogspot.com/_W90V87w3sr8/TP3RPYwrrjI/AAAAAAAAAXk/riN0GwRwhFM/s1600/leap-of-faith-adelie-penguin-pictures.jpg \ No newline at end of file diff --git a/src/Bot/Storage/pumpkin b/src/Bot/Storage/pumpkin index 4b8e6f2..3652397 100644 --- a/src/Bot/Storage/pumpkin +++ b/src/Bot/Storage/pumpkin @@ -1,23 +1,14 @@ https://i.pinimg.com/736x/0a/a7/8a/0aa78af25e114836e1a42585fb7b09ed--funny-pumpkins-pumkin-carving.jpg http://wdy.h-cdn.co/assets/16/31/980x1470/gallery-1470321728-shot-two-021.jpg -https://i.pinimg.com/736x/6c/62/bf/6c62bfa73a19ffd9fc6f2d720d5e9764--cool-pumpkin-carving-carving-pumpkins.jpg http://images6.fanpop.com/image/photos/38900000/Jack-o-Lantern-halloween-38991566-500-415.jpg http://ghk.h-cdn.co/assets/15/37/1441834730-pumpkin-carve-2.jpg http://diy.sndimg.com/content/dam/images/diy/fullset/2011/7/26/1/iStock-10761186_halloween-pumpkin-in-garden_s4x3.jpg.rend.hgtvcom.966.725.suffix/1420851319631.jpeg -http://ghk.h-cdn.co/assets/cm/15/11/54ffe537af882-snail-pumpkin-de.jpg https://www.digsdigs.com/photos/2009/10/100-halloween-pumpkin-carving-ideas-12.jpg -http://diy.sndimg.com/content/dam/images/diy/fullset/2010/6/4/0/CI-Kyle-Nishioka_big-teeth-Jack-O-Lantern_s4x3.jpg.rend.hgtvcom.966.725.suffix/1420699522718.jpeg -https://twistedsifter.files.wordpress.com/2011/10/most-amazing-pumpkin-carving-ray-villafane-10.jpg?w=521&h=739 -https://i.pinimg.com/736x/09/c4/b1/09c4b187b266c1f65332294f66009944--funny-pumpkins-halloween-pumpkins.jpg -http://www.evilmilk.com/pictures/The_Pumpkin_Man.jpg -http://cache.lovethispic.com/uploaded_images/blogs/13-Funny-Pumpkin-Carvings-5773-9.JPG -http://ihappyhalloweenpictures.com/wp-content/uploads/2016/10/funny-halloween-pumpkin.jpg -http://www.smallhomelove.com/wp-content/uploads/2012/08/leg-eating-pumpkin.jpg -https://cdn.shopify.com/s/files/1/0773/6789/articles/Halloween_Feature_8ff7a7c4-2cb3-4584-a85f-5d4d1e6ca26e.jpg?v=1476211360 -http://4vector.com/i/free-vector-pumpkin-boy-color-version-clip-art_107714_Pumpkin_Boy_Color_Version_clip_art_hight.png https://i.pinimg.com/736x/59/8a/0f/598a0fbf789631b76c1ffd4443194d8e--halloween-pumpkins-fall-halloween.jpg -https://i.pinimg.com/originals/8f/86/f9/8f86f95457467872b371ba697d341961.jpg -http://nerdist.com/wp-content/uploads/2015/08/taleshalloween1.jpg -http://www.designbolts.com/wp-content/uploads/2014/09/Scary-Pumpkin_Grin_stencil-Ideas.jpg -http://vignette2.wikia.nocookie.net/scoobydoo/images/7/75/Pumpkin_monsters_%28Witch%27s_Ghost%29.png/revision/latest?cb=20140520070213 -https://taholtorf.files.wordpress.com/2013/10/36307-1920x1280.jpg +http://i.huffpost.com/gen/1405530/images/o-PUMPKINS-facebook.jpg +https://www.reviewjournal.com/wp-content/uploads/2016/10/web1_thinkstockphotos-491684958_7239666.jpg +https://img.sunset02.com/sites/default/files/1494265591/pumpkins-growing-on-farm-getty-sun-0517.jpg +https://toronto.citynews.ca/wp-content/blogs.dir/sites/10/2015/10/06/pumpkin-patch.jpg +http://i.huffpost.com/gen/3494726/images/o-PUMPKIN-facebook.jpg +https://servingjoy.com/wp-content/uploads/2014/12/Beautiful-autumn-halloween-pumpkins.jpg +https://www.history.com/.image/t_share/MTU3ODc5MDg2NDI4OTg4NzQ1/still-life-of-a-jack-o-lantern.jpg \ No newline at end of file diff --git a/src/Bot/Storage/squirrel b/src/Bot/Storage/squirrel index 2216465..91fd240 100644 --- a/src/Bot/Storage/squirrel +++ b/src/Bot/Storage/squirrel @@ -1,45 +1,25 @@ -http://orig14.deviantart.net/6016/f/2010/035/c/b/first_squirrel_assassin_by_shotokanteddy.jpg -https://thumbs-prod.si-cdn.com/eoEYA_2Hau4795uKoecUZZgz-3w=/800x600/filters:no_upscale()/https://public-media.smithsonianmag.com/filer/52/f9/52f93262-c29b-4a4f-b031-0c7ad145ed5f/42-33051942.jpg +https://public-media.smithsonianmag.com/filer/52/f9/52f93262-c29b-4a4f-b031-0c7ad145ed5f/42-33051942.jpg http://images5.fanpop.com/image/photos/30700000/Squirrel-squirrels-30710732-400-300.jpg -https://www.lovethegarden.com/sites/default/files/files/Red%20%26%20Grey%20Squirrel%20picture%20side%20by%20side-LR.jpg http://i.dailymail.co.uk/i/pix/2016/02/24/16/158F7E7C000005DC-3462228-image-a-65_1456331226865.jpg http://2.bp.blogspot.com/-egfnMhUb8tg/T_dAIu1m6cI/AAAAAAAAPPU/v4x9q4WqWl8/s640/cute-squirrel-hey-watcha-thinkin-about.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Squirrel_posing.jpg/287px-Squirrel_posing.jpg https://i.pinimg.com/736x/51/db/9b/51db9bad4a87d445d321923c7d56b501--red-squirrel-animal-kingdom.jpg -https://metrouk2.files.wordpress.com/2016/10/ad_223291521.jpg?w=620&h=949&crop=1 -http://www.redsquirrelsunited.org.uk/wp-content/uploads/2016/07/layer-slider.jpg -http://images.mentalfloss.com/sites/default/files/squirrel-hero.jpg?resize=1100x740 https://i.pinimg.com/736x/ce/9c/59/ce9c5990b193046400d98724595cdaf3--red-squirrel-chipmunks.jpg https://www.brooklynpaper.com/assets/photos/40/30/dtg-squirrel-attacks-prospect-park-patrons-2017-07-28-bk01_z.jpg -http://www.freakingnews.com/pictures/16000/Squirrel-Shark-16467.jpg -http://img09.deviantart.net/5c1c/i/2013/138/0/6/barbarian_squirel_by_coucoucmoa-d64r9m4.jpg https://i.pinimg.com/736x/b4/5c/0d/b45c0d00b1a57e9f84f27f13cb019001--baby-squirrel-red-squirrel.jpg https://i.pinimg.com/736x/0f/75/87/0f7587bb613ab524763afe8c9a532e5c--cute-squirrel-squirrels.jpg http://cdn.images.express.co.uk/img/dynamic/128/590x/Grey-squirrel-828838.jpg http://www.lovethispic.com/uploaded_images/79964-Squirrel-Smelling-A-Flower.jpg https://i.pinimg.com/736x/23/d5/f9/23d5f9868f7d76c79c49bef53ae08f7f--squirrel-funny-red-squirrel.jpg -http://stories.barkpost.com/wp-content/uploads/2016/01/squirrel-3-copy.jpg https://i.ytimg.com/vi/pzUs0DdzK3Y/hqdefault.jpg -https://www.askideas.com/media/41/I-Swear-It-Wasnt-Me-Funny-Squirrel-Meme-Picture-For-Facebook.jpg -https://i.pinimg.com/736x/2d/54/d8/2d54d8d2a9b3ab9d3e78544b75afd88e--funny-animal-pictures-humorous-pictures.jpg -http://www.funny-animalpictures.com/media/content/items/images/funnysquirrels0012_O.jpg -http://funny-pics.co/wp-content/uploads/funny-squirrel-and-coffee-picture.jpg -https://pbs.twimg.com/media/Bi4Ij6CIgAAgEdZ.jpg -http://www.funnyjunksite.com/pictures/wp-content/uploads/2015/06/Funny-Superman-Squirrels.jpg -https://i.pinimg.com/736x/bf/35/00/bf3500104f8394909d116259d1f0575e--funny-squirrel-squirrel-girl.jpg -http://quotespill.com/wp-content/uploads/2017/07/Squirrel-Meme-Draw-me-like-one-of-your-french-squirrrels-min.jpg https://i.pinimg.com/736x/e2/16/bb/e216bba53f80fc8e0111d371e9850159--funny-squirrels-cute-squirrel.jpg https://i.pinimg.com/736x/52/43/c9/5243c93377245be1f686218c266d775c--funny-squirrel-baby-squirrel.jpg https://i.pinimg.com/736x/0c/be/1d/0cbe1da8ad2c0cf3882a806b6fd88965--cute-pictures-funny-animal-pictures.jpg -https://i.pinimg.com/736x/e5/08/67/e508670aa00ca3c896eccb81c4f6e2a8--funny-squirrel-baby-squirrel.jpg https://i.pinimg.com/736x/1c/7d/4f/1c7d4f067a10066aad802ce5ac468d71--group-boards-a-squirrel.jpg -http://funny-pics.co/wp-content/uploads/funny-squirrel-on-a-branch.jpg -http://loldamn.com/wp-content/uploads/2016/06/funny-squirrel-playing-water-bending.jpg -https://cdn.trendhunterstatic.com/thumbs/squirrel-photography.jpeg https://i.pinimg.com/736x/d6/42/12/d64212cc6221916db4173962bf6c131a--cute-squirrel-baby-squirrel.jpg -https://i.pinimg.com/236x/10/13/58/101358f2afc2c7d6b6a668046e7b8382--funny-animal-pictures-funny-animals.jpg https://i.pinimg.com/736x/da/0d/fe/da0dfe93bb26887795f906e8fa97d68e--secret-squirrel-cute-squirrel.jpg http://2.bp.blogspot.com/-HLieBqEuQoM/UDkRmeyzB5I/AAAAAAAABHs/RtsEynn5t6Y/s1600/hd-squirrel-wallpaper-with-a-brown-squirrel-eating-watermelon-wallpapers-backgrounds-pictures-photos.jpg -http://www.city-data.com/forum/members/brenda-starz-328928-albums-brenda-s-funny-squirrel-comment-pic-s-pic5075-punk-squirrels.jpg http://img15.deviantart.net/9c50/i/2011/213/c/9/just_taking_it_easy_by_lou_in_canada-d42do3d.jpg -http://3.bp.blogspot.com/-AwsSk76R2Is/USQa3-dszKI/AAAAAAAABUQ/KF_F8HbtP1U/w1200-h630-p-k-no-nu/crazySquirrel.jpg +https://insider.si.edu/wp-content/uploads/2018/01/Chipmunk-Photo-Mark-Rounds.jpg +https://media.mnn.com/assets/images/2014/12/gray-squirrel-uc-berkeley.jpg.1080x0_q100_crop-scale.jpg +https://citywildlife.org/wp-content/uploads/Juvenile-squirrel.jpg \ No newline at end of file diff --git a/src/Bot/Storage/turtles b/src/Bot/Storage/turtles index 9dbbf72..aa0fbcf 100644 --- a/src/Bot/Storage/turtles +++ b/src/Bot/Storage/turtles @@ -1,21 +1,20 @@ https://i.guim.co.uk/img/media/6b9be13031738e642f93f9271f3592044726a9b1/0_0_2863_1610/2863.jpg?w=640&h=360&q=55&auto=format&usm=12&fit=max&s=85f3b33cc158b5aa120c143dae1916ed http://cf.ltkcdn.net/small-pets/images/std/212089-676x450-Turtle-feeding-on-leaf.jpg -https://static1.squarespace.com/static/5369465be4b0507a1fd05af0/53767a6be4b0ad0822345e52/57e40ba4893fc031e05a018f/1498243318058/solvin.jpg?format=1500w https://c402277.ssl.cf1.rackcdn.com/photos/419/images/story_full_width/HI_287338Hero.jpg?1433950119 https://www.cdc.gov/salmonella/agbeni-08-17/images/turtle.jpg https://cdn.arstechnica.net/wp-content/uploads/2017/08/GettyImages-524757168.jpg http://pmdvod.nationalgeographic.com/NG_Video/595/319/4504517_098_05_TOS_thumbnail_640x360_636296259676.jpg -http://cdn1.arkive.org/media/7D/7D46329A-6ED2-4F08-909E-7B596417994A/Presentation.Large/Big-headed-turtle-close-up.jpg http://s7d2.scene7.com/is/image/PetSmart/ARTHMB-CleaningYourTortoiseOrTurtlesHabitat-20160818?$AR1104$ https://fthmb.tqn.com/9VGWzK_GWlvrjxtdFPX6EJxOq24=/960x0/filters:no_upscale()/133605352-56a2bce53df78cf7727960db.jpg -https://i.imgur.com/46QmzgF.jpg https://www.wildgratitude.com/wp-content/uploads/2015/07/turtle-spirit-animal1.jpg http://www.backwaterreptiles.com/images/turtles/red-eared-slider-turtle-for-sale.jpg -https://i.pinimg.com/736x/f1/f4/13/f1f413d6d07912be6080c08b186630ac--happy-turtle-funny-stuff.jpg -http://www.dupageforest.org/uploadedImages/Content/District_News/Nature_Stories/2016/Snapping%20Turtle%20Scott%20Plantier%20STP4793.jpg http://turtlebackzoo.com/wp-content/uploads/2016/07/exhibit-headers_0008_SOUTH-AMERICA-600x400.jpg -https://i.ytimg.com/vi/_YfYHFM3Das/maxresdefault.jpg https://i.pinimg.com/736x/dd/4e/7f/dd4e7f2f921ac28b1d5a59174d477131--cute-baby-sea-turtles-adorable-turtles.jpg http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Reptiles/A-G/green-sea-turtle-closeup-underwater.adapt.945.1.jpg -https://i.ytimg.com/vi/p4Jj9QZFJvw/hqdefault.jpg https://fthmb.tqn.com/nirxHkH3jBAe74ife6fJJu6k6q8=/2121x1414/filters:fill(auto,1)/Red-eared-sliders-GettyImages-617946009-58fae8835f9b581d59a5bab6.jpg +http://assets.worldwildlife.org/photos/167/images/original/MID_225023-circle-hawksbill-turtle.jpg?1345565600 +https://seaturtles.org/wp-content/uploads/2013/11/GRN-honuAnitaWintner2.jpg +https://images2.minutemediacdn.com/image/upload/c_crop,h_2549,w_4536,x_0,y_237/v1560186367/shape/mentalfloss/istock-687398754.jpg?itok=QsiF5yHP +https://c402277.ssl.cf1.rackcdn.com/photos/13028/images/story_full_width/seaturtle_spring2017.jpg?1485359391 +https://i2.wp.com/rangerrick.org/wp-content/uploads/2018/03/Turtle-Tale-RR-Jr-June-July-2017.jpg?fit=1156%2C650&ssl=1 +https://boyslifeorg.files.wordpress.com/2019/07/greenseaturtle.jpg \ No newline at end of file From 90af781c7ba5f484ba34ef714c84aab1d455f9d2 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 14 Aug 2020 03:30:54 +0200 Subject: [PATCH 091/264] Start Using resource files (.resx) for translations. Create GeekbotCommandBase to reduce command boilerplate. Convert admin, choose, cookies, karma, quote, rank, roll and ship to the new localization method. --- src/Bot/Bot.csproj | 88 ++++++++++ src/Bot/Commands/Admin/Admin.cs | 71 +++++--- src/Bot/Commands/Games/Roll/Roll.cs | 23 ++- src/Bot/Commands/Randomness/Ship.cs | 29 ++-- src/Bot/Commands/Rpg/Cookies.cs | 38 ++--- src/Bot/Commands/User/Karma.cs | 47 +++--- src/Bot/Commands/User/Ranking/Rank.cs | 40 ++--- src/Bot/Commands/Utils/Choose.cs | 15 +- src/Bot/Commands/Utils/Quote/Quote.cs | 61 +++---- src/Bot/Localization/Admin.Designer.cs | 81 ++++++++++ src/Bot/Localization/Admin.de-ch.resx | 20 +++ src/Bot/Localization/Admin.resx | 27 ++++ src/Bot/Localization/Choose.Designer.cs | 72 +++++++++ src/Bot/Localization/Choose.de-ch.resx | 17 ++ src/Bot/Localization/Choose.resx | 24 +++ src/Bot/Localization/Cookies.Designer.cs | 126 +++++++++++++++ src/Bot/Localization/Cookies.de-ch.resx | 35 ++++ src/Bot/Localization/Cookies.resx | 42 +++++ src/Bot/Localization/Internal.Designer.cs | 126 +++++++++++++++ src/Bot/Localization/Internal.de-ch.resx | 35 ++++ src/Bot/Localization/Internal.resx | 42 +++++ src/Bot/Localization/Karma.Designer.cs | 135 ++++++++++++++++ src/Bot/Localization/Karma.de-ch.resx | 38 +++++ src/Bot/Localization/Karma.resx | 45 ++++++ src/Bot/Localization/Quote.Designer.cs | 162 +++++++++++++++++++ src/Bot/Localization/Quote.de-ch.resx | 47 ++++++ src/Bot/Localization/Quote.resx | 54 +++++++ src/Bot/Localization/Rank.Designer.cs | 108 +++++++++++++ src/Bot/Localization/Rank.de-ch.resx | 29 ++++ src/Bot/Localization/Rank.resx | 36 +++++ src/Bot/Localization/Roll.Designer.cs | 99 ++++++++++++ src/Bot/Localization/Roll.de-ch.resx | 26 +++ src/Bot/Localization/Roll.resx | 33 ++++ src/Bot/Localization/Ship.Designer.cs | 117 ++++++++++++++ src/Bot/Localization/Ship.de-ch.resx | 32 ++++ src/Bot/Localization/Ship.resx | 39 +++++ src/Core/GeekbotCommandBase.cs | 27 ++++ src/Core/Localization/ITranslationHandler.cs | 1 + src/Core/Localization/TranslationHandler.cs | 16 +- src/Core/Localization/Translations.yml | 159 +----------------- 40 files changed, 1935 insertions(+), 327 deletions(-) create mode 100644 src/Bot/Localization/Admin.Designer.cs create mode 100644 src/Bot/Localization/Admin.de-ch.resx create mode 100644 src/Bot/Localization/Admin.resx create mode 100644 src/Bot/Localization/Choose.Designer.cs create mode 100644 src/Bot/Localization/Choose.de-ch.resx create mode 100644 src/Bot/Localization/Choose.resx create mode 100644 src/Bot/Localization/Cookies.Designer.cs create mode 100644 src/Bot/Localization/Cookies.de-ch.resx create mode 100644 src/Bot/Localization/Cookies.resx create mode 100644 src/Bot/Localization/Internal.Designer.cs create mode 100644 src/Bot/Localization/Internal.de-ch.resx create mode 100644 src/Bot/Localization/Internal.resx create mode 100644 src/Bot/Localization/Karma.Designer.cs create mode 100644 src/Bot/Localization/Karma.de-ch.resx create mode 100644 src/Bot/Localization/Karma.resx create mode 100644 src/Bot/Localization/Quote.Designer.cs create mode 100644 src/Bot/Localization/Quote.de-ch.resx create mode 100644 src/Bot/Localization/Quote.resx create mode 100644 src/Bot/Localization/Rank.Designer.cs create mode 100644 src/Bot/Localization/Rank.de-ch.resx create mode 100644 src/Bot/Localization/Rank.resx create mode 100644 src/Bot/Localization/Roll.Designer.cs create mode 100644 src/Bot/Localization/Roll.de-ch.resx create mode 100644 src/Bot/Localization/Roll.resx create mode 100644 src/Bot/Localization/Ship.Designer.cs create mode 100644 src/Bot/Localization/Ship.de-ch.resx create mode 100644 src/Bot/Localization/Ship.resx create mode 100644 src/Core/GeekbotCommandBase.cs diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index c7889ae..601766a 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -40,4 +40,92 @@ + + + ResXFileCodeGenerator + Ship.Designer.cs + + + ResXFileCodeGenerator + Rank.Designer.cs + + + ResXFileCodeGenerator + Karma.Designer.cs + + + ResXFileCodeGenerator + Internal.Designer.cs + + + ResXFileCodeGenerator + Cookies.Designer.cs + + + ResXFileCodeGenerator + Roll.Designer.cs + + + ResXFileCodeGenerator + Choose.Designer.cs + + + ResXFileCodeGenerator + Admin.Designer.cs + + + ResXFileCodeGenerator + Quote.Designer.cs + + + + + True + True + ship.resx + + + True + True + Rank.resx + + + Ship.resx + + + True + True + Karma.resx + + + True + True + Internal.resx + + + True + True + Cookies.resx + + + True + True + Roll.resx + + + True + True + Choose.resx + + + True + True + Admin.resx + + + True + True + Quote.resx + + diff --git a/src/Bot/Commands/Admin/Admin.cs b/src/Bot/Commands/Admin/Admin.cs index f6c4210..2627f86 100644 --- a/src/Bot/Commands/Admin/Admin.cs +++ b/src/Bot/Commands/Admin/Admin.cs @@ -1,9 +1,15 @@ using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Resources; using System.Text; +using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; @@ -15,19 +21,15 @@ namespace Geekbot.Bot.Commands.Admin [Group("admin")] [RequireUserPermission(GuildPermission.Administrator)] [DisableInDirectMessage] - public class Admin : ModuleBase + public class Admin : GeekbotCommandBase { private readonly DiscordSocketClient _client; - private readonly IErrorHandler _errorHandler; private readonly IGuildSettingsManager _guildSettingsManager; - private readonly ITranslationHandler _translation; - public Admin(DiscordSocketClient client, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager, ITranslationHandler translationHandler) + public Admin(DiscordSocketClient client, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager, ITranslationHandler translationHandler) : base(errorHandler, translationHandler) { _client = client; - _errorHandler = errorHandler; _guildSettingsManager = guildSettingsManager; - _translation = translationHandler; } [Command("welcome", RunMode = RunMode.Async)] @@ -60,7 +62,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, "That channel doesn't seem to exist or i don't have write permissions"); + await ErrorHandler.HandleCommandException(e, Context, "That channel doesn't seem to exist or i don't have write permissions"); } } @@ -84,7 +86,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, "That channel doesn't seem to exist or i don't have write permissions"); + await ErrorHandler.HandleCommandException(e, Context, "That channel doesn't seem to exist or i don't have write permissions"); } } @@ -107,7 +109,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -130,7 +132,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -141,24 +143,30 @@ namespace Geekbot.Bot.Commands.Admin try { var language = languageRaw.ToUpper(); - var success = await _translation.SetLanguage(Context.Guild.Id, language); + var success = await Translations.SetLanguage(Context.Guild.Id, language); if (success) { var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); guild.Language = language; await _guildSettingsManager.UpdateSettings(guild); - var transContext = await _translation.GetGuildContext(Context); - await ReplyAsync(transContext.GetString("NewLanguageSet")); + if (language.ToLower() == "chde") + { + Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-ch"); + } + + await ReplyAsync(Localization.Admin.NewLanguageSet); return; } - await ReplyAsync( - $"That doesn't seem to be a supported language\r\nSupported Languages are {string.Join(", ", _translation.SupportedLanguages)}"); + var available = new List(); + available.Add("en-GB"); // default + available.AddRange(GetAvailableCultures().Select(culture => culture.Name)); + await ReplyAsync($"That doesn't seem to be a supported language\nSupported Languages are {string.Join(", ", available)}"); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -177,7 +185,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -194,7 +202,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -211,7 +219,7 @@ namespace Geekbot.Bot.Commands.Admin } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -230,5 +238,30 @@ namespace Geekbot.Bot.Commands.Admin return null; } } + + private IEnumerable GetAvailableCultures() + { + var result = new List(); + var rm = new ResourceManager(typeof(Localization.Admin)); + var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); + foreach (var culture in cultures) + { + try + { + if (culture.Equals(CultureInfo.InvariantCulture)) continue; //do not use "==", won't work + + var rs = rm.GetResourceSet(culture, true, false); + if (rs != null) + { + result.Add(culture); + } + } + catch (CultureNotFoundException) + { + //NOP + } + } + return result; + } } } \ No newline at end of file diff --git a/src/Bot/Commands/Games/Roll/Roll.cs b/src/Bot/Commands/Games/Roll/Roll.cs index 6241ba1..244edbe 100644 --- a/src/Bot/Commands/Games/Roll/Roll.cs +++ b/src/Bot/Commands/Games/Roll/Roll.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; @@ -12,21 +13,17 @@ using Geekbot.Core.RandomNumberGenerator; namespace Geekbot.Bot.Commands.Games.Roll { - public class Roll : ModuleBase + public class Roll : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly IKvInMemoryStore _kvInMemoryStore; - private readonly ITranslationHandler _translation; private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Roll(IKvInMemoryStore kvInMemoryStore,IErrorHandler errorHandler, ITranslationHandler translation, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) + public Roll(IKvInMemoryStore kvInMemoryStore,IErrorHandler errorHandler, ITranslationHandler translation, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) : base(errorHandler, translation) { _kvInMemoryStore = kvInMemoryStore; - _translation = translation; _database = database; _randomNumberGenerator = randomNumberGenerator; - _errorHandler = errorHandler; } [Command("roll", RunMode = RunMode.Async)] @@ -37,7 +34,7 @@ namespace Geekbot.Bot.Commands.Games.Roll { var number = _randomNumberGenerator.Next(1, 100); int.TryParse(stuff, out var guess); - var transContext = await _translation.GetGuildContext(Context); + var transContext = await Translations.GetGuildContext(Context); if (guess <= 100 && guess > 0) { var kvKey = $"{Context.Guild.Id}:{Context.User.Id}:RollsPrevious"; @@ -46,8 +43,8 @@ namespace Geekbot.Bot.Commands.Games.Roll if (prevRoll?.LastGuess == guess && prevRoll?.GuessedOn.AddDays(1) > DateTime.Now) { - await ReplyAsync(transContext.GetString( - "NoPrevGuess", + await ReplyAsync(string.Format( + Localization.Roll.NoPrevGuess, Context.Message.Author.Mention, transContext.FormatDateTimeAsRemaining(prevRoll.GuessedOn.AddDays(1)))); return; @@ -55,10 +52,10 @@ namespace Geekbot.Bot.Commands.Games.Roll _kvInMemoryStore.Set(kvKey, new RollTimeout { LastGuess = guess, GuessedOn = DateTime.Now }); - await ReplyAsync(transContext.GetString("Rolled", Context.Message.Author.Mention, number, guess)); + await ReplyAsync(string.Format(Localization.Roll.Rolled, Context.Message.Author.Mention, number, guess)); if (guess == number) { - await ReplyAsync(transContext.GetString("Gratz", Context.Message.Author)); + await ReplyAsync(string.Format(Localization.Roll.Gratz, Context.Message.Author)); var user = await GetUser(Context.User.Id); user.Rolls += 1; _database.Rolls.Update(user); @@ -67,12 +64,12 @@ namespace Geekbot.Bot.Commands.Games.Roll } else { - await ReplyAsync(transContext.GetString("RolledNoGuess", Context.Message.Author.Mention, number)); + await ReplyAsync(string.Format(Localization.Roll.RolledNoGuess, Context.Message.Author.Mention, number)); } } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } diff --git a/src/Bot/Commands/Randomness/Ship.cs b/src/Bot/Commands/Randomness/Ship.cs index d5d9eea..78f3c99 100644 --- a/src/Bot/Commands/Randomness/Ship.cs +++ b/src/Bot/Commands/Randomness/Ship.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; @@ -12,19 +13,15 @@ using Geekbot.Core.RandomNumberGenerator; namespace Geekbot.Bot.Commands.Randomness { - public class Ship : ModuleBase + public class Ship : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly IRandomNumberGenerator _randomNumberGenerator; - private readonly ITranslationHandler _translation; private readonly DatabaseContext _database; - public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translation) + public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translations) : base(errorHandler, translations) { _database = database; - _errorHandler = errorHandler; _randomNumberGenerator = randomNumberGenerator; - _translation = translation; } [Command("Ship", RunMode = RunMode.Async)] @@ -58,28 +55,26 @@ namespace Geekbot.Bot.Commands.Randomness shippingRate = dbval.Strength; } - var transContext = await _translation.GetGuildContext(Context); - - var reply = $":heartpulse: **{transContext.GetString("Matchmaking")}** :heartpulse:\r\n"; + var reply = $":heartpulse: **{Localization.Ship.Matchmaking}** :heartpulse:\r\n"; reply += $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n"; - reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate, transContext)}"; + reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}"; await ReplyAsync(reply); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } - private string DeterminateSuccess(int rate, TranslationGuildContext transContext) + private string DeterminateSuccess(int rate) { return (rate / 20) switch { - 0 => transContext.GetString("NotGonnaToHappen"), - 1 => transContext.GetString("NotSuchAGoodIdea"), - 2 => transContext.GetString("ThereMightBeAChance"), - 3 => transContext.GetString("CouldWork"), - 4 => transContext.GetString("ItsAMatch"), + 0 => Localization.Ship.NotGoingToHappen, + 1 => Localization.Ship.NotSuchAGoodIdea, + 2 => Localization.Ship.ThereMightBeAChance, + 3 => Localization.Ship.CouldWork, + 4 => Localization.Ship.ItsAMatch, _ => "nope" }; } diff --git a/src/Bot/Commands/Rpg/Cookies.cs b/src/Bot/Commands/Rpg/Cookies.cs index f581105..570f08a 100644 --- a/src/Bot/Commands/Rpg/Cookies.cs +++ b/src/Bot/Commands/Rpg/Cookies.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; @@ -16,18 +17,14 @@ namespace Geekbot.Bot.Commands.Rpg [DisableInDirectMessage] [Group("cookies")] [Alias("cookie")] - public class Cookies : ModuleBase + public class Cookies : GeekbotCommandBase { private readonly DatabaseContext _database; - private readonly IErrorHandler _errorHandler; - private readonly ITranslationHandler _translation; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Cookies(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translation , IRandomNumberGenerator randomNumberGenerator) + public Cookies(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translations , IRandomNumberGenerator randomNumberGenerator) : base(errorHandler, translations) { _database = database; - _errorHandler = errorHandler; - _translation = translation; _randomNumberGenerator = randomNumberGenerator; } @@ -37,23 +34,23 @@ namespace Geekbot.Bot.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); + var transContext = await Translations.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (actor.LastPayout.Value.AddDays(1).Date > DateTime.Now.Date) { var formatedWaitTime = transContext.FormatDateTimeAsRemaining(DateTimeOffset.Now.AddDays(1).Date); - await ReplyAsync(transContext.GetString("WaitForMoreCookies", formatedWaitTime)); + await ReplyAsync(string.Format(Localization.Cookies.WaitForMoreCookies, formatedWaitTime)); return; } actor.Cookies += 10; actor.LastPayout = DateTimeOffset.Now; await SetUser(actor); - await ReplyAsync(transContext.GetString("GetCookies", 10, actor.Cookies)); + await ReplyAsync(string.Format(Localization.Cookies.GetCookies, 10, actor.Cookies)); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -63,13 +60,12 @@ namespace Geekbot.Bot.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); - await ReplyAsync(transContext.GetString("InYourJar", actor.Cookies)); + await ReplyAsync(string.Format(Localization.Cookies.InYourJar, actor.Cookies)); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -79,12 +75,11 @@ namespace Geekbot.Bot.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var giver = await GetUser(Context.User.Id); if (giver.Cookies < amount) { - await ReplyAsync(transContext.GetString("NotEnoughToGive")); + await ReplyAsync(Localization.Cookies.NotEnoughToGive); return; } @@ -96,11 +91,11 @@ namespace Geekbot.Bot.Commands.Rpg await SetUser(giver); await SetUser(taker); - await ReplyAsync(transContext.GetString("Given", amount, user.Username)); + await ReplyAsync(string.Format(Localization.Cookies.Given, amount, user.Username)); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -110,12 +105,11 @@ namespace Geekbot.Bot.Commands.Rpg { try { - var transContext = await _translation.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (actor.Cookies < 5) { - await ReplyAsync(transContext.GetString("NotEnoughCookiesToEat")); + await ReplyAsync(Localization.Cookies.NotEnoughCookiesToEat); return; } @@ -124,14 +118,14 @@ namespace Geekbot.Bot.Commands.Rpg await SetUser(actor); - await ReplyAsync(transContext.GetString("AteCookies", amount, actor.Cookies)); + await ReplyAsync(string.Format(Localization.Cookies.AteCookies, amount, actor.Cookies)); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } - + private async Task GetUser(ulong userId) { var user = _database.Cookies.FirstOrDefault(u =>u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId); diff --git a/src/Bot/Commands/User/Karma.cs b/src/Bot/Commands/User/Karma.cs index 3efc381..41a401c 100644 --- a/src/Bot/Commands/User/Karma.cs +++ b/src/Bot/Commands/User/Karma.cs @@ -1,8 +1,11 @@ using System; +using System.Globalization; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; @@ -13,17 +16,15 @@ using Geekbot.Core.Localization; namespace Geekbot.Bot.Commands.User { [DisableInDirectMessage] - public class Karma : ModuleBase + public class Karma : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; - private readonly ITranslationHandler _translation; + private readonly ITranslationHandler _translations; - public Karma(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translation) + public Karma(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translations) : base(errorHandler, translations) { _database = database; - _errorHandler = errorHandler; - _translation = translation; + _translations = translations; } [Command("good", RunMode = RunMode.Async)] @@ -32,16 +33,17 @@ namespace Geekbot.Bot.Commands.User { try { - var transContext = await _translation.GetGuildContext(Context); + var transContext = await _translations.GetGuildContext(Context); + var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { - await ReplyAsync(transContext.GetString("CannotChangeOwn", Context.User.Username)); + await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnUp, Context.User.Username)); } else if (TimeoutFinished(actor.TimeOut)) { var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(transContext.GetString("WaitUntill", Context.User.Username, formatedWaitTime)); + await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); } else { @@ -60,16 +62,16 @@ namespace Geekbot.Bot.Commands.User .WithName(user.Username)); eb.WithColor(new Color(138, 219, 146)); - eb.Title = transContext.GetString("Increased"); - eb.AddInlineField(transContext.GetString("By"), Context.User.Username); - eb.AddInlineField(transContext.GetString("Amount"), "+1"); - eb.AddInlineField(transContext.GetString("Current"), target.Karma); + eb.Title = Localization.Karma.Increased; + eb.AddInlineField(Localization.Karma.By, Context.User.Username); + eb.AddInlineField(Localization.Karma.Amount, "+1"); + eb.AddInlineField(Localization.Karma.Current, target.Karma); await ReplyAsync("", false, eb.Build()); } } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -79,16 +81,17 @@ namespace Geekbot.Bot.Commands.User { try { - var transContext = await _translation.GetGuildContext(Context); + var transContext = await _translations.GetGuildContext(Context); + var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { - await ReplyAsync(transContext.GetString("CannotChangeOwn", Context.User.Username)); + await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnDown, Context.User.Username)); } else if (TimeoutFinished(actor.TimeOut)) { var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(transContext.GetString("WaitUntill", Context.User.Username, formatedWaitTime)); + await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); } else { @@ -107,16 +110,16 @@ namespace Geekbot.Bot.Commands.User .WithName(user.Username)); eb.WithColor(new Color(138, 219, 146)); - eb.Title = transContext.GetString("Decreased"); - eb.AddInlineField(transContext.GetString("By"), Context.User.Username); - eb.AddInlineField(transContext.GetString("Amount"), "-1"); - eb.AddInlineField(transContext.GetString("Current"), target.Karma); + eb.Title = Localization.Karma.Decreased; + eb.AddInlineField(Localization.Karma.By, Context.User.Username); + eb.AddInlineField(Localization.Karma.Amount, "-1"); + eb.AddInlineField(Localization.Karma.Current, target.Karma); await ReplyAsync("", false, eb.Build()); } } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } diff --git a/src/Bot/Commands/User/Ranking/Rank.cs b/src/Bot/Commands/User/Ranking/Rank.cs index ae1bec9..d73aacc 100644 --- a/src/Bot/Commands/User/Ranking/Rank.cs +++ b/src/Bot/Commands/User/Ranking/Rank.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Converters; using Geekbot.Core.Database; @@ -11,28 +12,20 @@ using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; using Geekbot.Core.Highscores; using Geekbot.Core.Localization; -using Geekbot.Core.UserRepository; namespace Geekbot.Bot.Commands.User.Ranking { - public class Rank : ModuleBase + public class Rank : GeekbotCommandBase { private readonly IEmojiConverter _emojiConverter; private readonly IHighscoreManager _highscoreManager; - private readonly ITranslationHandler _translationHandler; - private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; - private readonly IUserRepository _userRepository; - public Rank(DatabaseContext database, IErrorHandler errorHandler, IUserRepository userRepository, - IEmojiConverter emojiConverter, IHighscoreManager highscoreManager, ITranslationHandler translationHandler) + public Rank(DatabaseContext database, IErrorHandler errorHandler, IEmojiConverter emojiConverter, IHighscoreManager highscoreManager, ITranslationHandler translations): base(errorHandler, translations) { _database = database; - _errorHandler = errorHandler; - _userRepository = userRepository; _emojiConverter = emojiConverter; _highscoreManager = highscoreManager; - _translationHandler = translationHandler; } [Command("rank", RunMode = RunMode.Async)] @@ -42,7 +35,6 @@ namespace Geekbot.Bot.Commands.User.Ranking { try { - var transContext = await _translationHandler.GetGuildContext(Context); HighscoreTypes type; try { @@ -51,14 +43,14 @@ namespace Geekbot.Bot.Commands.User.Ranking } catch { - await ReplyAsync(transContext.GetString("InvalidType")); + await ReplyAsync(Localization.Rank.InvalidType); return; } var replyBuilder = new StringBuilder(); if (amount > 20) { - await ReplyAsync(transContext.GetString("LimitingTo20Warning")); + await ReplyAsync(Localization.Rank.LimitingTo20Warning); amount = 20; } @@ -70,7 +62,7 @@ namespace Geekbot.Bot.Commands.User.Ranking } catch (HighscoreListEmptyException) { - await ReplyAsync(transContext.GetString("NoTypeFoundForServer", type)); + await ReplyAsync(string.Format(Localization.Rank.NoTypeFoundForServer, type)); return; } @@ -85,22 +77,24 @@ namespace Geekbot.Bot.Commands.User.Ranking var failedToRetrieveUser = highscoreUsers.Any(e => string.IsNullOrEmpty(e.Key.Username)); - if (failedToRetrieveUser) replyBuilder.AppendLine(transContext.GetString("FailedToResolveAllUsernames")); - replyBuilder.AppendLine(transContext.GetString("HighscoresFor", type.ToString().CapitalizeFirst(), Context.Guild.Name)); + if (failedToRetrieveUser) replyBuilder.AppendLine(Localization.Rank.FailedToResolveAllUsernames).AppendLine(); + + replyBuilder.AppendLine(string.Format(Localization.Rank.HighscoresFor, type.ToString().CapitalizeFirst(), Context.Guild.Name)); + var highscorePlace = 1; - foreach (var user in highscoreUsers) + foreach (var (user, value) in highscoreUsers) { replyBuilder.Append(highscorePlace < 11 ? $"{_emojiConverter.NumberToEmoji(highscorePlace)} " : $"`{highscorePlace}.` "); - replyBuilder.Append(user.Key.Username != null - ? $"**{user.Key.Username}#{user.Key.Discriminator}**" - : $"**{user.Key.Id}**"); + replyBuilder.Append(user.Username != null + ? $"**{user.Username}#{user.Discriminator}**" + : $"**{user.Id}**"); replyBuilder.Append(type == HighscoreTypes.messages - ? $" - {user.Value} {type} - {Math.Round((double) (100 * user.Value) / guildMessages, 2)}%\n" - : $" - {user.Value} {type}\n"); + ? $" - {value} {type} - {Math.Round((double) (100 * value) / guildMessages, 2)}%\n" + : $" - {value} {type}\n"); highscorePlace++; } @@ -109,7 +103,7 @@ namespace Geekbot.Bot.Commands.User.Ranking } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } } diff --git a/src/Bot/Commands/Utils/Choose.cs b/src/Bot/Commands/Utils/Choose.cs index d245bd2..ea239d7 100644 --- a/src/Bot/Commands/Utils/Choose.cs +++ b/src/Bot/Commands/Utils/Choose.cs @@ -1,20 +1,16 @@ using System; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Localization; namespace Geekbot.Bot.Commands.Utils { - public class Choose : ModuleBase + public class Choose : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; - private readonly ITranslationHandler _translation; - - public Choose(IErrorHandler errorHandler, ITranslationHandler translation) + public Choose(IErrorHandler errorHandler, ITranslationHandler translation) : base(errorHandler, translation) { - _errorHandler = errorHandler; - _translation = translation; } [Command("choose", RunMode = RunMode.Async)] @@ -24,14 +20,13 @@ namespace Geekbot.Bot.Commands.Utils { try { - var transContext = await _translation.GetGuildContext(Context); var choicesArray = choices.Split(';'); var choice = new Random().Next(choicesArray.Length); - await ReplyAsync(transContext.GetString("Choice", choicesArray[choice].Trim())); + await ReplyAsync(string.Format(Localization.Choose.Choice, choicesArray[choice].Trim())); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } } diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index a731273..5bb23a9 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -17,20 +17,16 @@ namespace Geekbot.Bot.Commands.Utils.Quote { [Group("quote")] [DisableInDirectMessage] - public class Quote : ModuleBase + public class Quote : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - private readonly ITranslationHandler _translationHandler; private readonly bool _isDev; - public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translationHandler) + public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translationHandler) : base(errorHandler, translationHandler) { - _errorHandler = errorHandler; _database = database; _randomNumberGenerator = randomNumberGenerator; - _translationHandler = translationHandler; // to remove restrictions when developing _isDev = Constants.BotVersion() == "0.0.0-DEV"; } @@ -45,8 +41,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote if (!s.Any()) { - var transContext = await _translationHandler.GetGuildContext(Context); - await ReplyAsync(transContext.GetString("NoQuotesFound")); + await ReplyAsync(Localization.Quote.NoQuotesFound); return; } @@ -58,7 +53,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, "Whoops, seems like the quote was to edgy to return"); + await ErrorHandler.HandleCommandException(e, Context, "Whoops, seems like the quote was to edgy to return"); } } @@ -117,23 +112,22 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); var quote = _database.Quotes.Where(e => e.GuildId == Context.Guild.Id.AsLong() && e.InternalId == id)?.FirstOrDefault(); if (quote != null) { _database.Quotes.Remove(quote); await _database.SaveChangesAsync(); var embed = QuoteBuilder(quote); - await ReplyAsync(transContext.GetString("Removed", id), false, embed.Build()); + await ReplyAsync(string.Format(Localization.Quote.Removed, id), false, embed.Build()); } else { - await ReplyAsync(transContext.GetString("NotFoundWithId")); + await ReplyAsync(Localization.Quote.NotFoundWithId); } } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, "I couldn't find a quote with that id :disappointed:"); + await ErrorHandler.HandleCommandException(e, Context, "I couldn't find a quote with that id :disappointed:"); } } @@ -144,12 +138,11 @@ namespace Geekbot.Bot.Commands.Utils.Quote try { // setup - var transContext = await _translationHandler.GetGuildContext(Context); var eb = new EmbedBuilder(); eb.Author = new EmbedAuthorBuilder() { IconUrl = Context.Guild.IconUrl, - Name = $"{Context.Guild.Name} - {transContext.GetString("QuoteStats")}" + Name = $"{Context.Guild.Name} - {Localization.Quote.QuoteStats}" }; // gather data @@ -157,7 +150,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote if (totalQuotes == 0) { // no quotes, no stats, end of the road - await ReplyAsync(transContext.GetString("NoQuotesFound")); + await ReplyAsync(Localization.Quote.NoQuotesFound); return; } @@ -176,8 +169,8 @@ namespace Geekbot.Bot.Commands.Utils.Quote .OrderBy(row => row.year); // add data to the embed - eb.AddField(transContext.GetString("MostQuotesPerson"), $"{mostQuotedPersonUser.Username} ({mostQuotedPerson.amount})"); - eb.AddInlineField(transContext.GetString("TotalQuotes"), totalQuotes); + eb.AddField(Localization.Quote.MostQuotesPerson, $"{mostQuotedPersonUser.Username} ({mostQuotedPerson.amount})"); + eb.AddInlineField(Localization.Quote.TotalQuotes, totalQuotes); foreach (var year in quotesByYear) { @@ -188,7 +181,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -196,8 +189,6 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); - var list = Context.Channel.GetMessagesAsync().Flatten(); var message = await list.FirstOrDefaultAsync(msg => msg.Author.Id == user.Id && @@ -206,11 +197,11 @@ namespace Geekbot.Bot.Commands.Utils.Quote !msg.Content.ToLower().StartsWith("!")); if (message == null) return; - await ProcessQuote(message, saveToDb, transContext); + await ProcessQuote(message, saveToDb); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, $"No quoteable messages have been sent by {user.Username} in this channel"); + await ErrorHandler.HandleCommandException(e, Context, $"No quoteable messages have been sent by {user.Username} in this channel"); } } @@ -219,14 +210,14 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); + // var transContext = await _translationHandler.GetGuildContext(Context); var message = await Context.Channel.GetMessageAsync(messageId); - await ProcessQuote(message, saveToDb, transContext); + await ProcessQuote(message, saveToDb); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); + await ErrorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); } } @@ -234,18 +225,18 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - var transContext = await _translationHandler.GetGuildContext(Context); + // var transContext = await _translationHandler.GetGuildContext(Context); if (!MessageLink.IsValid(messageLink)) { - await ReplyAsync(transContext.GetString("NotAValidMessageLink")); + await ReplyAsync(Localization.Quote.NotAValidMessageLink); return; } var link = new MessageLink(messageLink); if (link.GuildId != Context.Guild.Id) { - await ReplyAsync(transContext.GetString("OnlyQuoteFromSameServer")); + await ReplyAsync(Localization.Quote.OnlyQuoteFromSameServer); return; } @@ -255,25 +246,25 @@ namespace Geekbot.Bot.Commands.Utils.Quote var message = await channel.GetMessageAsync(link.MessageId); - await ProcessQuote(message, saveToDb, transContext); + await ProcessQuote(message, saveToDb); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, "I couldn't find that message :disappointed:"); + await ErrorHandler.HandleCommandException(e, Context, "I couldn't find that message :disappointed:"); } } - private async Task ProcessQuote(IMessage message, bool saveToDb, TranslationGuildContext transContext) + private async Task ProcessQuote(IMessage message, bool saveToDb) { if (message.Author.Id == Context.Message.Author.Id && saveToDb && !_isDev) { - await ReplyAsync(transContext.GetString("CannotSaveOwnQuotes")); + await ReplyAsync(Localization.Quote.CannotSaveOwnQuotes); return; } if (message.Author.IsBot && saveToDb && !_isDev) { - await ReplyAsync(transContext.GetString("CannotQuoteBots")); + await ReplyAsync(Localization.Quote.CannotQuoteBots); return; } @@ -285,7 +276,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote } var embed = QuoteBuilder(quote); - await ReplyAsync(saveToDb ? transContext.GetString("QuoteAdded") : string.Empty, false, embed.Build()); + await ReplyAsync(saveToDb ? Localization.Quote.QuoteAdded : string.Empty, false, embed.Build()); } private EmbedBuilder QuoteBuilder(QuoteModel quote) diff --git a/src/Bot/Localization/Admin.Designer.cs b/src/Bot/Localization/Admin.Designer.cs new file mode 100644 index 0000000..c55adf1 --- /dev/null +++ b/src/Bot/Localization/Admin.Designer.cs @@ -0,0 +1,81 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Admin { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Admin() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Admin", typeof(Admin).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to I'm talking english. + /// + internal static string GetLanguage { + get { + return ResourceManager.GetString("GetLanguage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to I will reply in english from now on. + /// + internal static string NewLanguageSet { + get { + return ResourceManager.GetString("NewLanguageSet", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Admin.de-ch.resx b/src/Bot/Localization/Admin.de-ch.resx new file mode 100644 index 0000000..b89939b --- /dev/null +++ b/src/Bot/Localization/Admin.de-ch.resx @@ -0,0 +1,20 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + I werd ab jetzt uf schwiizerdüütsch antworte, äuuä + + + I red schwiizerdüütsch + + \ No newline at end of file diff --git a/src/Bot/Localization/Admin.resx b/src/Bot/Localization/Admin.resx new file mode 100644 index 0000000..6fd2c62 --- /dev/null +++ b/src/Bot/Localization/Admin.resx @@ -0,0 +1,27 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + I will reply in english from now on + + + I'm talking english + + \ No newline at end of file diff --git a/src/Bot/Localization/Choose.Designer.cs b/src/Bot/Localization/Choose.Designer.cs new file mode 100644 index 0000000..1319140 --- /dev/null +++ b/src/Bot/Localization/Choose.Designer.cs @@ -0,0 +1,72 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Choose { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Choose() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Choose", typeof(Choose).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to I Choose **{0}**. + /// + internal static string Choice { + get { + return ResourceManager.GetString("Choice", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Choose.de-ch.resx b/src/Bot/Localization/Choose.de-ch.resx new file mode 100644 index 0000000..eedc39b --- /dev/null +++ b/src/Bot/Localization/Choose.de-ch.resx @@ -0,0 +1,17 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + I nimme **{0}** + + \ No newline at end of file diff --git a/src/Bot/Localization/Choose.resx b/src/Bot/Localization/Choose.resx new file mode 100644 index 0000000..052177b --- /dev/null +++ b/src/Bot/Localization/Choose.resx @@ -0,0 +1,24 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + I Choose **{0}** + + \ No newline at end of file diff --git a/src/Bot/Localization/Cookies.Designer.cs b/src/Bot/Localization/Cookies.Designer.cs new file mode 100644 index 0000000..5f2528f --- /dev/null +++ b/src/Bot/Localization/Cookies.Designer.cs @@ -0,0 +1,126 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Cookies { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Cookies() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Cookies", typeof(Cookies).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to You ate {0} cookies, you've only got {1} cookies left. + /// + internal static string AteCookies { + get { + return ResourceManager.GetString("AteCookies", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You got {0} cookies, there are now {1} cookies in you cookie jar. + /// + internal static string GetCookies { + get { + return ResourceManager.GetString("GetCookies", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You gave {0} cookies to {1}. + /// + internal static string Given { + get { + return ResourceManager.GetString("Given", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are {0} cookies in you cookie jar. + /// + internal static string InYourJar { + get { + return ResourceManager.GetString("InYourJar", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your cookie jar looks almost empty, you should probably not eat a cookie. + /// + internal static string NotEnoughCookiesToEat { + get { + return ResourceManager.GetString("NotEnoughCookiesToEat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You don't have enough cookies. + /// + internal static string NotEnoughToGive { + get { + return ResourceManager.GetString("NotEnoughToGive", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You already got cookies today, you can have more cookies in {0}. + /// + internal static string WaitForMoreCookies { + get { + return ResourceManager.GetString("WaitForMoreCookies", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Cookies.de-ch.resx b/src/Bot/Localization/Cookies.de-ch.resx new file mode 100644 index 0000000..b53b588 --- /dev/null +++ b/src/Bot/Localization/Cookies.de-ch.resx @@ -0,0 +1,35 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Du häsch {0} guetzli becho, du häsch jetzt {1} guetzli ih dr büchse + + + Du hesch scho guetzli becho hüt, du chasch meh ha in {0} + + + Es hät {0} guetzli ih dineri büchs + + + Du hesch {1} {0} guetzli geh + + + Du hesch nid gnueg guetzli + + + Du hesch chuum no guetzli ih dineri büchs, du sötsch warschinli keini esse + + + Du hesch {0} guetzli gesse und hesch jezt no {1} übrig + + \ No newline at end of file diff --git a/src/Bot/Localization/Cookies.resx b/src/Bot/Localization/Cookies.resx new file mode 100644 index 0000000..53207fa --- /dev/null +++ b/src/Bot/Localization/Cookies.resx @@ -0,0 +1,42 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + You got {0} cookies, there are now {1} cookies in you cookie jar + + + You already got cookies today, you can have more cookies in {0} + + + There are {0} cookies in you cookie jar + + + You gave {0} cookies to {1} + + + You don't have enough cookies + + + Your cookie jar looks almost empty, you should probably not eat a cookie + + + You ate {0} cookies, you've only got {1} cookies left + + \ No newline at end of file diff --git a/src/Bot/Localization/Internal.Designer.cs b/src/Bot/Localization/Internal.Designer.cs new file mode 100644 index 0000000..e7c18af --- /dev/null +++ b/src/Bot/Localization/Internal.Designer.cs @@ -0,0 +1,126 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Internal { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Internal() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Internal", typeof(Internal).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to and. + /// + internal static string And { + get { + return ResourceManager.GetString("And", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to day|days. + /// + internal static string Days { + get { + return ResourceManager.GetString("Days", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to hour|hours. + /// + internal static string Hours { + get { + return ResourceManager.GetString("Hours", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Seems like i don't have enough permission to that :confused:. + /// + internal static string Http403 { + get { + return ResourceManager.GetString("Http403", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to minute|minutes. + /// + internal static string Minutes { + get { + return ResourceManager.GetString("Minutes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to second|seconds. + /// + internal static string Seconds { + get { + return ResourceManager.GetString("Seconds", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Something went wrong :confused:. + /// + internal static string SomethingWentWrong { + get { + return ResourceManager.GetString("SomethingWentWrong", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Internal.de-ch.resx b/src/Bot/Localization/Internal.de-ch.resx new file mode 100644 index 0000000..568bb1f --- /dev/null +++ b/src/Bot/Localization/Internal.de-ch.resx @@ -0,0 +1,35 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Öppis isch schief gange :confused: + + + Gseht danach us das ich nid gnueg recht han zum das mache :confused: + + + tag|täg + + + stund|stunde + + + minute|minute + + + sekunde|sekunde + + + und + + \ No newline at end of file diff --git a/src/Bot/Localization/Internal.resx b/src/Bot/Localization/Internal.resx new file mode 100644 index 0000000..a771d6b --- /dev/null +++ b/src/Bot/Localization/Internal.resx @@ -0,0 +1,42 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Something went wrong :confused: + + + Seems like i don't have enough permission to that :confused: + + + day|days + + + hour|hours + + + minute|minutes + + + second|seconds + + + and + + \ No newline at end of file diff --git a/src/Bot/Localization/Karma.Designer.cs b/src/Bot/Localization/Karma.Designer.cs new file mode 100644 index 0000000..4191fa2 --- /dev/null +++ b/src/Bot/Localization/Karma.Designer.cs @@ -0,0 +1,135 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Karma { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Karma() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Karma", typeof(Karma).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Amount. + /// + internal static string Amount { + get { + return ResourceManager.GetString("Amount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By. + /// + internal static string By { + get { + return ResourceManager.GetString("By", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sorry {0}, but you can't lower your own karma. + /// + internal static string CannotChangeOwnDown { + get { + return ResourceManager.GetString("CannotChangeOwnDown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sorry {0}, but you can't give yourself karma. + /// + internal static string CannotChangeOwnUp { + get { + return ResourceManager.GetString("CannotChangeOwnUp", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Current. + /// + internal static string Current { + get { + return ResourceManager.GetString("Current", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Karma lowered. + /// + internal static string Decreased { + get { + return ResourceManager.GetString("Decreased", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Gained Karma. + /// + internal static string Increased { + get { + return ResourceManager.GetString("Increased", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sorry {0}, but you have to wait {1} before you can give karma again.... + /// + internal static string WaitUntill { + get { + return ResourceManager.GetString("WaitUntill", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Karma.de-ch.resx b/src/Bot/Localization/Karma.de-ch.resx new file mode 100644 index 0000000..294c105 --- /dev/null +++ b/src/Bot/Localization/Karma.de-ch.resx @@ -0,0 +1,38 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Sorry {0}, aber du chasch dr selber kei karma geh + + + Sorry {0}, aber du musch no {1} warte bisch d wieder karma chasch geh... + + + Karma becho + + + Vo + + + Mengi + + + Jetzt + + + Sorry {0}, aber du chasch dr din eigete karma nid weg neh + + + Karma gsenkt + + \ No newline at end of file diff --git a/src/Bot/Localization/Karma.resx b/src/Bot/Localization/Karma.resx new file mode 100644 index 0000000..3a8fe5a --- /dev/null +++ b/src/Bot/Localization/Karma.resx @@ -0,0 +1,45 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Sorry {0}, but you can't give yourself karma + + + Sorry {0}, but you have to wait {1} before you can give karma again... + + + Gained Karma + + + By + + + Amount + + + Current + + + Sorry {0}, but you can't lower your own karma + + + Karma lowered + + \ No newline at end of file diff --git a/src/Bot/Localization/Quote.Designer.cs b/src/Bot/Localization/Quote.Designer.cs new file mode 100644 index 0000000..342c181 --- /dev/null +++ b/src/Bot/Localization/Quote.Designer.cs @@ -0,0 +1,162 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Quote { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Quote() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Quote", typeof(Quote).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to You can't save quotes by a bot.... + /// + internal static string CannotQuoteBots { + get { + return ResourceManager.GetString("CannotQuoteBots", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You can't save your own quotes.... + /// + internal static string CannotSaveOwnQuotes { + get { + return ResourceManager.GetString("CannotSaveOwnQuotes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Most quoted person. + /// + internal static string MostQuotesPerson { + get { + return ResourceManager.GetString("MostQuotesPerson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This server doesn't seem to have any quotes yet. You can add a quote with `!quote save @user` or `!quote save <messageId>`. + /// + internal static string NoQuotesFound { + get { + return ResourceManager.GetString("NoQuotesFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to That is not a valid message link. + /// + internal static string NotAValidMessageLink { + get { + return ResourceManager.GetString("NotAValidMessageLink", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to I couldn't find a quote with that ID :disappointed:. + /// + internal static string NotFoundWithId { + get { + return ResourceManager.GetString("NotFoundWithId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You can only quote messages from the same server. + /// + internal static string OnlyQuoteFromSameServer { + get { + return ResourceManager.GetString("OnlyQuoteFromSameServer", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to **Quote Added**. + /// + internal static string QuoteAdded { + get { + return ResourceManager.GetString("QuoteAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Quote Stats. + /// + internal static string QuoteStats { + get { + return ResourceManager.GetString("QuoteStats", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to **Removed #{0}**. + /// + internal static string Removed { + get { + return ResourceManager.GetString("Removed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Total. + /// + internal static string TotalQuotes { + get { + return ResourceManager.GetString("TotalQuotes", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Quote.de-ch.resx b/src/Bot/Localization/Quote.de-ch.resx new file mode 100644 index 0000000..99fd959 --- /dev/null +++ b/src/Bot/Localization/Quote.de-ch.resx @@ -0,0 +1,47 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Dä server het no kei quotes. Du chasch quotes hinzuefüege mit `!quote save @user` oder `!quote save <messageId>` + + + Du chasch kei quotes vo dir selber speichere... + + + Du chasch kei quotes vomne bot speichere... + + + **Quote hinzugfüegt** + + + **#{0} glöscht** + + + Ich chan kei quote finde mit därri ID :disappointed: + + + Quote statistike + + + Total + + + Meist quoteti person + + + Das isch kei korrete nachrichtelink + + + Du chasch numme nachrichte vom gliche server quote + + \ No newline at end of file diff --git a/src/Bot/Localization/Quote.resx b/src/Bot/Localization/Quote.resx new file mode 100644 index 0000000..b51d79c --- /dev/null +++ b/src/Bot/Localization/Quote.resx @@ -0,0 +1,54 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + This server doesn't seem to have any quotes yet. You can add a quote with `!quote save @user` or `!quote save <messageId>` + + + You can't save your own quotes... + + + You can't save quotes by a bot... + + + **Quote Added** + + + **Removed #{0}** + + + I couldn't find a quote with that ID :disappointed: + + + Quote Stats + + + Total + + + Most quoted person + + + That is not a valid message link + + + You can only quote messages from the same server + + \ No newline at end of file diff --git a/src/Bot/Localization/Rank.Designer.cs b/src/Bot/Localization/Rank.Designer.cs new file mode 100644 index 0000000..23f5e16 --- /dev/null +++ b/src/Bot/Localization/Rank.Designer.cs @@ -0,0 +1,108 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Rank { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Rank() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Rank", typeof(Rank).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to :warning: I couldn't find all usernames. Maybe they left the server?. + /// + internal static string FailedToResolveAllUsernames { + get { + return ResourceManager.GetString("FailedToResolveAllUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to :bar_chart: **{0} Highscore for {1}**. + /// + internal static string HighscoresFor { + get { + return ResourceManager.GetString("HighscoresFor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`'. + /// + internal static string InvalidType { + get { + return ResourceManager.GetString("InvalidType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to :warning: Limiting to 20. + /// + internal static string LimitingTo20Warning { + get { + return ResourceManager.GetString("LimitingTo20Warning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No {0} found on this server. + /// + internal static string NoTypeFoundForServer { + get { + return ResourceManager.GetString("NoTypeFoundForServer", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Rank.de-ch.resx b/src/Bot/Localization/Rank.de-ch.resx new file mode 100644 index 0000000..0b22fe4 --- /dev/null +++ b/src/Bot/Localization/Rank.de-ch.resx @@ -0,0 +1,29 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + :warning: Limitiert uf 20 + + + Kei {0} gfunde für dä server + + + :warning: Ich han nid alli benutzername gfunde. villiicht hend sie de server verlah? + + + :bar_chart: **{0} Highscore für {1}** + + + Gültigi paramenter sind '`messages`' '`karma`', '`rolls`' und '`cookies` + + \ No newline at end of file diff --git a/src/Bot/Localization/Rank.resx b/src/Bot/Localization/Rank.resx new file mode 100644 index 0000000..9598cf8 --- /dev/null +++ b/src/Bot/Localization/Rank.resx @@ -0,0 +1,36 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`' + + + :warning: Limiting to 20 + + + No {0} found on this server + + + :warning: I couldn't find all usernames. Maybe they left the server? + + + :bar_chart: **{0} Highscore for {1}** + + \ No newline at end of file diff --git a/src/Bot/Localization/Roll.Designer.cs b/src/Bot/Localization/Roll.Designer.cs new file mode 100644 index 0000000..fda0536 --- /dev/null +++ b/src/Bot/Localization/Roll.Designer.cs @@ -0,0 +1,99 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Roll { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Roll() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Roll", typeof(Roll).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Congratulations {0}, your guess was correct!. + /// + internal static string Gratz { + get { + return ResourceManager.GetString("Gratz", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to :red_circle: {0}, you can't guess the same number again, guess another number or wait {1}. + /// + internal static string NoPrevGuess { + get { + return ResourceManager.GetString("NoPrevGuess", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}, you rolled {1}, your guess was {2}. + /// + internal static string Rolled { + get { + return ResourceManager.GetString("Rolled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}, you rolled {1}. + /// + internal static string RolledNoGuess { + get { + return ResourceManager.GetString("RolledNoGuess", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Roll.de-ch.resx b/src/Bot/Localization/Roll.de-ch.resx new file mode 100644 index 0000000..ba73316 --- /dev/null +++ b/src/Bot/Localization/Roll.de-ch.resx @@ -0,0 +1,26 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}, du hesch {1} grollt und hesch {2} grate + + + Gratuliere {0}, du hesch richtig grate! + + + {0}, du hesch {1} grollt + + + :red_circle: {0}, du chasch nid nomol es gliche rate, rate öppis anders oder warte {1} + + \ No newline at end of file diff --git a/src/Bot/Localization/Roll.resx b/src/Bot/Localization/Roll.resx new file mode 100644 index 0000000..822abb6 --- /dev/null +++ b/src/Bot/Localization/Roll.resx @@ -0,0 +1,33 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}, you rolled {1}, your guess was {2} + + + Congratulations {0}, your guess was correct! + + + {0}, you rolled {1} + + + :red_circle: {0}, you can't guess the same number again, guess another number or wait {1} + + \ No newline at end of file diff --git a/src/Bot/Localization/Ship.Designer.cs b/src/Bot/Localization/Ship.Designer.cs new file mode 100644 index 0000000..d959693 --- /dev/null +++ b/src/Bot/Localization/Ship.Designer.cs @@ -0,0 +1,117 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Ship { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Ship() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Ship", typeof(Ship).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Almost a match. + /// + internal static string CouldWork { + get { + return ResourceManager.GetString("CouldWork", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to It's a match. + /// + internal static string ItsAMatch { + get { + return ResourceManager.GetString("ItsAMatch", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Matchmaking. + /// + internal static string Matchmaking { + get { + return ResourceManager.GetString("Matchmaking", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Not going happen. + /// + internal static string NotGoingToHappen { + get { + return ResourceManager.GetString("NotGoingToHappen", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Not such a good idea. + /// + internal static string NotSuchAGoodIdea { + get { + return ResourceManager.GetString("NotSuchAGoodIdea", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There might be a chance. + /// + internal static string ThereMightBeAChance { + get { + return ResourceManager.GetString("ThereMightBeAChance", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Ship.de-ch.resx b/src/Bot/Localization/Ship.de-ch.resx new file mode 100644 index 0000000..ec2880b --- /dev/null +++ b/src/Bot/Localization/Ship.de-ch.resx @@ -0,0 +1,32 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Verkupple + + + Wird nöd klappe + + + Nöd so ä gueti idee + + + Es gid eventuel ä chance + + + Fasch en match + + + Es isch es traumpaar + + \ No newline at end of file diff --git a/src/Bot/Localization/Ship.resx b/src/Bot/Localization/Ship.resx new file mode 100644 index 0000000..611040f --- /dev/null +++ b/src/Bot/Localization/Ship.resx @@ -0,0 +1,39 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Matchmaking + + + Not going happen + + + Not such a good idea + + + There might be a chance + + + Almost a match + + + It's a match + + \ No newline at end of file diff --git a/src/Core/GeekbotCommandBase.cs b/src/Core/GeekbotCommandBase.cs new file mode 100644 index 0000000..8df5265 --- /dev/null +++ b/src/Core/GeekbotCommandBase.cs @@ -0,0 +1,27 @@ +using System.Globalization; +using System.Threading; +using Discord.Commands; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Localization; + +namespace Geekbot.Core +{ + public class GeekbotCommandBase : ModuleBase + { + protected readonly IErrorHandler ErrorHandler; + protected readonly ITranslationHandler Translations; + + protected GeekbotCommandBase(IErrorHandler errorHandler, ITranslationHandler translations) + { + ErrorHandler = errorHandler; + Translations = translations; + } + + protected override void BeforeExecute(CommandInfo command) + { + base.BeforeExecute(command); + var language = Translations.GetServerLanguage(Context.Guild.Id); + Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language == "CHDE" ? "de-ch" : language); + } + } +} \ No newline at end of file diff --git a/src/Core/Localization/ITranslationHandler.cs b/src/Core/Localization/ITranslationHandler.cs index 74b3e88..1cc06fa 100644 --- a/src/Core/Localization/ITranslationHandler.cs +++ b/src/Core/Localization/ITranslationHandler.cs @@ -12,5 +12,6 @@ namespace Geekbot.Core.Localization Task GetGuildContext(ICommandContext context); Task SetLanguage(ulong guildId, string language); List SupportedLanguages { get; } + string GetServerLanguage(ulong guildId); } } \ No newline at end of file diff --git a/src/Core/Localization/TranslationHandler.cs b/src/Core/Localization/TranslationHandler.cs index c7d35e9..1a46ada 100644 --- a/src/Core/Localization/TranslationHandler.cs +++ b/src/Core/Localization/TranslationHandler.cs @@ -89,7 +89,7 @@ namespace Geekbot.Core.Localization } } - private Task GetServerLanguage(ulong guildId) + public string GetServerLanguage(ulong guildId) { try { @@ -99,7 +99,7 @@ namespace Geekbot.Core.Localization lang = _serverLanguages[guildId]; if (!string.IsNullOrEmpty(lang)) { - return Task.FromResult(lang); + return lang; } throw new Exception(); } @@ -107,19 +107,19 @@ namespace Geekbot.Core.Localization { lang = _guildSettingsManager.GetSettings(guildId, false)?.Language ?? "EN"; _serverLanguages[guildId] = lang; - return Task.FromResult(lang); + return lang; } } catch (Exception e) { _logger.Error(LogSource.Geekbot, "Could not get guild language", e); - return Task.FromResult("EN"); + return "EN"; } } public async Task GetString(ulong guildId, string command, string stringName) { - var serverLang = await GetServerLanguage(guildId); + var serverLang = GetServerLanguage(guildId); return GetString(serverLang, command, stringName); } @@ -140,7 +140,7 @@ namespace Geekbot.Core.Localization try { var command = context.Message.Content.Split(' ').First().TrimStart('!').ToLower(); - var serverLanguage = await GetServerLanguage(context.Guild?.Id ?? 0); + var serverLanguage = GetServerLanguage(context.Guild?.Id ?? 0); return _translations[serverLanguage][command]; } catch (Exception e) @@ -153,7 +153,7 @@ namespace Geekbot.Core.Localization public async Task GetGuildContext(ICommandContext context) { var dict = await GetDict(context); - var language = await GetServerLanguage(context.Guild?.Id ?? 0); + var language = GetServerLanguage(context.Guild?.Id ?? 0); return new TranslationGuildContext(this, language, dict); } @@ -161,7 +161,7 @@ namespace Geekbot.Core.Localization { try { - var serverLanguage = await GetServerLanguage(context.Guild?.Id ?? 0); + var serverLanguage = GetServerLanguage(context.Guild?.Id ?? 0); return _translations[serverLanguage][command]; } catch (Exception e) diff --git a/src/Core/Localization/Translations.yml b/src/Core/Localization/Translations.yml index fbb55bf..678755d 100644 --- a/src/Core/Localization/Translations.yml +++ b/src/Core/Localization/Translations.yml @@ -15,13 +15,6 @@ dateTime: And: EN: "and" CHDE: "und" -admin: - NewLanguageSet: - EN: "I will reply in english from now on" - CHDE: "I werd ab jetzt uf schwiizerdüütsch antworte, äuuä" - GetLanguage: - EN: "I'm talking english" - CHDE: "I red schwiizerdüütsch" errorHandler: SomethingWentWrong: EN: "Something went wrong :confused:" @@ -30,86 +23,6 @@ httpErrors: 403: EN: "Seems like i don't have enough permission to that :confused:" CHDE: "Gseht danach us das ich nid gnueg recht han zum das mache :confused:" -choose: - Choice: - EN: "I Choose **{0}**" - CHDE: "I nimme **{0}**" -good: - CannotChangeOwn: - EN: "Sorry {0}, but you can't give yourself karma" - CHDE: "Sorry {0}, aber du chasch dr selber kei karma geh" - WaitUntill: - EN: "Sorry {0}, but you have to wait {1} before you can give karma again..." - CHDE: "Sorry {0}, aber du musch no {1} warte bisch d wieder karma chasch geh..." - Increased: - EN: "Karma gained" - CHDE: "Karma becho" - By: - EN: "By" - CHDE: "Vo" - Amount: - EN: "Amount" - CHDE: "Mengi" - Current: - EN: "Current" - CHDE: "Jetzt" -bad: - CannotChangeOwn: - EN: "Sorry {0}, but you can't lower your own karma" - CHDE: "Sorry {0}, aber du chasch dr din eigete karma nid weg neh" - WaitUntill: - EN: "Sorry {0}, but you have to wait {1} before you can lower karma again..." - CHDE: "Sorry {0}, aber du musch no {1} warte bisch d wieder karma chasch senke..." - Decreased: - EN: "Karma lowered" - CHDE: "Karma gsenkt" - By: - EN: "By" - CHDE: "Vo" - Amount: - EN: "Amount" - CHDE: "Mengi" - Current: - EN: "Current" - CHDE: "Jetzt" -roll: - Rolled: - EN: "{0}, you rolled {1}, your guess was {2}" - CHDE: "{0}, du hesch {1} grollt und hesch {2} grate" - Gratz: - EN: "Congratulations {0}, your guess was correct!" - CHDE: "Gratuliere {0}, du hesch richtig grate!" - RolledNoGuess: - EN: "{0}, you rolled {1}" - CHDE: "{0}, du hesch {1} grollt" - NoPrevGuess: - EN: ":red_circle: {0}, you can't guess the same number again, guess another number or wait {1}" - CHDE: ":red_circle: {0}, du chasch nid nomol es gliche rate, rate öppis anders oder warte {1}" -cookies: &cookiesAlias - GetCookies: - EN: "You got {0} cookies, there are now {1} cookies in you cookie jar" - CHDE: "Du häsch {0} guetzli becho, du häsch jetzt {1} guetzli ih dr büchse" - WaitForMoreCookies: - EN: "You already got cookies today, you can have more cookies in {0}" - CHDE: "Du hesch scho guetzli becho hüt, du chasch meh ha in {0}" - InYourJar: - EN: "There are {0} cookies in you cookie jar" - CHDE: "Es hät {0} guetzli ih dineri büchs" - Given: - EN: "You gave {0} cookies to {1}" - CHDE: "Du hesch {1} {0} guetzli geh" - NotEnoughToGive: - EN: "You don't have enough cookies" - CHDE: "Du hesch nid gnueg guetzli" - NotEnoughCookiesToEat: - EN: "Your cookie jar looks almost empty, you should probably not eat a cookie" - CHDE: "Du hesch chuum no guetzli ih dineri büchs, du sötsch warschinli keini esse" - AteCookies: - EN: "You ate {0} cookies, you've only got {1} cookies left" - CHDE: "Du hesch {0} guetzli gesse und hesch jezt no {1} übrig" -cookie: - # because command aliases are to hard to deal with... - <<: *cookiesAlias role: NoRolesConfigured: EN: "There are no roles configured for this server" @@ -140,74 +53,4 @@ role: CHDE: "{0} isch zur whitelist hinzuegfüegt" RemovedRoleFromWhitelist: EN: "Removed {0} from the whitelist" - CHDE: "{0} isch vo dr whitelist glöscht" -quote: - NoQuotesFound: - EN: "This server doesn't seem to have any quotes yet. You can add a quote with `!quote save @user` or `!quote save `" - CHDE: "Dä server het no kei quotes. Du chasch quotes hinzuefüege mit `!quote save @user` oder `!quote save `" - CannotSaveOwnQuotes: - EN: "You can't save your own quotes..." - CHDE: "Du chasch kei quotes vo dir selber speichere..." - CannotQuoteBots: - EN: "You can't save quotes by a bot..." - CHDE: "Du chasch kei quotes vomne bot speichere..." - QuoteAdded: - EN: "**Quote Added**" - CHDE: "**Quote hinzugfüegt**" - Removed: - EN: "**Removed #{0}**" - CHDE: "**#{0} glöscht**" - NotFoundWithId: - EN: "I couldn't find a quote with that ID :disappointed:" - CHDE: "Ich chan kei quote finde mit därri ID :disappointed:" - QuoteStats: - EN: "Quote Stats" - CHDE: "Quote statistike" - TotalQuotes: - EN: "Total" - CHDE: "Total" - MostQuotesPerson: - EN: "Most quoted person" - CHDE: "Meist quoteti person" - NotAValidMessageLink: - EN: "That is not a valid message link" - CHDE: "Das isch kei korrete nachrichtelink" - OnlyQuoteFromSameServer: - EN: "You can only quote messages from the same server" - CHDE: "Du chasch numme nachrichte vom gliche server quote" -rank: - InvalidType: - EN: "Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`'" - CHDE: "Gültigi paramenter sind '`messages`' '`karma`', '`rolls`' und '`cookies`'" - LimitingTo20Warning: - EN: ":warning: Limiting to 20\n" - CHDE: ":warning: Limitiert uf 20\n" - NoTypeFoundForServer: - EN: "No {0} found on this server" - CHDE: "Kei {0} gfunde für dä server" - FailedToResolveAllUsernames: - EN: ":warning: I couldn't find all usernames. Maybe they left the server?\n" - CHDE: ":warning: Ich han nid alli benutzername gfunde. villiicht hend sie de server verlah?\n" - HighscoresFor: - EN: ":bar_chart: **{0} Highscore for {1}**" - CHDE: ":bar_chart: **{0} Highscore für {1}**" -ship: - Matchmaking: - EN: "Matchmaking" - CHDE: "Verkupple" - NotGonnaToHappen: - EN: "Not gonna happen" - CHDE: "Wird nöd klappe" - NotSuchAGoodIdea: - EN: "Not such a good idea" - CHDE: "Nöd so ä gueti idee" - ThereMightBeAChance: - EN: "There might be a chance" - CHDE: "Es gid eventuel ä chance" - CouldWork: - EN: "Almost a match" - CHDE: "Fasch en match" - ItsAMatch: - EN: "It's a match" - CHDE: "Es isch es traumpaar" - \ No newline at end of file + CHDE: "{0} isch vo dr whitelist glöscht" \ No newline at end of file From 078c884df73c668aab75f916cd175deaaac7bd4c Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 14 Aug 2020 18:11:52 +0200 Subject: [PATCH 092/264] Convert Role command to new localization method --- src/Bot/Bot.csproj | 9 ++ src/Bot/Commands/Admin/Role.cs | 52 ++++----- src/Bot/Localization/Role.Designer.cs | 153 +++++++++++++++++++++++++ src/Bot/Localization/Role.de-ch.resx | 44 +++++++ src/Bot/Localization/Role.resx | 51 +++++++++ src/Core/Localization/Translations.yml | 33 +----- 6 files changed, 280 insertions(+), 62 deletions(-) create mode 100644 src/Bot/Localization/Role.Designer.cs create mode 100644 src/Bot/Localization/Role.de-ch.resx create mode 100644 src/Bot/Localization/Role.resx diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 601766a..2d3cd2f 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -77,6 +77,10 @@ ResXFileCodeGenerator Quote.Designer.cs + + ResXFileCodeGenerator + Role.Designer.cs + @@ -127,5 +131,10 @@ True Quote.resx + + True + True + Role.resx + diff --git a/src/Bot/Commands/Admin/Role.cs b/src/Bot/Commands/Admin/Role.cs index e997fa8..c8459dd 100644 --- a/src/Bot/Commands/Admin/Role.cs +++ b/src/Bot/Commands/Admin/Role.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.Net; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; @@ -17,19 +18,15 @@ namespace Geekbot.Bot.Commands.Admin { [Group("role")] [DisableInDirectMessage] - public class Role : ModuleBase + public class Role : GeekbotCommandBase { private readonly DatabaseContext _database; - private readonly IErrorHandler _errorHandler; private readonly IReactionListener _reactionListener; - private readonly ITranslationHandler _translationHandler; - public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener, ITranslationHandler translationHandler) + public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener, ITranslationHandler translationHandler) : base(errorHandler, translationHandler) { _database = database; - _errorHandler = errorHandler; _reactionListener = reactionListener; - _translationHandler = translationHandler; } [Command(RunMode = RunMode.Async)] @@ -38,23 +35,22 @@ namespace Geekbot.Bot.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); var roles = _database.RoleSelfService.Where(g => g.GuildId.Equals(Context.Guild.Id.AsLong())).ToList(); if (roles.Count == 0) { - await ReplyAsync(transContext.GetString("NoRolesConfigured")); + await ReplyAsync(Localization.Role.NoRolesConfigured); return; } var sb = new StringBuilder(); - sb.AppendLine(transContext.GetString("ListHeader", Context.Guild.Name)); - sb.AppendLine(transContext.GetString("ListInstruction")); + sb.AppendLine(string.Format(Localization.Role.ListHeader, Context.Guild.Name)); + sb.AppendLine(Localization.Role.ListInstruction); foreach (var role in roles) sb.AppendLine($"- {role.WhiteListName}"); await ReplyAsync(sb.ToString()); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -64,7 +60,6 @@ namespace Geekbot.Bot.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); var roleName = roleNameRaw.ToLower(); var roleFromDb = _database.RoleSelfService.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName)); @@ -74,31 +69,31 @@ namespace Geekbot.Bot.Commands.Admin var role = Context.Guild.Roles.First(r => r.Id == roleFromDb.RoleId.AsUlong()); if (role == null) { - await ReplyAsync(transContext.GetString("RoleNotFound")); + await ReplyAsync(Localization.Role.RoleNotFound); return; } if (guildUser.RoleIds.Contains(role.Id)) { await guildUser.RemoveRoleAsync(role); - await ReplyAsync(transContext.GetString("RemovedUserFromRole", role.Name)); + await ReplyAsync(string.Format(Localization.Role.RemovedUserFromRole, role.Name)); return; } await guildUser.AddRoleAsync(role); - await ReplyAsync(transContext.GetString("AddedUserFromRole", role.Name)); + await ReplyAsync(string.Format(Localization.Role.AddedUserFromRole, role.Name)); return; } - await ReplyAsync(transContext.GetString("RoleNotFound")); + await ReplyAsync(Localization.Role.RoleNotFound); } catch (HttpException e) { - await _errorHandler.HandleHttpException(e, Context); + await ErrorHandler.HandleHttpException(e, Context); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -109,10 +104,9 @@ namespace Geekbot.Bot.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); if (role.IsManaged) { - await ReplyAsync(transContext.GetString("CannotAddManagedRole")); + await ReplyAsync(Localization.Role.CannotAddManagedRole); return; } @@ -122,7 +116,7 @@ namespace Geekbot.Bot.Commands.Admin || role.Permissions.BanMembers || role.Permissions.KickMembers) { - await ReplyAsync(transContext.GetString("CannotAddDangerousRole")); + await ReplyAsync(Localization.Role.CannotAddDangerousRole); return; } @@ -133,11 +127,11 @@ namespace Geekbot.Bot.Commands.Admin WhiteListName = roleName }); await _database.SaveChangesAsync(); - await ReplyAsync(transContext.GetString("AddedRoleToWhitelist", role.Name)); + await ReplyAsync(string.Format(Localization.Role.AddedRoleToWhitelist, role.Name)); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -148,22 +142,21 @@ namespace Geekbot.Bot.Commands.Admin { try { - var transContext = await _translationHandler.GetGuildContext(Context); var roleFromDb = _database.RoleSelfService.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName)); if (roleFromDb != null) { _database.RoleSelfService.Remove(roleFromDb); await _database.SaveChangesAsync(); - await ReplyAsync(transContext.GetString("RemovedRoleFromWhitelist", roleName)); + await ReplyAsync(string.Format(Localization.Role.RemovedRoleFromWhitelist, roleName)); return; } - await ReplyAsync(transContext.GetString("RoleNotFound")); + await ReplyAsync(Localization.Role.RoleNotFound); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -182,14 +175,13 @@ namespace Geekbot.Bot.Commands.Admin await _reactionListener.AddRoleToListener(messageId, Context.Guild.Id, emoji, role); await Context.Message.DeleteAsync(); } - catch (HttpException e) + catch (HttpException) { await Context.Channel.SendMessageAsync("Custom emojis from other servers are not supported"); - Console.WriteLine(e); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } } diff --git a/src/Bot/Localization/Role.Designer.cs b/src/Bot/Localization/Role.Designer.cs new file mode 100644 index 0000000..9128e3d --- /dev/null +++ b/src/Bot/Localization/Role.Designer.cs @@ -0,0 +1,153 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Role { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Role() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Role", typeof(Role).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Added {0} to the whitelist. + /// + internal static string AddedRoleToWhitelist { + get { + return ResourceManager.GetString("AddedRoleToWhitelist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Added you to {0}. + /// + internal static string AddedUserFromRole { + get { + return ResourceManager.GetString("AddedUserFromRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You cannot add that role to self service because it contains one or more dangerous permissions. + /// + internal static string CannotAddDangerousRole { + get { + return ResourceManager.GetString("CannotAddDangerousRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You can't add a role that is managed by discord. + /// + internal static string CannotAddManagedRole { + get { + return ResourceManager.GetString("CannotAddManagedRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to **Self Service Roles on {0}**. + /// + internal static string ListHeader { + get { + return ResourceManager.GetString("ListHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To get a role, use `!role [name]`. + /// + internal static string ListInstruction { + get { + return ResourceManager.GetString("ListInstruction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no roles configured for this server. + /// + internal static string NoRolesConfigured { + get { + return ResourceManager.GetString("NoRolesConfigured", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removed {0} from the whitelist. + /// + internal static string RemovedRoleFromWhitelist { + get { + return ResourceManager.GetString("RemovedRoleFromWhitelist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removed you from {0}. + /// + internal static string RemovedUserFromRole { + get { + return ResourceManager.GetString("RemovedUserFromRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to That role doesn't exist or is not on the whitelist. + /// + internal static string RoleNotFound { + get { + return ResourceManager.GetString("RoleNotFound", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Role.de-ch.resx b/src/Bot/Localization/Role.de-ch.resx new file mode 100644 index 0000000..b0b3259 --- /dev/null +++ b/src/Bot/Localization/Role.de-ch.resx @@ -0,0 +1,44 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Es sind kei rolle für dä server konfiguriert + + + **Self Service Rollene uf {0}** + + + Zum ä rolle becho, schriib `!role [name]` + + + Die rolle gids nid or isch nid uf dr whitelist + + + Han di entfernt vo {0} + + + Han di hinzue gfüegt zu {0} + + + Du chasch kei rolle hinzuefüge wo verwalted wird vo discord + + + Du chasch die rolle nid hinzuefüge will er ein oder mehreri gföhrlichi berechtigunge het + + + {0} isch zur whitelist hinzuegfüegt + + + {0} isch vo dr whitelist glöscht + + \ No newline at end of file diff --git a/src/Bot/Localization/Role.resx b/src/Bot/Localization/Role.resx new file mode 100644 index 0000000..63b70d0 --- /dev/null +++ b/src/Bot/Localization/Role.resx @@ -0,0 +1,51 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + There are no roles configured for this server + + + **Self Service Roles on {0}** + + + To get a role, use `!role [name]` + + + That role doesn't exist or is not on the whitelist + + + Removed you from {0} + + + Added you to {0} + + + You can't add a role that is managed by discord + + + You cannot add that role to self service because it contains one or more dangerous permissions + + + Added {0} to the whitelist + + + Removed {0} from the whitelist + + \ No newline at end of file diff --git a/src/Core/Localization/Translations.yml b/src/Core/Localization/Translations.yml index 678755d..dc18c2b 100644 --- a/src/Core/Localization/Translations.yml +++ b/src/Core/Localization/Translations.yml @@ -22,35 +22,4 @@ errorHandler: httpErrors: 403: EN: "Seems like i don't have enough permission to that :confused:" - CHDE: "Gseht danach us das ich nid gnueg recht han zum das mache :confused:" -role: - NoRolesConfigured: - EN: "There are no roles configured for this server" - CHDE: "Es sind kei rolle für dä server konfiguriert" - ListHeader: - EN: "**Self Service Roles on {0}**" - CHDE: "**Self Service Rollene uf {0}**" - ListInstruction: - EN: "To get a role, use `!role [name]`" - CHDE: "Zum ä rolle becho, schriib `!role [name]`" - RoleNotFound: - EN: "That role doesn't exist or is not on the whitelist" - CHDE: "Die rolle gids nid or isch nid uf dr whitelist" - RemovedUserFromRole: - EN: "Removed you from {0}" - CHDE: "Han di entfernt vo {0}" - AddedUserFromRole: - EN: "Added you to {0}" - CHDE: "Han di hinzue gfüegt zu {0}" - CannotAddManagedRole: - EN: "You can't add a role that is managed by discord" - CHDE: "Du chasch kei rolle hinzuefüge wo verwalted wird vo discord" - CannotAddDangerousRole: - EN: "You cannot add that role to self service because it contains one or more dangerous permissions" - CHDE: "Du chasch die rolle nid hinzuefüge will er ein oder mehreri gföhrlichi berechtigunge het" - AddedRoleToWhitelist: - EN: "Added {0} to the whitelist" - CHDE: "{0} isch zur whitelist hinzuegfüegt" - RemovedRoleFromWhitelist: - EN: "Removed {0} from the whitelist" - CHDE: "{0} isch vo dr whitelist glöscht" \ No newline at end of file + CHDE: "Gseht danach us das ich nid gnueg recht han zum das mache :confused:" \ No newline at end of file From 33829e91bc2df8c1852c0c32d91c97dcc9f7c71f Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 14 Aug 2020 23:15:11 +0200 Subject: [PATCH 093/264] Delete the TranslationHandler and the old translations file. Refactor GeekbotCommandBase to get the server language from guild settings. Create DateLocalization to create a localized relative time remaining string. --- src/Bot/Commands/Admin/Admin.cs | 87 ++++---- src/Bot/Commands/Admin/Owner/Owner.cs | 19 +- src/Bot/Commands/Admin/Role.cs | 14 +- src/Bot/Commands/Games/Roll/Roll.cs | 19 +- src/Bot/Commands/Randomness/Ship.cs | 4 +- src/Bot/Commands/Rpg/Cookies.cs | 11 +- src/Bot/Commands/User/Karma.cs | 17 +- src/Bot/Commands/User/Ranking/Rank.cs | 13 +- src/Bot/Commands/Utils/Choose.cs | 4 +- src/Bot/Commands/Utils/Quote/Quote.cs | 5 +- src/Bot/Program.cs | 5 +- src/Bot/Utils/DateLocalization.cs | 49 +++++ src/Core/Core.csproj | 6 - src/Core/ErrorHandling/ErrorHandler.cs | 24 +-- src/Core/ErrorHandling/IErrorHandler.cs | 2 - src/Core/GeekbotCommandBase.cs | 13 +- src/Core/Localization/ITranslationHandler.cs | 17 -- .../Localization/TranslationGuildContext.cs | 90 -------- src/Core/Localization/TranslationHandler.cs | 194 ------------------ src/Core/Localization/Translations.yml | 25 --- .../TranslationGuildContext.test.cs | 71 ------- tests/Core/Localization/Translations.test.cs | 46 ----- 22 files changed, 156 insertions(+), 579 deletions(-) create mode 100644 src/Bot/Utils/DateLocalization.cs delete mode 100644 src/Core/Localization/ITranslationHandler.cs delete mode 100644 src/Core/Localization/TranslationGuildContext.cs delete mode 100644 src/Core/Localization/TranslationHandler.cs delete mode 100644 src/Core/Localization/Translations.yml delete mode 100644 tests/Core/Localization/TranslationGuildContext.test.cs delete mode 100644 tests/Core/Localization/Translations.test.cs diff --git a/src/Bot/Commands/Admin/Admin.cs b/src/Bot/Commands/Admin/Admin.cs index 2627f86..60ba8ac 100644 --- a/src/Bot/Commands/Admin/Admin.cs +++ b/src/Bot/Commands/Admin/Admin.cs @@ -14,7 +14,6 @@ using Geekbot.Core.CommandPreconditions; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; using Geekbot.Core.GuildSettingsManager; -using Geekbot.Core.Localization; namespace Geekbot.Bot.Commands.Admin { @@ -24,21 +23,18 @@ namespace Geekbot.Bot.Commands.Admin public class Admin : GeekbotCommandBase { private readonly DiscordSocketClient _client; - private readonly IGuildSettingsManager _guildSettingsManager; - public Admin(DiscordSocketClient client, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager, ITranslationHandler translationHandler) : base(errorHandler, translationHandler) + public Admin(DiscordSocketClient client, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _client = client; - _guildSettingsManager = guildSettingsManager; } [Command("welcome", RunMode = RunMode.Async)] [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] public async Task SetWelcomeMessage([Remainder, Summary("message")] string welcomeMessage) { - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.WelcomeMessage = welcomeMessage; - await _guildSettingsManager.UpdateSettings(guild); + GuildSettings.WelcomeMessage = welcomeMessage; + await GuildSettingsManager.UpdateSettings(GuildSettings); var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention); await ReplyAsync($"Welcome message has been changed\r\nHere is an example of how it would look:\r\n{formatedMessage}"); @@ -52,9 +48,8 @@ namespace Geekbot.Bot.Commands.Admin { var m = await channel.SendMessageAsync("..."); - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.WelcomeChannel = channel.Id.AsLong(); - await _guildSettingsManager.UpdateSettings(guild); + GuildSettings.WelcomeChannel = channel.Id.AsLong(); + await GuildSettingsManager.UpdateSettings(GuildSettings); await m.DeleteAsync(); @@ -74,9 +69,8 @@ namespace Geekbot.Bot.Commands.Admin { var m = await channel.SendMessageAsync("verifying..."); - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.ModChannel = channel.Id.AsLong(); - await _guildSettingsManager.UpdateSettings(guild); + GuildSettings.ModChannel = channel.Id.AsLong(); + await GuildSettingsManager.UpdateSettings(GuildSettings); var sb = new StringBuilder(); sb.AppendLine("Successfully saved mod channel, you can now do the following"); @@ -96,13 +90,12 @@ namespace Geekbot.Bot.Commands.Admin { try { - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - var modChannel = await GetModChannel(guild.ModChannel.AsUlong()); + var modChannel = await GetModChannel(GuildSettings.ModChannel.AsUlong()); if (modChannel == null) return; - guild.ShowLeave = !guild.ShowLeave; - await _guildSettingsManager.UpdateSettings(guild); - await modChannel.SendMessageAsync(guild.ShowLeave + GuildSettings.ShowLeave = !GuildSettings.ShowLeave; + await GuildSettingsManager.UpdateSettings(GuildSettings); + await modChannel.SendMessageAsync(GuildSettings.ShowLeave ? "Saved - now sending messages here when someone leaves" : "Saved - stopping sending messages here when someone leaves" ); @@ -119,13 +112,12 @@ namespace Geekbot.Bot.Commands.Admin { try { - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - var modChannel = await GetModChannel(guild.ModChannel.AsUlong()); + var modChannel = await GetModChannel(GuildSettings.ModChannel.AsUlong()); if (modChannel == null) return; - guild.ShowDelete = !guild.ShowDelete; - await _guildSettingsManager.UpdateSettings(guild); - await modChannel.SendMessageAsync(guild.ShowDelete + GuildSettings.ShowDelete = !GuildSettings.ShowDelete; + await GuildSettingsManager.UpdateSettings(GuildSettings); + await modChannel.SendMessageAsync(GuildSettings.ShowDelete ? "Saved - now sending messages here when someone deletes a message" : "Saved - stopping sending messages here when someone deletes a message" ); @@ -138,31 +130,25 @@ namespace Geekbot.Bot.Commands.Admin [Command("setlang", RunMode = RunMode.Async)] [Summary("Change the bots language")] - public async Task SetLanguage([Summary("language")] string languageRaw) + public async Task SetLanguage([Summary("language")] string language) { try { - var language = languageRaw.ToUpper(); - var success = await Translations.SetLanguage(Context.Guild.Id, language); - if (success) + var availableLanguages = new List(); + availableLanguages.Add("en-GB"); // default + availableLanguages.AddRange(GetAvailableCultures().Select(culture => culture.Name)); + if (availableLanguages.Contains(language)) { - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.Language = language; - await _guildSettingsManager.UpdateSettings(guild); + GuildSettings.Language = language; + await GuildSettingsManager.UpdateSettings(GuildSettings); + + Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language.ToLower() == "chde" ? "de-CH" : language); - if (language.ToLower() == "chde") - { - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-ch"); - } - await ReplyAsync(Localization.Admin.NewLanguageSet); return; } - - var available = new List(); - available.Add("en-GB"); // default - available.AddRange(GetAvailableCultures().Select(culture => culture.Name)); - await ReplyAsync($"That doesn't seem to be a supported language\nSupported Languages are {string.Join(", ", available)}"); + + await ReplyAsync($"That doesn't seem to be a supported language\nSupported Languages are {string.Join(", ", availableLanguages)}"); } catch (Exception e) { @@ -177,9 +163,8 @@ namespace Geekbot.Bot.Commands.Admin try { var language = languageRaw.ToLower(); - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.WikiLang = language; - await _guildSettingsManager.UpdateSettings(guild); + GuildSettings.WikiLang = language; + await GuildSettingsManager.UpdateSettings(GuildSettings); await ReplyAsync($"Now using the {language} wikipedia"); } @@ -195,10 +180,10 @@ namespace Geekbot.Bot.Commands.Admin { try { - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.Ping = !guild.Ping; - await _guildSettingsManager.UpdateSettings(guild); - await ReplyAsync(guild.Ping ? "i will reply to ping now" : "No more pongs..."); + // var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); + GuildSettings.Ping = !GuildSettings.Ping; + await GuildSettingsManager.UpdateSettings(GuildSettings); + await ReplyAsync(GuildSettings.Ping ? "i will reply to ping now" : "No more pongs..."); } catch (Exception e) { @@ -212,10 +197,10 @@ namespace Geekbot.Bot.Commands.Admin { try { - var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); - guild.Hui = !guild.Hui; - await _guildSettingsManager.UpdateSettings(guild); - await ReplyAsync(guild.Hui ? "i will reply to hui now" : "No more hui's..."); + // var guild = _guildSettingsManager.GetSettings(Context.Guild.Id); + GuildSettings.Hui = !GuildSettings.Hui; + await GuildSettingsManager.UpdateSettings(GuildSettings); + await ReplyAsync(GuildSettings.Hui ? "i will reply to hui now" : "No more hui's..."); } catch (Exception e) { diff --git a/src/Bot/Commands/Admin/Owner/Owner.cs b/src/Bot/Commands/Admin/Owner/Owner.cs index 5fa3976..64292e9 100644 --- a/src/Bot/Commands/Admin/Owner/Owner.cs +++ b/src/Bot/Commands/Admin/Owner/Owner.cs @@ -3,8 +3,10 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.GlobalSettings; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Logger; using Geekbot.Core.UserRepository; @@ -12,20 +14,19 @@ namespace Geekbot.Bot.Commands.Admin.Owner { [Group("owner")] [RequireOwner] - public class Owner : ModuleBase + public class Owner : GeekbotCommandBase { private readonly DiscordSocketClient _client; - private readonly IErrorHandler _errorHandler; private readonly IGlobalSettings _globalSettings; private readonly IGeekbotLogger _logger; private readonly IUserRepository _userRepository; - public Owner(DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, IGlobalSettings globalSettings) + public Owner(DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, IGlobalSettings globalSettings, + IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _client = client; _logger = logger; _userRepository = userRepositry; - _errorHandler = errorHandler; _globalSettings = globalSettings; } @@ -73,7 +74,7 @@ namespace Geekbot.Bot.Commands.Admin.Owner } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context, + await ErrorHandler.HandleCommandException(e, Context, "Couldn't complete User Repository, see console for more info"); } } @@ -89,10 +90,10 @@ namespace Geekbot.Bot.Commands.Admin.Owner } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } - + [Command("refreshuser", RunMode = RunMode.Async)] [Summary("Refresh a user in the user cache")] public async Task PopUserRepoCommand([Summary("user-id")] ulong userId) @@ -105,7 +106,7 @@ namespace Geekbot.Bot.Commands.Admin.Owner } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -119,7 +120,7 @@ namespace Geekbot.Bot.Commands.Admin.Owner } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } } diff --git a/src/Bot/Commands/Admin/Role.cs b/src/Bot/Commands/Admin/Role.cs index c8459dd..efec7bd 100644 --- a/src/Bot/Commands/Admin/Role.cs +++ b/src/Bot/Commands/Admin/Role.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Net; using System.Text; using System.Threading.Tasks; using Discord; @@ -11,7 +12,7 @@ using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.ReactionListener; namespace Geekbot.Bot.Commands.Admin @@ -23,7 +24,7 @@ namespace Geekbot.Bot.Commands.Admin private readonly DatabaseContext _database; private readonly IReactionListener _reactionListener; - public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener, ITranslationHandler translationHandler) : base(errorHandler, translationHandler) + public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _database = database; _reactionListener = reactionListener; @@ -89,7 +90,14 @@ namespace Geekbot.Bot.Commands.Admin } catch (HttpException e) { - await ErrorHandler.HandleHttpException(e, Context); + if (e.HttpCode == HttpStatusCode.Forbidden) + { + await ReplyAsync(Localization.Internal.Http403); + } + else + { + await ErrorHandler.HandleCommandException(e, Context); + } } catch (Exception e) { diff --git a/src/Bot/Commands/Games/Roll/Roll.cs b/src/Bot/Commands/Games/Roll/Roll.cs index 244edbe..6ef9322 100644 --- a/src/Bot/Commands/Games/Roll/Roll.cs +++ b/src/Bot/Commands/Games/Roll/Roll.cs @@ -2,13 +2,14 @@ using System.Linq; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Bot.Utils; using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.KvInMemoryStore; -using Geekbot.Core.Localization; using Geekbot.Core.RandomNumberGenerator; namespace Geekbot.Bot.Commands.Games.Roll @@ -19,7 +20,8 @@ namespace Geekbot.Bot.Commands.Games.Roll private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Roll(IKvInMemoryStore kvInMemoryStore,IErrorHandler errorHandler, ITranslationHandler translation, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator) : base(errorHandler, translation) + public Roll(IKvInMemoryStore kvInMemoryStore, IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager) + : base(errorHandler, guildSettingsManager) { _kvInMemoryStore = kvInMemoryStore; _database = database; @@ -34,10 +36,9 @@ namespace Geekbot.Bot.Commands.Games.Roll { var number = _randomNumberGenerator.Next(1, 100); int.TryParse(stuff, out var guess); - var transContext = await Translations.GetGuildContext(Context); if (guess <= 100 && guess > 0) { - var kvKey = $"{Context.Guild.Id}:{Context.User.Id}:RollsPrevious"; + var kvKey = $"{Context?.Guild?.Id ?? 0}:{Context.User.Id}:RollsPrevious"; var prevRoll = _kvInMemoryStore.Get(kvKey); @@ -46,11 +47,11 @@ namespace Geekbot.Bot.Commands.Games.Roll await ReplyAsync(string.Format( Localization.Roll.NoPrevGuess, Context.Message.Author.Mention, - transContext.FormatDateTimeAsRemaining(prevRoll.GuessedOn.AddDays(1)))); + DateLocalization.FormatDateTimeAsRemaining(prevRoll.GuessedOn.AddDays(1)))); return; } - _kvInMemoryStore.Set(kvKey, new RollTimeout { LastGuess = guess, GuessedOn = DateTime.Now }); + _kvInMemoryStore.Set(kvKey, new RollTimeout {LastGuess = guess, GuessedOn = DateTime.Now}); await ReplyAsync(string.Format(Localization.Roll.Rolled, Context.Message.Author.Mention, number, guess)); if (guess == number) @@ -72,13 +73,13 @@ namespace Geekbot.Bot.Commands.Games.Roll await ErrorHandler.HandleCommandException(e, Context); } } - + private async Task GetUser(ulong userId) { - var user = _database.Rolls.FirstOrDefault(u =>u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId); + var user = _database.Rolls.FirstOrDefault(u => u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId); return user; } - + private async Task CreateNewRow(ulong userId) { var user = new RollsModel() diff --git a/src/Bot/Commands/Randomness/Ship.cs b/src/Bot/Commands/Randomness/Ship.cs index 78f3c99..f48713e 100644 --- a/src/Bot/Commands/Randomness/Ship.cs +++ b/src/Bot/Commands/Randomness/Ship.cs @@ -8,7 +8,7 @@ using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.RandomNumberGenerator; namespace Geekbot.Bot.Commands.Randomness @@ -18,7 +18,7 @@ namespace Geekbot.Bot.Commands.Randomness private readonly IRandomNumberGenerator _randomNumberGenerator; private readonly DatabaseContext _database; - public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translations) : base(errorHandler, translations) + public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _database = database; _randomNumberGenerator = randomNumberGenerator; diff --git a/src/Bot/Commands/Rpg/Cookies.cs b/src/Bot/Commands/Rpg/Cookies.cs index 570f08a..a51d652 100644 --- a/src/Bot/Commands/Rpg/Cookies.cs +++ b/src/Bot/Commands/Rpg/Cookies.cs @@ -3,13 +3,14 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Bot.Utils; using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.RandomNumberGenerator; namespace Geekbot.Bot.Commands.Rpg @@ -22,7 +23,8 @@ namespace Geekbot.Bot.Commands.Rpg private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; - public Cookies(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translations , IRandomNumberGenerator randomNumberGenerator) : base(errorHandler, translations) + public Cookies(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager) + : base(errorHandler, guildSettingsManager) { _database = database; _randomNumberGenerator = randomNumberGenerator; @@ -34,12 +36,11 @@ namespace Geekbot.Bot.Commands.Rpg { try { - var transContext = await Translations.GetGuildContext(Context); var actor = await GetUser(Context.User.Id); if (actor.LastPayout.Value.AddDays(1).Date > DateTime.Now.Date) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(DateTimeOffset.Now.AddDays(1).Date); - await ReplyAsync(string.Format(Localization.Cookies.WaitForMoreCookies, formatedWaitTime)); + var formattedWaitTime = DateLocalization.FormatDateTimeAsRemaining(DateTimeOffset.Now.AddDays(1).Date); + await ReplyAsync(string.Format(Localization.Cookies.WaitForMoreCookies, formattedWaitTime)); return; } actor.Cookies += 10; diff --git a/src/Bot/Commands/User/Karma.cs b/src/Bot/Commands/User/Karma.cs index 41a401c..4778bce 100644 --- a/src/Bot/Commands/User/Karma.cs +++ b/src/Bot/Commands/User/Karma.cs @@ -1,17 +1,16 @@ using System; -using System.Globalization; using System.Linq; -using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Bot.Utils; using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; namespace Geekbot.Bot.Commands.User { @@ -19,12 +18,10 @@ namespace Geekbot.Bot.Commands.User public class Karma : GeekbotCommandBase { private readonly DatabaseContext _database; - private readonly ITranslationHandler _translations; - public Karma(DatabaseContext database, IErrorHandler errorHandler, ITranslationHandler translations) : base(errorHandler, translations) + public Karma(DatabaseContext database, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _database = database; - _translations = translations; } [Command("good", RunMode = RunMode.Async)] @@ -33,8 +30,6 @@ namespace Geekbot.Bot.Commands.User { try { - var transContext = await _translations.GetGuildContext(Context); - var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { @@ -42,7 +37,7 @@ namespace Geekbot.Bot.Commands.User } else if (TimeoutFinished(actor.TimeOut)) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); + var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); } else @@ -81,8 +76,6 @@ namespace Geekbot.Bot.Commands.User { try { - var transContext = await _translations.GetGuildContext(Context); - var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { @@ -90,7 +83,7 @@ namespace Geekbot.Bot.Commands.User } else if (TimeoutFinished(actor.TimeOut)) { - var formatedWaitTime = transContext.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); + var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); } else diff --git a/src/Bot/Commands/User/Ranking/Rank.cs b/src/Bot/Commands/User/Ranking/Rank.cs index d73aacc..20749a8 100644 --- a/src/Bot/Commands/User/Ranking/Rank.cs +++ b/src/Bot/Commands/User/Ranking/Rank.cs @@ -10,8 +10,8 @@ using Geekbot.Core.Converters; using Geekbot.Core.Database; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Highscores; -using Geekbot.Core.Localization; namespace Geekbot.Bot.Commands.User.Ranking { @@ -21,7 +21,8 @@ namespace Geekbot.Bot.Commands.User.Ranking private readonly IHighscoreManager _highscoreManager; private readonly DatabaseContext _database; - public Rank(DatabaseContext database, IErrorHandler errorHandler, IEmojiConverter emojiConverter, IHighscoreManager highscoreManager, ITranslationHandler translations): base(errorHandler, translations) + public Rank(DatabaseContext database, IErrorHandler errorHandler, IEmojiConverter emojiConverter, IHighscoreManager highscoreManager, IGuildSettingsManager guildSettingsManager) + : base(errorHandler, guildSettingsManager) { _database = database; _emojiConverter = emojiConverter; @@ -53,7 +54,7 @@ namespace Geekbot.Bot.Commands.User.Ranking await ReplyAsync(Localization.Rank.LimitingTo20Warning); amount = 20; } - + var guildId = Context.Guild.Id; Dictionary highscoreUsers; try @@ -78,9 +79,9 @@ namespace Geekbot.Bot.Commands.User.Ranking var failedToRetrieveUser = highscoreUsers.Any(e => string.IsNullOrEmpty(e.Key.Username)); if (failedToRetrieveUser) replyBuilder.AppendLine(Localization.Rank.FailedToResolveAllUsernames).AppendLine(); - + replyBuilder.AppendLine(string.Format(Localization.Rank.HighscoresFor, type.ToString().CapitalizeFirst(), Context.Guild.Name)); - + var highscorePlace = 1; foreach (var (user, value) in highscoreUsers) { @@ -91,7 +92,7 @@ namespace Geekbot.Bot.Commands.User.Ranking replyBuilder.Append(user.Username != null ? $"**{user.Username}#{user.Discriminator}**" : $"**{user.Id}**"); - + replyBuilder.Append(type == HighscoreTypes.messages ? $" - {value} {type} - {Math.Round((double) (100 * value) / guildMessages, 2)}%\n" : $" - {value} {type}\n"); diff --git a/src/Bot/Commands/Utils/Choose.cs b/src/Bot/Commands/Utils/Choose.cs index ea239d7..731bee6 100644 --- a/src/Bot/Commands/Utils/Choose.cs +++ b/src/Bot/Commands/Utils/Choose.cs @@ -3,13 +3,13 @@ using System.Threading.Tasks; using Discord.Commands; using Geekbot.Core; using Geekbot.Core.ErrorHandling; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; namespace Geekbot.Bot.Commands.Utils { public class Choose : GeekbotCommandBase { - public Choose(IErrorHandler errorHandler, ITranslationHandler translation) : base(errorHandler, translation) + public Choose(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { } diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 5bb23a9..a7d3ff1 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -9,7 +9,7 @@ using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Polyfills; using Geekbot.Core.RandomNumberGenerator; @@ -23,7 +23,8 @@ namespace Geekbot.Bot.Commands.Utils.Quote private readonly IRandomNumberGenerator _randomNumberGenerator; private readonly bool _isDev; - public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, ITranslationHandler translationHandler) : base(errorHandler, translationHandler) + public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager) + : base(errorHandler, guildSettingsManager) { _database = database; _randomNumberGenerator = randomNumberGenerator; diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 04b1450..5a4b456 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -17,7 +17,6 @@ using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Highscores; using Geekbot.Core.KvInMemoryStore; using Geekbot.Core.Levels; -using Geekbot.Core.Localization; using Geekbot.Core.Logger; using Geekbot.Core.MalClient; using Geekbot.Core.Media; @@ -168,8 +167,7 @@ namespace Geekbot.Bot var randomNumberGenerator = new RandomNumberGenerator(); var mediaProvider = new MediaProvider(_logger, randomNumberGenerator); var kvMemoryStore = new KvInInMemoryStore(); - var translationHandler = new TranslationHandler(_logger, _guildSettingsManager); - var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters); + var errorHandler = new ErrorHandler(_logger, _runParameters, () => Localization.Internal.SomethingWentWrong); var diceParser = new DiceParser(randomNumberGenerator); services.AddSingleton(_userRepository); @@ -186,7 +184,6 @@ namespace Geekbot.Bot services.AddSingleton(_globalSettings); services.AddSingleton(errorHandler); services.AddSingleton(diceParser); - services.AddSingleton(translationHandler); services.AddSingleton(_reactionListener); services.AddSingleton(_guildSettingsManager); services.AddSingleton(_client); diff --git a/src/Bot/Utils/DateLocalization.cs b/src/Bot/Utils/DateLocalization.cs new file mode 100644 index 0000000..eea40fb --- /dev/null +++ b/src/Bot/Utils/DateLocalization.cs @@ -0,0 +1,49 @@ +using System; +using System.Text; + +namespace Geekbot.Bot.Utils +{ + public class DateLocalization + { + public static string FormatDateTimeAsRemaining(DateTimeOffset dateTime) + { + var remaining = dateTime - DateTimeOffset.Now; + const string formattable = "{0} {1}"; + var sb = new StringBuilder(); + + if (remaining.Days > 0) + { + sb.AppendFormat(formattable, remaining.Days, GetSingularOrPlural(remaining.Days, Localization.Internal.Days)); + } + + if (remaining.Hours > 0) + { + if (sb.Length > 0) sb.Append(", "); + sb.AppendFormat(formattable, remaining.Hours, GetSingularOrPlural(remaining.Hours, Localization.Internal.Hours)); + } + + if (remaining.Minutes > 0) + { + if (sb.Length > 0) sb.Append(", "); + sb.AppendFormat(formattable, remaining.Minutes, GetSingularOrPlural(remaining.Minutes, Localization.Internal.Minutes)); + } + + if (remaining.Seconds > 0) + { + if (sb.Length > 0) + { + sb.AppendFormat(" {0} ", Localization.Internal.And); + } + sb.AppendFormat(formattable, remaining.Seconds, GetSingularOrPlural(remaining.Seconds, Localization.Internal.Seconds)); + } + + return sb.ToString().Trim(); + } + + private static string GetSingularOrPlural(int number, string rawString) + { + var versions = rawString.Split('|'); + return number == 1 ? versions[0] : versions[1]; + } + } +} \ No newline at end of file diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index fcbce09..fd44a95 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -31,10 +31,4 @@ - - - PreserveNewest - - - diff --git a/src/Core/ErrorHandling/ErrorHandler.cs b/src/Core/ErrorHandling/ErrorHandler.cs index 02402f2..47ed22d 100644 --- a/src/Core/ErrorHandling/ErrorHandler.cs +++ b/src/Core/ErrorHandling/ErrorHandler.cs @@ -1,9 +1,6 @@ using System; -using System.Net; using System.Threading.Tasks; using Discord.Commands; -using Discord.Net; -using Geekbot.Core.Localization; using Geekbot.Core.Logger; using SharpRaven; using SharpRaven.Data; @@ -14,14 +11,14 @@ namespace Geekbot.Core.ErrorHandling public class ErrorHandler : IErrorHandler { private readonly IGeekbotLogger _logger; - private readonly ITranslationHandler _translation; + private readonly Func _getDefaultErrorText; private readonly IRavenClient _raven; private readonly bool _errorsInChat; - public ErrorHandler(IGeekbotLogger logger, ITranslationHandler translation, RunParameters runParameters) + public ErrorHandler(IGeekbotLogger logger, RunParameters runParameters, Func getDefaultErrorText) { _logger = logger; - _translation = translation; + _getDefaultErrorText = getDefaultErrorText; _errorsInChat = runParameters.ExposeErrors; var sentryDsn = runParameters.SentryEndpoint; @@ -40,7 +37,9 @@ namespace Geekbot.Core.ErrorHandling { try { - var errorString = errorMessage == "def" ? await _translation.GetString(context.Guild?.Id ?? 0, "errorHandler", "SomethingWentWrong") : errorMessage; + var errorString = errorMessage == "def" + ? _getDefaultErrorText() + : errorMessage; var errorObj = SimpleConextConverter.ConvertContext(context); if (e.Message.Contains("50007")) return; if (e.Message.Contains("50013")) return; @@ -76,17 +75,6 @@ namespace Geekbot.Core.ErrorHandling } } - public async Task HandleHttpException(HttpException e, ICommandContext context) - { - var errorStrings = await _translation.GetDict(context, "httpErrors"); - switch(e.HttpCode) - { - case HttpStatusCode.Forbidden: - await context.Channel.SendMessageAsync(errorStrings["403"]); - break; - } - } - private void ReportExternal(Exception e, MessageDto errorObj) { if (_raven == null) return; diff --git a/src/Core/ErrorHandling/IErrorHandler.cs b/src/Core/ErrorHandling/IErrorHandler.cs index c012b82..d0e1d20 100644 --- a/src/Core/ErrorHandling/IErrorHandler.cs +++ b/src/Core/ErrorHandling/IErrorHandler.cs @@ -1,13 +1,11 @@ using System; using System.Threading.Tasks; using Discord.Commands; -using Discord.Net; namespace Geekbot.Core.ErrorHandling { public interface IErrorHandler { Task HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def"); - Task HandleHttpException(HttpException e, ICommandContext context); } } \ No newline at end of file diff --git a/src/Core/GeekbotCommandBase.cs b/src/Core/GeekbotCommandBase.cs index 8df5265..43ced95 100644 --- a/src/Core/GeekbotCommandBase.cs +++ b/src/Core/GeekbotCommandBase.cs @@ -1,26 +1,29 @@ using System.Globalization; using System.Threading; using Discord.Commands; +using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; -using Geekbot.Core.Localization; +using Geekbot.Core.GuildSettingsManager; namespace Geekbot.Core { public class GeekbotCommandBase : ModuleBase { + protected readonly IGuildSettingsManager GuildSettingsManager; + protected GuildSettingsModel GuildSettings; protected readonly IErrorHandler ErrorHandler; - protected readonly ITranslationHandler Translations; - protected GeekbotCommandBase(IErrorHandler errorHandler, ITranslationHandler translations) + protected GeekbotCommandBase(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) { + GuildSettingsManager = guildSettingsManager; ErrorHandler = errorHandler; - Translations = translations; } protected override void BeforeExecute(CommandInfo command) { base.BeforeExecute(command); - var language = Translations.GetServerLanguage(Context.Guild.Id); + GuildSettings = GuildSettingsManager.GetSettings(Context?.Guild?.Id ?? 0); + var language = GuildSettings.Language; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language == "CHDE" ? "de-ch" : language); } } diff --git a/src/Core/Localization/ITranslationHandler.cs b/src/Core/Localization/ITranslationHandler.cs deleted file mode 100644 index 1cc06fa..0000000 --- a/src/Core/Localization/ITranslationHandler.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Discord.Commands; - -namespace Geekbot.Core.Localization -{ - public interface ITranslationHandler - { - Task GetString(ulong guildId, string command, string stringName); - string GetString(string language, string command, string stringName); - Task> GetDict(ICommandContext context, string command); - Task GetGuildContext(ICommandContext context); - Task SetLanguage(ulong guildId, string language); - List SupportedLanguages { get; } - string GetServerLanguage(ulong guildId); - } -} \ No newline at end of file diff --git a/src/Core/Localization/TranslationGuildContext.cs b/src/Core/Localization/TranslationGuildContext.cs deleted file mode 100644 index 25685da..0000000 --- a/src/Core/Localization/TranslationGuildContext.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Geekbot.Core.Localization -{ - public class TranslationGuildContext - { - public ITranslationHandler TranslationHandler { get; } - public string Language { get; } - public Dictionary Dict { get; } - - public TranslationGuildContext(ITranslationHandler translationHandler, string language, Dictionary dict) - { - TranslationHandler = translationHandler; - Language = language; - Dict = dict; - } - - public string GetString(string stringToFormat, params object[] args) - { - return string.Format(Dict[stringToFormat] ?? "", args); - } - - public string FormatDateTimeAsRemaining(DateTimeOffset dateTime) - { - var remaining = dateTime - DateTimeOffset.Now; - const string formattable = "{0} {1}"; - var sb = new StringBuilder(); - - if (remaining.Days > 0) - { - var s = GetTimeString(TimeTypes.Days); - sb.AppendFormat(formattable, remaining.Days, GetSingOrPlur(remaining.Days, s)); - } - - if (remaining.Hours > 0) - { - if (sb.Length > 0) sb.Append(", "); - var s = GetTimeString(TimeTypes.Hours); - sb.AppendFormat(formattable, remaining.Hours, GetSingOrPlur(remaining.Hours, s)); - } - - if (remaining.Minutes > 0) - { - if (sb.Length > 0) sb.Append(", "); - var s = GetTimeString(TimeTypes.Minutes); - sb.AppendFormat(formattable, remaining.Minutes, GetSingOrPlur(remaining.Minutes, s)); - } - - if (remaining.Seconds > 0) - { - if (sb.Length > 0) - { - var and = TranslationHandler.GetString(Language, "dateTime", "And"); - sb.AppendFormat(" {0} ", and); - } - var s = GetTimeString(TimeTypes.Seconds); - sb.AppendFormat(formattable, remaining.Seconds, GetSingOrPlur(remaining.Seconds, s)); - } - - return sb.ToString().Trim(); - } - - public Task SetLanguage(ulong guildId, string language) - { - return TranslationHandler.SetLanguage(guildId, language); - } - - private string GetTimeString(TimeTypes type) - { - return TranslationHandler.GetString(Language, "dateTime", type.ToString()); - } - - private string GetSingOrPlur(int number, string rawString) - { - var versions = rawString.Split('|'); - return number == 1 ? versions[0] : versions[1]; - } - - private enum TimeTypes - { - Days, - Hours, - Minutes, - Seconds - } - } -} \ No newline at end of file diff --git a/src/Core/Localization/TranslationHandler.cs b/src/Core/Localization/TranslationHandler.cs deleted file mode 100644 index 1a46ada..0000000 --- a/src/Core/Localization/TranslationHandler.cs +++ /dev/null @@ -1,194 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Discord.Commands; -using Geekbot.Core.GuildSettingsManager; -using Geekbot.Core.Logger; -using YamlDotNet.Core; -using YamlDotNet.Serialization; - -namespace Geekbot.Core.Localization -{ - public class TranslationHandler : ITranslationHandler - { - private readonly IGeekbotLogger _logger; - private readonly IGuildSettingsManager _guildSettingsManager; - private readonly Dictionary _serverLanguages; - private Dictionary>> _translations; - - public TranslationHandler(IGeekbotLogger logger, IGuildSettingsManager guildSettingsManager) - { - _logger = logger; - _guildSettingsManager = guildSettingsManager; - _logger.Information(LogSource.Geekbot, "Loading Translations"); - LoadTranslations(); - _serverLanguages = new Dictionary(); - } - - private void LoadTranslations() - { - try - { - // Read the file - var translationFile = File.ReadAllText(Path.GetFullPath("./Localization/Translations.yml")); - - // Deserialize - var input = new StringReader(translationFile); - var mergingParser = new MergingParser(new Parser(input)); - var deserializer = new DeserializerBuilder().Build(); - var rawTranslations = deserializer.Deserialize>>>(mergingParser); - - // Sort - var sortedPerLanguage = new Dictionary>>(); - foreach (var command in rawTranslations) - { - foreach (var str in command.Value) - { - foreach (var lang in str.Value) - { - if (!sortedPerLanguage.ContainsKey(lang.Key)) - { - var commandDict = new Dictionary>(); - var strDict = new Dictionary - { - {str.Key, lang.Value} - }; - commandDict.Add(command.Key, strDict); - sortedPerLanguage.Add(lang.Key, commandDict); - } - if (!sortedPerLanguage[lang.Key].ContainsKey(command.Key)) - { - var strDict = new Dictionary - { - {str.Key, lang.Value} - }; - sortedPerLanguage[lang.Key].Add(command.Key, strDict); - } - if (!sortedPerLanguage[lang.Key][command.Key].ContainsKey(str.Key)) - { - sortedPerLanguage[lang.Key][command.Key].Add(str.Key, lang.Value); - } - } - } - } - _translations = sortedPerLanguage; - - // Find Languages - SupportedLanguages = new List(); - foreach (var lang in sortedPerLanguage) - { - SupportedLanguages.Add(lang.Key); - } - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Failed to load Translations", e); - Environment.Exit(GeekbotExitCode.TranslationsFailed.GetHashCode()); - } - } - - public string GetServerLanguage(ulong guildId) - { - try - { - string lang; - try - { - lang = _serverLanguages[guildId]; - if (!string.IsNullOrEmpty(lang)) - { - return lang; - } - throw new Exception(); - } - catch - { - lang = _guildSettingsManager.GetSettings(guildId, false)?.Language ?? "EN"; - _serverLanguages[guildId] = lang; - return lang; - } - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Could not get guild language", e); - return "EN"; - } - } - - public async Task GetString(ulong guildId, string command, string stringName) - { - var serverLang = GetServerLanguage(guildId); - return GetString(serverLang, command, stringName); - } - - public string GetString(string language, string command, string stringName) - { - var translation = _translations[language][command][stringName]; - if (!string.IsNullOrWhiteSpace(translation)) return translation; - translation = _translations[command][stringName]["EN"]; - if (string.IsNullOrWhiteSpace(translation)) - { - _logger.Warning(LogSource.Geekbot, $"No translation found for {command} - {stringName}"); - } - return translation; - } - - private async Task> GetDict(ICommandContext context) - { - try - { - var command = context.Message.Content.Split(' ').First().TrimStart('!').ToLower(); - var serverLanguage = GetServerLanguage(context.Guild?.Id ?? 0); - return _translations[serverLanguage][command]; - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "No translations for command found", e); - return new Dictionary(); - } - } - - public async Task GetGuildContext(ICommandContext context) - { - var dict = await GetDict(context); - var language = GetServerLanguage(context.Guild?.Id ?? 0); - return new TranslationGuildContext(this, language, dict); - } - - public async Task> GetDict(ICommandContext context, string command) - { - try - { - var serverLanguage = GetServerLanguage(context.Guild?.Id ?? 0); - return _translations[serverLanguage][command]; - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "No translations for command found", e); - return new Dictionary(); - } - } - - public async Task SetLanguage(ulong guildId, string language) - { - try - { - if (!SupportedLanguages.Contains(language)) return false; - var guild = _guildSettingsManager.GetSettings(guildId); - guild.Language = language; - await _guildSettingsManager.UpdateSettings(guild); - _serverLanguages[guildId] = language; - return true; - } - catch (Exception e) - { - _logger.Error(LogSource.Geekbot, "Error while changing language", e); - return false; - } - } - - public List SupportedLanguages { get; private set; } - } -} \ No newline at end of file diff --git a/src/Core/Localization/Translations.yml b/src/Core/Localization/Translations.yml deleted file mode 100644 index dc18c2b..0000000 --- a/src/Core/Localization/Translations.yml +++ /dev/null @@ -1,25 +0,0 @@ ---- -dateTime: - Days: - EN: "day|days" - CHDE: "tag|täg" - Hours: - EN: "hour|hours" - CHDE: "stund|stunde" - Minutes: - EN: "minute|minutes" - CHDE: "minute|minute" - Seconds: - EN: "second|seconds" - CHDE: "sekunde|sekunde" - And: - EN: "and" - CHDE: "und" -errorHandler: - SomethingWentWrong: - EN: "Something went wrong :confused:" - CHDE: "Öppis isch schief gange :confused:" -httpErrors: - 403: - EN: "Seems like i don't have enough permission to that :confused:" - CHDE: "Gseht danach us das ich nid gnueg recht han zum das mache :confused:" \ No newline at end of file diff --git a/tests/Core/Localization/TranslationGuildContext.test.cs b/tests/Core/Localization/TranslationGuildContext.test.cs deleted file mode 100644 index 4aaca16..0000000 --- a/tests/Core/Localization/TranslationGuildContext.test.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using Geekbot.Core.Localization; -using Moq; -using Xunit; - -namespace Tests.Core.Localization -{ - public class TranslationGuildContext_test - { - public class FormatDateTimeAsRemainingTestDto - { - public DateTimeOffset DateTime { get; set; } - public string Expected { get; set; } - } - - public static TestData FormatDateTimeAsRemainingData => - new TestData - { - { - "Wait for days", - new FormatDateTimeAsRemainingTestDto - { - DateTime = DateTimeOffset.Now.AddDays(5), - Expected = "4 days, 23 hours, 59 minutes and 59 seconds" - } - }, - { - "Wait for minutes", - new FormatDateTimeAsRemainingTestDto - { - DateTime = DateTimeOffset.Now.AddMinutes(5), - Expected = "4 minutes and 59 seconds" - } - }, - { - "Wait for seconds", - new FormatDateTimeAsRemainingTestDto - { - DateTime = DateTimeOffset.Now.AddSeconds(5), - Expected = "4 seconds" - } - } - }; - - [Theory, MemberData(nameof(FormatDateTimeAsRemainingData))] - public void FormatDateTimeAsRemaining(string testName, FormatDateTimeAsRemainingTestDto testData) - { - var translationHandlerMock = new Mock(MockBehavior.Loose); - translationHandlerMock - .Setup(thm => thm.GetString("EN", "dateTime", "Days")) - .Returns("day|days"); - translationHandlerMock - .Setup(thm => thm.GetString("EN", "dateTime", "Hours")) - .Returns("hour|hours"); - translationHandlerMock - .Setup(thm => thm.GetString("EN", "dateTime", "Minutes")) - .Returns("minute|minutes"); - translationHandlerMock - .Setup(thm => thm.GetString("EN", "dateTime", "Seconds")) - .Returns("second|seconds"); - translationHandlerMock - .Setup(thm => thm.GetString("EN", "dateTime", "And")) - .Returns("and"); - - var context = new TranslationGuildContext(translationHandlerMock.Object, "EN", new Dictionary()); - var result = context.FormatDateTimeAsRemaining(testData.DateTime); - Assert.Equal(result, testData.Expected); - } - } -} \ No newline at end of file diff --git a/tests/Core/Localization/Translations.test.cs b/tests/Core/Localization/Translations.test.cs deleted file mode 100644 index d8a0879..0000000 --- a/tests/Core/Localization/Translations.test.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using FluentAssertions; -using Xunit; -using YamlDotNet.Core; -using YamlDotNet.Serialization; - -namespace Tests.Core.Localization -{ - public class Translations_test - { - [Fact] - public void TranslationsYamlIsValid() - { - // Read the file - var translationFile = File.ReadAllText(Path.GetFullPath("./../../../../src/Core/Localization/Translations.yml")); - - // Deserialize - var input = new StringReader(translationFile); - var mergingParser = new MergingParser(new Parser(input)); - var deserializer = new DeserializerBuilder().Build(); - var rawTranslations = deserializer.Deserialize>>>(mergingParser); - - // These languages must be supported - var supportedLanguages = new List - { - "EN", - "CHDE" - }; - - // Iterate every single key to make sure it's populated - foreach (var command in rawTranslations) - { - foreach (var str in command.Value) - { - str.Value.Select(e => e.Key).ToList().Should().BeEquivalentTo(supportedLanguages, str.Key); - foreach (var lang in str.Value) - { - lang.Value.Should().NotBeNullOrEmpty($"{command.Key} / {str.Key} / {lang.Key}"); - } - } - } - } - } -} \ No newline at end of file From 60e36daaec4a587e48d716e307c9652d7b064723 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 14 Aug 2020 23:34:02 +0200 Subject: [PATCH 094/264] Translate !stats --- src/Bot/Bot.csproj | 9 ++ src/Bot/Commands/User/Stats.cs | 26 ++--- src/Bot/Localization/Stats.Designer.cs | 135 +++++++++++++++++++++++++ src/Bot/Localization/Stats.de-ch.resx | 38 +++++++ src/Bot/Localization/Stats.resx | 45 +++++++++ 5 files changed, 240 insertions(+), 13 deletions(-) create mode 100644 src/Bot/Localization/Stats.Designer.cs create mode 100644 src/Bot/Localization/Stats.de-ch.resx create mode 100644 src/Bot/Localization/Stats.resx diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 2d3cd2f..49f0b16 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -81,6 +81,10 @@ ResXFileCodeGenerator Role.Designer.cs + + ResXFileCodeGenerator + Stats.Designer.cs + @@ -136,5 +140,10 @@ True Role.resx + + True + True + Stats.resx + diff --git a/src/Bot/Commands/User/Stats.cs b/src/Bot/Commands/User/Stats.cs index 70f6247..a2a54a2 100644 --- a/src/Bot/Commands/User/Stats.cs +++ b/src/Bot/Commands/User/Stats.cs @@ -3,24 +3,24 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Levels; namespace Geekbot.Bot.Commands.User { - public class Stats : ModuleBase + public class Stats : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly ILevelCalc _levelCalc; private readonly DatabaseContext _database; - public Stats(DatabaseContext database, IErrorHandler errorHandler, ILevelCalc levelCalc) + public Stats(DatabaseContext database, IErrorHandler errorHandler, ILevelCalc levelCalc, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _database = database; - _errorHandler = errorHandler; _levelCalc = levelCalc; } @@ -67,23 +67,23 @@ namespace Geekbot.Bot.Commands.User e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.UserId.Equals(userInfo.Id.AsLong())); - eb.AddInlineField("Discordian Since", + eb.AddInlineField(Localization.Stats.OnDiscordSince, $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)") - .AddInlineField("Joined Server", + .AddInlineField(Localization.Stats.JoinedServer, $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)") - .AddInlineField("Karma", karma?.Karma ?? 0) - .AddInlineField("Level", level) - .AddInlineField("Messages Sent", messages) - .AddInlineField("Server Total", $"{percent}%"); + .AddInlineField(Localization.Stats.Karma, karma?.Karma ?? 0) + .AddInlineField(Localization.Stats.Level, level) + .AddInlineField(Localization.Stats.MessagesSent, messages) + .AddInlineField(Localization.Stats.ServerTotal, $"{percent}%"); - if (correctRolls != null) eb.AddInlineField("Guessed Rolls", correctRolls.Rolls); - if (cookies > 0) eb.AddInlineField("Cookies", cookies); + if (correctRolls != null) eb.AddInlineField(Localization.Stats.GuessedRolls, correctRolls.Rolls); + if (cookies > 0) eb.AddInlineField(Localization.Stats.Cookies, cookies); await ReplyAsync("", false, eb.Build()); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } } diff --git a/src/Bot/Localization/Stats.Designer.cs b/src/Bot/Localization/Stats.Designer.cs new file mode 100644 index 0000000..d05f937 --- /dev/null +++ b/src/Bot/Localization/Stats.Designer.cs @@ -0,0 +1,135 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Stats { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Stats() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Stats", typeof(Stats).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Cookies. + /// + internal static string Cookies { + get { + return ResourceManager.GetString("Cookies", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Guessed Rolls. + /// + internal static string GuessedRolls { + get { + return ResourceManager.GetString("GuessedRolls", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Joined Server. + /// + internal static string JoinedServer { + get { + return ResourceManager.GetString("JoinedServer", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Karma. + /// + internal static string Karma { + get { + return ResourceManager.GetString("Karma", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Level. + /// + internal static string Level { + get { + return ResourceManager.GetString("Level", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Messages Sent. + /// + internal static string MessagesSent { + get { + return ResourceManager.GetString("MessagesSent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to On Discord Since. + /// + internal static string OnDiscordSince { + get { + return ResourceManager.GetString("OnDiscordSince", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Server Total. + /// + internal static string ServerTotal { + get { + return ResourceManager.GetString("ServerTotal", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Stats.de-ch.resx b/src/Bot/Localization/Stats.de-ch.resx new file mode 100644 index 0000000..ab44a2e --- /dev/null +++ b/src/Bot/Localization/Stats.de-ch.resx @@ -0,0 +1,38 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Server Total + + + Uf Discord siit + + + Nachrichte versendet + + + Level + + + Karma + + + Server Bitrette + + + Grateni Rolls + + + Guetzli + + \ No newline at end of file diff --git a/src/Bot/Localization/Stats.resx b/src/Bot/Localization/Stats.resx new file mode 100644 index 0000000..3b8303a --- /dev/null +++ b/src/Bot/Localization/Stats.resx @@ -0,0 +1,45 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + On Discord Since + + + Joined Server + + + Karma + + + Level + + + Messages Sent + + + Server Total + + + Guessed Rolls + + + Cookies + + \ No newline at end of file From a78e92d230acbb90322bc572a603ce57f122d79d Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 15 Aug 2020 00:40:59 +0200 Subject: [PATCH 095/264] Remove YamlDotNet --- src/Core/Core.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index fd44a95..7f278cf 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -28,7 +28,6 @@ - From 3c4a5c638b887833c6414170c0e2455ea365d838 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 26 Aug 2020 23:15:57 +0200 Subject: [PATCH 096/264] Upgrade Microsoft.Extensions.* to .NET5 preview 8 --- src/Core/Core.csproj | 6 +++--- tests/Tests.csproj | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 7f278cf..28729a7 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -18,9 +18,9 @@ - - - + + + diff --git a/tests/Tests.csproj b/tests/Tests.csproj index b8d1fc4..75a5f9c 100644 --- a/tests/Tests.csproj +++ b/tests/Tests.csproj @@ -12,7 +12,6 @@ - From 546b5450e7d10b325461bf7cfea1d750de5c2270 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 26 Aug 2020 23:28:03 +0200 Subject: [PATCH 097/264] Deal with MTG Gatherer downtime --- src/Bot/Commands/Integrations/MagicTheGathering.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Integrations/MagicTheGathering.cs b/src/Bot/Commands/Integrations/MagicTheGathering.cs index 66a87fe..b179d6e 100644 --- a/src/Bot/Commands/Integrations/MagicTheGathering.cs +++ b/src/Bot/Commands/Integrations/MagicTheGathering.cs @@ -28,7 +28,7 @@ namespace Geekbot.Bot.Commands.Integrations { try { - var message = await Context.Channel.SendMessageAsync($":mag: Looking up\"{cardName}\", please wait..."); + var message = await Context.Channel.SendMessageAsync($":mag: Looking up \"{cardName}\", please wait..."); var service = new CardService(); var result = service @@ -36,7 +36,15 @@ namespace Geekbot.Bot.Commands.Integrations // fewer cards less risk of deserialization problems, don't need more than one anyways... .Where(x => x.PageSize, 1); - var card = result.All().Value.FirstOrDefault(); + var cards = await result.AllAsync(); + if (!cards.IsSuccess) + { + await message.ModifyAsync(properties => properties.Content = $":warning: The Gatherer reacted in an unexpected way: {cards.Exception.Message}"); + return; + } + + var card = cards.Value.FirstOrDefault(); + if (card == null) { await message.ModifyAsync(properties => properties.Content = ":red_circle: I couldn't find a card with that name..."); From 8246c7a862128f7161aa798eac26fe6716db9ae8 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 31 Aug 2020 18:46:00 +0200 Subject: [PATCH 098/264] When json logging is enabled, log it to the console without color or additional timestamp, also log the messages with the correct log level. Remove the logs folder. --- src/Bot/Logs/.keep | 0 src/Core/Logger/GeekbotLogger.cs | 49 ++++++++++---------------------- src/Core/Logger/LoggerFactory.cs | 44 ++++++++++++++-------------- 3 files changed, 36 insertions(+), 57 deletions(-) delete mode 100644 src/Bot/Logs/.keep diff --git a/src/Bot/Logs/.keep b/src/Bot/Logs/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Core/Logger/GeekbotLogger.cs b/src/Core/Logger/GeekbotLogger.cs index 8d4a8eb..652faef 100644 --- a/src/Core/Logger/GeekbotLogger.cs +++ b/src/Core/Logger/GeekbotLogger.cs @@ -20,44 +20,25 @@ namespace Geekbot.Core.Logger }; Information(LogSource.Geekbot, "Using GeekbotLogger"); } - + public void Trace(LogSource source, string message, object extra = null) - { - _logger.Trace(CreateLogString("Trace", source, message, null, extra)); - } - + => _logger.Trace(CreateLogString("Trace", source, message, null, extra)); + public void Debug(LogSource source, string message, object extra = null) - { - if (_logAsJson) _logger.Info(CreateLogString("Debug", source, message, null, extra)); - else _logger.Debug(CreateLogString("Debug", source, message, null, extra)); - } - + => _logger.Debug(CreateLogString("Debug", source, message, null, extra)); + public void Information(LogSource source, string message, object extra = null) - { - _logger.Info(CreateLogString("Information", source, message, null, extra)); - } - + => _logger.Info(CreateLogString("Information", source, message, null, extra)); + public void Warning(LogSource source, string message, Exception stackTrace = null, object extra = null) - { - if (_logAsJson) _logger.Info(CreateLogString("Warning", source, message, stackTrace, extra)); - else _logger.Warn(CreateLogString("Warning", source, message, stackTrace, extra)); - } - + => _logger.Warn(CreateLogString("Warning", source, message, stackTrace, extra)); + public void Error(LogSource source, string message, Exception stackTrace, object extra = null) - { - if (_logAsJson) _logger.Info(CreateLogString("Error", source, message, stackTrace, extra)); - else _logger.Error(stackTrace, CreateLogString("Error", source, message, stackTrace, extra)); - } + => _logger.Error(stackTrace, CreateLogString("Error", source, message, stackTrace, extra)); - public NLog.Logger GetNLogger() - { - return _logger; - } + public NLog.Logger GetNLogger() => _logger; - public bool LogAsJson() - { - return _logAsJson; - } + public bool LogAsJson() => _logAsJson; private string CreateLogString(string type, LogSource source, string message, Exception stackTrace = null, object extra = null) { @@ -74,10 +55,10 @@ namespace Geekbot.Core.Logger }; return JsonConvert.SerializeObject(logObject, Formatting.None, _serializerSettings); } - + if (source != LogSource.Message) return $"[{source}] - {message}"; - - var m = (MessageDto) extra; + + var m = (MessageDto) extra; return $"[{source}] - [{m?.Guild.Name} - {m?.Channel.Name}] {m?.User.Name}: {m?.Message.Content}"; } } diff --git a/src/Core/Logger/LoggerFactory.cs b/src/Core/Logger/LoggerFactory.cs index bc129fc..bf3d926 100644 --- a/src/Core/Logger/LoggerFactory.cs +++ b/src/Core/Logger/LoggerFactory.cs @@ -12,12 +12,13 @@ namespace Geekbot.Core.Logger public static NLog.Logger CreateNLog(RunParameters runParameters) { var config = new LoggingConfiguration(); + var minLevel = runParameters.Verbose ? LogLevel.Trace : LogLevel.Info; if (!string.IsNullOrEmpty(runParameters.SumologicEndpoint)) { Console.WriteLine("Logging Geekbot Logs to Sumologic"); config.LoggingRules.Add( - new LoggingRule("*", LogLevel.Debug, LogLevel.Fatal, + new LoggingRule("*", minLevel, LogLevel.Fatal, new SumoLogicTarget() { Url = runParameters.SumologicEndpoint, @@ -27,11 +28,23 @@ namespace Geekbot.Core.Logger OptimizeBufferReuse = true, Name = "Geekbot" }) - ); + ); + } + else if (runParameters.LogJson) + { + config.LoggingRules.Add( + new LoggingRule("*", minLevel, LogLevel.Fatal, + new ConsoleTarget + { + Name = "Console", + Encoding = Encoding.UTF8, + Layout = "${message}" + } + ) + ); } else { - var minLevel = runParameters.Verbose ? LogLevel.Trace : LogLevel.Info; config.LoggingRules.Add( new LoggingRule("*", minLevel, LogLevel.Fatal, new ColoredConsoleTarget @@ -39,27 +52,12 @@ namespace Geekbot.Core.Logger Name = "Console", Encoding = Encoding.UTF8, Layout = "[${longdate} ${level:format=FirstCharacter}] ${message} ${exception:format=toString}" - }) - ); - - config.LoggingRules.Add( - new LoggingRule("*", minLevel, LogLevel.Fatal, - new FileTarget - { - Name = "File", - Layout = "[${longdate} ${level}] ${message}", - Encoding = Encoding.UTF8, - LineEnding = LineEndingMode.Default, - MaxArchiveFiles = 30, - ArchiveNumbering = ArchiveNumberingMode.Date, - ArchiveEvery = FileArchivePeriod.Day, - ArchiveFileName = "./Logs/Archive/{#####}.log", - FileName = "./Logs/Geekbot.log" - }) - ); + } + ) + ); } - - var loggerConfig = new LogFactory { Configuration = config }; + + var loggerConfig = new LogFactory {Configuration = config}; return loggerConfig.GetCurrentClassLogger(); } } From ce1153a0e2c843b91d5ed716a4ee460554449023 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 31 Aug 2020 19:29:03 +0200 Subject: [PATCH 099/264] Upgrade Entity Framework to preview 8 --- src/Core/Core.csproj | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 28729a7..5ad67b3 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -13,11 +13,11 @@ - - - - - + + + + + @@ -25,7 +25,7 @@ - + From 81373b76144f9acf231c76e75c564d19a86d12c1 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 31 Aug 2020 21:50:01 +0200 Subject: [PATCH 100/264] Make the ErrorHandler more resilient in case an exception is thrown during the error handling --- src/Core/ErrorHandling/ErrorHandler.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Core/ErrorHandling/ErrorHandler.cs b/src/Core/ErrorHandling/ErrorHandler.cs index 47ed22d..60d97e9 100644 --- a/src/Core/ErrorHandling/ErrorHandler.cs +++ b/src/Core/ErrorHandling/ErrorHandler.cs @@ -70,8 +70,14 @@ namespace Geekbot.Core.ErrorHandling } catch (Exception ex) { - await context.Channel.SendMessageAsync("Something went really really wrong here"); - _logger.Error(LogSource.Geekbot, "Errorception", ex); + try + { + await context.Channel.SendMessageAsync("Something went really really wrong here"); + } + finally + { + _logger.Error(LogSource.Geekbot, "Errorception", ex); + } } } From f71349b3780145ded0f685eaa5efe74ea34bac2a Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 8 Sep 2020 20:20:09 +0200 Subject: [PATCH 101/264] Reduce logging by making the user repo update message a debug log message --- src/Core/UserRepository/UserRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/UserRepository/UserRepository.cs b/src/Core/UserRepository/UserRepository.cs index 94d5df4..31fe2e2 100644 --- a/src/Core/UserRepository/UserRepository.cs +++ b/src/Core/UserRepository/UserRepository.cs @@ -48,7 +48,7 @@ namespace Geekbot.Core.UserRepository await _database.SaveChangesAsync(); - _logger.Information(LogSource.UserRepository, "Updated User", savedUser); + _logger.Debug(LogSource.UserRepository, "Updated User", savedUser); await Task.Delay(500); return true; } From d3c284102b5c674e5eb5def62fe08c6d250f126e Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 15 Sep 2020 00:14:27 +0200 Subject: [PATCH 102/264] Add an api endpoint to shutdown the bot from the browser --- src/Core/GeekbotExitCode.cs | 1 + src/Web/Controllers/KillController.cs | 64 +++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 src/Web/Controllers/KillController.cs diff --git a/src/Core/GeekbotExitCode.cs b/src/Core/GeekbotExitCode.cs index 5598f48..51006e1 100644 --- a/src/Core/GeekbotExitCode.cs +++ b/src/Core/GeekbotExitCode.cs @@ -8,6 +8,7 @@ // Geekbot Internals TranslationsFailed = 201, + KilledByApiCall = 210, // Dependent Services /* 301 not in use anymore (redis) */ diff --git a/src/Web/Controllers/KillController.cs b/src/Web/Controllers/KillController.cs new file mode 100644 index 0000000..2492b0d --- /dev/null +++ b/src/Web/Controllers/KillController.cs @@ -0,0 +1,64 @@ +using System; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Geekbot.Core; +using Geekbot.Core.GlobalSettings; +using Microsoft.AspNetCore.Mvc; + +namespace Geekbot.Web.Controllers +{ + /* + * Sometimes for some unknown reason command responses may become incredibly slow. + * Because i don't have time to debug it and may not always know directly when it happens, + * i want to give some trusted people the possibility to restart the bot. + * The kill code must be set manually in the db, it should end it `---1' + * + * ToDo: Actually fix the underlying issue + */ + public class KillController : Controller + { + private readonly IGlobalSettings _globalSettings; + private const string KillCodeDbKey = "KillCode"; + + public KillController(IGlobalSettings globalSettings) + { + _globalSettings = globalSettings; + } + + [HttpGet("/v1/kill/{providedKillCode}")] + public async Task KillTheBot([FromRoute] string providedKillCode) + { + var killCode = _globalSettings.GetKey(KillCodeDbKey); + if (providedKillCode != killCode) + { + return Unauthorized(new ApiError { Message = $"Go Away ({GetKillCodeInt(killCode)})" }); + } + + await UpdateKillCode(killCode); +#pragma warning disable CS4014 + Kill(); +#pragma warning restore CS4014 + return Ok(); + } + + private int GetKillCodeInt(string code) + { + var group = Regex.Match(code, @".+(\-\-\-(?\d+))").Groups["int"]; + return group.Success ? int.Parse(group.Value) : 0; + } + + private async Task UpdateKillCode(string oldCode) + { + var newKillCodeInt = new Random().Next(1, 100); + var newCode = oldCode.Replace($"---{GetKillCodeInt(oldCode)}", $"---{newKillCodeInt}"); + await _globalSettings.SetKey(KillCodeDbKey, newCode); + } + + private async Task Kill() + { + // wait a second so the http response can still be sent successfully + await Task.Delay(1000); + Environment.Exit(GeekbotExitCode.KilledByApiCall.GetHashCode()); + } + } +} \ No newline at end of file From cbe2aa23c955d01dcf31455a45cf448f922d95dc Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 15 Sep 2020 23:25:40 +0200 Subject: [PATCH 103/264] Make sure that examples in the !urban command are not longer than 1024 characters. --- .../Integrations/UbranDictionary/UrbanDictionary.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index bc1f478..72bc8cd 100644 --- a/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -33,12 +33,6 @@ namespace Geekbot.Bot.Commands.Integrations.UbranDictionary var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example)); - var description = definition.Definition; - if (description.Length > 1801) - { - description = description.Substring(0, 1800) + " [...]"; - } - var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder { @@ -46,8 +40,11 @@ namespace Geekbot.Bot.Commands.Integrations.UbranDictionary Url = definition.Permalink }); eb.WithColor(new Color(239, 255, 0)); - if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = description; - if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)"); + + static string ShortenIfToLong(string str, int maxLength) => str.Length > maxLength ? $"{str.Substring(0, maxLength - 5)}[...]" : str; + + if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = ShortenIfToLong(definition.Definition, 1800); + if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", ShortenIfToLong(definition.Example, 1024)); if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp); if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown); if (definitions.Tags?.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags)); From 482a74839ac6edb07bbcd784df46e2f58755ace8 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 22 Sep 2020 12:24:12 +0200 Subject: [PATCH 104/264] Fix some swiss german grammar (never heard of it either) in the !quote command --- src/Bot/Localization/Karma.de-ch.resx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Bot/Localization/Karma.de-ch.resx b/src/Bot/Localization/Karma.de-ch.resx index 294c105..5605f8b 100644 --- a/src/Bot/Localization/Karma.de-ch.resx +++ b/src/Bot/Localization/Karma.de-ch.resx @@ -30,7 +30,7 @@ Jetzt - Sorry {0}, aber du chasch dr din eigete karma nid weg neh + Sorry {0}, aber du chasch dis eigete karma nid senke Karma gsenkt From b743539c749dd19fe74fa6d6633cd2f7a3be9006 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 22 Sep 2020 13:06:57 +0200 Subject: [PATCH 105/264] Upgrade to .net5 rc1 and fix all breaking changes in the web api since .net core 2.2 --- .gitlab-ci.yml | 2 +- Dockerfile | 2 +- src/Bot/Bot.csproj | 1 - src/Core/Core.csproj | 18 +++++++++--------- src/Web/Web.csproj | 11 +---------- src/Web/WebApiStartup.cs | 22 +++++++++++++++------- 6 files changed, 27 insertions(+), 29 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 8efd1d1..c4d8b15 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,7 +10,7 @@ variables: Build: stage: build - image: mcr.microsoft.com/dotnet/core/sdk:5.0-focal + image: mcr.microsoft.com/dotnet/sdk:5.0 artifacts: expire_in: 1h paths: diff --git a/Dockerfile b/Dockerfile index 479dd40..245e06b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:5.0-focal +FROM mcr.microsoft.com/dotnet/aspnet:5.0 COPY ./app /app/ diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 49f0b16..60f6473 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -22,7 +22,6 @@ - diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 5ad67b3..7b273fd 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -13,19 +13,19 @@ - - - - - - - - + + + + + + + + - + diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index 429165b..5080a3d 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -1,4 +1,4 @@ - + net5.0 @@ -10,15 +10,6 @@ NU1701 - - - - - - - - - diff --git a/src/Web/WebApiStartup.cs b/src/Web/WebApiStartup.cs index 9aeedf9..0c18886 100644 --- a/src/Web/WebApiStartup.cs +++ b/src/Web/WebApiStartup.cs @@ -18,6 +18,9 @@ namespace Geekbot.Web { public static class WebApiStartup { + // Using the "Microsoft.NET.Sdk.Web" SDK requires a static main function... + public static void Main() {} + public static void StartWebApi(IGeekbotLogger logger, RunParameters runParameters, CommandService commandService, DatabaseContext databaseContext, DiscordSocketClient client, IGlobalSettings globalSettings, IHighscoreManager highscoreManager) { @@ -28,22 +31,27 @@ namespace Geekbot.Web }) .ConfigureServices(services => { - services.AddMvc(); - services.AddSingleton(commandService); - services.AddSingleton(databaseContext); - services.AddSingleton(client); - services.AddSingleton(globalSettings); - services.AddSingleton(highscoreManager); + services.AddControllers(); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); }); + + services.AddSingleton(commandService); + services.AddSingleton(databaseContext); + services.AddSingleton(client); + services.AddSingleton(globalSettings); + services.AddSingleton(highscoreManager); }) .Configure(app => { - app.UseMvc(); + app.UseRouting(); app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().Build()); + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); }) .ConfigureLogging(logging => { From ae9b9caeb90451c860e5be7fe19e51f81267c9f8 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 23 Sep 2020 16:05:43 +0200 Subject: [PATCH 106/264] Add random.org for random number generation. --- src/Bot/Commands/Utils/Quote/Quote.cs | 2 +- src/Bot/Program.cs | 2 +- src/Core/Core.csproj | 1 + .../RandomNumberGenerator.cs | 57 +++++++++++++++++-- tests/Core/DiceParser/DiceParser.test.cs | 6 +- tests/Core/DiceParser/SingleDie.test.cs | 6 +- 6 files changed, 62 insertions(+), 12 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index a7d3ff1..6f4cd1c 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -46,7 +46,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote return; } - var random = _randomNumberGenerator.Next(0, s.Count); + var random = _randomNumberGenerator.Next(0, s.Count - 1); var quote = s[random]; var embed = QuoteBuilder(quote); diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 5a4b456..5994f8c 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -164,7 +164,7 @@ namespace Geekbot.Bot var emojiConverter = new EmojiConverter(); var mtgManaConverter = new MtgManaConverter(); var wikipediaClient = new WikipediaClient(); - var randomNumberGenerator = new RandomNumberGenerator(); + var randomNumberGenerator = new RandomNumberGenerator(_globalSettings); var mediaProvider = new MediaProvider(_logger, randomNumberGenerator); var kvMemoryStore = new KvInInMemoryStore(); var errorHandler = new ErrorHandler(_logger, _runParameters, () => Localization.Internal.SomethingWentWrong); diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 7b273fd..0b3ff44 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -11,6 +11,7 @@ + diff --git a/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs index 63381b5..db990a7 100644 --- a/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs +++ b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs @@ -1,25 +1,69 @@ using System; using System.Security.Cryptography; +using Anemonis.RandomOrg; +using Geekbot.Core.GlobalSettings; namespace Geekbot.Core.RandomNumberGenerator { public class RandomNumberGenerator : IRandomNumberGenerator { - readonly RNGCryptoServiceProvider csp; + private readonly RNGCryptoServiceProvider csp; + private readonly bool _canUseRandomOrg; + private readonly RandomOrgClient _randomOrgClient; - public RandomNumberGenerator() + public RandomNumberGenerator(IGlobalSettings globalSettings) { csp = new RNGCryptoServiceProvider(); + + var randomOrgApiKey = globalSettings.GetKey("RandomOrgApiKey"); + if (!string.IsNullOrEmpty(randomOrgApiKey)) + { + _canUseRandomOrg = true; + _randomOrgClient = new RandomOrgClient(randomOrgApiKey); + } } - public int Next(int minValue, int maxExclusiveValue) + public int Next(int minValue, int maxInclusiveValue) { - if (minValue >= maxExclusiveValue) + if (minValue == maxInclusiveValue) + { + return maxInclusiveValue; + } + + if (minValue >= maxInclusiveValue) { throw new ArgumentOutOfRangeException("minValue must be lower than maxExclusiveValue"); } + + if (_canUseRandomOrg) + { + try + { + return GetFromRandomOrg(minValue, maxInclusiveValue); + } + catch + { + // ignore + } + } - var diff = (long)maxExclusiveValue - minValue; + return GetFromCrypto(minValue, maxInclusiveValue); + } + + private int GetFromRandomOrg(int minValue, int maxInclusiveValue) + { + return _randomOrgClient + .GenerateIntegersAsync(1, minValue, maxInclusiveValue, false) + .Result + .Random + .Data[0]; + } + + private int GetFromCrypto(int minValue, int maxInclusiveValue) + { + var maxExclusiveValue = maxInclusiveValue + 1; + + var diff = (long) maxExclusiveValue - minValue; var upperBound = uint.MaxValue / diff * diff; uint ui; @@ -27,7 +71,8 @@ namespace Geekbot.Core.RandomNumberGenerator { ui = GetRandomUInt(); } while (ui >= upperBound); - return (int)(minValue + (ui % diff)); + + return (int) (minValue + (ui % diff)); } private uint GetRandomUInt() diff --git a/tests/Core/DiceParser/DiceParser.test.cs b/tests/Core/DiceParser/DiceParser.test.cs index 8a9163a..ed9425f 100644 --- a/tests/Core/DiceParser/DiceParser.test.cs +++ b/tests/Core/DiceParser/DiceParser.test.cs @@ -1,15 +1,17 @@ using System.Collections.Generic; using System.Text.Json; using Geekbot.Core.DiceParser; +using Geekbot.Core.GlobalSettings; using Geekbot.Core.RandomNumberGenerator; +using Moq; using Xunit; namespace Tests.Core.DiceParser { public class DiceParserTest { - private static readonly RandomNumberGenerator _randomNumberGenerator = new RandomNumberGenerator(); - + private static readonly RandomNumberGenerator _randomNumberGenerator = new RandomNumberGenerator(new Mock().Object); + public struct DiceParserTestDto { public string Input { get; set; } diff --git a/tests/Core/DiceParser/SingleDie.test.cs b/tests/Core/DiceParser/SingleDie.test.cs index 813a33b..5173902 100644 --- a/tests/Core/DiceParser/SingleDie.test.cs +++ b/tests/Core/DiceParser/SingleDie.test.cs @@ -1,5 +1,7 @@ using Geekbot.Core.DiceParser; +using Geekbot.Core.GlobalSettings; using Geekbot.Core.RandomNumberGenerator; +using Moq; using Xunit; namespace Tests.Core.DiceParser @@ -43,7 +45,7 @@ namespace Tests.Core.DiceParser [Theory, MemberData(nameof(SingleDieNameTestData))] public void SingleDieNameTestFunc(string testName, SingleDieNameTestDto testData) { - var die = new SingleDie(new RandomNumberGenerator()) {AdvantageType = testData.AdvantageType}; + var die = new SingleDie(new RandomNumberGenerator(new Mock().Object)) {AdvantageType = testData.AdvantageType}; Assert.Equal(die.DiceName, testData.Expected); } @@ -106,7 +108,7 @@ namespace Tests.Core.DiceParser [Theory, MemberData(nameof(SingleDieValidationTestData))] public void SingleDieValidationTestFunc(string testName, SingleDieValidationTestDto testData) { - var die = new SingleDie(new RandomNumberGenerator()) + var die = new SingleDie(new RandomNumberGenerator(new Mock().Object)) { Amount = testData.Amount, Sides = testData.Sides From 58bd4d17d0ecaa09ca0d64219c601cae021a6163 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 23 Sep 2020 16:28:50 +0200 Subject: [PATCH 107/264] Optimize the !quote database query --- src/Bot/Commands/Utils/Quote/Quote.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 6f4cd1c..db6b1ac 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -33,23 +33,23 @@ namespace Geekbot.Bot.Commands.Utils.Quote } [Command] - [Summary("Return a random quoute from the database")] + [Summary("Return a random quote from the database")] public async Task GetRandomQuote() { try { - var s = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).ToList(); + var totalQuotes = await _database.Quotes.CountAsync(e => e.GuildId.Equals(Context.Guild.Id.AsLong())); - if (!s.Any()) + if (totalQuotes == 0) { await ReplyAsync(Localization.Quote.NoQuotesFound); return; } - var random = _randomNumberGenerator.Next(0, s.Count - 1); - var quote = s[random]; - - var embed = QuoteBuilder(quote); + var random = _randomNumberGenerator.Next(0, totalQuotes - 1); + var quote = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).Skip(random).Take(1); + + var embed = QuoteBuilder(quote.FirstOrDefault()); await ReplyAsync("", false, embed.Build()); } catch (Exception e) From 216188f61fc05bdd255980f076d44f2904539d51 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 23 Sep 2020 16:46:13 +0200 Subject: [PATCH 108/264] Add a deprecation warning for quoting by message ID --- src/Bot/Commands/Utils/Quote/Quote.cs | 15 +++++++++------ src/Bot/Localization/Quote.Designer.cs | 9 +++++++++ src/Bot/Localization/Quote.de-ch.resx | 3 +++ src/Bot/Localization/Quote.resx | 3 +++ 4 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index db6b1ac..0b197cd 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; @@ -211,10 +212,9 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - // var transContext = await _translationHandler.GetGuildContext(Context); var message = await Context.Channel.GetMessageAsync(messageId); - await ProcessQuote(message, saveToDb); + await ProcessQuote(message, saveToDb, true); } catch (Exception e) { @@ -226,8 +226,6 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - // var transContext = await _translationHandler.GetGuildContext(Context); - if (!MessageLink.IsValid(messageLink)) { await ReplyAsync(Localization.Quote.NotAValidMessageLink); @@ -255,7 +253,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote } } - private async Task ProcessQuote(IMessage message, bool saveToDb) + private async Task ProcessQuote(IMessage message, bool saveToDb, bool showMessageIdWarning = false) { if (message.Author.Id == Context.Message.Author.Id && saveToDb && !_isDev) { @@ -277,7 +275,12 @@ namespace Geekbot.Bot.Commands.Utils.Quote } var embed = QuoteBuilder(quote); - await ReplyAsync(saveToDb ? Localization.Quote.QuoteAdded : string.Empty, false, embed.Build()); + + var sb = new StringBuilder(); + if (saveToDb) sb.AppendLine(Localization.Quote.QuoteAdded); + if (showMessageIdWarning) sb.AppendLine(Localization.Quote.MessageIdDeprecation); + + await ReplyAsync(sb.ToString(), false, embed.Build()); } private EmbedBuilder QuoteBuilder(QuoteModel quote) diff --git a/src/Bot/Localization/Quote.Designer.cs b/src/Bot/Localization/Quote.Designer.cs index 342c181..d0926ae 100644 --- a/src/Bot/Localization/Quote.Designer.cs +++ b/src/Bot/Localization/Quote.Designer.cs @@ -78,6 +78,15 @@ namespace Geekbot.Bot.Localization { } } + /// + /// Looks up a localized string similar to :warning: Creating quotes by message ID is deprecated in favour of message links and will be removed on 1 December 2020. + /// + internal static string MessageIdDeprecation { + get { + return ResourceManager.GetString("MessageIdDeprecation", resourceCulture); + } + } + /// /// Looks up a localized string similar to Most quoted person. /// diff --git a/src/Bot/Localization/Quote.de-ch.resx b/src/Bot/Localization/Quote.de-ch.resx index 99fd959..c7e3b8b 100644 --- a/src/Bot/Localization/Quote.de-ch.resx +++ b/src/Bot/Localization/Quote.de-ch.resx @@ -44,4 +44,7 @@ Du chasch numme nachrichte vom gliche server quote + + :warning: Es mache vo quotes mit message-IDs isch zgunste vo message-links veraltet und wird am 1. dezember 2020 entfernt + \ No newline at end of file diff --git a/src/Bot/Localization/Quote.resx b/src/Bot/Localization/Quote.resx index b51d79c..215f0ea 100644 --- a/src/Bot/Localization/Quote.resx +++ b/src/Bot/Localization/Quote.resx @@ -51,4 +51,7 @@ You can only quote messages from the same server + + :warning: Creating quotes by message ID is deprecated in favour of message links and will be removed on 1 December 2020 + \ No newline at end of file From 7ef0b6a3195a379f06ca7f33056131dbd192aea5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 24 Sep 2020 12:21:21 +0200 Subject: [PATCH 109/264] Swap the my anime list wrapper for the !anime and !manga commands --- src/Bot/Bot.csproj | 2 +- src/Bot/Commands/Integrations/Mal.cs | 116 +++++++++++---------------- src/Bot/Program.cs | 3 - src/Core/Core.csproj | 1 - src/Core/MalClient/IMalClient.cs | 12 --- src/Core/MalClient/MalClient.cs | 63 --------------- 6 files changed, 47 insertions(+), 150 deletions(-) delete mode 100644 src/Core/MalClient/IMalClient.cs delete mode 100644 src/Core/MalClient/MalClient.cs diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 60f6473..4cd5b39 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -24,8 +24,8 @@ + - diff --git a/src/Bot/Commands/Integrations/Mal.cs b/src/Bot/Commands/Integrations/Mal.cs index ae30493..ab8c021 100644 --- a/src/Bot/Commands/Integrations/Mal.cs +++ b/src/Bot/Commands/Integrations/Mal.cs @@ -1,23 +1,23 @@ using System; +using System.Linq; using System.Threading.Tasks; using System.Web; -using System.Xml; using Discord; using Discord.Commands; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; -using Geekbot.Core.MalClient; +using JikanDotNet; namespace Geekbot.Bot.Commands.Integrations { public class Mal : ModuleBase { private readonly IErrorHandler _errorHandler; - private readonly IMalClient _malClient; + private readonly IJikan _client; - public Mal(IMalClient malClient, IErrorHandler errorHandler) + public Mal(IErrorHandler errorHandler) { - _malClient = malClient; + _client = new Jikan(); _errorHandler = errorHandler; } @@ -27,46 +27,34 @@ namespace Geekbot.Bot.Commands.Integrations { try { - if (_malClient.IsLoggedIn()) + var results = await _client.SearchAnime(animeName); + var anime = results.Results.FirstOrDefault(); + if (anime != null) { - var anime = await _malClient.GetAnime(animeName); - if (anime != null) - { - var eb = new EmbedBuilder(); + var eb = new EmbedBuilder(); - var description = HttpUtility.HtmlDecode(anime.Synopsis) - .Replace("
", "") - .Replace("[i]", "*") - .Replace("[/i]", "*"); + var description = HttpUtility.HtmlDecode(anime.Description) + .Replace("
", "") + .Replace("[i]", "*") + .Replace("[/i]", "*"); - eb.Title = anime.Title; - eb.Description = description; - eb.ImageUrl = anime.Image; - eb.AddInlineField("Premiered", $"{anime.StartDate}"); - eb.AddInlineField("Ended", anime.EndDate == "0000-00-00" ? "???" : anime.EndDate); - eb.AddInlineField("Status", anime.Status); - eb.AddInlineField("Episodes", anime.Episodes); - eb.AddInlineField("MAL Score", anime.Score); - eb.AddInlineField("Type", anime.Type); - eb.AddField("MAL Link", $"https://myanimelist.net/anime/{anime.Id}"); + eb.Title = anime.Title; + eb.Description = description; + eb.ImageUrl = anime.ImageURL; + eb.AddInlineField("Premiered", $"{anime.StartDate.Value.ToShortDateString()}"); + eb.AddInlineField("Ended", anime.Airing ? "Present" : anime.EndDate.Value.ToShortDateString()); + eb.AddInlineField("Episodes", anime.Episodes); + eb.AddInlineField("MAL Score", anime.Score); + eb.AddInlineField("Type", anime.Type); + eb.AddField("MAL Link", $"https://myanimelist.net/anime/{anime.MalId}"); - await ReplyAsync("", false, eb.Build()); - } - else - { - await ReplyAsync("No anime found with that name..."); - } + await ReplyAsync("", false, eb.Build()); } else { - await ReplyAsync( - "Unfortunally i'm not connected to MyAnimeList.net, please tell my senpai to connect me"); + await ReplyAsync("No anime found with that name..."); } } - catch (XmlException e) - { - await _errorHandler.HandleCommandException(e, Context, "The MyAnimeList.net API refused to answer"); - } catch (Exception e) { await _errorHandler.HandleCommandException(e, Context); @@ -79,46 +67,34 @@ namespace Geekbot.Bot.Commands.Integrations { try { - if (_malClient.IsLoggedIn()) + var results = await _client.SearchManga(mangaName); + var manga = results.Results.FirstOrDefault(); + if (manga != null) { - var manga = await _malClient.GetManga(mangaName); - if (manga != null) - { - var eb = new EmbedBuilder(); - - var description = HttpUtility.HtmlDecode(manga.Synopsis) - .Replace("
", "") - .Replace("[i]", "*") - .Replace("[/i]", "*"); - - eb.Title = manga.Title; - eb.Description = description; - eb.ImageUrl = manga.Image; - eb.AddInlineField("Premiered", $"{manga.StartDate}"); - eb.AddInlineField("Ended", manga.EndDate == "0000-00-00" ? "???" : manga.EndDate); - eb.AddInlineField("Status", manga.Status); - eb.AddInlineField("Volumes", manga.Volumes); - eb.AddInlineField("Chapters", manga.Chapters); - eb.AddInlineField("MAL Score", manga.Score); - eb.AddField("MAL Link", $"https://myanimelist.net/manga/{manga.Id}"); - - await ReplyAsync("", false, eb.Build()); - } - else - { - await ReplyAsync("No manga found with that name..."); - } + var eb = new EmbedBuilder(); + + var description = HttpUtility.HtmlDecode(manga.Description) + .Replace("
", "") + .Replace("[i]", "*") + .Replace("[/i]", "*"); + + eb.Title = manga.Title; + eb.Description = description; + eb.ImageUrl = manga.ImageURL; + eb.AddInlineField("Premiered", $"{manga.StartDate.Value.ToShortDateString()}"); + eb.AddInlineField("Ended", manga.Publishing ? "Present" : manga.EndDate.Value.ToShortDateString()); + eb.AddInlineField("Volumes", manga.Volumes); + eb.AddInlineField("Chapters", manga.Chapters); + eb.AddInlineField("MAL Score", manga.Score); + eb.AddField("MAL Link", $"https://myanimelist.net/manga/{manga.MalId}"); + + await ReplyAsync("", false, eb.Build()); } else { - await ReplyAsync( - "Unfortunally i'm not connected to MyAnimeList.net, please tell my senpai to connect me"); + await ReplyAsync("No manga found with that name..."); } } - catch (XmlException e) - { - await _errorHandler.HandleCommandException(e, Context, "The MyAnimeList.net API refused to answer"); - } catch (Exception e) { await _errorHandler.HandleCommandException(e, Context); diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 5994f8c..dee6ec3 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -18,7 +18,6 @@ using Geekbot.Core.Highscores; using Geekbot.Core.KvInMemoryStore; using Geekbot.Core.Levels; using Geekbot.Core.Logger; -using Geekbot.Core.MalClient; using Geekbot.Core.Media; using Geekbot.Core.RandomNumberGenerator; using Geekbot.Core.ReactionListener; @@ -159,7 +158,6 @@ namespace Geekbot.Bot _reactionListener = new ReactionListener(_databaseInitializer.Initialize()); _guildSettingsManager = new GuildSettingsManager(_databaseInitializer.Initialize()); var fortunes = new FortunesProvider(_logger); - var malClient = new MalClient(_globalSettings, _logger); var levelCalc = new LevelCalc(); var emojiConverter = new EmojiConverter(); var mtgManaConverter = new MtgManaConverter(); @@ -176,7 +174,6 @@ namespace Geekbot.Bot services.AddSingleton(emojiConverter); services.AddSingleton(fortunes); services.AddSingleton(mediaProvider); - services.AddSingleton(malClient); services.AddSingleton(mtgManaConverter); services.AddSingleton(wikipediaClient); services.AddSingleton(randomNumberGenerator); diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 0b3ff44..780d0e2 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -22,7 +22,6 @@ - diff --git a/src/Core/MalClient/IMalClient.cs b/src/Core/MalClient/IMalClient.cs deleted file mode 100644 index 70851c1..0000000 --- a/src/Core/MalClient/IMalClient.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Threading.Tasks; -using MyAnimeListSharp.Core; - -namespace Geekbot.Core.MalClient -{ - public interface IMalClient - { - bool IsLoggedIn(); - Task GetAnime(string query); - Task GetManga(string query); - } -} \ No newline at end of file diff --git a/src/Core/MalClient/MalClient.cs b/src/Core/MalClient/MalClient.cs deleted file mode 100644 index 3f5f165..0000000 --- a/src/Core/MalClient/MalClient.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Threading.Tasks; -using Geekbot.Core.GlobalSettings; -using Geekbot.Core.Logger; -using MyAnimeListSharp.Auth; -using MyAnimeListSharp.Core; -using MyAnimeListSharp.Facade.Async; - -namespace Geekbot.Core.MalClient -{ - public class MalClient : IMalClient - { - private readonly IGlobalSettings _globalSettings; - private readonly IGeekbotLogger _logger; - private ICredentialContext _credentials; - private AnimeSearchMethodsAsync _animeSearch; - private MangaSearchMethodsAsync _mangaSearch; - - public MalClient(IGlobalSettings globalSettings, IGeekbotLogger logger) - { - _globalSettings = globalSettings; - _logger = logger; - ReloadClient(); - } - - private bool ReloadClient() - { - var malCredentials = _globalSettings.GetKey("MalCredentials"); - if (!string.IsNullOrEmpty(malCredentials)) - { - var credSplit = malCredentials.Split('|'); - _credentials = new CredentialContext() - { - UserName = credSplit[0], - Password = credSplit[1] - }; - _animeSearch = new AnimeSearchMethodsAsync(_credentials); - _mangaSearch = new MangaSearchMethodsAsync(_credentials); - _logger.Debug(LogSource.Geekbot, "Logged in to MAL"); - return true; - } - _logger.Debug(LogSource.Geekbot, "No MAL Credentials Set!"); - return false; - - } - - public bool IsLoggedIn() - { - return _credentials != null; - } - - public async Task GetAnime(string query) - { - var response = await _animeSearch.SearchDeserializedAsync(query); - return response.Entries.Count == 0 ? null : response.Entries[0]; - } - - public async Task GetManga(string query) - { - var response = await _mangaSearch.SearchDeserializedAsync(query); - return response.Entries.Count == 0 ? null : response.Entries[0]; - } - } -} \ No newline at end of file From ed7748833aa499e8a19778f81a575e8a052c41f0 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 24 Sep 2020 12:49:55 +0200 Subject: [PATCH 110/264] Format dates in the !anime and !manga commands with the correct culture info --- src/Bot/Commands/Integrations/Mal.cs | 31 +++++++++++++++++++--------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/Bot/Commands/Integrations/Mal.cs b/src/Bot/Commands/Integrations/Mal.cs index ab8c021..f44d04e 100644 --- a/src/Bot/Commands/Integrations/Mal.cs +++ b/src/Bot/Commands/Integrations/Mal.cs @@ -1,24 +1,25 @@ using System; using System.Linq; +using System.Threading; using System.Threading.Tasks; using System.Web; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; using JikanDotNet; namespace Geekbot.Bot.Commands.Integrations { - public class Mal : ModuleBase + public class Mal : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly IJikan _client; - public Mal(IErrorHandler errorHandler) + public Mal(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _client = new Jikan(); - _errorHandler = errorHandler; } [Command("anime", RunMode = RunMode.Async)] @@ -41,8 +42,8 @@ namespace Geekbot.Bot.Commands.Integrations eb.Title = anime.Title; eb.Description = description; eb.ImageUrl = anime.ImageURL; - eb.AddInlineField("Premiered", $"{anime.StartDate.Value.ToShortDateString()}"); - eb.AddInlineField("Ended", anime.Airing ? "Present" : anime.EndDate.Value.ToShortDateString()); + eb.AddInlineField("Premiered", FormatDate(anime.StartDate)); + eb.AddInlineField("Ended", anime.Airing ? "Present" : FormatDate(anime.EndDate)); eb.AddInlineField("Episodes", anime.Episodes); eb.AddInlineField("MAL Score", anime.Score); eb.AddInlineField("Type", anime.Type); @@ -57,7 +58,7 @@ namespace Geekbot.Bot.Commands.Integrations } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } @@ -81,8 +82,8 @@ namespace Geekbot.Bot.Commands.Integrations eb.Title = manga.Title; eb.Description = description; eb.ImageUrl = manga.ImageURL; - eb.AddInlineField("Premiered", $"{manga.StartDate.Value.ToShortDateString()}"); - eb.AddInlineField("Ended", manga.Publishing ? "Present" : manga.EndDate.Value.ToShortDateString()); + eb.AddInlineField("Premiered", FormatDate(manga.StartDate)); + eb.AddInlineField("Ended", manga.Publishing ? "Present" : FormatDate(manga.EndDate)); eb.AddInlineField("Volumes", manga.Volumes); eb.AddInlineField("Chapters", manga.Chapters); eb.AddInlineField("MAL Score", manga.Score); @@ -97,8 +98,18 @@ namespace Geekbot.Bot.Commands.Integrations } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } + + private string FormatDate(DateTime? dateTime) + { + if (!dateTime.HasValue) + { + return DateTime.MinValue.ToString("d", Thread.CurrentThread.CurrentUICulture); + } + + return dateTime.Value.ToString("d", Thread.CurrentThread.CurrentUICulture); + } } } \ No newline at end of file From 41795aa13f0a806caf8cb7acb6e29d7653fb1d51 Mon Sep 17 00:00:00 2001 From: runebaas Date: Thu, 24 Sep 2020 18:29:21 +0200 Subject: [PATCH 111/264] Small wording tweaks to the !anime and !manga commands. They also no long need their description html decoded. --- src/Bot/Commands/Integrations/Mal.cs | 63 +++++++++++++--------------- 1 file changed, 28 insertions(+), 35 deletions(-) diff --git a/src/Bot/Commands/Integrations/Mal.cs b/src/Bot/Commands/Integrations/Mal.cs index f44d04e..ffc8dd7 100644 --- a/src/Bot/Commands/Integrations/Mal.cs +++ b/src/Bot/Commands/Integrations/Mal.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using System.Web; using Discord; using Discord.Commands; using Geekbot.Core; @@ -32,22 +31,19 @@ namespace Geekbot.Bot.Commands.Integrations var anime = results.Results.FirstOrDefault(); if (anime != null) { - var eb = new EmbedBuilder(); - - var description = HttpUtility.HtmlDecode(anime.Description) - .Replace("
", "") - .Replace("[i]", "*") - .Replace("[/i]", "*"); - - eb.Title = anime.Title; - eb.Description = description; - eb.ImageUrl = anime.ImageURL; - eb.AddInlineField("Premiered", FormatDate(anime.StartDate)); - eb.AddInlineField("Ended", anime.Airing ? "Present" : FormatDate(anime.EndDate)); - eb.AddInlineField("Episodes", anime.Episodes); - eb.AddInlineField("MAL Score", anime.Score); - eb.AddInlineField("Type", anime.Type); - eb.AddField("MAL Link", $"https://myanimelist.net/anime/{anime.MalId}"); + var eb = new EmbedBuilder + { + Title = anime.Title, + Description = anime.Description, + ImageUrl = anime.ImageURL + }; + + eb.AddInlineField("Premiere", FormatDate(anime.StartDate)) + .AddInlineField("Ended", anime.Airing ? "-" : FormatDate(anime.EndDate)) + .AddInlineField("Episodes", anime.Episodes) + .AddInlineField("MAL Score", anime.Score) + .AddInlineField("Type", anime.Type) + .AddField("MAL Link", $"https://myanimelist.net/anime/{anime.MalId}"); await ReplyAsync("", false, eb.Build()); } @@ -72,23 +68,20 @@ namespace Geekbot.Bot.Commands.Integrations var manga = results.Results.FirstOrDefault(); if (manga != null) { - var eb = new EmbedBuilder(); - - var description = HttpUtility.HtmlDecode(manga.Description) - .Replace("
", "") - .Replace("[i]", "*") - .Replace("[/i]", "*"); - - eb.Title = manga.Title; - eb.Description = description; - eb.ImageUrl = manga.ImageURL; - eb.AddInlineField("Premiered", FormatDate(manga.StartDate)); - eb.AddInlineField("Ended", manga.Publishing ? "Present" : FormatDate(manga.EndDate)); - eb.AddInlineField("Volumes", manga.Volumes); - eb.AddInlineField("Chapters", manga.Chapters); - eb.AddInlineField("MAL Score", manga.Score); - eb.AddField("MAL Link", $"https://myanimelist.net/manga/{manga.MalId}"); - + var eb = new EmbedBuilder + { + Title = manga.Title, + Description = manga.Description, + ImageUrl = manga.ImageURL + }; + + eb.AddInlineField("Premiere", FormatDate(manga.StartDate)) + .AddInlineField("Ended", manga.Publishing ? "-" : FormatDate(manga.EndDate)) + .AddInlineField("Volumes", manga.Volumes) + .AddInlineField("Chapters", manga.Chapters) + .AddInlineField("MAL Score", manga.Score) + .AddField("MAL Link", $"https://myanimelist.net/manga/{manga.MalId}"); + await ReplyAsync("", false, eb.Build()); } else @@ -108,7 +101,7 @@ namespace Geekbot.Bot.Commands.Integrations { return DateTime.MinValue.ToString("d", Thread.CurrentThread.CurrentUICulture); } - + return dateTime.Value.ToString("d", Thread.CurrentThread.CurrentUICulture); } } From 28a5b9322e831517f87e8cb08d85bf6a364bcecd Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 9 Oct 2020 17:10:49 +0200 Subject: [PATCH 112/264] Allow Rune#0007 to bypass the ignored servers restriction --- src/Bot/Handlers/CommandHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Bot/Handlers/CommandHandler.cs b/src/Bot/Handlers/CommandHandler.cs index 52e9a52..3c072fe 100644 --- a/src/Bot/Handlers/CommandHandler.cs +++ b/src/Bot/Handlers/CommandHandler.cs @@ -58,7 +58,8 @@ namespace Geekbot.Bot.Handlers _ => 0 // DM Channel }; - if (IsIgnoredGuild(guildId, message.Author.Id)) return Task.CompletedTask; + // temp hack, will fix later + if (IsIgnoredGuild(guildId, message.Author.Id) || messageParam.Author.Id == 93061333972455424) return Task.CompletedTask; var lowCaseMsg = message.ToString().ToLower(); if (ShouldHui(lowCaseMsg, guildId)) From fe51dfe540d9dfae1ff9a2d5c15067adf65c0942 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 9 Oct 2020 17:25:53 +0200 Subject: [PATCH 113/264] Revert last commit --- src/Bot/Handlers/CommandHandler.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Bot/Handlers/CommandHandler.cs b/src/Bot/Handlers/CommandHandler.cs index 3c072fe..52e9a52 100644 --- a/src/Bot/Handlers/CommandHandler.cs +++ b/src/Bot/Handlers/CommandHandler.cs @@ -58,8 +58,7 @@ namespace Geekbot.Bot.Handlers _ => 0 // DM Channel }; - // temp hack, will fix later - if (IsIgnoredGuild(guildId, message.Author.Id) || messageParam.Author.Id == 93061333972455424) return Task.CompletedTask; + if (IsIgnoredGuild(guildId, message.Author.Id)) return Task.CompletedTask; var lowCaseMsg = message.ToString().ToLower(); if (ShouldHui(lowCaseMsg, guildId)) From ffab56d4a5e893aac0416ef75283fbb9f2b53129 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 23 Oct 2020 21:46:59 +0200 Subject: [PATCH 114/264] Delete original message from user after using !emojify --- src/Bot/Commands/Utils/Emojify.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Bot/Commands/Utils/Emojify.cs b/src/Bot/Commands/Utils/Emojify.cs index c8328ee..8bb880e 100644 --- a/src/Bot/Commands/Utils/Emojify.cs +++ b/src/Bot/Commands/Utils/Emojify.cs @@ -32,6 +32,14 @@ namespace Geekbot.Bot.Commands.Utils await ReplyAsync($"{Context.User.Username}#{Context.User.Discriminator} said:"); await ReplyAsync(emojis); + try + { + await Context.Message.DeleteAsync(); + } + catch + { + // bot may not have enough permission, doesn't matter if it fails + } } catch (Exception e) { From 2fb815bc97356d274d7f7edc80d380f97d634019 Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 2 Nov 2020 18:01:57 +0100 Subject: [PATCH 115/264] Don't use embeds for !dog --- src/Bot/Commands/Randomness/Dog/Dog.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Bot/Commands/Randomness/Dog/Dog.cs b/src/Bot/Commands/Randomness/Dog/Dog.cs index 2a8a3f1..051dbf3 100644 --- a/src/Bot/Commands/Randomness/Dog/Dog.cs +++ b/src/Bot/Commands/Randomness/Dog/Dog.cs @@ -23,11 +23,7 @@ namespace Geekbot.Bot.Commands.Randomness.Dog try { var response = await HttpAbstractions.Get(new Uri("http://random.dog/woof.json")); - var eb = new EmbedBuilder - { - ImageUrl = response.Url - }; - await ReplyAsync("", false, eb.Build()); + await ReplyAsync(response.Url); } catch (Exception e) { From 4c3b7044ce6543bc7cbfd9fc80fd71bee19a449d Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 2 Nov 2020 18:33:05 +0100 Subject: [PATCH 116/264] Don't count 1 to many sides in the !dice command --- src/Core/DiceParser/SingleDie.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/DiceParser/SingleDie.cs b/src/Core/DiceParser/SingleDie.cs index f13dbcd..4e0f474 100644 --- a/src/Core/DiceParser/SingleDie.cs +++ b/src/Core/DiceParser/SingleDie.cs @@ -32,7 +32,7 @@ namespace Geekbot.Core.DiceParser { var result = new DieResult { - Roll1 = _random.Next(1, Sides + 1), + Roll1 = _random.Next(1, Sides), AdvantageType = AdvantageType }; From 09dbeb97667d12adcfd9fab69fc14b2811a6abdb Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 24 Nov 2020 21:40:33 +0100 Subject: [PATCH 117/264] Fix a stupid bug with the !avatar command --- src/Bot/Commands/Utils/AvatarGetter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Utils/AvatarGetter.cs b/src/Bot/Commands/Utils/AvatarGetter.cs index 6585a75..2aa6b07 100644 --- a/src/Bot/Commands/Utils/AvatarGetter.cs +++ b/src/Bot/Commands/Utils/AvatarGetter.cs @@ -21,8 +21,8 @@ namespace Geekbot.Bot.Commands.Utils { try { - if (user == null) user = Context.User; - var url = user.GetAvatarUrl().Replace("128", "1024"); + user ??= Context.User; + var url = user.GetAvatarUrl(ImageFormat.Auto, 1024); await ReplyAsync(url); } catch (Exception e) From baf09e2f3807c9aa3fbd652f344399fee835eb89 Mon Sep 17 00:00:00 2001 From: runebaas Date: Wed, 25 Nov 2020 15:21:55 +0100 Subject: [PATCH 118/264] Remove the ability to create quotes from message ids --- src/Bot/Commands/Utils/Quote/Quote.cs | 35 ++------------------------ src/Bot/Localization/Quote.Designer.cs | 9 ------- src/Bot/Localization/Quote.de-ch.resx | 3 --- src/Bot/Localization/Quote.resx | 3 --- 4 files changed, 2 insertions(+), 48 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 0b197cd..a5f2e3c 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -74,22 +74,6 @@ namespace Geekbot.Bot.Commands.Utils.Quote { await QuoteFromMention(user, false); } - - [Command("add")] - [Alias("save")] - [Summary("Add a quote from a message id")] - public async Task AddQuote([Summary("message-ID")] ulong messageId) - { - await QuoteFromMessageId(messageId, true); - } - - [Command("make")] - [Alias("preview")] - [Summary("Preview a quote from a message id")] - public async Task ReturnSpecifiedQuote([Summary("message-ID")] ulong messageId) - { - await QuoteFromMessageId(messageId, false); - } [Command("add")] [Alias("save")] @@ -208,21 +192,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote } - private async Task QuoteFromMessageId(ulong messageId, bool saveToDb) - { - try - { - var message = await Context.Channel.GetMessageAsync(messageId); - - await ProcessQuote(message, saveToDb, true); - } - catch (Exception e) - { - await ErrorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); - } - } - - private async Task QuoteFromMessageLink(string messageLink, bool saveToDb) + private async Task QuoteFromMessageLink(string messageLink, bool saveToDb) { try { @@ -253,7 +223,7 @@ namespace Geekbot.Bot.Commands.Utils.Quote } } - private async Task ProcessQuote(IMessage message, bool saveToDb, bool showMessageIdWarning = false) + private async Task ProcessQuote(IMessage message, bool saveToDb) { if (message.Author.Id == Context.Message.Author.Id && saveToDb && !_isDev) { @@ -278,7 +248,6 @@ namespace Geekbot.Bot.Commands.Utils.Quote var sb = new StringBuilder(); if (saveToDb) sb.AppendLine(Localization.Quote.QuoteAdded); - if (showMessageIdWarning) sb.AppendLine(Localization.Quote.MessageIdDeprecation); await ReplyAsync(sb.ToString(), false, embed.Build()); } diff --git a/src/Bot/Localization/Quote.Designer.cs b/src/Bot/Localization/Quote.Designer.cs index d0926ae..342c181 100644 --- a/src/Bot/Localization/Quote.Designer.cs +++ b/src/Bot/Localization/Quote.Designer.cs @@ -78,15 +78,6 @@ namespace Geekbot.Bot.Localization { } } - /// - /// Looks up a localized string similar to :warning: Creating quotes by message ID is deprecated in favour of message links and will be removed on 1 December 2020. - /// - internal static string MessageIdDeprecation { - get { - return ResourceManager.GetString("MessageIdDeprecation", resourceCulture); - } - } - /// /// Looks up a localized string similar to Most quoted person. /// diff --git a/src/Bot/Localization/Quote.de-ch.resx b/src/Bot/Localization/Quote.de-ch.resx index c7e3b8b..99fd959 100644 --- a/src/Bot/Localization/Quote.de-ch.resx +++ b/src/Bot/Localization/Quote.de-ch.resx @@ -44,7 +44,4 @@ Du chasch numme nachrichte vom gliche server quote - - :warning: Es mache vo quotes mit message-IDs isch zgunste vo message-links veraltet und wird am 1. dezember 2020 entfernt - \ No newline at end of file diff --git a/src/Bot/Localization/Quote.resx b/src/Bot/Localization/Quote.resx index 215f0ea..b51d79c 100644 --- a/src/Bot/Localization/Quote.resx +++ b/src/Bot/Localization/Quote.resx @@ -51,7 +51,4 @@ You can only quote messages from the same server - - :warning: Creating quotes by message ID is deprecated in favour of message links and will be removed on 1 December 2020 - \ No newline at end of file From 714b0008bc480ebb1ac56f9f397d5591dc066df9 Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 11 Dec 2020 22:38:43 +0100 Subject: [PATCH 119/264] Allow a die to have 145 sides --- src/Core/DiceParser/SingleDie.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Core/DiceParser/SingleDie.cs b/src/Core/DiceParser/SingleDie.cs index 4e0f474..7c1ae41 100644 --- a/src/Core/DiceParser/SingleDie.cs +++ b/src/Core/DiceParser/SingleDie.cs @@ -63,9 +63,9 @@ namespace Geekbot.Core.DiceParser throw new DiceException("Die must have at least 2 sides") { DiceName = DiceName }; } - if (Sides > 144) + if (Sides > 145) { - throw new DiceException("Die can not have more than 144 sides") { DiceName = DiceName }; + throw new DiceException("Die can not have more than 145 sides") { DiceName = DiceName }; } } } From 7e792bd7821ada737086c3b8a5171cc82ffc55b4 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 29 Dec 2020 17:12:03 +0100 Subject: [PATCH 120/264] Fallback to user repo when retrieving a user via the discord gateway fails or times out --- src/Bot/Commands/Utils/Quote/Quote.cs | 16 ++++++++++++++-- src/Core/Polyfills/UserPolyfillDto.cs | 3 ++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index a5f2e3c..47986a0 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -13,6 +13,7 @@ using Geekbot.Core.Extensions; using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Polyfills; using Geekbot.Core.RandomNumberGenerator; +using Geekbot.Core.UserRepository; namespace Geekbot.Bot.Commands.Utils.Quote { @@ -22,13 +23,15 @@ namespace Geekbot.Bot.Commands.Utils.Quote { private readonly DatabaseContext _database; private readonly IRandomNumberGenerator _randomNumberGenerator; + private readonly IUserRepository _userRepository; private readonly bool _isDev; - public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager) + public Quote(IErrorHandler errorHandler, DatabaseContext database, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager, IUserRepository userRepository) : base(errorHandler, guildSettingsManager) { _database = database; _randomNumberGenerator = randomNumberGenerator; + _userRepository = userRepository; // to remove restrictions when developing _isDev = Constants.BotVersion() == "0.0.0-DEV"; } @@ -254,7 +257,16 @@ namespace Geekbot.Bot.Commands.Utils.Quote private EmbedBuilder QuoteBuilder(QuoteModel quote) { - var user = Context.Client.GetUserAsync(quote.UserId.AsUlong()).Result ?? new UserPolyfillDto { Username = "Unknown User" }; + var user = Context.Client.GetUserAsync(quote.UserId.AsUlong()).Result; + if (user == null) + { + var fallbackUserFromRepo = _userRepository.Get(quote.UserId.AsUlong()); + user = new UserPolyfillDto() + { + Username = fallbackUserFromRepo?.Username ?? "Unknown User", + AvatarUrl = fallbackUserFromRepo?.AvatarUrl + }; + } var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 167, 232)); if (quote.InternalId == 0) diff --git a/src/Core/Polyfills/UserPolyfillDto.cs b/src/Core/Polyfills/UserPolyfillDto.cs index 3a8f43f..1d3a54b 100644 --- a/src/Core/Polyfills/UserPolyfillDto.cs +++ b/src/Core/Polyfills/UserPolyfillDto.cs @@ -14,6 +14,7 @@ namespace Geekbot.Core.Polyfills public UserStatus Status { get; set; } public IImmutableSet ActiveClients { get; } public string AvatarId { get; set; } + public string AvatarUrl { get; set; } public string Discriminator { get; set; } public ushort DiscriminatorValue { get; set; } public bool IsBot { get; set; } @@ -22,7 +23,7 @@ namespace Geekbot.Core.Polyfills public string GetAvatarUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128) { - return "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png"; + return AvatarUrl ?? "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png"; } public string GetDefaultAvatarUrl() From 29c0def713fb668cdbd1d3bc7a74d94e0738a23c Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 29 Dec 2020 22:33:19 +0100 Subject: [PATCH 121/264] Start counting messages per quarter starting 1 january 2021 --- src/Bot/Handlers/StatsHandler.cs | 88 +++++++++++++++---- src/Core/Database/DatabaseContext.cs | 1 + .../Database/Models/MessageSeasonsModel.cs | 21 +++++ 3 files changed, 95 insertions(+), 15 deletions(-) create mode 100644 src/Core/Database/Models/MessageSeasonsModel.cs diff --git a/src/Bot/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs index 197bbb8..e5962a9 100644 --- a/src/Bot/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -1,5 +1,7 @@ using System; +using System.Globalization; using System.Threading.Tasks; +using System.Timers; using Discord.WebSocket; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; @@ -13,11 +15,28 @@ namespace Geekbot.Bot.Handlers { private readonly IGeekbotLogger _logger; private readonly DatabaseContext _database; + private string _season; + // ToDo: Clean up in 2021 + private bool _seasonsStarted; public StatsHandler(IGeekbotLogger logger, DatabaseContext database) { _logger = logger; _database = database; + _season = GetSeason(); + _seasonsStarted = DateTime.Now.Year == 2021; + + var timer = new Timer() + { + Enabled = true, + AutoReset = true, + Interval = TimeSpan.FromHours(1).TotalMilliseconds + }; + timer.Elapsed += (sender, args) => + { + _season = GetSeason(); + _seasonsStarted = DateTime.Now.Year == 2021; + }; } public async Task UpdateStats(SocketMessage message) @@ -32,23 +51,12 @@ namespace Geekbot.Bot.Handlers } var channel = (SocketGuildChannel) message.Channel; - - var rowId = await _database.Database.ExecuteSqlRawAsync( - "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", - channel.Guild.Id.AsLong(), - message.Author.Id.AsLong() - ); - - if (rowId == 0) + await UpdateTotalTable(message, channel); + if (_seasonsStarted) { - await _database.Messages.AddAsync(new MessagesModel - { - UserId = message.Author.Id.AsLong(), - GuildId = channel.Guild.Id.AsLong(), - MessageCount = 1 - }); - await _database.SaveChangesAsync(); + await UpdateSeasonsTable(message, channel); } + if (message.Author.IsBot) return; _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); @@ -58,5 +66,55 @@ namespace Geekbot.Bot.Handlers _logger.Error(LogSource.Message, "Could not process message stats", e); } } + + private async Task UpdateTotalTable(SocketMessage message, SocketGuildChannel channel) + { + var rowId = await _database.Database.ExecuteSqlRawAsync( + "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}", + channel.Guild.Id.AsLong(), + message.Author.Id.AsLong() + ); + + if (rowId == 0) + { + await _database.Messages.AddAsync(new MessagesModel + { + UserId = message.Author.Id.AsLong(), + GuildId = channel.Guild.Id.AsLong(), + MessageCount = 1 + }); + await _database.SaveChangesAsync(); + } + } + + private async Task UpdateSeasonsTable(SocketMessage message, SocketGuildChannel channel) + { + var rowId = await _database.Database.ExecuteSqlRawAsync( + "UPDATE \"MessagesSeasons\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1} AND \"Season\" = {2}", + channel.Guild.Id.AsLong(), + message.Author.Id.AsLong(), + _season + ); + + if (rowId == 0) + { + await _database.MessagesSeasons.AddAsync(new MessageSeasonsModel() + { + UserId = message.Author.Id.AsLong(), + GuildId = channel.Guild.Id.AsLong(), + Season = _season, + MessageCount = 1 + }); + await _database.SaveChangesAsync(); + } + } + + private static string GetSeason() + { + var now = DateTime.Now; + var year = (now.Year - 2000).ToString(CultureInfo.InvariantCulture); + var quarter = Math.Ceiling(now.Month / 3.0).ToString(CultureInfo.InvariantCulture); + return $"{year}Q{quarter}"; + } } } \ No newline at end of file diff --git a/src/Core/Database/DatabaseContext.cs b/src/Core/Database/DatabaseContext.cs index 93d46d3..14a1275 100644 --- a/src/Core/Database/DatabaseContext.cs +++ b/src/Core/Database/DatabaseContext.cs @@ -11,6 +11,7 @@ namespace Geekbot.Core.Database public DbSet Karma { get; set; } public DbSet Ships { get; set; } public DbSet Rolls { get; set; } + public DbSet MessagesSeasons { get; set; } public DbSet Messages { get; set; } public DbSet Slaps { get; set; } public DbSet Globals { get; set; } diff --git a/src/Core/Database/Models/MessageSeasonsModel.cs b/src/Core/Database/Models/MessageSeasonsModel.cs new file mode 100644 index 0000000..5a4252c --- /dev/null +++ b/src/Core/Database/Models/MessageSeasonsModel.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations; + +namespace Geekbot.Core.Database.Models +{ + public class MessageSeasonsModel + { + [Key] + public int Id { get; set; } + + [Required] + public long GuildId { get; set; } + + [Required] + public long UserId { get; set; } + + [Required] + public string Season { get; set; } + + public int MessageCount { get; set; } + } +} \ No newline at end of file From 29bb8035fe14f4f9a2b34c60f91548433fd82535 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 30 Dec 2020 23:17:00 +0100 Subject: [PATCH 122/264] add !rank seasons to the rank command --- src/Bot/Commands/User/Ranking/Rank.cs | 22 ++++++++++++++++++---- src/Bot/Handlers/StatsHandler.cs | 16 +++++----------- src/Core/Highscores/HighscoreManager.cs | 16 +++++++++++++++- src/Core/Highscores/HighscoreTypes.cs | 3 ++- src/Core/Highscores/IHighscoreManager.cs | 3 ++- src/Core/Highscores/SeasonsUtils.cs | 16 ++++++++++++++++ 6 files changed, 58 insertions(+), 18 deletions(-) create mode 100644 src/Core/Highscores/SeasonsUtils.cs diff --git a/src/Bot/Commands/User/Ranking/Rank.cs b/src/Bot/Commands/User/Ranking/Rank.cs index 20749a8..14a7650 100644 --- a/src/Bot/Commands/User/Ranking/Rank.cs +++ b/src/Bot/Commands/User/Ranking/Rank.cs @@ -30,9 +30,12 @@ namespace Geekbot.Bot.Commands.User.Ranking } [Command("rank", RunMode = RunMode.Async)] - [Summary("get user top 10 in messages or karma")] + [Summary("Get the highscore for various stats like message count, karma, correctly guessed roles, etc...")] [DisableInDirectMessage] - public async Task RankCmd([Summary("type")] string typeUnformated = "messages", [Summary("amount")] int amount = 10) + public async Task RankCmd( + [Summary("type")] string typeUnformated = "messages", + [Summary("amount")] int amount = 10, + [Summary("season")] string season = null) { try { @@ -59,7 +62,7 @@ namespace Geekbot.Bot.Commands.User.Ranking Dictionary highscoreUsers; try { - highscoreUsers = _highscoreManager.GetHighscoresWithUserData(type, guildId, amount); + highscoreUsers = _highscoreManager.GetHighscoresWithUserData(type, guildId, amount, season); } catch (HighscoreListEmptyException) { @@ -80,7 +83,18 @@ namespace Geekbot.Bot.Commands.User.Ranking if (failedToRetrieveUser) replyBuilder.AppendLine(Localization.Rank.FailedToResolveAllUsernames).AppendLine(); - replyBuilder.AppendLine(string.Format(Localization.Rank.HighscoresFor, type.ToString().CapitalizeFirst(), Context.Guild.Name)); + if (type == HighscoreTypes.seasons) + { + if (string.IsNullOrEmpty(season)) + { + season = SeasonsUtils.GetCurrentSeason(); + } + replyBuilder.AppendLine(string.Format(Localization.Rank.HighscoresFor, $"{type.ToString().CapitalizeFirst()} ({season})", Context.Guild.Name)); + } + else + { + replyBuilder.AppendLine(string.Format(Localization.Rank.HighscoresFor, type.ToString().CapitalizeFirst(), Context.Guild.Name)); + } var highscorePlace = 1; foreach (var (user, value) in highscoreUsers) diff --git a/src/Bot/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs index e5962a9..669be0f 100644 --- a/src/Bot/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -1,11 +1,11 @@ using System; -using System.Globalization; using System.Threading.Tasks; using System.Timers; using Discord.WebSocket; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.Extensions; +using Geekbot.Core.Highscores; using Geekbot.Core.Logger; using Microsoft.EntityFrameworkCore; @@ -23,7 +23,7 @@ namespace Geekbot.Bot.Handlers { _logger = logger; _database = database; - _season = GetSeason(); + _season = SeasonsUtils.GetCurrentSeason(); _seasonsStarted = DateTime.Now.Year == 2021; var timer = new Timer() @@ -34,7 +34,9 @@ namespace Geekbot.Bot.Handlers }; timer.Elapsed += (sender, args) => { - _season = GetSeason(); + var current = SeasonsUtils.GetCurrentSeason(); + if (current == _season) return; + _season = SeasonsUtils.GetCurrentSeason(); _seasonsStarted = DateTime.Now.Year == 2021; }; } @@ -108,13 +110,5 @@ namespace Geekbot.Bot.Handlers await _database.SaveChangesAsync(); } } - - private static string GetSeason() - { - var now = DateTime.Now; - var year = (now.Year - 2000).ToString(CultureInfo.InvariantCulture); - var quarter = Math.Ceiling(now.Month / 3.0).ToString(CultureInfo.InvariantCulture); - return $"{year}Q{quarter}"; - } } } \ No newline at end of file diff --git a/src/Core/Highscores/HighscoreManager.cs b/src/Core/Highscores/HighscoreManager.cs index ac8580b..7379e5e 100644 --- a/src/Core/Highscores/HighscoreManager.cs +++ b/src/Core/Highscores/HighscoreManager.cs @@ -18,7 +18,7 @@ namespace Geekbot.Core.Highscores } - public Dictionary GetHighscoresWithUserData(HighscoreTypes type, ulong guildId, int amount) + public Dictionary GetHighscoresWithUserData(HighscoreTypes type, ulong guildId, int amount, string season = null) { var list = type switch { @@ -26,6 +26,7 @@ namespace Geekbot.Core.Highscores HighscoreTypes.karma => GetKarmaList(guildId, amount), HighscoreTypes.rolls => GetRollsList(guildId, amount), HighscoreTypes.cookies => GetCookiesList(guildId, amount), + HighscoreTypes.seasons => GetMessageSeasonList(guildId, amount, season), _ => new Dictionary() }; @@ -75,6 +76,19 @@ namespace Geekbot.Core.Highscores .ToDictionary(key => key.UserId.AsUlong(), key => key.MessageCount); } + public Dictionary GetMessageSeasonList(ulong guildId, int amount, string season) + { + if (string.IsNullOrEmpty(season)) + { + season = SeasonsUtils.GetCurrentSeason(); + } + return _database.MessagesSeasons + .Where(k => k.GuildId.Equals(guildId.AsLong()) && k.Season.Equals(season)) + .OrderByDescending(o => o.MessageCount) + .Take(amount) + .ToDictionary(key => key.UserId.AsUlong(), key => key.MessageCount); + } + public Dictionary GetKarmaList(ulong guildId, int amount) { return _database.Karma diff --git a/src/Core/Highscores/HighscoreTypes.cs b/src/Core/Highscores/HighscoreTypes.cs index b577642..9901c98 100644 --- a/src/Core/Highscores/HighscoreTypes.cs +++ b/src/Core/Highscores/HighscoreTypes.cs @@ -5,6 +5,7 @@ messages, karma, rolls, - cookies + cookies, + seasons } } \ No newline at end of file diff --git a/src/Core/Highscores/IHighscoreManager.cs b/src/Core/Highscores/IHighscoreManager.cs index 83ba2da..9c2d6f0 100644 --- a/src/Core/Highscores/IHighscoreManager.cs +++ b/src/Core/Highscores/IHighscoreManager.cs @@ -4,8 +4,9 @@ namespace Geekbot.Core.Highscores { public interface IHighscoreManager { - Dictionary GetHighscoresWithUserData(HighscoreTypes type, ulong guildId, int amount); + Dictionary GetHighscoresWithUserData(HighscoreTypes type, ulong guildId, int amount, string season = null); Dictionary GetMessageList(ulong guildId, int amount); + Dictionary GetMessageSeasonList(ulong guildId, int amount, string season); Dictionary GetKarmaList(ulong guildId, int amount); Dictionary GetRollsList(ulong guildId, int amount); } diff --git a/src/Core/Highscores/SeasonsUtils.cs b/src/Core/Highscores/SeasonsUtils.cs new file mode 100644 index 0000000..d2a8e3e --- /dev/null +++ b/src/Core/Highscores/SeasonsUtils.cs @@ -0,0 +1,16 @@ +using System; +using System.Globalization; + +namespace Geekbot.Core.Highscores +{ + public class SeasonsUtils + { + public static string GetCurrentSeason() + { + var now = DateTime.Now; + var year = (now.Year - 2000).ToString(CultureInfo.InvariantCulture); + var quarter = Math.Ceiling(now.Month / 3.0).ToString(CultureInfo.InvariantCulture); + return $"{year}Q{quarter}"; + } + } +} \ No newline at end of file From 01f0d2f43b613d07b9a5be365c6274f2f9dbd983 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 30 Dec 2020 23:19:15 +0100 Subject: [PATCH 123/264] Check every 5 minutes if it's 2021 instead of every hour in the stats handler --- src/Bot/Handlers/StatsHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Bot/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs index 669be0f..137842c 100644 --- a/src/Bot/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -30,7 +30,7 @@ namespace Geekbot.Bot.Handlers { Enabled = true, AutoReset = true, - Interval = TimeSpan.FromHours(1).TotalMilliseconds + Interval = TimeSpan.FromMinutes(5).TotalMilliseconds }; timer.Elapsed += (sender, args) => { From 17f62d76079f48c49e9943a6f11f73adb15970ca Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 30 Dec 2020 23:23:40 +0100 Subject: [PATCH 124/264] Ignore the discord bots server when updating stats --- src/Bot/Handlers/StatsHandler.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Bot/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs index 137842c..5ee7871 100644 --- a/src/Bot/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using System.Timers; using Discord.WebSocket; @@ -25,7 +26,7 @@ namespace Geekbot.Bot.Handlers _database = database; _season = SeasonsUtils.GetCurrentSeason(); _seasonsStarted = DateTime.Now.Year == 2021; - + var timer = new Timer() { Enabled = true, @@ -53,6 +54,14 @@ namespace Geekbot.Bot.Handlers } var channel = (SocketGuildChannel) message.Channel; + + // ignore the discord bots server + // ToDo: create a clean solution for this... + if (channel.Guild.Id == 110373943822540800) + { + return; + } + await UpdateTotalTable(message, channel); if (_seasonsStarted) { From 8bdf2e96818c2ef2ad5acb6906ca8200e7851e77 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 30 Dec 2020 23:31:15 +0100 Subject: [PATCH 125/264] Add support for !rank quote --- src/Bot/Commands/Utils/Quote/Quote.cs | 4 ++-- src/Core/Highscores/HighscoreManager.cs | 12 ++++++++++++ src/Core/Highscores/HighscoreTypes.cs | 3 ++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 47986a0..6a94309 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -147,8 +147,8 @@ namespace Geekbot.Bot.Commands.Utils.Quote .Where(row => row.GuildId == Context.Guild.Id.AsLong()) .GroupBy(row => row.UserId) .Select(row => new { userId = row.Key, amount = row.Count()}) - .OrderBy(row => row.amount) - .Last(); + .OrderByDescending(row => row.amount) + .First(); var mostQuotedPersonUser = Context.Client.GetUserAsync(mostQuotedPerson.userId.AsUlong()).Result ?? new UserPolyfillDto {Username = "Unknown User"}; var quotesByYear = _database.Quotes diff --git a/src/Core/Highscores/HighscoreManager.cs b/src/Core/Highscores/HighscoreManager.cs index 7379e5e..c839b39 100644 --- a/src/Core/Highscores/HighscoreManager.cs +++ b/src/Core/Highscores/HighscoreManager.cs @@ -27,6 +27,7 @@ namespace Geekbot.Core.Highscores HighscoreTypes.rolls => GetRollsList(guildId, amount), HighscoreTypes.cookies => GetCookiesList(guildId, amount), HighscoreTypes.seasons => GetMessageSeasonList(guildId, amount, season), + HighscoreTypes.quotes => GetQuotesList(guildId, amount), _ => new Dictionary() }; @@ -115,5 +116,16 @@ namespace Geekbot.Core.Highscores .Take(amount) .ToDictionary(key => key.UserId.AsUlong(), key => key.Cookies); } + + private Dictionary GetQuotesList(ulong guildId, int amount) + { + return _database.Quotes + .Where(row => row.GuildId == guildId.AsLong()) + .GroupBy(row => row.UserId) + .Select(row => new { userId = row.Key, amount = row.Count()}) + .OrderByDescending(row => row.amount) + .Take(amount) + .ToDictionary(key => key.userId.AsUlong(), key => key.amount); + } } } \ No newline at end of file diff --git a/src/Core/Highscores/HighscoreTypes.cs b/src/Core/Highscores/HighscoreTypes.cs index 9901c98..3aa396e 100644 --- a/src/Core/Highscores/HighscoreTypes.cs +++ b/src/Core/Highscores/HighscoreTypes.cs @@ -6,6 +6,7 @@ karma, rolls, cookies, - seasons + seasons, + quotes } } \ No newline at end of file From d477a4b056e209c4462fc369e311ec7044afb3e7 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 30 Dec 2020 23:33:27 +0100 Subject: [PATCH 126/264] Update the translations for !rank with the new rank types --- src/Bot/Localization/Rank.Designer.cs | 2 +- src/Bot/Localization/Rank.de-ch.resx | 2 +- src/Bot/Localization/Rank.resx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Bot/Localization/Rank.Designer.cs b/src/Bot/Localization/Rank.Designer.cs index 23f5e16..6d54030 100644 --- a/src/Bot/Localization/Rank.Designer.cs +++ b/src/Bot/Localization/Rank.Designer.cs @@ -79,7 +79,7 @@ namespace Geekbot.Bot.Localization { } /// - /// Looks up a localized string similar to Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`'. + /// Looks up a localized string similar to Valid types are '`messages`' '`karma`', '`rolls`', '`cookies`', '`seasons`' and '`quotes`'. /// internal static string InvalidType { get { diff --git a/src/Bot/Localization/Rank.de-ch.resx b/src/Bot/Localization/Rank.de-ch.resx index 0b22fe4..743b8cd 100644 --- a/src/Bot/Localization/Rank.de-ch.resx +++ b/src/Bot/Localization/Rank.de-ch.resx @@ -24,6 +24,6 @@ :bar_chart: **{0} Highscore für {1}**
- Gültigi paramenter sind '`messages`' '`karma`', '`rolls`' und '`cookies` + Gültigi paramenter sind '`messages`' '`karma`', '`rolls`', '`cookies`', '`seasons`' und '`quotes`' \ No newline at end of file diff --git a/src/Bot/Localization/Rank.resx b/src/Bot/Localization/Rank.resx index 9598cf8..606a34e 100644 --- a/src/Bot/Localization/Rank.resx +++ b/src/Bot/Localization/Rank.resx @@ -19,7 +19,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Valid types are '`messages`' '`karma`', '`rolls`' and '`cookies`' + Valid types are '`messages`' '`karma`', '`rolls`', '`cookies`', '`seasons`' and '`quotes`' :warning: Limiting to 20 From e495e2df17178bf0f444fe5a9bc0c73ad19dc920 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 1 Jan 2021 02:48:28 +0100 Subject: [PATCH 127/264] Use the correct unit when listing messages in a season --- src/Bot/Commands/User/Ranking/Rank.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Bot/Commands/User/Ranking/Rank.cs b/src/Bot/Commands/User/Ranking/Rank.cs index 14a7650..2f5f841 100644 --- a/src/Bot/Commands/User/Ranking/Rank.cs +++ b/src/Bot/Commands/User/Ranking/Rank.cs @@ -106,10 +106,13 @@ namespace Geekbot.Bot.Commands.User.Ranking replyBuilder.Append(user.Username != null ? $"**{user.Username}#{user.Discriminator}**" : $"**{user.Id}**"); - - replyBuilder.Append(type == HighscoreTypes.messages - ? $" - {value} {type} - {Math.Round((double) (100 * value) / guildMessages, 2)}%\n" - : $" - {value} {type}\n"); + + replyBuilder.Append(type switch + { + HighscoreTypes.messages => $" - {value} {HighscoreTypes.messages} - {Math.Round((double) (100 * value) / guildMessages, 2)}%\n", + HighscoreTypes.seasons => $" - {value} {HighscoreTypes.messages}\n", + _ => $" - {value} {type}\n" + }); highscorePlace++; } From 21303bfca81015af03e02d3a92f15e86f98d00ba Mon Sep 17 00:00:00 2001 From: runebaas Date: Fri, 1 Jan 2021 18:06:40 +0100 Subject: [PATCH 128/264] Remove code in the stats handler that checks if 2021 has started --- src/Bot/Handlers/StatsHandler.cs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/Bot/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs index 5ee7871..d1384cd 100644 --- a/src/Bot/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -17,15 +17,12 @@ namespace Geekbot.Bot.Handlers private readonly IGeekbotLogger _logger; private readonly DatabaseContext _database; private string _season; - // ToDo: Clean up in 2021 - private bool _seasonsStarted; public StatsHandler(IGeekbotLogger logger, DatabaseContext database) { _logger = logger; _database = database; _season = SeasonsUtils.GetCurrentSeason(); - _seasonsStarted = DateTime.Now.Year == 2021; var timer = new Timer() { @@ -38,7 +35,6 @@ namespace Geekbot.Bot.Handlers var current = SeasonsUtils.GetCurrentSeason(); if (current == _season) return; _season = SeasonsUtils.GetCurrentSeason(); - _seasonsStarted = DateTime.Now.Year == 2021; }; } @@ -62,11 +58,8 @@ namespace Geekbot.Bot.Handlers return; } - await UpdateTotalTable(message, channel); - if (_seasonsStarted) - { - await UpdateSeasonsTable(message, channel); - } + await UpdateTotalTable(message, channel); + await UpdateSeasonsTable(message, channel); if (message.Author.IsBot) return; From 04343352395a6f015e2acf919f64e5de2f5aca92 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 24 Jan 2021 22:15:15 +0100 Subject: [PATCH 129/264] Fix !corona by changing data source to covid19-api.org, added a country code parameter as well --- .../Corona/CoronaApiCountryResponseDto.cs | 19 +++++ src/Bot/Commands/Utils/Corona/CoronaStats.cs | 72 +++++++++++++++---- .../Commands/Utils/Corona/CoronaSummaryDto.cs | 9 --- .../Commands/Utils/Corona/CoronaTotalDto.cs | 9 +++ 4 files changed, 87 insertions(+), 22 deletions(-) create mode 100644 src/Bot/Commands/Utils/Corona/CoronaApiCountryResponseDto.cs delete mode 100644 src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs create mode 100644 src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs diff --git a/src/Bot/Commands/Utils/Corona/CoronaApiCountryResponseDto.cs b/src/Bot/Commands/Utils/Corona/CoronaApiCountryResponseDto.cs new file mode 100644 index 0000000..84da7f0 --- /dev/null +++ b/src/Bot/Commands/Utils/Corona/CoronaApiCountryResponseDto.cs @@ -0,0 +1,19 @@ +using Newtonsoft.Json; + +namespace Geekbot.Bot.Commands.Utils.Corona +{ + public record CoronaApiCountryResponseDto + { + [JsonProperty("country")] + public string Country { get; init; } + + [JsonProperty("cases")] + public decimal Cases { get; init; } + + [JsonProperty("deaths")] + public decimal Deaths { get; init; } + + [JsonProperty("recovered")] + public decimal Recovered { get; init; } + } +} \ No newline at end of file diff --git a/src/Bot/Commands/Utils/Corona/CoronaStats.cs b/src/Bot/Commands/Utils/Corona/CoronaStats.cs index 3f9f3ea..5880030 100644 --- a/src/Bot/Commands/Utils/Corona/CoronaStats.cs +++ b/src/Bot/Commands/Utils/Corona/CoronaStats.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; @@ -11,7 +13,7 @@ namespace Geekbot.Bot.Commands.Utils.Corona public class CoronaStats : ModuleBase { private readonly IErrorHandler _errorHandler; - + public CoronaStats(IErrorHandler errorHandler) { _errorHandler = errorHandler; @@ -19,24 +21,30 @@ namespace Geekbot.Bot.Commands.Utils.Corona [Command("corona", RunMode = RunMode.Async)] [Summary("Get the latest worldwide corona statistics")] - public async Task Summary() + public async Task Summary([Summary("CountryCode")] string countryCode = null) { try { - var summary = await HttpAbstractions.Get(new Uri("https://api.covid19api.com/world/total")); - var activeCases = summary.TotalConfirmed - (summary.TotalRecovered + summary.TotalDeaths); + var summary = await GetCoronaInfo(countryCode); + if (summary == null) + { + await Context.Channel.SendMessageAsync($"`{countryCode}` is not a valid country code"); + return; + } + + var activeCases = summary.Cases - (summary.Recovered + summary.Deaths); - string CalculatePercentage(decimal i) => (i / summary.TotalConfirmed).ToString("#0.##%"); + string CalculatePercentage(decimal i) => (i / summary.Cases).ToString("#0.##%"); var activePercent = CalculatePercentage(activeCases); - var recoveredPercentage = CalculatePercentage(summary.TotalRecovered); - var deathsPercentage = CalculatePercentage(summary.TotalDeaths); + var recoveredPercentage = CalculatePercentage(summary.Recovered); + var deathsPercentage = CalculatePercentage(summary.Deaths); var numberFormat = "#,#"; - var totalFormatted = summary.TotalConfirmed.ToString(numberFormat); + var totalFormatted = summary.Cases.ToString(numberFormat); var activeFormatted = activeCases.ToString(numberFormat); - var recoveredFormatted = summary.TotalRecovered.ToString(numberFormat); - var deathsFormatted = summary.TotalDeaths.ToString(numberFormat); - + var recoveredFormatted = summary.Recovered.ToString(numberFormat); + var deathsFormatted = summary.Deaths.ToString(numberFormat); + var eb = new EmbedBuilder { Author = new EmbedAuthorBuilder @@ -46,7 +54,7 @@ namespace Geekbot.Bot.Commands.Utils.Corona }, Footer = new EmbedFooterBuilder { - Text = "Source: covid19api.com", + Text = "Source: covid19-api.org", }, Color = Color.Red }; @@ -54,7 +62,7 @@ namespace Geekbot.Bot.Commands.Utils.Corona eb.AddInlineField("Active", $"{activeFormatted} ({activePercent})"); eb.AddInlineField("Recovered", $"{recoveredFormatted} ({recoveredPercentage})"); eb.AddInlineField("Deaths", $"{deathsFormatted} ({deathsPercentage})"); - + await Context.Channel.SendMessageAsync(String.Empty, false, eb.Build()); } catch (Exception e) @@ -62,5 +70,43 @@ namespace Geekbot.Bot.Commands.Utils.Corona await _errorHandler.HandleCommandException(e, Context); } } + + private async Task GetCoronaInfo(string countryCode = null) + { + var allCountries = await HttpAbstractions.Get>(new Uri("https://covid19-api.org/api/status")); + + if (string.IsNullOrEmpty(countryCode)) + { + return allCountries.Aggregate( + new CoronaTotalDto(), + (accumulate, source) => + { + accumulate.Cases += source.Cases; + accumulate.Deaths += source.Deaths; + accumulate.Recovered += source.Recovered; + return accumulate; + } + ); + } + + if (countryCode.Length != 2) + { + return null; + } + + var upcasedCountryCode = countryCode.ToUpper(); + var countryStats = allCountries.Find(x => x.Country == upcasedCountryCode); + if (countryStats == null) + { + return null; + } + + return new CoronaTotalDto() + { + Cases = countryStats.Cases, + Deaths = countryStats.Deaths, + Recovered = countryStats.Recovered, + }; + } } } \ No newline at end of file diff --git a/src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs b/src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs deleted file mode 100644 index 3f6a820..0000000 --- a/src/Bot/Commands/Utils/Corona/CoronaSummaryDto.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Geekbot.Bot.Commands.Utils.Corona -{ - public class CoronaSummaryDto - { - public decimal TotalConfirmed { get; set; } - public decimal TotalDeaths { get; set; } - public decimal TotalRecovered { get; set; } - } -} \ No newline at end of file diff --git a/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs b/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs new file mode 100644 index 0000000..c135927 --- /dev/null +++ b/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs @@ -0,0 +1,9 @@ +namespace Geekbot.Bot.Commands.Utils.Corona +{ + public record CoronaTotalDto + { + public decimal Cases { get; set; } + public decimal Deaths { get; set; } + public decimal Recovered { get; set; } + } +} \ No newline at end of file From 4fd62e9184145db1f76f33ebc3762c782e7fcde5 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 24 Jan 2021 22:20:59 +0100 Subject: [PATCH 130/264] Make sure that the build version suffix is not a number --- .gitlab-ci.yml | 4 ++-- src/Bot/Bot.csproj | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c4d8b15..20b1c84 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -5,7 +5,7 @@ stages: - ops variables: - VERSION: 4.3.0-$CI_COMMIT_SHORT_SHA + VERSION: 4.3.0-V$CI_COMMIT_SHORT_SHA IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG Build: @@ -18,7 +18,7 @@ Build: script: - dotnet restore - dotnet test tests - - dotnet publish --version-suffix $VERSION -r linux-x64 -c Release -o ./app ./src/Bot/ + - dotnet publish --version-suffix "$VERSION" -r linux-x64 -c Release -o ./app ./src/Bot/ Package: stage: docker diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 4cd5b39..ec32e8f 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -7,7 +7,7 @@ $(VersionSuffix) Geekbot.Bot Geekbot - $(VersionSuffix) + $(VersionSuffix) 0.0.0-DEV Pizza and Coffee Studios Pizza and Coffee Studios From bbb9b894227f6f136bddfa1f8b418166d623d82d Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 25 Jan 2021 00:48:42 +0100 Subject: [PATCH 131/264] Add Support for emoji flags in the emoji converter --- src/Core/Converters/EmojiConverter.cs | 166 ++++++++++++++++--------- src/Core/Converters/IEmojiConverter.cs | 1 + 2 files changed, 107 insertions(+), 60 deletions(-) diff --git a/src/Core/Converters/EmojiConverter.cs b/src/Core/Converters/EmojiConverter.cs index 327aab8..7527321 100644 --- a/src/Core/Converters/EmojiConverter.cs +++ b/src/Core/Converters/EmojiConverter.cs @@ -1,90 +1,136 @@ using System.Collections; +using System.Net.NetworkInformation; using System.Text; namespace Geekbot.Core.Converters { public class EmojiConverter : IEmojiConverter { + private readonly string[] NumberEmojiMap = + { + ":zero:", + ":one:", + ":two:", + ":three:", + ":four:", + ":five:", + ":six:", + ":seven:", + ":eight:", + ":nine:" + }; + public string NumberToEmoji(int number) { if (number == 10) { return "🔟"; } - var emojiMap = new[] - { - ":zero:", - ":one:", - ":two:", - ":three:", - ":four:", - ":five:", - ":six:", - ":seven:", - ":eight:", - ":nine:" - }; + var numbers = number.ToString().ToCharArray(); var returnString = new StringBuilder(); foreach (var n in numbers) { - returnString.Append(emojiMap[int.Parse(n.ToString())]); + returnString.Append(NumberEmojiMap[int.Parse(n.ToString())]); } return returnString.ToString(); } + private readonly Hashtable TextEmojiMap = new Hashtable + { + ['A'] = ":regional_indicator_a: ", + ['B'] = ":b: ", + ['C'] = ":regional_indicator_c: ", + ['D'] = ":regional_indicator_d: ", + ['E'] = ":regional_indicator_e: ", + ['F'] = ":regional_indicator_f: ", + ['G'] = ":regional_indicator_g: ", + ['H'] = ":regional_indicator_h: ", + ['I'] = ":regional_indicator_i: ", + ['J'] = ":regional_indicator_j: ", + ['K'] = ":regional_indicator_k: ", + ['L'] = ":regional_indicator_l: ", + ['M'] = ":regional_indicator_m: ", + ['N'] = ":regional_indicator_n: ", + ['O'] = ":regional_indicator_o: ", + ['P'] = ":regional_indicator_p: ", + ['Q'] = ":regional_indicator_q: ", + ['R'] = ":regional_indicator_r: ", + ['S'] = ":regional_indicator_s: ", + ['T'] = ":regional_indicator_t: ", + ['U'] = ":regional_indicator_u: ", + ['V'] = ":regional_indicator_v: ", + ['W'] = ":regional_indicator_w: ", + ['X'] = ":regional_indicator_x: ", + ['Y'] = ":regional_indicator_y: ", + ['Z'] = ":regional_indicator_z: ", + ['!'] = ":exclamation: ", + ['?'] = ":question: ", + ['#'] = ":hash: ", + ['*'] = ":star2: ", + ['+'] = ":heavy_plus_sign: ", + ['0'] = ":zero: ", + ['1'] = ":one: ", + ['2'] = ":two: ", + ['3'] = ":three: ", + ['4'] = ":four: ", + ['5'] = ":five: ", + ['6'] = ":six: ", + ['7'] = ":seven: ", + ['8'] = ":eight: ", + ['9'] = ":nine: ", + [' '] = " " + }; + public string TextToEmoji(string text) { - var emojiMap = new Hashtable - { - ['A'] = ":regional_indicator_a: ", - ['B'] = ":b: ", - ['C'] = ":regional_indicator_c: ", - ['D'] = ":regional_indicator_d: ", - ['E'] = ":regional_indicator_e: ", - ['F'] = ":regional_indicator_f: ", - ['G'] = ":regional_indicator_g: ", - ['H'] = ":regional_indicator_h: ", - ['I'] = ":regional_indicator_i: ", - ['J'] = ":regional_indicator_j: ", - ['K'] = ":regional_indicator_k: ", - ['L'] = ":regional_indicator_l: ", - ['M'] = ":regional_indicator_m: ", - ['N'] = ":regional_indicator_n: ", - ['O'] = ":regional_indicator_o: ", - ['P'] = ":regional_indicator_p: ", - ['Q'] = ":regional_indicator_q: ", - ['R'] = ":regional_indicator_r: ", - ['S'] = ":regional_indicator_s: ", - ['T'] = ":regional_indicator_t: ", - ['U'] = ":regional_indicator_u: ", - ['V'] = ":regional_indicator_v: ", - ['W'] = ":regional_indicator_w: ", - ['X'] = ":regional_indicator_x: ", - ['Y'] = ":regional_indicator_y: ", - ['Z'] = ":regional_indicator_z: ", - ['!'] = ":exclamation: ", - ['?'] = ":question: ", - ['#'] = ":hash: ", - ['*'] = ":star2: ", - ['+'] = ":heavy_plus_sign: ", - ['0'] = ":zero: ", - ['1'] = ":one: ", - ['2'] = ":two: ", - ['3'] = ":three: ", - ['4'] = ":four: ", - ['5'] = ":five: ", - ['6'] = ":six: ", - ['7'] = ":seven: ", - ['8'] = ":eight: ", - ['9'] = ":nine: ", - [' '] = " " - }; var letters = text.ToUpper().ToCharArray(); var returnString = new StringBuilder(); foreach (var n in letters) { - var emoji = emojiMap[n] ?? n; + var emoji = TextEmojiMap[n] ?? n; + returnString.Append(emoji); + } + return returnString.ToString(); + } + + private readonly Hashtable RegionalIndicatorMap = new Hashtable() + { + ['A'] = new Rune(0x1F1E6), + ['B'] = new Rune(0x1F1E7), + ['C'] = new Rune(0x1F1E8), + ['D'] = new Rune(0x1F1E9), + ['E'] = new Rune(0x1F1EA), + ['F'] = new Rune(0x1F1EB), + ['G'] = new Rune(0x1F1EC), + ['H'] = new Rune(0x1F1ED), + ['I'] = new Rune(0x1F1EE), + ['J'] = new Rune(0x1F1EF), + ['K'] = new Rune(0x1F1F0), + ['L'] = new Rune(0x1F1F1), + ['M'] = new Rune(0x1F1F2), + ['N'] = new Rune(0x1F1F3), + ['O'] = new Rune(0x1F1F4), + ['P'] = new Rune(0x1F1F5), + ['Q'] = new Rune(0x1F1F6), + ['R'] = new Rune(0x1F1F7), + ['S'] = new Rune(0x1F1F8), + ['T'] = new Rune(0x1F1F9), + ['U'] = new Rune(0x1F1FA), + ['V'] = new Rune(0x1F1FB), + ['W'] = new Rune(0x1F1FC), + ['X'] = new Rune(0x1F1FD), + ['Y'] = new Rune(0x1F1FE), + ['Z'] = new Rune(0x1F1FF) + }; + + public string CountryCodeToEmoji(string countryCode) + { + var letters = countryCode.ToUpper().ToCharArray(); + var returnString = new StringBuilder(); + foreach (var n in letters) + { + var emoji = RegionalIndicatorMap[n]; returnString.Append(emoji); } return returnString.ToString(); diff --git a/src/Core/Converters/IEmojiConverter.cs b/src/Core/Converters/IEmojiConverter.cs index 79ca0a7..0c364ea 100644 --- a/src/Core/Converters/IEmojiConverter.cs +++ b/src/Core/Converters/IEmojiConverter.cs @@ -4,5 +4,6 @@ { string NumberToEmoji(int number); string TextToEmoji(string text); + string CountryCodeToEmoji(string countryCode); } } \ No newline at end of file From 644d877e29adda6752be60578281572ca648138b Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 25 Jan 2021 00:49:18 +0100 Subject: [PATCH 132/264] Show country flag when !corona has a country code parameter --- src/Bot/Commands/Utils/Corona/CoronaStats.cs | 17 +++++++++++++++-- src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs | 1 + 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Utils/Corona/CoronaStats.cs b/src/Bot/Commands/Utils/Corona/CoronaStats.cs index 5880030..15431d2 100644 --- a/src/Bot/Commands/Utils/Corona/CoronaStats.cs +++ b/src/Bot/Commands/Utils/Corona/CoronaStats.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.Core; +using Geekbot.Core.Converters; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; @@ -13,10 +15,12 @@ namespace Geekbot.Bot.Commands.Utils.Corona public class CoronaStats : ModuleBase { private readonly IErrorHandler _errorHandler; + private readonly IEmojiConverter _emojiConverter; - public CoronaStats(IErrorHandler errorHandler) + public CoronaStats(IErrorHandler errorHandler, IEmojiConverter emojiConverter) { _errorHandler = errorHandler; + _emojiConverter = emojiConverter; } [Command("corona", RunMode = RunMode.Async)] @@ -45,11 +49,19 @@ namespace Geekbot.Bot.Commands.Utils.Corona var recoveredFormatted = summary.Recovered.ToString(numberFormat); var deathsFormatted = summary.Deaths.ToString(numberFormat); + var embedTitleBuilder = new StringBuilder(); + embedTitleBuilder.Append("Confirmed Corona Cases"); + if (!string.IsNullOrEmpty(summary.Country)) + { + embedTitleBuilder.Append(" - "); + embedTitleBuilder.Append(_emojiConverter.CountryCodeToEmoji(summary.Country)); + } + var eb = new EmbedBuilder { Author = new EmbedAuthorBuilder { - Name = "Confirmed Corona Cases", + Name = embedTitleBuilder.ToString(), IconUrl = "https://www.redcross.org/content/dam/icons/disasters/virus/Virus-1000x1000-R-Pl.png" }, Footer = new EmbedFooterBuilder @@ -103,6 +115,7 @@ namespace Geekbot.Bot.Commands.Utils.Corona return new CoronaTotalDto() { + Country = upcasedCountryCode, Cases = countryStats.Cases, Deaths = countryStats.Deaths, Recovered = countryStats.Recovered, diff --git a/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs b/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs index c135927..58e5ac9 100644 --- a/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs +++ b/src/Bot/Commands/Utils/Corona/CoronaTotalDto.cs @@ -2,6 +2,7 @@ namespace Geekbot.Bot.Commands.Utils.Corona { public record CoronaTotalDto { + public string Country { get; set; } public decimal Cases { get; set; } public decimal Deaths { get; set; } public decimal Recovered { get; set; } From eddd005d34159ab7890c2795707157d4bef5d6c4 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 25 Jan 2021 01:40:51 +0100 Subject: [PATCH 133/264] Add translations for !corona --- src/Bot/Bot.csproj | 9 ++ src/Bot/Commands/Utils/Corona/CoronaStats.cs | 21 ++-- src/Bot/Localization/Corona.Designer.cs | 117 +++++++++++++++++++ src/Bot/Localization/Corona.de-ch.resx | 32 +++++ src/Bot/Localization/Corona.resx | 39 +++++++ 5 files changed, 207 insertions(+), 11 deletions(-) create mode 100644 src/Bot/Localization/Corona.Designer.cs create mode 100644 src/Bot/Localization/Corona.de-ch.resx create mode 100644 src/Bot/Localization/Corona.resx diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index ec32e8f..6c6f56f 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -84,6 +84,10 @@ ResXFileCodeGenerator Stats.Designer.cs + + ResXFileCodeGenerator + Corona.Designer.cs +
@@ -144,5 +148,10 @@ True Stats.resx + + True + True + Corona.resx + diff --git a/src/Bot/Commands/Utils/Corona/CoronaStats.cs b/src/Bot/Commands/Utils/Corona/CoronaStats.cs index 15431d2..e39be0a 100644 --- a/src/Bot/Commands/Utils/Corona/CoronaStats.cs +++ b/src/Bot/Commands/Utils/Corona/CoronaStats.cs @@ -9,17 +9,16 @@ using Geekbot.Core; using Geekbot.Core.Converters; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; namespace Geekbot.Bot.Commands.Utils.Corona { - public class CoronaStats : ModuleBase + public class CoronaStats : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; private readonly IEmojiConverter _emojiConverter; - public CoronaStats(IErrorHandler errorHandler, IEmojiConverter emojiConverter) + public CoronaStats(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager, IEmojiConverter emojiConverter) : base(errorHandler, guildSettingsManager) { - _errorHandler = errorHandler; _emojiConverter = emojiConverter; } @@ -50,7 +49,7 @@ namespace Geekbot.Bot.Commands.Utils.Corona var deathsFormatted = summary.Deaths.ToString(numberFormat); var embedTitleBuilder = new StringBuilder(); - embedTitleBuilder.Append("Confirmed Corona Cases"); + embedTitleBuilder.Append(Localization.Corona.ConfirmedCases); if (!string.IsNullOrEmpty(summary.Country)) { embedTitleBuilder.Append(" - "); @@ -66,20 +65,20 @@ namespace Geekbot.Bot.Commands.Utils.Corona }, Footer = new EmbedFooterBuilder { - Text = "Source: covid19-api.org", + Text = $"{Localization.Corona.Source}: covid19-api.org", }, Color = Color.Red }; - eb.AddField("Total", totalFormatted); - eb.AddInlineField("Active", $"{activeFormatted} ({activePercent})"); - eb.AddInlineField("Recovered", $"{recoveredFormatted} ({recoveredPercentage})"); - eb.AddInlineField("Deaths", $"{deathsFormatted} ({deathsPercentage})"); + eb.AddField(Localization.Corona.Total, totalFormatted); + eb.AddInlineField(Localization.Corona.Active, $"{activeFormatted} ({activePercent})"); + eb.AddInlineField(Localization.Corona.Recovered, $"{recoveredFormatted} ({recoveredPercentage})"); + eb.AddInlineField(Localization.Corona.Deaths, $"{deathsFormatted} ({deathsPercentage})"); await Context.Channel.SendMessageAsync(String.Empty, false, eb.Build()); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } diff --git a/src/Bot/Localization/Corona.Designer.cs b/src/Bot/Localization/Corona.Designer.cs new file mode 100644 index 0000000..b243bfc --- /dev/null +++ b/src/Bot/Localization/Corona.Designer.cs @@ -0,0 +1,117 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Corona { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Corona() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Corona", typeof(Corona).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Active. + /// + internal static string Active { + get { + return ResourceManager.GetString("Active", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirmed Corona Cases. + /// + internal static string ConfirmedCases { + get { + return ResourceManager.GetString("ConfirmedCases", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deaths. + /// + internal static string Deaths { + get { + return ResourceManager.GetString("Deaths", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Recovered. + /// + internal static string Recovered { + get { + return ResourceManager.GetString("Recovered", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Source. + /// + internal static string Source { + get { + return ResourceManager.GetString("Source", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Total. + /// + internal static string Total { + get { + return ResourceManager.GetString("Total", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Corona.de-ch.resx b/src/Bot/Localization/Corona.de-ch.resx new file mode 100644 index 0000000..3c4180c --- /dev/null +++ b/src/Bot/Localization/Corona.de-ch.resx @@ -0,0 +1,32 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Bstätigti Corona Fallzahle + + + Total + + + Aktiv + + + Erholt + + + Gstorbe + + + Quelle + + \ No newline at end of file diff --git a/src/Bot/Localization/Corona.resx b/src/Bot/Localization/Corona.resx new file mode 100644 index 0000000..44bf85e --- /dev/null +++ b/src/Bot/Localization/Corona.resx @@ -0,0 +1,39 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Confirmed Corona Cases + + + Total + + + Active + + + Recovered + + + Deaths + + + Source + + \ No newline at end of file From c1b8394e1b092d9d7b459f2969cad5ebb21e1b24 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Thu, 18 Mar 2021 12:06:41 +0100 Subject: [PATCH 134/264] Add a !neutral command for karma, it does nothing. --- src/Bot/Commands/User/Karma.cs | 41 ++++++++++++++++++++++++++ src/Bot/Localization/Karma.Designer.cs | 9 ++++++ src/Bot/Localization/Karma.de-ch.resx | 3 ++ src/Bot/Localization/Karma.resx | 3 ++ 4 files changed, 56 insertions(+) diff --git a/src/Bot/Commands/User/Karma.cs b/src/Bot/Commands/User/Karma.cs index 4778bce..3ba8650 100644 --- a/src/Bot/Commands/User/Karma.cs +++ b/src/Bot/Commands/User/Karma.cs @@ -115,6 +115,47 @@ namespace Geekbot.Bot.Commands.User await ErrorHandler.HandleCommandException(e, Context); } } + + [Command("neutral", RunMode = RunMode.Async)] + [Summary("Do nothing to someones karma")] + public async Task Neutral([Summary("@someone")] IUser user) + { + try + { + var actor = await GetUser(Context.User.Id); + if (user.Id == Context.User.Id) + { + await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnDown, Context.User.Username)); + return; + } + + if (TimeoutFinished(actor.TimeOut)) + { + var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); + await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); + return; + } + + var target = await GetUser(user.Id); + + var eb = new EmbedBuilder(); + eb.WithAuthor(new EmbedAuthorBuilder() + .WithIconUrl(user.GetAvatarUrl()) + .WithName(user.Username)); + + eb.WithColor(new Color(138, 219, 146)); + eb.Title = Localization.Karma.Neutral; + eb.AddInlineField(Localization.Karma.By, Context.User.Username); + eb.AddInlineField(Localization.Karma.Amount, "0"); + eb.AddInlineField(Localization.Karma.Current, target.Karma); + await ReplyAsync("", false, eb.Build()); + + } + catch (Exception e) + { + await ErrorHandler.HandleCommandException(e, Context); + } + } private bool TimeoutFinished(DateTimeOffset lastKarma) { diff --git a/src/Bot/Localization/Karma.Designer.cs b/src/Bot/Localization/Karma.Designer.cs index 4191fa2..71cab3b 100644 --- a/src/Bot/Localization/Karma.Designer.cs +++ b/src/Bot/Localization/Karma.Designer.cs @@ -123,6 +123,15 @@ namespace Geekbot.Bot.Localization { } } + /// + /// Looks up a localized string similar to Neutral Karma. + /// + internal static string Neutral { + get { + return ResourceManager.GetString("Neutral", resourceCulture); + } + } + /// /// Looks up a localized string similar to Sorry {0}, but you have to wait {1} before you can give karma again.... /// diff --git a/src/Bot/Localization/Karma.de-ch.resx b/src/Bot/Localization/Karma.de-ch.resx index 5605f8b..7b739b7 100644 --- a/src/Bot/Localization/Karma.de-ch.resx +++ b/src/Bot/Localization/Karma.de-ch.resx @@ -35,4 +35,7 @@ Karma gsenkt + + Neutral Karma + \ No newline at end of file diff --git a/src/Bot/Localization/Karma.resx b/src/Bot/Localization/Karma.resx index 3a8fe5a..2ebea1d 100644 --- a/src/Bot/Localization/Karma.resx +++ b/src/Bot/Localization/Karma.resx @@ -42,4 +42,7 @@ Karma lowered + + Neutral Karma + \ No newline at end of file From 6c142f41d3b16582cd5bcaa4dd871ca522b43698 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Thu, 18 Mar 2021 12:23:18 +0100 Subject: [PATCH 135/264] Upgrade discord.net --- src/Core/Core.csproj | 2 +- src/Core/Polyfills/UserPolyfillDto.cs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 780d0e2..0a4e989 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/Core/Polyfills/UserPolyfillDto.cs b/src/Core/Polyfills/UserPolyfillDto.cs index 1d3a54b..385a30d 100644 --- a/src/Core/Polyfills/UserPolyfillDto.cs +++ b/src/Core/Polyfills/UserPolyfillDto.cs @@ -13,6 +13,7 @@ namespace Geekbot.Core.Polyfills public IActivity Activity { get; } public UserStatus Status { get; set; } public IImmutableSet ActiveClients { get; } + public IImmutableList Activities { get; } public string AvatarId { get; set; } public string AvatarUrl { get; set; } public string Discriminator { get; set; } @@ -20,7 +21,8 @@ namespace Geekbot.Core.Polyfills public bool IsBot { get; set; } public bool IsWebhook { get; set; } public string Username { get; set; } - + public UserProperties? PublicFlags { get; } + public string GetAvatarUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128) { return AvatarUrl ?? "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png"; From c77b501b6c6d6fd3492a881686fca4c801311921 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Thu, 18 Mar 2021 12:27:26 +0100 Subject: [PATCH 136/264] Fix message sent when user is trying give themselves !neutral karma --- src/Bot/Commands/User/Karma.cs | 2 +- src/Bot/Localization/Karma.Designer.cs | 9 +++++++++ src/Bot/Localization/Karma.de-ch.resx | 3 +++ src/Bot/Localization/Karma.resx | 3 +++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Bot/Commands/User/Karma.cs b/src/Bot/Commands/User/Karma.cs index 3ba8650..61e381e 100644 --- a/src/Bot/Commands/User/Karma.cs +++ b/src/Bot/Commands/User/Karma.cs @@ -125,7 +125,7 @@ namespace Geekbot.Bot.Commands.User var actor = await GetUser(Context.User.Id); if (user.Id == Context.User.Id) { - await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnDown, Context.User.Username)); + await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnSame, Context.User.Username)); return; } diff --git a/src/Bot/Localization/Karma.Designer.cs b/src/Bot/Localization/Karma.Designer.cs index 71cab3b..041fec4 100644 --- a/src/Bot/Localization/Karma.Designer.cs +++ b/src/Bot/Localization/Karma.Designer.cs @@ -87,6 +87,15 @@ namespace Geekbot.Bot.Localization { } } + /// + /// Looks up a localized string similar to Sorry {0}, but you can't give yourself neutral karma. + /// + internal static string CannotChangeOwnSame { + get { + return ResourceManager.GetString("CannotChangeOwnSame", resourceCulture); + } + } + /// /// Looks up a localized string similar to Sorry {0}, but you can't give yourself karma. /// diff --git a/src/Bot/Localization/Karma.de-ch.resx b/src/Bot/Localization/Karma.de-ch.resx index 7b739b7..5805a27 100644 --- a/src/Bot/Localization/Karma.de-ch.resx +++ b/src/Bot/Localization/Karma.de-ch.resx @@ -38,4 +38,7 @@ Neutral Karma + + Sorry {0}, aber du chasch dr selber kei neutrals karma geh + \ No newline at end of file diff --git a/src/Bot/Localization/Karma.resx b/src/Bot/Localization/Karma.resx index 2ebea1d..a16e14a 100644 --- a/src/Bot/Localization/Karma.resx +++ b/src/Bot/Localization/Karma.resx @@ -45,4 +45,7 @@ Neutral Karma + + Sorry {0}, but you can't give yourself neutral karma + \ No newline at end of file From d1d57ba7144e497c9fcf7991060e7bfcee6d5d6c Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Thu, 18 Mar 2021 23:53:56 +0100 Subject: [PATCH 137/264] Refactor karma commands --- src/Bot/Commands/User/Karma.cs | 190 --------------------- src/Bot/Commands/User/Karma/Karma.cs | 137 +++++++++++++++ src/Bot/Commands/User/Karma/KarmaChange.cs | 9 + 3 files changed, 146 insertions(+), 190 deletions(-) delete mode 100644 src/Bot/Commands/User/Karma.cs create mode 100644 src/Bot/Commands/User/Karma/Karma.cs create mode 100644 src/Bot/Commands/User/Karma/KarmaChange.cs diff --git a/src/Bot/Commands/User/Karma.cs b/src/Bot/Commands/User/Karma.cs deleted file mode 100644 index 61e381e..0000000 --- a/src/Bot/Commands/User/Karma.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Discord; -using Discord.Commands; -using Geekbot.Bot.Utils; -using Geekbot.Core; -using Geekbot.Core.CommandPreconditions; -using Geekbot.Core.Database; -using Geekbot.Core.Database.Models; -using Geekbot.Core.ErrorHandling; -using Geekbot.Core.Extensions; -using Geekbot.Core.GuildSettingsManager; - -namespace Geekbot.Bot.Commands.User -{ - [DisableInDirectMessage] - public class Karma : GeekbotCommandBase - { - private readonly DatabaseContext _database; - - public Karma(DatabaseContext database, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) - { - _database = database; - } - - [Command("good", RunMode = RunMode.Async)] - [Summary("Increase Someones Karma")] - public async Task Good([Summary("@someone")] IUser user) - { - try - { - var actor = await GetUser(Context.User.Id); - if (user.Id == Context.User.Id) - { - await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnUp, Context.User.Username)); - } - else if (TimeoutFinished(actor.TimeOut)) - { - var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); - } - else - { - var target = await GetUser(user.Id); - target.Karma += 1; - SetUser(target); - - actor.TimeOut = DateTimeOffset.Now; - SetUser(actor); - - await _database.SaveChangesAsync(); - - var eb = new EmbedBuilder(); - eb.WithAuthor(new EmbedAuthorBuilder() - .WithIconUrl(user.GetAvatarUrl()) - .WithName(user.Username)); - - eb.WithColor(new Color(138, 219, 146)); - eb.Title = Localization.Karma.Increased; - eb.AddInlineField(Localization.Karma.By, Context.User.Username); - eb.AddInlineField(Localization.Karma.Amount, "+1"); - eb.AddInlineField(Localization.Karma.Current, target.Karma); - await ReplyAsync("", false, eb.Build()); - } - } - catch (Exception e) - { - await ErrorHandler.HandleCommandException(e, Context); - } - } - - [Command("bad", RunMode = RunMode.Async)] - [Summary("Decrease Someones Karma")] - public async Task Bad([Summary("@someone")] IUser user) - { - try - { - var actor = await GetUser(Context.User.Id); - if (user.Id == Context.User.Id) - { - await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnDown, Context.User.Username)); - } - else if (TimeoutFinished(actor.TimeOut)) - { - var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); - } - else - { - var target = await GetUser(user.Id); - target.Karma -= 1; - SetUser(target); - - actor.TimeOut = DateTimeOffset.Now; - SetUser(actor); - - await _database.SaveChangesAsync(); - - var eb = new EmbedBuilder(); - eb.WithAuthor(new EmbedAuthorBuilder() - .WithIconUrl(user.GetAvatarUrl()) - .WithName(user.Username)); - - eb.WithColor(new Color(138, 219, 146)); - eb.Title = Localization.Karma.Decreased; - eb.AddInlineField(Localization.Karma.By, Context.User.Username); - eb.AddInlineField(Localization.Karma.Amount, "-1"); - eb.AddInlineField(Localization.Karma.Current, target.Karma); - await ReplyAsync("", false, eb.Build()); - } - } - catch (Exception e) - { - await ErrorHandler.HandleCommandException(e, Context); - } - } - - [Command("neutral", RunMode = RunMode.Async)] - [Summary("Do nothing to someones karma")] - public async Task Neutral([Summary("@someone")] IUser user) - { - try - { - var actor = await GetUser(Context.User.Id); - if (user.Id == Context.User.Id) - { - await ReplyAsync(string.Format(Localization.Karma.CannotChangeOwnSame, Context.User.Username)); - return; - } - - if (TimeoutFinished(actor.TimeOut)) - { - var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); - await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); - return; - } - - var target = await GetUser(user.Id); - - var eb = new EmbedBuilder(); - eb.WithAuthor(new EmbedAuthorBuilder() - .WithIconUrl(user.GetAvatarUrl()) - .WithName(user.Username)); - - eb.WithColor(new Color(138, 219, 146)); - eb.Title = Localization.Karma.Neutral; - eb.AddInlineField(Localization.Karma.By, Context.User.Username); - eb.AddInlineField(Localization.Karma.Amount, "0"); - eb.AddInlineField(Localization.Karma.Current, target.Karma); - await ReplyAsync("", false, eb.Build()); - - } - catch (Exception e) - { - await ErrorHandler.HandleCommandException(e, Context); - } - } - - private bool TimeoutFinished(DateTimeOffset lastKarma) - { - return lastKarma.AddMinutes(3) > DateTimeOffset.Now; - } - - private async Task GetUser(ulong userId) - { - var user = _database.Karma.FirstOrDefault(u =>u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId); - return user; - } - - private void SetUser(KarmaModel user) - { - _database.Karma.Update(user); - } - - private async Task CreateNewRow(ulong userId) - { - var user = new KarmaModel() - { - GuildId = Context.Guild.Id.AsLong(), - UserId = userId.AsLong(), - Karma = 0, - TimeOut = DateTimeOffset.MinValue - }; - var newUser = _database.Karma.Add(user).Entity; - await _database.SaveChangesAsync(); - return newUser; - } - } -} \ No newline at end of file diff --git a/src/Bot/Commands/User/Karma/Karma.cs b/src/Bot/Commands/User/Karma/Karma.cs new file mode 100644 index 0000000..a248422 --- /dev/null +++ b/src/Bot/Commands/User/Karma/Karma.cs @@ -0,0 +1,137 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Geekbot.Bot.Utils; +using Geekbot.Core; +using Geekbot.Core.CommandPreconditions; +using Geekbot.Core.Database; +using Geekbot.Core.Database.Models; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.Extensions; +using Geekbot.Core.GuildSettingsManager; + +namespace Geekbot.Bot.Commands.User.Karma +{ + [DisableInDirectMessage] + public class Karma : GeekbotCommandBase + { + private readonly DatabaseContext _database; + + public Karma(DatabaseContext database, IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) + { + _database = database; + } + + [Command("good", RunMode = RunMode.Async)] + [Summary("Increase Someones Karma")] + public async Task Good([Summary("@someone")] IUser user) + { + await ChangeKarma(user, KarmaChange.Up); + } + + [Command("bad", RunMode = RunMode.Async)] + [Summary("Decrease Someones Karma")] + public async Task Bad([Summary("@someone")] IUser user) + { + await ChangeKarma(user, KarmaChange.Down); + } + + [Command("neutral", RunMode = RunMode.Async)] + [Summary("Do nothing to someones Karma")] + public async Task Neutral([Summary("@someone")] IUser user) + { + await ChangeKarma(user, KarmaChange.Same); + } + + private async Task ChangeKarma(IUser user, KarmaChange change) + { + try + { + // Get the user + var actor = await GetUser(Context.User.Id); + + // Check if the user can change karma + if (user.Id == Context.User.Id) + { + var message = change switch + { + KarmaChange.Up => Localization.Karma.CannotChangeOwnUp, + KarmaChange.Same => Localization.Karma.CannotChangeOwnSame, + KarmaChange.Down => Localization.Karma.CannotChangeOwnDown, + _ => throw new ArgumentOutOfRangeException(nameof(change), change, null) + }; + await ReplyAsync(string.Format(message, Context.User.Username)); + return; + } + + if (actor.TimeOut.AddMinutes(3) > DateTimeOffset.Now) + { + var formatedWaitTime = DateLocalization.FormatDateTimeAsRemaining(actor.TimeOut.AddMinutes(3)); + await ReplyAsync(string.Format(Localization.Karma.WaitUntill, Context.User.Username, formatedWaitTime)); + return; + } + + // Get the values for the change direction + var (title, amount) = change switch + { + KarmaChange.Up => (Localization.Karma.Increased, 1), + KarmaChange.Same => (Localization.Karma.Neutral, 0), + KarmaChange.Down => (Localization.Karma.Decreased, -1), + _ => throw new ArgumentOutOfRangeException(nameof(change), change, null) + }; + + // Change it + var target = await GetUser(user.Id); + target.Karma += amount; + _database.Karma.Update(target); + + actor.TimeOut = DateTimeOffset.Now; + _database.Karma.Update(actor); + + await _database.SaveChangesAsync(); + + // Respond + var eb = new EmbedBuilder() + { + Author = new EmbedAuthorBuilder() + { + Name = user.Username, + IconUrl = user.GetAvatarUrl() + }, + Title = title, + Color = new Color(138, 219, 146) + }; + eb.AddInlineField(Localization.Karma.By, Context.User.Username); + eb.AddInlineField(Localization.Karma.Amount, amount.ToString()); + eb.AddInlineField(Localization.Karma.Current, target.Karma.ToString()); + await ReplyAsync("", false, eb.Build()); + } + catch (Exception e) + { + await ErrorHandler.HandleCommandException(e, Context); + } + } + + private async Task GetUser(ulong userId) + { + var user = _database.Karma.FirstOrDefault(u => u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId); + return user; + } + + private async Task CreateNewRow(ulong userId) + { + var user = new KarmaModel() + { + GuildId = Context.Guild.Id.AsLong(), + UserId = userId.AsLong(), + Karma = 0, + TimeOut = DateTimeOffset.MinValue + }; + var newUser = _database.Karma.Add(user).Entity; + await _database.SaveChangesAsync(); + return newUser; + } + } +} \ No newline at end of file diff --git a/src/Bot/Commands/User/Karma/KarmaChange.cs b/src/Bot/Commands/User/Karma/KarmaChange.cs new file mode 100644 index 0000000..01dafc1 --- /dev/null +++ b/src/Bot/Commands/User/Karma/KarmaChange.cs @@ -0,0 +1,9 @@ +namespace Geekbot.Bot.Commands.User.Karma +{ + public enum KarmaChange + { + Up, + Same, + Down + } +} \ No newline at end of file From 1c643285874df4a92b633cf3dd2c63a2559084f5 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 19 Mar 2021 00:21:35 +0100 Subject: [PATCH 138/264] Upgrade to .net6 preview --- .gitlab-ci.yml | 2 +- Dockerfile | 2 +- src/Bot/Bot.csproj | 2 +- src/Bot/Commands/Utils/Quote/Quote.cs | 1 + src/Core/Core.csproj | 26 ++++++++++++++++---------- src/Web/Web.csproj | 2 +- tests/Tests.csproj | 6 +++--- 7 files changed, 24 insertions(+), 17 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 20b1c84..967def1 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,7 +10,7 @@ variables: Build: stage: build - image: mcr.microsoft.com/dotnet/sdk:5.0 + image: mcr.microsoft.com/dotnet/sdk:6.0 artifacts: expire_in: 1h paths: diff --git a/Dockerfile b/Dockerfile index 245e06b..39529ff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/aspnet:5.0 +FROM mcr.microsoft.com/dotnet/aspnet:6.0 COPY ./app /app/ diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 6c6f56f..86ab9a3 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -1,7 +1,7 @@ Exe - net5.0 + net6.0 win-x64;linux-x64 derp.ico $(VersionSuffix) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 6a94309..e79663c 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -14,6 +14,7 @@ using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.Polyfills; using Geekbot.Core.RandomNumberGenerator; using Geekbot.Core.UserRepository; +using Microsoft.EntityFrameworkCore; namespace Geekbot.Bot.Commands.Utils.Quote { diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 0a4e989..474478e 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -1,7 +1,7 @@ - net5.0 + net6.0 $(VersionSuffix) $(VersionSuffix) 0.0.0-DEV @@ -14,18 +14,24 @@ - - - - - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - + diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index 5080a3d..744cadf 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -1,7 +1,7 @@ - net5.0 + net6.0 $(VersionSuffix) $(VersionSuffix) 0.0.0-DEV diff --git a/tests/Tests.csproj b/tests/Tests.csproj index 75a5f9c..6b9b84f 100644 --- a/tests/Tests.csproj +++ b/tests/Tests.csproj @@ -1,13 +1,13 @@  - net5.0 + net6.0 false NU1701 xUnit1026 - - + + From f25c9250ec109485e05f366f32fb18f5f9c2b309 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 19 Mar 2021 01:10:22 +0100 Subject: [PATCH 139/264] Switch to an alpine container and single file, self-contained deployments --- .gitlab-ci.yml | 2 +- Dockerfile | 2 +- src/Bot/Bot.csproj | 2 +- src/Core/Core.csproj | 1 + src/Web/Web.csproj | 1 + tests/Tests.csproj | 1 + 6 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 967def1..f92ba14 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -18,7 +18,7 @@ Build: script: - dotnet restore - dotnet test tests - - dotnet publish --version-suffix "$VERSION" -r linux-x64 -c Release -o ./app ./src/Bot/ + - dotnet publish --version-suffix "$VERSION" -r linux-musl-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./app ./src/Bot/ Package: stage: docker diff --git a/Dockerfile b/Dockerfile index 39529ff..6e81339 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/aspnet:6.0 +FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine COPY ./app /app/ diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 86ab9a3..9312ac1 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -2,7 +2,7 @@ Exe net6.0 - win-x64;linux-x64 + win10-x64;linux-x64;linux-musl-x64 derp.ico $(VersionSuffix) Geekbot.Bot diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 474478e..17b4a26 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -2,6 +2,7 @@ net6.0 + win10-x64;linux-x64;linux-musl-x64 $(VersionSuffix) $(VersionSuffix) 0.0.0-DEV diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index 744cadf..d57c63c 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -2,6 +2,7 @@ net6.0 + win10-x64;linux-x64;linux-musl-x64 $(VersionSuffix) $(VersionSuffix) 0.0.0-DEV diff --git a/tests/Tests.csproj b/tests/Tests.csproj index 6b9b84f..4823e0b 100644 --- a/tests/Tests.csproj +++ b/tests/Tests.csproj @@ -1,6 +1,7 @@  net6.0 + win10-x64;linux-x64;linux-musl-x64 false NU1701 xUnit1026 From 52fe5bdec11dc2327f4703e83bd1b6eb7ff2c646 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sat, 20 Mar 2021 04:06:10 +0100 Subject: [PATCH 140/264] Switch back to a debian container, alpine is missing locale info --- .gitlab-ci.yml | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f92ba14..b0135b6 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -18,7 +18,7 @@ Build: script: - dotnet restore - dotnet test tests - - dotnet publish --version-suffix "$VERSION" -r linux-musl-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./app ./src/Bot/ + - dotnet publish --version-suffix "$VERSION" -r linux-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./app ./src/Bot/ Package: stage: docker diff --git a/Dockerfile b/Dockerfile index 6e81339..39529ff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine +FROM mcr.microsoft.com/dotnet/aspnet:6.0 COPY ./app /app/ From 49870b6b91da13fdb7ec3b9b4a53696eafc2e058 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sat, 20 Mar 2021 04:17:14 +0100 Subject: [PATCH 141/264] Stop using single-file deployments due to missing locale data --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b0135b6..967def1 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -18,7 +18,7 @@ Build: script: - dotnet restore - dotnet test tests - - dotnet publish --version-suffix "$VERSION" -r linux-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./app ./src/Bot/ + - dotnet publish --version-suffix "$VERSION" -r linux-x64 -c Release -o ./app ./src/Bot/ Package: stage: docker From 41e0a9f8d72c24766019a4e7844337cab62ce281 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 26 Mar 2021 00:11:15 +0100 Subject: [PATCH 142/264] Add !evergiven to see if the ship is still stuck in the suez canal --- src/Bot/Bot.csproj | 9 +++ src/Bot/Commands/Utils/Evergiven.cs | 50 +++++++++++++ src/Bot/Localization/Evergiven.Designer.cs | 81 ++++++++++++++++++++++ src/Bot/Localization/Evergiven.de-ch.resx | 20 ++++++ src/Bot/Localization/Evergiven.resx | 27 ++++++++ src/Bot/Utils/DateLocalization.cs | 6 +- 6 files changed, 192 insertions(+), 1 deletion(-) create mode 100644 src/Bot/Commands/Utils/Evergiven.cs create mode 100644 src/Bot/Localization/Evergiven.Designer.cs create mode 100644 src/Bot/Localization/Evergiven.de-ch.resx create mode 100644 src/Bot/Localization/Evergiven.resx diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 9312ac1..2b1cdae 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -88,6 +88,10 @@ ResXFileCodeGenerator Corona.Designer.cs + + ResXFileCodeGenerator + Evergiven.Designer.cs + @@ -153,5 +157,10 @@ True Corona.resx + + True + True + Evergiven.resx + diff --git a/src/Bot/Commands/Utils/Evergiven.cs b/src/Bot/Commands/Utils/Evergiven.cs new file mode 100644 index 0000000..663fb0a --- /dev/null +++ b/src/Bot/Commands/Utils/Evergiven.cs @@ -0,0 +1,50 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Discord.Commands; +using Geekbot.Bot.Utils; +using Geekbot.Core; +using Geekbot.Core.ErrorHandling; +using Geekbot.Core.GuildSettingsManager; +using HtmlAgilityPack; + +namespace Geekbot.Bot.Commands.Utils +{ + public class Evergiven : GeekbotCommandBase + { + public Evergiven(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) + { + } + + [Command("evergiven", RunMode = RunMode.Async)] + [Summary("Check if the evergiven ship is still stuck in the suez canal")] + public async Task GetStatus() + { + try + { + var httpClient = HttpAbstractions.CreateDefaultClient(); + var response = await httpClient.GetAsync("https://istheshipstillstuck.com/"); + response.EnsureSuccessStatusCode(); + var stringResponse = await response.Content.ReadAsStringAsync(); + + var doc = new HtmlDocument(); + doc.LoadHtml(stringResponse); + var yesOrNoNode = doc.DocumentNode.SelectNodes("//a").FirstOrDefault(); + + if (yesOrNoNode?.InnerHtml == "Yes.") + { + var stuckSince = DateTime.Now - new DateTime(2021, 03, 23, 10, 39, 0); + var formatted = DateLocalization.FormatDateTimeAsRemaining(stuckSince); + await ReplyAsync(string.Format(Localization.Evergiven.StillStuck, formatted));// $"Ever Given is **still stuck** in the suez canal! It has been stuck for {formatted}"); + return; + } + + await ReplyAsync(Localization.Evergiven.NotStuckAnymore); + } + catch (Exception e) + { + await ErrorHandler.HandleCommandException(e, Context); + } + } + } +} \ No newline at end of file diff --git a/src/Bot/Localization/Evergiven.Designer.cs b/src/Bot/Localization/Evergiven.Designer.cs new file mode 100644 index 0000000..7f66fed --- /dev/null +++ b/src/Bot/Localization/Evergiven.Designer.cs @@ -0,0 +1,81 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Evergiven { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Evergiven() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Evergiven", typeof(Evergiven).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Seems like Ever Given has moved on, check https://istheshipstillstuck.com/. + /// + internal static string NotStuckAnymore { + get { + return ResourceManager.GetString("NotStuckAnymore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ever Given is **still stuck** in the suez canal! It has been stuck for {0}. + /// + internal static string StillStuck { + get { + return ResourceManager.GetString("StillStuck", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/Evergiven.de-ch.resx b/src/Bot/Localization/Evergiven.de-ch.resx new file mode 100644 index 0000000..b1563fc --- /dev/null +++ b/src/Bot/Localization/Evergiven.de-ch.resx @@ -0,0 +1,20 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Ever Given **steckt immer no fescht** im Suez Kanal! Es isch derte siit {0} + + + Es gseht danach us das Ever Given wiiter gange isch, gsehne https://istheshipstillstuck.com/ + + \ No newline at end of file diff --git a/src/Bot/Localization/Evergiven.resx b/src/Bot/Localization/Evergiven.resx new file mode 100644 index 0000000..36fb012 --- /dev/null +++ b/src/Bot/Localization/Evergiven.resx @@ -0,0 +1,27 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Seems like Ever Given has moved on, check https://istheshipstillstuck.com/ + + + Ever Given is **still stuck** in the suez canal! It has been stuck for {0} + + \ No newline at end of file diff --git a/src/Bot/Utils/DateLocalization.cs b/src/Bot/Utils/DateLocalization.cs index eea40fb..ee52d73 100644 --- a/src/Bot/Utils/DateLocalization.cs +++ b/src/Bot/Utils/DateLocalization.cs @@ -7,7 +7,11 @@ namespace Geekbot.Bot.Utils { public static string FormatDateTimeAsRemaining(DateTimeOffset dateTime) { - var remaining = dateTime - DateTimeOffset.Now; + return FormatDateTimeAsRemaining(dateTime - DateTimeOffset.Now); + } + + public static string FormatDateTimeAsRemaining(TimeSpan remaining) + { const string formattable = "{0} {1}"; var sb = new StringBuilder(); From 9ad39058ac71a2a1e19091dcc4d910d8fa92d70e Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 29 Mar 2021 11:39:50 +0200 Subject: [PATCH 143/264] Update the !evergiven command to directly reflect what istheshipstillstuck.com says --- src/Bot/Bot.csproj | 9 --- src/Bot/Commands/Utils/Evergiven.cs | 28 ++++++-- src/Bot/Localization/Evergiven.Designer.cs | 81 ---------------------- src/Bot/Localization/Evergiven.de-ch.resx | 20 ------ src/Bot/Localization/Evergiven.resx | 27 -------- 5 files changed, 21 insertions(+), 144 deletions(-) delete mode 100644 src/Bot/Localization/Evergiven.Designer.cs delete mode 100644 src/Bot/Localization/Evergiven.de-ch.resx delete mode 100644 src/Bot/Localization/Evergiven.resx diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 2b1cdae..9312ac1 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -88,10 +88,6 @@ ResXFileCodeGenerator Corona.Designer.cs - - ResXFileCodeGenerator - Evergiven.Designer.cs - @@ -157,10 +153,5 @@ True Corona.resx - - True - True - Evergiven.resx - diff --git a/src/Bot/Commands/Utils/Evergiven.cs b/src/Bot/Commands/Utils/Evergiven.cs index 663fb0a..1115eaf 100644 --- a/src/Bot/Commands/Utils/Evergiven.cs +++ b/src/Bot/Commands/Utils/Evergiven.cs @@ -1,8 +1,9 @@ using System; using System.Linq; +using System.Text; using System.Threading.Tasks; +using System.Web; using Discord.Commands; -using Geekbot.Bot.Utils; using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.GuildSettingsManager; @@ -29,17 +30,30 @@ namespace Geekbot.Bot.Commands.Utils var doc = new HtmlDocument(); doc.LoadHtml(stringResponse); - var yesOrNoNode = doc.DocumentNode.SelectNodes("//a").FirstOrDefault(); + var statusNode = doc.DocumentNode.SelectNodes("//a").FirstOrDefault(); - if (yesOrNoNode?.InnerHtml == "Yes.") + if (statusNode == null) { - var stuckSince = DateTime.Now - new DateTime(2021, 03, 23, 10, 39, 0); - var formatted = DateLocalization.FormatDateTimeAsRemaining(stuckSince); - await ReplyAsync(string.Format(Localization.Evergiven.StillStuck, formatted));// $"Ever Given is **still stuck** in the suez canal! It has been stuck for {formatted}"); + await ReplyAsync("Maybe, check "); return; } - await ReplyAsync(Localization.Evergiven.NotStuckAnymore); + var sb = new StringBuilder(); + + sb.Append($"Is that ship still stuck? {statusNode.InnerHtml}"); + if (statusNode.Attributes.Contains("href")) + { + sb.Append($" {statusNode.Attributes["href"].Value}"); + } + + var stuckTimer = doc.DocumentNode.SelectNodes("//p")?.First(node => node.Attributes.First(attr => attr.Name == "style")?.Value == "text-align:center"); + if (stuckTimer != null) + { + sb.AppendLine(); + sb.AppendLine(HttpUtility.HtmlDecode(stuckTimer.InnerText)); + } + + await ReplyAsync(sb.ToString()); } catch (Exception e) { diff --git a/src/Bot/Localization/Evergiven.Designer.cs b/src/Bot/Localization/Evergiven.Designer.cs deleted file mode 100644 index 7f66fed..0000000 --- a/src/Bot/Localization/Evergiven.Designer.cs +++ /dev/null @@ -1,81 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Geekbot.Bot.Localization { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Evergiven { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Evergiven() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.Evergiven", typeof(Evergiven).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Seems like Ever Given has moved on, check https://istheshipstillstuck.com/. - /// - internal static string NotStuckAnymore { - get { - return ResourceManager.GetString("NotStuckAnymore", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Ever Given is **still stuck** in the suez canal! It has been stuck for {0}. - /// - internal static string StillStuck { - get { - return ResourceManager.GetString("StillStuck", resourceCulture); - } - } - } -} diff --git a/src/Bot/Localization/Evergiven.de-ch.resx b/src/Bot/Localization/Evergiven.de-ch.resx deleted file mode 100644 index b1563fc..0000000 --- a/src/Bot/Localization/Evergiven.de-ch.resx +++ /dev/null @@ -1,20 +0,0 @@ - - - text/microsoft-resx - - - 1.3 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Ever Given **steckt immer no fescht** im Suez Kanal! Es isch derte siit {0} - - - Es gseht danach us das Ever Given wiiter gange isch, gsehne https://istheshipstillstuck.com/ - - \ No newline at end of file diff --git a/src/Bot/Localization/Evergiven.resx b/src/Bot/Localization/Evergiven.resx deleted file mode 100644 index 36fb012..0000000 --- a/src/Bot/Localization/Evergiven.resx +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - text/microsoft-resx - - - 1.3 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Seems like Ever Given has moved on, check https://istheshipstillstuck.com/ - - - Ever Given is **still stuck** in the suez canal! It has been stuck for {0} - - \ No newline at end of file From 5b99ee951bc6ea45a09347f5840154b7a92f0258 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 29 Mar 2021 17:45:43 +0200 Subject: [PATCH 144/264] Evergiven is free once again --- src/Bot/Commands/Utils/Evergiven.cs | 31 ++++------------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/src/Bot/Commands/Utils/Evergiven.cs b/src/Bot/Commands/Utils/Evergiven.cs index 1115eaf..c7c4335 100644 --- a/src/Bot/Commands/Utils/Evergiven.cs +++ b/src/Bot/Commands/Utils/Evergiven.cs @@ -23,35 +23,12 @@ namespace Geekbot.Bot.Commands.Utils { try { - var httpClient = HttpAbstractions.CreateDefaultClient(); - var response = await httpClient.GetAsync("https://istheshipstillstuck.com/"); - response.EnsureSuccessStatusCode(); - var stringResponse = await response.Content.ReadAsStringAsync(); - - var doc = new HtmlDocument(); - doc.LoadHtml(stringResponse); - var statusNode = doc.DocumentNode.SelectNodes("//a").FirstOrDefault(); - - if (statusNode == null) - { - await ReplyAsync("Maybe, check "); - return; - } - var sb = new StringBuilder(); - sb.Append($"Is that ship still stuck? {statusNode.InnerHtml}"); - if (statusNode.Attributes.Contains("href")) - { - sb.Append($" {statusNode.Attributes["href"].Value}"); - } - - var stuckTimer = doc.DocumentNode.SelectNodes("//p")?.First(node => node.Attributes.First(attr => attr.Name == "style")?.Value == "text-align:center"); - if (stuckTimer != null) - { - sb.AppendLine(); - sb.AppendLine(HttpUtility.HtmlDecode(stuckTimer.InnerText)); - } + sb.AppendLine("Is that ship still stuck?"); + sb.AppendLine("**No!**"); + sb.AppendLine("It was stuck for 6 days, 3 hours and 38 minutes. It (probably) cost \"us\" $59 billion."); + sb.AppendLine("You can follow it here: "); await ReplyAsync(sb.ToString()); } From 153ce3dca4b408a32dbfbdd12bfbcfd8c02acf27 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 29 Mar 2021 19:02:31 +0200 Subject: [PATCH 145/264] Translate !8ball --- src/Bot/Bot.csproj | 9 + src/Bot/Commands/Randomness/EightBall.cs | 41 +--- src/Bot/Localization/EightBall.Designer.cs | 243 +++++++++++++++++++++ src/Bot/Localization/EightBall.de-ch.resx | 94 ++++++++ src/Bot/Localization/EightBall.resx | 200 +++++++++++++++++ 5 files changed, 558 insertions(+), 29 deletions(-) create mode 100644 src/Bot/Localization/EightBall.Designer.cs create mode 100644 src/Bot/Localization/EightBall.de-ch.resx create mode 100644 src/Bot/Localization/EightBall.resx diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 9312ac1..cd04530 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -88,6 +88,10 @@ ResXFileCodeGenerator Corona.Designer.cs + + ResXFileCodeGenerator + EightBall.Designer.cs + @@ -153,5 +157,10 @@ True Corona.resx + + True + True + EightBall.resx + diff --git a/src/Bot/Commands/Randomness/EightBall.cs b/src/Bot/Commands/Randomness/EightBall.cs index e1a3a71..207afe3 100644 --- a/src/Bot/Commands/Randomness/EightBall.cs +++ b/src/Bot/Commands/Randomness/EightBall.cs @@ -1,18 +1,18 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; +using Geekbot.Core.GuildSettingsManager; namespace Geekbot.Bot.Commands.Randomness { - public class EightBall : ModuleBase + public class EightBall : GeekbotCommandBase { - private readonly IErrorHandler _errorHandler; - - public EightBall(IErrorHandler errorHandler) + public EightBall(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { - _errorHandler = errorHandler; } [Command("8ball", RunMode = RunMode.Async)] @@ -21,36 +21,19 @@ namespace Geekbot.Bot.Commands.Randomness { try { - var replies = new List + var enumerator = Localization.EightBall.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true).GetEnumerator(); + var replies = new List(); + while (enumerator.MoveNext()) { - "It is certain", - "It is decidedly so", - "Without a doubt", - "Yes, definitely", - "You may rely on it", - "As I see it, yes", - "Most likely", - "Outlook good", - "Yes", - "Signs point to yes", - "Reply hazy try again", - "Ask again later", - "Better not tell you now", - "Cannot predict now", - "Concentrate and ask again", - "Don't count on it", - "My reply is no", - "My sources say no", - "Outlook not so good", - "Very doubtful" - }; - + replies.Add(enumerator.Value?.ToString()); + } + var answer = new Random().Next(replies.Count); await ReplyAsync(replies[answer]); } catch (Exception e) { - await _errorHandler.HandleCommandException(e, Context); + await ErrorHandler.HandleCommandException(e, Context); } } } diff --git a/src/Bot/Localization/EightBall.Designer.cs b/src/Bot/Localization/EightBall.Designer.cs new file mode 100644 index 0000000..8214825 --- /dev/null +++ b/src/Bot/Localization/EightBall.Designer.cs @@ -0,0 +1,243 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Geekbot.Bot.Localization { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class EightBall { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal EightBall() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Geekbot.Bot.Localization.EightBall", typeof(EightBall).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to As I see it, yes. + /// + internal static string AsISeeItYes { + get { + return ResourceManager.GetString("AsISeeItYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ask again later. + /// + internal static string AskAgainLater { + get { + return ResourceManager.GetString("AskAgainLater", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Better not tell you now. + /// + internal static string BetterNotTellYouNow { + get { + return ResourceManager.GetString("BetterNotTellYouNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot predict now. + /// + internal static string CannotPredictNow { + get { + return ResourceManager.GetString("CannotPredictNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Concentrate and ask again. + /// + internal static string ConcentrateAndAskAgain { + get { + return ResourceManager.GetString("ConcentrateAndAskAgain", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Don't count on it. + /// + internal static string DontCountOnIt { + get { + return ResourceManager.GetString("DontCountOnIt", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to It is certain. + /// + internal static string ItIsCertain { + get { + return ResourceManager.GetString("ItIsCertain", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to It is decidedly so. + /// + internal static string ItIsDecidedlySo { + get { + return ResourceManager.GetString("ItIsDecidedlySo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Most likely. + /// + internal static string MostLikely { + get { + return ResourceManager.GetString("MostLikely", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to My reply is no. + /// + internal static string MyReplyIsNo { + get { + return ResourceManager.GetString("MyReplyIsNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to My sources say no. + /// + internal static string MySourcesSayNo { + get { + return ResourceManager.GetString("MySourcesSayNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Outlook good. + /// + internal static string OutlookGood { + get { + return ResourceManager.GetString("OutlookGood", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Outlook not so good. + /// + internal static string OutlookNotSoGood { + get { + return ResourceManager.GetString("OutlookNotSoGood", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reply hazy try again. + /// + internal static string ReplyHazyTryAgain { + get { + return ResourceManager.GetString("ReplyHazyTryAgain", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Signs point to yes. + /// + internal static string SignsPointToYes { + get { + return ResourceManager.GetString("SignsPointToYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Very doubtful. + /// + internal static string VeryDoubtful { + get { + return ResourceManager.GetString("VeryDoubtful", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Without a doubt. + /// + internal static string WithoutADoubt { + get { + return ResourceManager.GetString("WithoutADoubt", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + internal static string Yes { + get { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, definitely. + /// + internal static string YesDefinitely { + get { + return ResourceManager.GetString("YesDefinitely", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You may rely on it. + /// + internal static string YouMayRelyOnIt { + get { + return ResourceManager.GetString("YouMayRelyOnIt", resourceCulture); + } + } + } +} diff --git a/src/Bot/Localization/EightBall.de-ch.resx b/src/Bot/Localization/EightBall.de-ch.resx new file mode 100644 index 0000000..89d7a60 --- /dev/null +++ b/src/Bot/Localization/EightBall.de-ch.resx @@ -0,0 +1,94 @@ + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Es isch sicher + + + + So isch es entschiede worde + + + + Ohni zwifel + + + + Ja, absolut + + + + Chasch davo usgoh + + + + Wie ich es gsehn, ja + + + + Sehr waschinli + + + + Ussicht isch guet + + + + Ja + + + + Ahzeiche zeigend uf ja + + + + Antwort isch verschwumme, versuechs nomol + + + + Frög spöter nomol + + + + Segs dir jetzt besser nid + + + + Im mommnet chani das nid vorussege + + + + Konzentrier di und frog nomol + + + + Zähl nid druf + + + + Mini antwort isch nei + + + + Mini quellene seged nei + + + + Ussicht isch ned so guet + + + + Sehr froglich + + + \ No newline at end of file diff --git a/src/Bot/Localization/EightBall.resx b/src/Bot/Localization/EightBall.resx new file mode 100644 index 0000000..6eba369 --- /dev/null +++ b/src/Bot/Localization/EightBall.resx @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + It is certain + + + + It is decidedly so + + + + Without a doubt + + + + Yes, definitely + + + + You may rely on it + + + + As I see it, yes + + + + Most likely + + + + Outlook good + + + + Yes + + + + Signs point to yes + + + + Reply hazy try again + + + + Ask again later + + + + Better not tell you now + + + + Cannot predict now + + + + Concentrate and ask again + + + + Don't count on it + + + + My reply is no + + + + My sources say no + + + + Outlook not so good + + + + Very doubtful + + + \ No newline at end of file From 8bd8efa66a70f9769ee53b2d574ba03879b9a8cb Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 7 Apr 2021 22:49:13 +0200 Subject: [PATCH 146/264] Remove the !evergiven command --- src/Bot/Commands/Utils/Evergiven.cs | 41 ----------------------------- 1 file changed, 41 deletions(-) delete mode 100644 src/Bot/Commands/Utils/Evergiven.cs diff --git a/src/Bot/Commands/Utils/Evergiven.cs b/src/Bot/Commands/Utils/Evergiven.cs deleted file mode 100644 index c7c4335..0000000 --- a/src/Bot/Commands/Utils/Evergiven.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web; -using Discord.Commands; -using Geekbot.Core; -using Geekbot.Core.ErrorHandling; -using Geekbot.Core.GuildSettingsManager; -using HtmlAgilityPack; - -namespace Geekbot.Bot.Commands.Utils -{ - public class Evergiven : GeekbotCommandBase - { - public Evergiven(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) - { - } - - [Command("evergiven", RunMode = RunMode.Async)] - [Summary("Check if the evergiven ship is still stuck in the suez canal")] - public async Task GetStatus() - { - try - { - var sb = new StringBuilder(); - - sb.AppendLine("Is that ship still stuck?"); - sb.AppendLine("**No!**"); - sb.AppendLine("It was stuck for 6 days, 3 hours and 38 minutes. It (probably) cost \"us\" $59 billion."); - sb.AppendLine("You can follow it here: "); - - await ReplyAsync(sb.ToString()); - } - catch (Exception e) - { - await ErrorHandler.HandleCommandException(e, Context); - } - } - } -} \ No newline at end of file From 5a50ba58206e4fcfd85a2f55af909be9d7291cdb Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Tue, 20 Apr 2021 22:25:33 +0200 Subject: [PATCH 147/264] Add total quotes of a user to !stats --- src/Bot/Commands/User/Stats.cs | 7 +++++-- src/Bot/Localization/Stats.Designer.cs | 18 ++++++++++++++++++ src/Bot/Localization/Stats.de-ch.resx | 6 ++++++ src/Bot/Localization/Stats.resx | 6 ++++++ 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/User/Stats.cs b/src/Bot/Commands/User/Stats.cs index a2a54a2..aad2657 100644 --- a/src/Bot/Commands/User/Stats.cs +++ b/src/Bot/Commands/User/Stats.cs @@ -54,6 +54,8 @@ namespace Geekbot.Bot.Commands.User ?.FirstOrDefault(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.UserId.Equals(userInfo.Id.AsLong())) ?.Cookies ?? 0; + var quotes = _database.Quotes.Count(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.UserId.Equals(userInfo.Id.AsLong())); + var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder() .WithIconUrl(userInfo.GetAvatarUrl()) @@ -68,9 +70,9 @@ namespace Geekbot.Bot.Commands.User e.UserId.Equals(userInfo.Id.AsLong())); eb.AddInlineField(Localization.Stats.OnDiscordSince, - $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)") + $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} {Localization.Stats.Days})") .AddInlineField(Localization.Stats.JoinedServer, - $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)") + $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} {Localization.Stats.Days})") .AddInlineField(Localization.Stats.Karma, karma?.Karma ?? 0) .AddInlineField(Localization.Stats.Level, level) .AddInlineField(Localization.Stats.MessagesSent, messages) @@ -78,6 +80,7 @@ namespace Geekbot.Bot.Commands.User if (correctRolls != null) eb.AddInlineField(Localization.Stats.GuessedRolls, correctRolls.Rolls); if (cookies > 0) eb.AddInlineField(Localization.Stats.Cookies, cookies); + if (quotes > 0) eb.AddInlineField(Localization.Stats.Quotes, quotes); await ReplyAsync("", false, eb.Build()); } diff --git a/src/Bot/Localization/Stats.Designer.cs b/src/Bot/Localization/Stats.Designer.cs index d05f937..6f650e2 100644 --- a/src/Bot/Localization/Stats.Designer.cs +++ b/src/Bot/Localization/Stats.Designer.cs @@ -69,6 +69,15 @@ namespace Geekbot.Bot.Localization { } } + /// + /// Looks up a localized string similar to Days. + /// + internal static string Days { + get { + return ResourceManager.GetString("Days", resourceCulture); + } + } + /// /// Looks up a localized string similar to Guessed Rolls. /// @@ -123,6 +132,15 @@ namespace Geekbot.Bot.Localization { } } + /// + /// Looks up a localized string similar to Quotes. + /// + internal static string Quotes { + get { + return ResourceManager.GetString("Quotes", resourceCulture); + } + } + /// /// Looks up a localized string similar to Server Total. /// diff --git a/src/Bot/Localization/Stats.de-ch.resx b/src/Bot/Localization/Stats.de-ch.resx index ab44a2e..0af0477 100644 --- a/src/Bot/Localization/Stats.de-ch.resx +++ b/src/Bot/Localization/Stats.de-ch.resx @@ -35,4 +35,10 @@ Guetzli + + Täg + + + Quotes + \ No newline at end of file diff --git a/src/Bot/Localization/Stats.resx b/src/Bot/Localization/Stats.resx index 3b8303a..6eb3a92 100644 --- a/src/Bot/Localization/Stats.resx +++ b/src/Bot/Localization/Stats.resx @@ -42,4 +42,10 @@ Cookies + + Days + + + Quotes + \ No newline at end of file From 611b179d628aa56db4f5503c004814f1dde4bb3e Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 9 Jul 2021 20:21:17 +0200 Subject: [PATCH 148/264] Add a piece of low fat mozzarella to the !slap command --- src/Bot/Commands/Randomness/Slap.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Randomness/Slap.cs b/src/Bot/Commands/Randomness/Slap.cs index b512e73..7a858b1 100644 --- a/src/Bot/Commands/Randomness/Slap.cs +++ b/src/Bot/Commands/Randomness/Slap.cs @@ -76,7 +76,8 @@ namespace Geekbot.Bot.Commands.Randomness "teapot", "candle", "dictionary", - "powerless banhammer" + "powerless banhammer", + "piece of low fat mozzarella" }; await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(things.Count - 1)]}"); @@ -127,4 +128,4 @@ namespace Geekbot.Bot.Commands.Randomness e.UserId.Equals(userId.AsLong())); } } -} \ No newline at end of file +} From 8fcc6291065e9becd2e5f9ada1955dba7e83ad99 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 9 Jul 2021 20:39:04 +0200 Subject: [PATCH 149/264] Disable MSBuildEnableWorkloadResolver in gitlab ci --- .gitlab-ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 967def1..fc1cd0e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -7,6 +7,8 @@ stages: variables: VERSION: 4.3.0-V$CI_COMMIT_SHORT_SHA IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG + # ToDo: Remove when .net6 is released + MSBuildEnableWorkloadResolver: false Build: stage: build From 86068ecc443dd18d709dcf1f52d6d291ce06c500 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 9 Jul 2021 20:48:42 +0200 Subject: [PATCH 150/264] Disable self contained publishing for the test, web and bot dlls --- .gitlab-ci.yml | 2 +- src/Bot/Bot.csproj | 1 + src/Web/Web.csproj | 1 + tests/Tests.csproj | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index fc1cd0e..7da242b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -8,7 +8,7 @@ variables: VERSION: 4.3.0-V$CI_COMMIT_SHORT_SHA IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG # ToDo: Remove when .net6 is released - MSBuildEnableWorkloadResolver: false + MSBuildEnableWorkloadResolver: 'false' Build: stage: build diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index cd04530..ff10a94 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -3,6 +3,7 @@ Exe net6.0 win10-x64;linux-x64;linux-musl-x64 + false derp.ico $(VersionSuffix) Geekbot.Bot diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index d57c63c..a9ffcc4 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -3,6 +3,7 @@ net6.0 win10-x64;linux-x64;linux-musl-x64 + false $(VersionSuffix) $(VersionSuffix) 0.0.0-DEV diff --git a/tests/Tests.csproj b/tests/Tests.csproj index 4823e0b..786164e 100644 --- a/tests/Tests.csproj +++ b/tests/Tests.csproj @@ -2,6 +2,7 @@ net6.0 win10-x64;linux-x64;linux-musl-x64 + false false NU1701 xUnit1026 From 8d037c786ea5b916add8b1219e1d3e2836ed91f6 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sat, 10 Jul 2021 00:41:22 +0200 Subject: [PATCH 151/264] Reenable MSBuildEnableWorkloadResolver --- .gitlab-ci.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 7da242b..967def1 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -7,8 +7,6 @@ stages: variables: VERSION: 4.3.0-V$CI_COMMIT_SHORT_SHA IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG - # ToDo: Remove when .net6 is released - MSBuildEnableWorkloadResolver: 'false' Build: stage: build From 90668b6aac1bb728eba9d1a4b924743e3503a1d0 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sat, 10 Jul 2021 00:49:03 +0200 Subject: [PATCH 152/264] Add padding at the end of things for the !slap command --- src/Bot/Commands/Randomness/Slap.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Randomness/Slap.cs b/src/Bot/Commands/Randomness/Slap.cs index 7a858b1..f5d21b8 100644 --- a/src/Bot/Commands/Randomness/Slap.cs +++ b/src/Bot/Commands/Randomness/Slap.cs @@ -77,10 +77,13 @@ namespace Geekbot.Bot.Commands.Randomness "candle", "dictionary", "powerless banhammer", - "piece of low fat mozzarella" + "piece of low fat mozzarella", + // For some reason it never picks the last one + // Adding this workaround, because i'm to lazy to actually fix it at the time of writing this + "padding" }; - await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(things.Count - 1)]}"); + await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(0, things.Count - 1)]}"); await UpdateRecieved(user.Id); await UpdateGiven(Context.User.Id); From 9a55d8447fef227f5b69790125651767bd92fb82 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 11 Aug 2021 17:58:06 +0200 Subject: [PATCH 153/264] Upgrade discord.net to version 2.4.0 --- src/Core/Core.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 17b4a26..629233a 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -14,7 +14,7 @@ - + all From f22956368b3a165a3cbe9135ff829cffa6ba8187 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 11 Aug 2021 17:58:45 +0200 Subject: [PATCH 154/264] Remove !gdq --- src/Bot/Commands/Randomness/Gdq.cs | 36 ------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 src/Bot/Commands/Randomness/Gdq.cs diff --git a/src/Bot/Commands/Randomness/Gdq.cs b/src/Bot/Commands/Randomness/Gdq.cs deleted file mode 100644 index c6d9fa8..0000000 --- a/src/Bot/Commands/Randomness/Gdq.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Net; -using System.Threading.Tasks; -using Discord.Commands; -using Geekbot.Core.ErrorHandling; - -namespace Geekbot.Bot.Commands.Randomness -{ - public class Gdq : ModuleBase - { - private readonly IErrorHandler _errorHandler; - - public Gdq(IErrorHandler errorHandler) - { - _errorHandler = errorHandler; - } - - [Command("gdq", RunMode = RunMode.Async)] - [Summary("Get a quote from the GDQ donation generator.")] - public async Task GetQuote() - { - try - { - using var client = new WebClient(); - var url = new Uri("http://taskinoz.com/gdq/api/"); - var response = client.DownloadString(url); - - await ReplyAsync(response); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context); - } - } - } -} \ No newline at end of file From 18ece35ffe88aaa8e5aa0204b499d72f5615ece4 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Wed, 11 Aug 2021 23:08:00 +0200 Subject: [PATCH 155/264] Remove System.Timers.Timer ambiguity for .net6-preview7 --- src/Bot/Handlers/StatsHandler.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Bot/Handlers/StatsHandler.cs b/src/Bot/Handlers/StatsHandler.cs index d1384cd..b089515 100644 --- a/src/Bot/Handlers/StatsHandler.cs +++ b/src/Bot/Handlers/StatsHandler.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; -using System.Timers; using Discord.WebSocket; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; @@ -24,7 +22,7 @@ namespace Geekbot.Bot.Handlers _database = database; _season = SeasonsUtils.GetCurrentSeason(); - var timer = new Timer() + var timer = new System.Timers.Timer() { Enabled = true, AutoReset = true, From e712403dd96d824688cc0077b5394397b5b233f2 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 11:21:42 +0200 Subject: [PATCH 156/264] Upgrade Sumologic, jikan and HtmlAgilityPack --- src/Bot/Bot.csproj | 4 ++-- src/Core/Core.csproj | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index ff10a94..c64eecb 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -24,8 +24,8 @@ - - + + diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 629233a..463c4e9 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -34,7 +34,7 @@ - + From f19ddb30b285352282722bc868f67827e029bddd Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 11:23:20 +0200 Subject: [PATCH 157/264] Replace RNGCryptoServiceProvider with System.Security.Cryptography.RandomNumberGenerator --- src/Core/RandomNumberGenerator/RandomNumberGenerator.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs index db990a7..1b7178b 100644 --- a/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs +++ b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs @@ -1,5 +1,4 @@ using System; -using System.Security.Cryptography; using Anemonis.RandomOrg; using Geekbot.Core.GlobalSettings; @@ -7,13 +6,13 @@ namespace Geekbot.Core.RandomNumberGenerator { public class RandomNumberGenerator : IRandomNumberGenerator { - private readonly RNGCryptoServiceProvider csp; + private readonly System.Security.Cryptography.RandomNumberGenerator rng; private readonly bool _canUseRandomOrg; private readonly RandomOrgClient _randomOrgClient; public RandomNumberGenerator(IGlobalSettings globalSettings) { - csp = new RNGCryptoServiceProvider(); + rng = System.Security.Cryptography.RandomNumberGenerator.Create(); var randomOrgApiKey = globalSettings.GetKey("RandomOrgApiKey"); if (!string.IsNullOrEmpty(randomOrgApiKey)) @@ -32,7 +31,7 @@ namespace Geekbot.Core.RandomNumberGenerator if (minValue >= maxInclusiveValue) { - throw new ArgumentOutOfRangeException("minValue must be lower than maxExclusiveValue"); + throw new ArgumentOutOfRangeException("minValue", "must be lower than maxExclusiveValue"); } if (_canUseRandomOrg) @@ -84,7 +83,7 @@ namespace Geekbot.Core.RandomNumberGenerator private byte[] GenerateRandomBytes(int bytesNumber) { var buffer = new byte[bytesNumber]; - csp.GetBytes(buffer); + rng.GetBytes(buffer); return buffer; } } From 989057a0b06c034658bf83d73ea16a289d480803 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 12:22:26 +0200 Subject: [PATCH 158/264] Migrate from RavenSharp to the SentrySDK --- src/Bot/Bot.csproj | 2 +- src/Core/Core.csproj | 2 +- src/Core/ErrorHandling/ErrorHandler.cs | 38 +++++++++++++------------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index c64eecb..998456c 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -29,7 +29,7 @@ - + diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 463c4e9..dfce63b 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -33,7 +33,7 @@ - + diff --git a/src/Core/ErrorHandling/ErrorHandler.cs b/src/Core/ErrorHandling/ErrorHandler.cs index 60d97e9..a5ccc8e 100644 --- a/src/Core/ErrorHandling/ErrorHandler.cs +++ b/src/Core/ErrorHandling/ErrorHandler.cs @@ -1,9 +1,9 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; using Geekbot.Core.Logger; -using SharpRaven; -using SharpRaven.Data; +using Sentry; using Exception = System.Exception; namespace Geekbot.Core.ErrorHandling @@ -12,7 +12,6 @@ namespace Geekbot.Core.ErrorHandling { private readonly IGeekbotLogger _logger; private readonly Func _getDefaultErrorText; - private readonly IRavenClient _raven; private readonly bool _errorsInChat; public ErrorHandler(IGeekbotLogger logger, RunParameters runParameters, Func getDefaultErrorText) @@ -22,15 +21,15 @@ namespace Geekbot.Core.ErrorHandling _errorsInChat = runParameters.ExposeErrors; var sentryDsn = runParameters.SentryEndpoint; - if (!string.IsNullOrEmpty(sentryDsn)) + if (string.IsNullOrEmpty(sentryDsn)) return; + + SentrySdk.Init(o => { - _raven = new RavenClient(sentryDsn) { Release = Constants.BotVersion(), Environment = "Production" }; - _logger.Information(LogSource.Geekbot, $"Command Errors will be logged to Sentry: {sentryDsn}"); - } - else - { - _raven = null; - } + o.Dsn = sentryDsn; + o.Release = Constants.BotVersion(); + o.Environment = "Production"; + }); + _logger.Information(LogSource.Geekbot, $"Command Errors will be logged to Sentry: {sentryDsn}"); } public async Task HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def") @@ -83,18 +82,19 @@ namespace Geekbot.Core.ErrorHandling private void ReportExternal(Exception e, MessageDto errorObj) { - if (_raven == null) return; + if (!SentrySdk.IsEnabled) return; + var sentryEvent = new SentryEvent(e) { - Tags = - { - ["discord_server"] = errorObj.Guild.Name, - ["discord_user"] = errorObj.User.Name - }, Message = errorObj.Message.Content, - Extra = errorObj }; - _raven.Capture(sentryEvent); + sentryEvent.SetTag("discord_server", errorObj.Guild.Name); + sentryEvent.SetExtra("Channel", errorObj.Channel); + sentryEvent.SetExtra("Guild", errorObj.Guild); + sentryEvent.SetExtra("Message", errorObj.Message); + sentryEvent.SetExtra("User", errorObj.User); + + SentrySdk.CaptureEvent(sentryEvent); } } } \ No newline at end of file From 5c507b026cc3f8bb94bc4cb8f92d77595c609a5c Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:03:35 +0200 Subject: [PATCH 159/264] Remove random.org integration --- src/Bot/Program.cs | 2 +- src/Core/Core.csproj | 1 - .../RandomNumberGenerator.cs | 34 +------------------ tests/Core/DiceParser/DiceParser.test.cs | 2 +- tests/Core/DiceParser/SingleDie.test.cs | 4 +-- 5 files changed, 5 insertions(+), 38 deletions(-) diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index dee6ec3..3429fbc 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -162,7 +162,7 @@ namespace Geekbot.Bot var emojiConverter = new EmojiConverter(); var mtgManaConverter = new MtgManaConverter(); var wikipediaClient = new WikipediaClient(); - var randomNumberGenerator = new RandomNumberGenerator(_globalSettings); + var randomNumberGenerator = new RandomNumberGenerator(); var mediaProvider = new MediaProvider(_logger, randomNumberGenerator); var kvMemoryStore = new KvInInMemoryStore(); var errorHandler = new ErrorHandler(_logger, _runParameters, () => Localization.Internal.SomethingWentWrong); diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index dfce63b..6d1b89b 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -12,7 +12,6 @@ - diff --git a/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs index 1b7178b..7460677 100644 --- a/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs +++ b/src/Core/RandomNumberGenerator/RandomNumberGenerator.cs @@ -1,25 +1,14 @@ using System; -using Anemonis.RandomOrg; -using Geekbot.Core.GlobalSettings; namespace Geekbot.Core.RandomNumberGenerator { public class RandomNumberGenerator : IRandomNumberGenerator { private readonly System.Security.Cryptography.RandomNumberGenerator rng; - private readonly bool _canUseRandomOrg; - private readonly RandomOrgClient _randomOrgClient; - public RandomNumberGenerator(IGlobalSettings globalSettings) + public RandomNumberGenerator() { rng = System.Security.Cryptography.RandomNumberGenerator.Create(); - - var randomOrgApiKey = globalSettings.GetKey("RandomOrgApiKey"); - if (!string.IsNullOrEmpty(randomOrgApiKey)) - { - _canUseRandomOrg = true; - _randomOrgClient = new RandomOrgClient(randomOrgApiKey); - } } public int Next(int minValue, int maxInclusiveValue) @@ -33,31 +22,10 @@ namespace Geekbot.Core.RandomNumberGenerator { throw new ArgumentOutOfRangeException("minValue", "must be lower than maxExclusiveValue"); } - - if (_canUseRandomOrg) - { - try - { - return GetFromRandomOrg(minValue, maxInclusiveValue); - } - catch - { - // ignore - } - } return GetFromCrypto(minValue, maxInclusiveValue); } - private int GetFromRandomOrg(int minValue, int maxInclusiveValue) - { - return _randomOrgClient - .GenerateIntegersAsync(1, minValue, maxInclusiveValue, false) - .Result - .Random - .Data[0]; - } - private int GetFromCrypto(int minValue, int maxInclusiveValue) { var maxExclusiveValue = maxInclusiveValue + 1; diff --git a/tests/Core/DiceParser/DiceParser.test.cs b/tests/Core/DiceParser/DiceParser.test.cs index ed9425f..fd9e5c5 100644 --- a/tests/Core/DiceParser/DiceParser.test.cs +++ b/tests/Core/DiceParser/DiceParser.test.cs @@ -10,7 +10,7 @@ namespace Tests.Core.DiceParser { public class DiceParserTest { - private static readonly RandomNumberGenerator _randomNumberGenerator = new RandomNumberGenerator(new Mock().Object); + private static readonly RandomNumberGenerator _randomNumberGenerator = new RandomNumberGenerator(); public struct DiceParserTestDto { diff --git a/tests/Core/DiceParser/SingleDie.test.cs b/tests/Core/DiceParser/SingleDie.test.cs index 5173902..fdba5e7 100644 --- a/tests/Core/DiceParser/SingleDie.test.cs +++ b/tests/Core/DiceParser/SingleDie.test.cs @@ -45,7 +45,7 @@ namespace Tests.Core.DiceParser [Theory, MemberData(nameof(SingleDieNameTestData))] public void SingleDieNameTestFunc(string testName, SingleDieNameTestDto testData) { - var die = new SingleDie(new RandomNumberGenerator(new Mock().Object)) {AdvantageType = testData.AdvantageType}; + var die = new SingleDie(new RandomNumberGenerator()) {AdvantageType = testData.AdvantageType}; Assert.Equal(die.DiceName, testData.Expected); } @@ -108,7 +108,7 @@ namespace Tests.Core.DiceParser [Theory, MemberData(nameof(SingleDieValidationTestData))] public void SingleDieValidationTestFunc(string testName, SingleDieValidationTestDto testData) { - var die = new SingleDie(new RandomNumberGenerator(new Mock().Object)) + var die = new SingleDie(new RandomNumberGenerator()) { Amount = testData.Amount, Sides = testData.Sides From 1f518e980c323b728e43b85d9f829738bd18754e Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:04:30 +0200 Subject: [PATCH 160/264] Move Sentry SDK init to the main init process --- src/Bot/Program.cs | 20 +++++++++++++++++++- src/Core/ErrorHandling/ErrorHandler.cs | 12 ------------ 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 3429fbc..4d7526b 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -26,6 +26,8 @@ using Geekbot.Core.WikipediaClient; using Geekbot.Web; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Sentry; +using Constants = Geekbot.Core.Constants; namespace Geekbot.Bot { @@ -90,7 +92,9 @@ namespace Geekbot.Bot _logger.Information(LogSource.Api, "Starting Web API"); StartWebApi(); - + + RegisterSentry(); + _logger.Information(LogSource.Geekbot, "Done and ready for use"); await Task.Delay(-1); @@ -224,5 +228,19 @@ namespace Geekbot.Bot var highscoreManager = new HighscoreManager(_databaseInitializer.Initialize(), _userRepository); WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize(), _client, _globalSettings, highscoreManager); } + + private void RegisterSentry() + { + var sentryDsn = _runParameters.SentryEndpoint; + if (string.IsNullOrEmpty(sentryDsn)) return; + SentrySdk.Init(o => + { + o.Dsn = sentryDsn; + o.Release = Constants.BotVersion(); + o.Environment = "Production"; + o.TracesSampleRate = 1.0; + }); + _logger.Information(LogSource.Geekbot, $"Command Errors will be logged to Sentry: {sentryDsn}"); + } } } \ No newline at end of file diff --git a/src/Core/ErrorHandling/ErrorHandler.cs b/src/Core/ErrorHandling/ErrorHandler.cs index a5ccc8e..0b55bd8 100644 --- a/src/Core/ErrorHandling/ErrorHandler.cs +++ b/src/Core/ErrorHandling/ErrorHandler.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; using Geekbot.Core.Logger; @@ -19,17 +18,6 @@ namespace Geekbot.Core.ErrorHandling _logger = logger; _getDefaultErrorText = getDefaultErrorText; _errorsInChat = runParameters.ExposeErrors; - - var sentryDsn = runParameters.SentryEndpoint; - if (string.IsNullOrEmpty(sentryDsn)) return; - - SentrySdk.Init(o => - { - o.Dsn = sentryDsn; - o.Release = Constants.BotVersion(); - o.Environment = "Production"; - }); - _logger.Information(LogSource.Geekbot, $"Command Errors will be logged to Sentry: {sentryDsn}"); } public async Task HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def") From 3299ac4eabafdb4c053ca0887aad73d0518c9635 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:06:10 +0200 Subject: [PATCH 161/264] Add generic sentry tracing to the main command module --- src/Core/GeekbotCommandBase.cs | 40 +++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Core/GeekbotCommandBase.cs b/src/Core/GeekbotCommandBase.cs index 43ced95..ae964e7 100644 --- a/src/Core/GeekbotCommandBase.cs +++ b/src/Core/GeekbotCommandBase.cs @@ -1,9 +1,13 @@ +using System.Collections.Generic; using System.Globalization; using System.Threading; +using System.Threading.Tasks; +using Discord; using Discord.Commands; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.GuildSettingsManager; +using Sentry; namespace Geekbot.Core { @@ -12,6 +16,7 @@ namespace Geekbot.Core protected readonly IGuildSettingsManager GuildSettingsManager; protected GuildSettingsModel GuildSettings; protected readonly IErrorHandler ErrorHandler; + protected ITransaction Transaction; protected GeekbotCommandBase(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) { @@ -22,9 +27,42 @@ namespace Geekbot.Core protected override void BeforeExecute(CommandInfo command) { base.BeforeExecute(command); + + // Transaction Setup + Transaction = SentrySdk.StartTransaction(new Transaction(command.Name, "Exec")); + Transaction.SetTags(new [] + { + new KeyValuePair("GuildId", Context.Guild.Id.ToString()), + new KeyValuePair("Guild", Context.Guild.Name), + }); + Transaction.User = new User() + { + Id = Context.User.Id.ToString(), + Username = Context.User.Username, + }; + + // Command Setup + var setupSpan = Transaction.StartChild("Setup"); + GuildSettings = GuildSettingsManager.GetSettings(Context?.Guild?.Id ?? 0); var language = GuildSettings.Language; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language == "CHDE" ? "de-ch" : language); + Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language); + + setupSpan.Finish(); + } + + protected override void AfterExecute(CommandInfo command) + { + base.AfterExecute(command); + Transaction.Finish(); + } + + protected override Task ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + { + var replySpan = Transaction.StartChild("Reply"); + var msg = base.ReplyAsync(message, isTTS, embed, options, allowedMentions, messageReference); + replySpan.Finish(); + return msg; } } } \ No newline at end of file From aa826f962d8715f2579a0c9ee79bee8776c74a4e Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:06:34 +0200 Subject: [PATCH 162/264] Add traces to the !roll command --- src/Bot/Commands/Games/Roll/Roll.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Games/Roll/Roll.cs b/src/Bot/Commands/Games/Roll/Roll.cs index 6ef9322..0361cbd 100644 --- a/src/Bot/Commands/Games/Roll/Roll.cs +++ b/src/Bot/Commands/Games/Roll/Roll.cs @@ -11,6 +11,7 @@ using Geekbot.Core.Extensions; using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.KvInMemoryStore; using Geekbot.Core.RandomNumberGenerator; +using Sentry; namespace Geekbot.Bot.Commands.Games.Roll { @@ -34,43 +35,54 @@ namespace Geekbot.Bot.Commands.Games.Roll { try { + var inputSpan = Transaction.StartChild("CommandInput"); var number = _randomNumberGenerator.Next(1, 100); int.TryParse(stuff, out var guess); + inputSpan.Finish(); + if (guess <= 100 && guess > 0) { + var prevRollCheckSpan = Transaction.StartChild("PrevRollCheck"); var kvKey = $"{Context?.Guild?.Id ?? 0}:{Context.User.Id}:RollsPrevious"; - + var prevRoll = _kvInMemoryStore.Get(kvKey); - + if (prevRoll?.LastGuess == guess && prevRoll?.GuessedOn.AddDays(1) > DateTime.Now) { await ReplyAsync(string.Format( Localization.Roll.NoPrevGuess, Context.Message.Author.Mention, DateLocalization.FormatDateTimeAsRemaining(prevRoll.GuessedOn.AddDays(1)))); + Transaction.Status = SpanStatus.InvalidArgument; return; } _kvInMemoryStore.Set(kvKey, new RollTimeout {LastGuess = guess, GuessedOn = DateTime.Now}); + prevRollCheckSpan.Finish(); await ReplyAsync(string.Format(Localization.Roll.Rolled, Context.Message.Author.Mention, number, guess)); if (guess == number) { + var correctGuessSpan = Transaction.StartChild("CorrectGuess"); await ReplyAsync(string.Format(Localization.Roll.Gratz, Context.Message.Author)); var user = await GetUser(Context.User.Id); user.Rolls += 1; _database.Rolls.Update(user); await _database.SaveChangesAsync(); + correctGuessSpan.Finish(); } } else { await ReplyAsync(string.Format(Localization.Roll.RolledNoGuess, Context.Message.Author.Mention, number)); } + + Transaction.Status = SpanStatus.Ok; } catch (Exception e) { await ErrorHandler.HandleCommandException(e, Context); + Transaction.Status = SpanStatus.InternalError; } } From d708525a2f59711599311782d1c663e7f4f65441 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:07:19 +0200 Subject: [PATCH 163/264] Add traces to the !quote command --- src/Bot/Commands/Utils/Quote/Quote.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index e79663c..fdf1030 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -15,6 +15,8 @@ using Geekbot.Core.Polyfills; using Geekbot.Core.RandomNumberGenerator; using Geekbot.Core.UserRepository; using Microsoft.EntityFrameworkCore; +using Sentry; +using Constants = Geekbot.Core.Constants; namespace Geekbot.Bot.Commands.Utils.Quote { @@ -43,23 +45,32 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { + var getTotalSpan = Transaction.StartChild("TotalQuotes"); var totalQuotes = await _database.Quotes.CountAsync(e => e.GuildId.Equals(Context.Guild.Id.AsLong())); + getTotalSpan.Finish(); if (totalQuotes == 0) { await ReplyAsync(Localization.Quote.NoQuotesFound); + Transaction.Status = SpanStatus.NotFound; return; } + var getQuoteFromDbSpan = Transaction.StartChild("GetQuoteFromDB"); var random = _randomNumberGenerator.Next(0, totalQuotes - 1); var quote = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).Skip(random).Take(1); + getQuoteFromDbSpan.Finish(); + var replySpan = Transaction.StartChild("Reply"); var embed = QuoteBuilder(quote.FirstOrDefault()); await ReplyAsync("", false, embed.Build()); + replySpan.Finish(); + Transaction.Status = SpanStatus.Ok; } catch (Exception e) { await ErrorHandler.HandleCommandException(e, Context, "Whoops, seems like the quote was to edgy to return"); + Transaction.Status = SpanStatus.InternalError; } } From 833a8a0dd8dfea3fa29019584cf448c41c4cc469 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:27:46 +0200 Subject: [PATCH 164/264] Split Transactions from the GeekbotCommandBase --- src/Core/GeekbotCommandBase.cs | 35 +----------------------- src/Core/TransactionModuleBase.cs | 45 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 34 deletions(-) create mode 100644 src/Core/TransactionModuleBase.cs diff --git a/src/Core/GeekbotCommandBase.cs b/src/Core/GeekbotCommandBase.cs index ae964e7..801c53c 100644 --- a/src/Core/GeekbotCommandBase.cs +++ b/src/Core/GeekbotCommandBase.cs @@ -1,22 +1,17 @@ -using System.Collections.Generic; using System.Globalization; using System.Threading; -using System.Threading.Tasks; -using Discord; using Discord.Commands; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.GuildSettingsManager; -using Sentry; namespace Geekbot.Core { - public class GeekbotCommandBase : ModuleBase + public class GeekbotCommandBase : TransactionModuleBase { protected readonly IGuildSettingsManager GuildSettingsManager; protected GuildSettingsModel GuildSettings; protected readonly IErrorHandler ErrorHandler; - protected ITransaction Transaction; protected GeekbotCommandBase(IErrorHandler errorHandler, IGuildSettingsManager guildSettingsManager) { @@ -28,20 +23,6 @@ namespace Geekbot.Core { base.BeforeExecute(command); - // Transaction Setup - Transaction = SentrySdk.StartTransaction(new Transaction(command.Name, "Exec")); - Transaction.SetTags(new [] - { - new KeyValuePair("GuildId", Context.Guild.Id.ToString()), - new KeyValuePair("Guild", Context.Guild.Name), - }); - Transaction.User = new User() - { - Id = Context.User.Id.ToString(), - Username = Context.User.Username, - }; - - // Command Setup var setupSpan = Transaction.StartChild("Setup"); GuildSettings = GuildSettingsManager.GetSettings(Context?.Guild?.Id ?? 0); @@ -50,19 +31,5 @@ namespace Geekbot.Core setupSpan.Finish(); } - - protected override void AfterExecute(CommandInfo command) - { - base.AfterExecute(command); - Transaction.Finish(); - } - - protected override Task ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) - { - var replySpan = Transaction.StartChild("Reply"); - var msg = base.ReplyAsync(message, isTTS, embed, options, allowedMentions, messageReference); - replySpan.Finish(); - return msg; - } } } \ No newline at end of file diff --git a/src/Core/TransactionModuleBase.cs b/src/Core/TransactionModuleBase.cs new file mode 100644 index 0000000..111ae18 --- /dev/null +++ b/src/Core/TransactionModuleBase.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Sentry; + +namespace Geekbot.Core +{ + public class TransactionModuleBase : ModuleBase + { + protected ITransaction Transaction; + + protected override void BeforeExecute(CommandInfo command) + { + base.BeforeExecute(command); + + // Transaction Setup + Transaction = SentrySdk.StartTransaction(new Transaction(command.Name, "Exec")); + Transaction.SetTags(new [] + { + new KeyValuePair("GuildId", Context.Guild.Id.ToString()), + new KeyValuePair("Guild", Context.Guild.Name), + }); + Transaction.User = new User() + { + Id = Context.User.Id.ToString(), + Username = Context.User.Username, + }; + } + + protected override void AfterExecute(CommandInfo command) + { + base.AfterExecute(command); + Transaction.Finish(); + } + + protected override Task ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + { + var replySpan = Transaction.StartChild("Reply"); + var msg = base.ReplyAsync(message, isTTS, embed, options, allowedMentions, messageReference); + replySpan.Finish(); + return msg; + } + } +} \ No newline at end of file From f02c30e66028930798a3146a188fc1f1ecf8f990 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:30:50 +0200 Subject: [PATCH 165/264] Remove the mod command class --- src/Bot/Commands/Admin/Mod.cs | 38 ----------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 src/Bot/Commands/Admin/Mod.cs diff --git a/src/Bot/Commands/Admin/Mod.cs b/src/Bot/Commands/Admin/Mod.cs deleted file mode 100644 index b642680..0000000 --- a/src/Bot/Commands/Admin/Mod.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Threading.Tasks; -using Discord; -using Discord.Commands; -using Geekbot.Core.CommandPreconditions; -using Geekbot.Core.ErrorHandling; - -namespace Geekbot.Bot.Commands.Admin -{ - [Group("mod")] - [RequireUserPermission(GuildPermission.KickMembers)] - [RequireUserPermission(GuildPermission.ManageMessages)] - [RequireUserPermission(GuildPermission.ManageRoles)] - [DisableInDirectMessage] - public class Mod : ModuleBase - { - private readonly IErrorHandler _errorHandler; - - public Mod(IErrorHandler errorHandler) - { - _errorHandler = errorHandler; - } - - [Command("namehistory", RunMode = RunMode.Async)] - [Summary("See past usernames of an user")] - public async Task UsernameHistory([Summary("@someone")] IUser user) - { - try - { - await Context.Channel.SendMessageAsync("This command has been removed due to low usage and excessively high database usage"); - } - catch (Exception e) - { - await _errorHandler.HandleCommandException(e, Context); - } - } - } -} \ No newline at end of file From a1f8d033c28e97b7963825f7492b423d21b62f2a Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:31:24 +0200 Subject: [PATCH 166/264] Use the TransactionModuleBase for all commands that haven't implemented GeekbotCommandBase --- src/Bot/Commands/Games/Pokedex.cs | 3 ++- src/Bot/Commands/Integrations/LolMmr/LolMmr.cs | 2 +- src/Bot/Commands/Integrations/MagicTheGathering.cs | 3 ++- .../Commands/Integrations/UbranDictionary/UrbanDictionary.cs | 2 +- src/Bot/Commands/Integrations/Wikipedia.cs | 3 ++- src/Bot/Commands/Integrations/Youtube.cs | 3 ++- .../Commands/Randomness/BenedictCumberbatchNameGenerator.cs | 3 ++- src/Bot/Commands/Randomness/Cat/Cat.cs | 2 +- src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs | 2 +- src/Bot/Commands/Randomness/Dad/DadJokes.cs | 2 +- src/Bot/Commands/Randomness/Dog/Dog.cs | 2 +- src/Bot/Commands/Randomness/Fortune.cs | 3 ++- src/Bot/Commands/Randomness/Greetings/Greetings.cs | 2 +- src/Bot/Commands/Randomness/Kanye/Kanye.cs | 2 +- src/Bot/Commands/Randomness/RandomAnimals.cs | 3 ++- src/Bot/Commands/Randomness/Slap.cs | 3 ++- src/Bot/Commands/User/GuildInfo.cs | 3 ++- src/Bot/Commands/Utils/AvatarGetter.cs | 3 ++- src/Bot/Commands/Utils/Changelog/Changelog.cs | 2 +- src/Bot/Commands/Utils/Dice.cs | 3 ++- src/Bot/Commands/Utils/Emojify.cs | 3 ++- src/Bot/Commands/Utils/Help.cs | 3 ++- src/Bot/Commands/Utils/Info.cs | 2 +- src/Bot/Commands/Utils/Lmgtfy.cs | 3 ++- src/Bot/Commands/Utils/Ping.cs | 3 ++- 25 files changed, 40 insertions(+), 25 deletions(-) diff --git a/src/Bot/Commands/Games/Pokedex.cs b/src/Bot/Commands/Games/Pokedex.cs index 426761c..325ee8c 100644 --- a/src/Bot/Commands/Games/Pokedex.cs +++ b/src/Bot/Commands/Games/Pokedex.cs @@ -3,13 +3,14 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; using PokeAPI; namespace Geekbot.Bot.Commands.Games { - public class Pokedex : ModuleBase + public class Pokedex : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Integrations/LolMmr/LolMmr.cs b/src/Bot/Commands/Integrations/LolMmr/LolMmr.cs index 4e75034..3049617 100644 --- a/src/Bot/Commands/Integrations/LolMmr/LolMmr.cs +++ b/src/Bot/Commands/Integrations/LolMmr/LolMmr.cs @@ -10,7 +10,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Integrations.LolMmr { - public class LolMmr : ModuleBase + public class LolMmr : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Integrations/MagicTheGathering.cs b/src/Bot/Commands/Integrations/MagicTheGathering.cs index b179d6e..359b41e 100644 --- a/src/Bot/Commands/Integrations/MagicTheGathering.cs +++ b/src/Bot/Commands/Integrations/MagicTheGathering.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Converters; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; @@ -11,7 +12,7 @@ using MtgApiManager.Lib.Service; namespace Geekbot.Bot.Commands.Integrations { - public class MagicTheGathering : ModuleBase + public class MagicTheGathering : TransactionModuleBase { private readonly IErrorHandler _errorHandler; private readonly IMtgManaConverter _manaConverter; diff --git a/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs index 72bc8cd..9060b91 100644 --- a/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs +++ b/src/Bot/Commands/Integrations/UbranDictionary/UrbanDictionary.cs @@ -9,7 +9,7 @@ using Geekbot.Core.Extensions; namespace Geekbot.Bot.Commands.Integrations.UbranDictionary { - public class UrbanDictionary : ModuleBase + public class UrbanDictionary : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Integrations/Wikipedia.cs b/src/Bot/Commands/Integrations/Wikipedia.cs index 709f974..82f42a0 100644 --- a/src/Bot/Commands/Integrations/Wikipedia.cs +++ b/src/Bot/Commands/Integrations/Wikipedia.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; @@ -14,7 +15,7 @@ using HtmlAgilityPack; namespace Geekbot.Bot.Commands.Integrations { - public class Wikipedia : ModuleBase + public class Wikipedia : TransactionModuleBase { private readonly IErrorHandler _errorHandler; private readonly IWikipediaClient _wikipediaClient; diff --git a/src/Bot/Commands/Integrations/Youtube.cs b/src/Bot/Commands/Integrations/Youtube.cs index 60ebdaa..74fcf52 100644 --- a/src/Bot/Commands/Integrations/Youtube.cs +++ b/src/Bot/Commands/Integrations/Youtube.cs @@ -1,6 +1,7 @@ using System; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.GlobalSettings; using Google.Apis.Services; @@ -8,7 +9,7 @@ using Google.Apis.YouTube.v3; namespace Geekbot.Bot.Commands.Integrations { - public class Youtube : ModuleBase + public class Youtube : TransactionModuleBase { private readonly IGlobalSettings _globalSettings; private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs b/src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs index 995c921..23187bd 100644 --- a/src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs +++ b/src/Bot/Commands/Randomness/BenedictCumberbatchNameGenerator.cs @@ -2,12 +2,13 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; using Geekbot.Core.RandomNumberGenerator; namespace Geekbot.Bot.Commands.Randomness { - public class BenedictCumberbatchNameGenerator : ModuleBase + public class BenedictCumberbatchNameGenerator : TransactionModuleBase { private readonly IErrorHandler _errorHandler; private readonly IRandomNumberGenerator _randomNumberGenerator; diff --git a/src/Bot/Commands/Randomness/Cat/Cat.cs b/src/Bot/Commands/Randomness/Cat/Cat.cs index 7bd7e57..1198113 100644 --- a/src/Bot/Commands/Randomness/Cat/Cat.cs +++ b/src/Bot/Commands/Randomness/Cat/Cat.cs @@ -7,7 +7,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Randomness.Cat { - public class Cat : ModuleBase + public class Cat : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs b/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs index be328b4..e2b1f16 100644 --- a/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs +++ b/src/Bot/Commands/Randomness/Chuck/ChuckNorrisJokes.cs @@ -7,7 +7,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Randomness.Chuck { - public class ChuckNorrisJokes : ModuleBase + public class ChuckNorrisJokes : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/Dad/DadJokes.cs b/src/Bot/Commands/Randomness/Dad/DadJokes.cs index 136650c..67f9679 100644 --- a/src/Bot/Commands/Randomness/Dad/DadJokes.cs +++ b/src/Bot/Commands/Randomness/Dad/DadJokes.cs @@ -6,7 +6,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Randomness.Dad { - public class DadJokes : ModuleBase + public class DadJokes : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/Dog/Dog.cs b/src/Bot/Commands/Randomness/Dog/Dog.cs index 051dbf3..39e57c7 100644 --- a/src/Bot/Commands/Randomness/Dog/Dog.cs +++ b/src/Bot/Commands/Randomness/Dog/Dog.cs @@ -7,7 +7,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Randomness.Dog { - public class Dog : ModuleBase + public class Dog : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/Fortune.cs b/src/Bot/Commands/Randomness/Fortune.cs index cc31536..1157603 100644 --- a/src/Bot/Commands/Randomness/Fortune.cs +++ b/src/Bot/Commands/Randomness/Fortune.cs @@ -1,10 +1,11 @@ using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Media; namespace Geekbot.Bot.Commands.Randomness { - public class Fortune : ModuleBase + public class Fortune : TransactionModuleBase { private readonly IFortunesProvider _fortunes; diff --git a/src/Bot/Commands/Randomness/Greetings/Greetings.cs b/src/Bot/Commands/Randomness/Greetings/Greetings.cs index cd69010..c32ee6d 100644 --- a/src/Bot/Commands/Randomness/Greetings/Greetings.cs +++ b/src/Bot/Commands/Randomness/Greetings/Greetings.cs @@ -8,7 +8,7 @@ using Geekbot.Core.Extensions; namespace Geekbot.Bot.Commands.Randomness.Greetings { - public class Greetings : ModuleBase + public class Greetings : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/Kanye/Kanye.cs b/src/Bot/Commands/Randomness/Kanye/Kanye.cs index 6ad67cb..e5d2e95 100644 --- a/src/Bot/Commands/Randomness/Kanye/Kanye.cs +++ b/src/Bot/Commands/Randomness/Kanye/Kanye.cs @@ -6,7 +6,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Randomness.Kanye { - public class Kanye : ModuleBase + public class Kanye : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Randomness/RandomAnimals.cs b/src/Bot/Commands/Randomness/RandomAnimals.cs index b9c1bdd..5493485 100644 --- a/src/Bot/Commands/Randomness/RandomAnimals.cs +++ b/src/Bot/Commands/Randomness/RandomAnimals.cs @@ -1,11 +1,12 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Media; namespace Geekbot.Bot.Commands.Randomness { - public class RandomAnimals : ModuleBase + public class RandomAnimals : TransactionModuleBase { private readonly IMediaProvider _mediaProvider; diff --git a/src/Bot/Commands/Randomness/Slap.cs b/src/Bot/Commands/Randomness/Slap.cs index f5d21b8..c99c325 100644 --- a/src/Bot/Commands/Randomness/Slap.cs +++ b/src/Bot/Commands/Randomness/Slap.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; @@ -11,7 +12,7 @@ using Geekbot.Core.Extensions; namespace Geekbot.Bot.Commands.Randomness { - public class Slap : ModuleBase + public class Slap : TransactionModuleBase { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; diff --git a/src/Bot/Commands/User/GuildInfo.cs b/src/Bot/Commands/User/GuildInfo.cs index c596186..c7a3b27 100644 --- a/src/Bot/Commands/User/GuildInfo.cs +++ b/src/Bot/Commands/User/GuildInfo.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.CommandPreconditions; using Geekbot.Core.Database; using Geekbot.Core.ErrorHandling; @@ -11,7 +12,7 @@ using Geekbot.Core.Levels; namespace Geekbot.Bot.Commands.User { - public class GuildInfo : ModuleBase + public class GuildInfo : TransactionModuleBase { private readonly IErrorHandler _errorHandler; private readonly DatabaseContext _database; diff --git a/src/Bot/Commands/Utils/AvatarGetter.cs b/src/Bot/Commands/Utils/AvatarGetter.cs index 2aa6b07..458eec8 100644 --- a/src/Bot/Commands/Utils/AvatarGetter.cs +++ b/src/Bot/Commands/Utils/AvatarGetter.cs @@ -2,11 +2,12 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Utils { - public class AvatarGetter : ModuleBase + public class AvatarGetter : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Utils/Changelog/Changelog.cs b/src/Bot/Commands/Utils/Changelog/Changelog.cs index 92d5ddd..989ac0d 100644 --- a/src/Bot/Commands/Utils/Changelog/Changelog.cs +++ b/src/Bot/Commands/Utils/Changelog/Changelog.cs @@ -11,7 +11,7 @@ using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Utils.Changelog { - public class Changelog : ModuleBase + public class Changelog : TransactionModuleBase { private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Utils/Dice.cs b/src/Bot/Commands/Utils/Dice.cs index 0668493..c57001f 100644 --- a/src/Bot/Commands/Utils/Dice.cs +++ b/src/Bot/Commands/Utils/Dice.cs @@ -3,12 +3,13 @@ using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.DiceParser; using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Utils { - public class Dice : ModuleBase + public class Dice : TransactionModuleBase { private readonly IErrorHandler _errorHandler; private readonly IDiceParser _diceParser; diff --git a/src/Bot/Commands/Utils/Emojify.cs b/src/Bot/Commands/Utils/Emojify.cs index 8bb880e..63b5456 100644 --- a/src/Bot/Commands/Utils/Emojify.cs +++ b/src/Bot/Commands/Utils/Emojify.cs @@ -1,12 +1,13 @@ using System; using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.Converters; using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Utils { - public class Emojify : ModuleBase + public class Emojify : TransactionModuleBase { private readonly IEmojiConverter _emojiConverter; private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Utils/Help.cs b/src/Bot/Commands/Utils/Help.cs index 58630fe..7377bfa 100644 --- a/src/Bot/Commands/Utils/Help.cs +++ b/src/Bot/Commands/Utils/Help.cs @@ -3,11 +3,12 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Utils { - public class Help : ModuleBase + public class Help : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Utils/Info.cs b/src/Bot/Commands/Utils/Info.cs index 663dd07..912528d 100644 --- a/src/Bot/Commands/Utils/Info.cs +++ b/src/Bot/Commands/Utils/Info.cs @@ -11,7 +11,7 @@ using Geekbot.Core.Extensions; namespace Geekbot.Bot.Commands.Utils { - public class Info : ModuleBase + public class Info : TransactionModuleBase { private readonly DiscordSocketClient _client; private readonly CommandService _commands; diff --git a/src/Bot/Commands/Utils/Lmgtfy.cs b/src/Bot/Commands/Utils/Lmgtfy.cs index 6063cf9..76fa6fa 100644 --- a/src/Bot/Commands/Utils/Lmgtfy.cs +++ b/src/Bot/Commands/Utils/Lmgtfy.cs @@ -2,11 +2,12 @@ using System; using System.Threading.Tasks; using System.Web; using Discord.Commands; +using Geekbot.Core; using Geekbot.Core.ErrorHandling; namespace Geekbot.Bot.Commands.Utils { - public class Lmgtfy : ModuleBase + public class Lmgtfy : TransactionModuleBase { private readonly IErrorHandler _errorHandler; diff --git a/src/Bot/Commands/Utils/Ping.cs b/src/Bot/Commands/Utils/Ping.cs index d4faa53..ee751cd 100644 --- a/src/Bot/Commands/Utils/Ping.cs +++ b/src/Bot/Commands/Utils/Ping.cs @@ -1,9 +1,10 @@ using System.Threading.Tasks; using Discord.Commands; +using Geekbot.Core; namespace Geekbot.Bot.Commands.Utils { - public class Ping : ModuleBase + public class Ping : TransactionModuleBase { [Command("👀", RunMode = RunMode.Async)] [Summary("Look at the bot.")] From d16828077d5098a807027857ab5871d4c85668bf Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:33:55 +0200 Subject: [PATCH 167/264] Set Transaction Status to OK by default --- src/Bot/Commands/Games/Roll/Roll.cs | 2 -- src/Bot/Commands/Utils/Quote/Quote.cs | 1 - src/Core/TransactionModuleBase.cs | 1 + 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Bot/Commands/Games/Roll/Roll.cs b/src/Bot/Commands/Games/Roll/Roll.cs index 0361cbd..172126b 100644 --- a/src/Bot/Commands/Games/Roll/Roll.cs +++ b/src/Bot/Commands/Games/Roll/Roll.cs @@ -76,8 +76,6 @@ namespace Geekbot.Bot.Commands.Games.Roll { await ReplyAsync(string.Format(Localization.Roll.RolledNoGuess, Context.Message.Author.Mention, number)); } - - Transaction.Status = SpanStatus.Ok; } catch (Exception e) { diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index fdf1030..8fbecbc 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -65,7 +65,6 @@ namespace Geekbot.Bot.Commands.Utils.Quote var embed = QuoteBuilder(quote.FirstOrDefault()); await ReplyAsync("", false, embed.Build()); replySpan.Finish(); - Transaction.Status = SpanStatus.Ok; } catch (Exception e) { diff --git a/src/Core/TransactionModuleBase.cs b/src/Core/TransactionModuleBase.cs index 111ae18..c35800b 100644 --- a/src/Core/TransactionModuleBase.cs +++ b/src/Core/TransactionModuleBase.cs @@ -26,6 +26,7 @@ namespace Geekbot.Core Id = Context.User.Id.ToString(), Username = Context.User.Username, }; + Transaction.Status = SpanStatus.Ok; } protected override void AfterExecute(CommandInfo command) From 0a9099a6d28ad99a5696f8c5548341ba666d1f00 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 14:53:24 +0200 Subject: [PATCH 168/264] Move Sentry Init priority between the discord connection and dependency registration --- src/Bot/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 4d7526b..883d92b 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -85,6 +85,8 @@ namespace Geekbot.Bot await Login(); _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); await _client.SetGameAsync(_globalSettings.GetKey("Game")); + + RegisterSentry(); _logger.Information(LogSource.Geekbot, "Loading Dependencies and Handlers"); RegisterDependencies(); @@ -93,8 +95,6 @@ namespace Geekbot.Bot _logger.Information(LogSource.Api, "Starting Web API"); StartWebApi(); - RegisterSentry(); - _logger.Information(LogSource.Geekbot, "Done and ready for use"); await Task.Delay(-1); From 3d117aebe1d8007ed644fcdfcc57d912cffcb140 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 15:12:22 +0200 Subject: [PATCH 169/264] Split reply and quote embed building trace apart in !quote --- src/Bot/Commands/Utils/Quote/Quote.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 8fbecbc..835cdcf 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -61,10 +61,10 @@ namespace Geekbot.Bot.Commands.Utils.Quote var quote = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).Skip(random).Take(1); getQuoteFromDbSpan.Finish(); - var replySpan = Transaction.StartChild("Reply"); + var buildQuoteEmbedSpan = Transaction.StartChild("BuildQuoteEmbed"); var embed = QuoteBuilder(quote.FirstOrDefault()); + buildQuoteEmbedSpan.Finish(); await ReplyAsync("", false, embed.Build()); - replySpan.Finish(); } catch (Exception e) { From 954c6c2be30ef93c96f3fdef8f61f25cdac718f3 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Fri, 17 Sep 2021 15:55:13 +0200 Subject: [PATCH 170/264] Remove Guild ID from the tracing tags --- src/Core/TransactionModuleBase.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Core/TransactionModuleBase.cs b/src/Core/TransactionModuleBase.cs index c35800b..726c355 100644 --- a/src/Core/TransactionModuleBase.cs +++ b/src/Core/TransactionModuleBase.cs @@ -18,7 +18,6 @@ namespace Geekbot.Core Transaction = SentrySdk.StartTransaction(new Transaction(command.Name, "Exec")); Transaction.SetTags(new [] { - new KeyValuePair("GuildId", Context.Guild.Id.ToString()), new KeyValuePair("Guild", Context.Guild.Name), }); Transaction.User = new User() From 1b9d8732d5c9cb50c42e40312e719b6466a0500c Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 19 Sep 2021 00:57:10 +0200 Subject: [PATCH 171/264] Add tracing to the !quote embed builder --- src/Bot/Commands/Utils/Quote/Quote.cs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 835cdcf..372bed7 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -268,29 +268,32 @@ namespace Geekbot.Bot.Commands.Utils.Quote private EmbedBuilder QuoteBuilder(QuoteModel quote) { + var getEmbedUserSpan = Transaction.StartChild("GetEmbedUser"); var user = Context.Client.GetUserAsync(quote.UserId.AsUlong()).Result; if (user == null) { + var getEmbedUserFromRepoSpan = Transaction.StartChild("GetEmbedUserFromRepo"); var fallbackUserFromRepo = _userRepository.Get(quote.UserId.AsUlong()); user = new UserPolyfillDto() { Username = fallbackUserFromRepo?.Username ?? "Unknown User", AvatarUrl = fallbackUserFromRepo?.AvatarUrl }; + getEmbedUserFromRepoSpan.Finish(); } + getEmbedUserSpan.Finish(); + + var embedBuilderSpan = Transaction.StartChild("EmbedBuilder"); var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 167, 232)); - if (quote.InternalId == 0) - { - eb.Title = $"{user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; - } - else - { - eb.Title = $"#{quote.InternalId} | {user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; - } + eb.Title = quote.InternalId == 0 + ? $"{user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}" + : $"#{quote.InternalId} | {user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; eb.Description = quote.Quote; eb.ThumbnailUrl = user.GetAvatarUrl(); if (quote.Image != null) eb.ImageUrl = quote.Image; + embedBuilderSpan.Finish(); + return eb; } From 447c6d80422237959dfb7867118c37e888b1b243 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 19 Sep 2021 00:58:00 +0200 Subject: [PATCH 172/264] Remove a database call from !quote by delegating the randomness to the database. --- src/Bot/Commands/Utils/Quote/Quote.cs | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/src/Bot/Commands/Utils/Quote/Quote.cs b/src/Bot/Commands/Utils/Quote/Quote.cs index 372bed7..e85c6fa 100644 --- a/src/Bot/Commands/Utils/Quote/Quote.cs +++ b/src/Bot/Commands/Utils/Quote/Quote.cs @@ -45,22 +45,17 @@ namespace Geekbot.Bot.Commands.Utils.Quote { try { - var getTotalSpan = Transaction.StartChild("TotalQuotes"); - var totalQuotes = await _database.Quotes.CountAsync(e => e.GuildId.Equals(Context.Guild.Id.AsLong())); - getTotalSpan.Finish(); - - if (totalQuotes == 0) + var getQuoteFromDbSpan = Transaction.StartChild("GetQuoteFromDB"); + var quote = _database.Quotes.FromSqlInterpolated($"select * from \"Quotes\" where \"GuildId\" = {Context.Guild.Id} order by random() limit 1"); + getQuoteFromDbSpan.Finish(); + + if (!quote.Any()) { await ReplyAsync(Localization.Quote.NoQuotesFound); Transaction.Status = SpanStatus.NotFound; return; } - var getQuoteFromDbSpan = Transaction.StartChild("GetQuoteFromDB"); - var random = _randomNumberGenerator.Next(0, totalQuotes - 1); - var quote = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).Skip(random).Take(1); - getQuoteFromDbSpan.Finish(); - var buildQuoteEmbedSpan = Transaction.StartChild("BuildQuoteEmbed"); var embed = QuoteBuilder(quote.FirstOrDefault()); buildQuoteEmbedSpan.Finish(); From 85d06b76e009b9542acba34d3bed6f2b1a328c8c Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 19 Sep 2021 16:06:11 +0200 Subject: [PATCH 173/264] Add --disable-gateway parameter to the run parameters to stop the bot from connecting to discord. Useful when working on the web-api --- src/Bot/Program.cs | 17 ++++++++++------- src/Core/RunParameters.cs | 3 +++ src/Web/WebApiStartup.cs | 8 +++++--- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 883d92b..31b67e0 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -80,17 +80,20 @@ namespace Geekbot.Bot var database = ConnectToDatabase(); _globalSettings = new GlobalSettings(database); - logger.Information(LogSource.Geekbot, "Connecting to Discord"); - SetupDiscordClient(); - await Login(); - _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); - await _client.SetGameAsync(_globalSettings.GetKey("Game")); + if (!runParameters.DisableGateway) + { + logger.Information(LogSource.Geekbot, "Connecting to Discord"); + SetupDiscordClient(); + await Login(); + _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); + await _client.SetGameAsync(_globalSettings.GetKey("Game")); + } RegisterSentry(); _logger.Information(LogSource.Geekbot, "Loading Dependencies and Handlers"); RegisterDependencies(); - await RegisterHandlers(); + if (!runParameters.DisableGateway) await RegisterHandlers(); _logger.Information(LogSource.Api, "Starting Web API"); StartWebApi(); @@ -187,9 +190,9 @@ namespace Geekbot.Bot services.AddSingleton(diceParser); services.AddSingleton(_reactionListener); services.AddSingleton(_guildSettingsManager); - services.AddSingleton(_client); services.AddTransient(e => new HighscoreManager(_databaseInitializer.Initialize(), _userRepository)); services.AddTransient(e => _databaseInitializer.Initialize()); + if (!_runParameters.DisableGateway) services.AddSingleton(_client); _servicesProvider = services.BuildServiceProvider(); } diff --git a/src/Core/RunParameters.cs b/src/Core/RunParameters.cs index 3210587..a886a98 100644 --- a/src/Core/RunParameters.cs +++ b/src/Core/RunParameters.cs @@ -20,6 +20,9 @@ namespace Geekbot.Core [Option('e', "expose-errors", HelpText = "Shows internal errors in the chat (default: false) (env: EXPOSE_ERRORS)")] public bool ExposeErrors { get; set; } = ParamFallback("EXPOSE_ERRORS", false); + + [Option("disable-gateway", HelpText = "Disables the Discord Gateway (default: false) (env: GATEWAY_DISABLE)")] + public bool DisableGateway { get; set; } = ParamFallback("GATEWAY_DISABLE", false); /************************************ * Database * diff --git a/src/Web/WebApiStartup.cs b/src/Web/WebApiStartup.cs index 0c18886..9c8a805 100644 --- a/src/Web/WebApiStartup.cs +++ b/src/Web/WebApiStartup.cs @@ -37,12 +37,14 @@ namespace Geekbot.Web options.AddPolicy("AllowSpecificOrigin", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); }); - - services.AddSingleton(commandService); + services.AddSingleton(databaseContext); - services.AddSingleton(client); services.AddSingleton(globalSettings); services.AddSingleton(highscoreManager); + + if (runParameters.DisableGateway) return; + services.AddSingleton(commandService); + services.AddSingleton(client); }) .Configure(app => { From d81fb2a3d977786079a69525f1d17357fb520ea0 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 19 Sep 2021 16:11:06 +0200 Subject: [PATCH 174/264] Add initial interaction support --- .../Interactions/InteractionController.cs | 90 +++++++++++++++++++ .../Model/ApplicationCommandOption.cs | 16 ++++ .../Interactions/Model/Interaction.cs | 22 +++++ .../Interactions/Model/InteractionData.cs | 14 +++ .../Interactions/Model/InteractionOption.cs | 12 +++ .../Model/InteractionResolvedData.cs | 15 ++++ .../Interactions/Model/InteractionResponse.cs | 13 +++ .../Model/InteractionResponseData.cs | 16 ++++ .../Model/InteractionResponseType.cs | 11 +++ .../Interactions/Model/InteractionType.cs | 9 ++ .../Model/MessageComponents/Component.cs | 7 ++ .../Interactions/Model/Resolved/Channel.cs | 12 +++ .../Model/Resolved/ChannelType.cs | 17 ++++ .../Interactions/Model/Resolved/Member.cs | 16 ++++ .../Interactions/Model/Resolved/RoleTag.cs | 9 ++ .../Interactions/Model/Resolved/Roles.cs | 15 ++++ .../Model/Resolved/ThreadMetadata.cs | 13 +++ .../Interactions/Model/Resolved/User.cs | 21 +++++ src/Web/Web.csproj | 4 + src/Web/WebApiStartup.cs | 5 +- 20 files changed, 336 insertions(+), 1 deletion(-) create mode 100644 src/Web/Controllers/Interactions/InteractionController.cs create mode 100644 src/Web/Controllers/Interactions/Model/ApplicationCommandOption.cs create mode 100644 src/Web/Controllers/Interactions/Model/Interaction.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionData.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionOption.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionResolvedData.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionResponse.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionResponseData.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionResponseType.cs create mode 100644 src/Web/Controllers/Interactions/Model/InteractionType.cs create mode 100644 src/Web/Controllers/Interactions/Model/MessageComponents/Component.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/Channel.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/ChannelType.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/Member.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/RoleTag.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/Roles.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/ThreadMetadata.cs create mode 100644 src/Web/Controllers/Interactions/Model/Resolved/User.cs diff --git a/src/Web/Controllers/Interactions/InteractionController.cs b/src/Web/Controllers/Interactions/InteractionController.cs new file mode 100644 index 0000000..3501c06 --- /dev/null +++ b/src/Web/Controllers/Interactions/InteractionController.cs @@ -0,0 +1,90 @@ +using System; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using Geekbot.Core.GlobalSettings; +using Geekbot.Web.Controllers.Interactions.Model; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Sodium; + +namespace Geekbot.Web.Controllers.Interactions +{ + public class InteractionController : Controller + { + private readonly byte[] publicKeyBytes; + + public InteractionController(IGlobalSettings globalSettings) + { + var publicKey = globalSettings.GetKey("DiscordPublicKey"); + publicKeyBytes = Convert.FromHexString(publicKey.AsSpan()); + } + + [HttpPost] + [Route("/interactions")] + public async Task HandleInteraction( + [FromHeader(Name = "X-Signature-Ed25519")] string signature, + [FromHeader(Name = "X-Signature-Timestamp")] string timestamp + ) + { + if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp)) + { + return BadRequest(); + } + + Request.EnableBuffering(); + if (!(await HasValidSignature(signature, timestamp))) + { + return Unauthorized(); + } + + if (Request.Body.CanSeek) Request.Body.Seek(0, SeekOrigin.Begin); + var interaction = await JsonSerializer.DeserializeAsync(Request.Body, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }).ConfigureAwait(false); + if (interaction is null) throw new JsonException("Failed to deserialize JSON body"); + + return (interaction.Type, interaction.Version) switch + { + (InteractionType.Ping, 1) => Ping(), + (InteractionType.ApplicationCommand, 1) => ApplicationCommand(interaction), + (InteractionType.MessageComponent, 1) => MessageComponent(interaction), + _ => StatusCode(501) + }; + } + + private IActionResult Ping() + { + var response = new InteractionResponse() + { + Type = InteractionResponseType.Pong, + }; + return Ok(response); + } + + private IActionResult ApplicationCommand(Interaction interaction) + { + return StatusCode(501); + } + + private IActionResult MessageComponent(Interaction interaction) + { + return StatusCode(501); + } + + private async Task HasValidSignature(string signature, string timestamp) + { + var timestampBytes = Encoding.Default.GetBytes(timestamp); + var signatureBytes = Convert.FromHexString(signature.AsSpan()); + + var memoryStream = new MemoryStream(); + await Request.Body.CopyToAsync(memoryStream).ConfigureAwait(false); + var body = memoryStream.ToArray(); + + var timestampLength = timestampBytes.Length; + Array.Resize(ref timestampBytes, timestampLength + body.Length); + Array.Copy(body, 0, timestampBytes, timestampLength, body.Length); + + return PublicKeyAuth.VerifyDetached(signatureBytes, timestampBytes, publicKeyBytes); + } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/ApplicationCommandOption.cs b/src/Web/Controllers/Interactions/Model/ApplicationCommandOption.cs new file mode 100644 index 0000000..794102b --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/ApplicationCommandOption.cs @@ -0,0 +1,16 @@ +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public enum ApplicationCommandOption + { + SubCommand = 1, + SubCommandGroup = 2, + String = 3, + Integer = 4, + Boolean = 5, + User = 6, + Channel = 7, + Role = 8, + Mentionable = 9, + Number = 10, + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Interaction.cs b/src/Web/Controllers/Interactions/Model/Interaction.cs new file mode 100644 index 0000000..6045504 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Interaction.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public record Interaction + { + public string Id { get; set; } + public string ApplicationId { get; init; } + [Required] + public InteractionType Type { get; set; } + public InteractionData Data { get; init; } + public string GuildId { get; init; } + public string Name { get; init; } + public string Description { get; init; } + public List Options { get; init; } + public bool DefaultPermission { get; init; } + [Required] + public int Version { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionData.cs b/src/Web/Controllers/Interactions/Model/InteractionData.cs new file mode 100644 index 0000000..cb0f594 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionData.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; + +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public record InteractionData + { + public string Id { get; set; } + public string Name { get; set; } + public int Type { get; set;} + public InteractionResolvedData Resolved { get; set; } + public List Options { get; set; } + public string TargetId { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionOption.cs b/src/Web/Controllers/Interactions/Model/InteractionOption.cs new file mode 100644 index 0000000..c5acfa7 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionOption.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; + +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public record InteractionOption + { + public string Name { get; set; } + public ApplicationCommandOption Type { get; set; } + public string Value { get; set; } + public List Options { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionResolvedData.cs b/src/Web/Controllers/Interactions/Model/InteractionResolvedData.cs new file mode 100644 index 0000000..ee90f48 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionResolvedData.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using Discord; +using Geekbot.Web.Controllers.Interactions.Model.Resolved; + +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public class InteractionResolvedData + { + public Dictionary Users { get; set; } + public Dictionary Members { get; set; } + public Dictionary Roles { get; set; } + public Dictionary Channels { get; set; } + // public Dictionary Messages { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionResponse.cs b/src/Web/Controllers/Interactions/Model/InteractionResponse.cs new file mode 100644 index 0000000..c3a2a1e --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionResponse.cs @@ -0,0 +1,13 @@ +using System.Text.Json.Serialization; + +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public record InteractionResponse + { + [JsonPropertyName("type")] + public InteractionResponseType Type { get; set; } + + [JsonPropertyName("data")] + public InteractionData Data { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionResponseData.cs b/src/Web/Controllers/Interactions/Model/InteractionResponseData.cs new file mode 100644 index 0000000..146e812 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionResponseData.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using Discord; +using Geekbot.Web.Controllers.Interactions.Model.MessageComponents; + +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public record InteractionResponseData + { + public bool Tts { get; set; } = false; + public string Content { get; set; } + public List Embeds { get; set; } + public AllowedMentions AllowedMentions { get; set; } + public int Flags { get; set; } + public List Components { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionResponseType.cs b/src/Web/Controllers/Interactions/Model/InteractionResponseType.cs new file mode 100644 index 0000000..5bc85dc --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionResponseType.cs @@ -0,0 +1,11 @@ +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public enum InteractionResponseType + { + Pong = 1, + ChannelMessageWithSource = 4, + DeferredChannelMessageWithSource = 5, + DeferredUpdateMessage = 6, + UpdateMessage = 7, + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/InteractionType.cs b/src/Web/Controllers/Interactions/Model/InteractionType.cs new file mode 100644 index 0000000..a8421c5 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/InteractionType.cs @@ -0,0 +1,9 @@ +namespace Geekbot.Web.Controllers.Interactions.Model +{ + public enum InteractionType + { + Ping = 1, + ApplicationCommand = 2, + MessageComponent = 3, + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/MessageComponents/Component.cs b/src/Web/Controllers/Interactions/Model/MessageComponents/Component.cs new file mode 100644 index 0000000..72097a4 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/MessageComponents/Component.cs @@ -0,0 +1,7 @@ +namespace Geekbot.Web.Controllers.Interactions.Model.MessageComponents +{ + public record Component + { + + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/Channel.cs b/src/Web/Controllers/Interactions/Model/Resolved/Channel.cs new file mode 100644 index 0000000..4b280d9 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/Channel.cs @@ -0,0 +1,12 @@ +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public record Channel + { + public string Id { get; set; } + public ChannelType Type { get; set; } + public string Name { get; set; } + public string ParentId { get; set; } + public ThreadMetadata ThreadMetadata { get; set; } + public string Permissions { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/ChannelType.cs b/src/Web/Controllers/Interactions/Model/Resolved/ChannelType.cs new file mode 100644 index 0000000..1fbc0af --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/ChannelType.cs @@ -0,0 +1,17 @@ +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public enum ChannelType + { + GuildText = 0, + Dm = 1, + GuildVoice = 2, + GroupDm = 3, + GuildCategory = 4, + GuildNews = 5, + GuildStore = 6, + GuildNewsThread = 10, + GuildPublicThread = 11, + GuildPrivateThread = 12, + GuildStageVoice = 13, + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/Member.cs b/src/Web/Controllers/Interactions/Model/Resolved/Member.cs new file mode 100644 index 0000000..e95a09a --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/Member.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public record Member + { + // public User User { get; set; } + public string Nick { get; set; } + public List Roles { get; set; } + public DateTime JoinedAt { get; set; } + public DateTime PremiumSince { get; set; } + public bool Pending { get; set; } + public string Permissions { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/RoleTag.cs b/src/Web/Controllers/Interactions/Model/Resolved/RoleTag.cs new file mode 100644 index 0000000..4f35ae1 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/RoleTag.cs @@ -0,0 +1,9 @@ +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public record RoleTag + { + public string BotId { get; set; } + public string IntegrationId { get; set; } + public bool PremiumSubscriber { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/Roles.cs b/src/Web/Controllers/Interactions/Model/Resolved/Roles.cs new file mode 100644 index 0000000..aab5d7c --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/Roles.cs @@ -0,0 +1,15 @@ +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public record Roles + { + public string Id { get; set; } + public string Name { get; set; } + public int Color { get; set; } + public bool Hoist { get; set; } + public int Position { get; set; } + public string Permissions { get; set; } + public bool Managed { get; set; } + public bool Mentionable { get; set; } + public RoleTag Tags { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/ThreadMetadata.cs b/src/Web/Controllers/Interactions/Model/Resolved/ThreadMetadata.cs new file mode 100644 index 0000000..e43ad89 --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/ThreadMetadata.cs @@ -0,0 +1,13 @@ +using System; + +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public record ThreadMetadata + { + public bool Archived { get; set; } + public int AutoArchiveDuration { get; set; } + public DateTime ArchiveTimestamp { get; set; } + public bool Locked { get; set; } + public bool Invitable { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Controllers/Interactions/Model/Resolved/User.cs b/src/Web/Controllers/Interactions/Model/Resolved/User.cs new file mode 100644 index 0000000..4ef1f8d --- /dev/null +++ b/src/Web/Controllers/Interactions/Model/Resolved/User.cs @@ -0,0 +1,21 @@ +namespace Geekbot.Web.Controllers.Interactions.Model.Resolved +{ + public record User + { + public string Id { get; set; } + public string Username { get; set; } + public string Discriminator { get; set; } + public string Avatar { get; set; } + public bool Bot { get; set; } + public bool System { get; set; } + public bool MfaEnabled { get; set; } + public string Banner { get; set; } + public int AccentColor { get; set; } + public string Locale { get; set; } + public bool Verified { get; set; } + public string Email { get; set; } + public int Flags { get; set; } + public int PremiumType { get; set; } + public int PublicFlags { get; set; } + } +} \ No newline at end of file diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index a9ffcc4..dc6b09a 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -16,4 +16,8 @@ + + + + diff --git a/src/Web/WebApiStartup.cs b/src/Web/WebApiStartup.cs index 9c8a805..34090d3 100644 --- a/src/Web/WebApiStartup.cs +++ b/src/Web/WebApiStartup.cs @@ -31,7 +31,10 @@ namespace Geekbot.Web }) .ConfigureServices(services => { - services.AddControllers(); + services.AddControllers().AddJsonOptions(options => + { + options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; + }); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", From 209887e237847fa9d49c1fd60d59e4e65a16adb7 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Sun, 19 Sep 2021 16:19:40 +0200 Subject: [PATCH 175/264] Add sentry support to the webapi --- src/Web/Web.csproj | 1 + src/Web/WebApiStartup.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index dc6b09a..48fcf86 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -17,6 +17,7 @@ + diff --git a/src/Web/WebApiStartup.cs b/src/Web/WebApiStartup.cs index 34090d3..f62dd58 100644 --- a/src/Web/WebApiStartup.cs +++ b/src/Web/WebApiStartup.cs @@ -40,6 +40,7 @@ namespace Geekbot.Web options.AddPolicy("AllowSpecificOrigin", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); }); + services.AddSentry(); services.AddSingleton(databaseContext); services.AddSingleton(globalSettings); From 60547140ea5838106c58bd61952ae5bc11be671c Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 20 Sep 2021 01:28:26 +0200 Subject: [PATCH 176/264] Create all interaction models --- .../ApplicationCommand/Command.cs | 73 ++++++++++++ .../ApplicationCommand/CommandType.cs | 21 ++++ .../Interactions/ApplicationCommand/Option.cs | 51 ++++++++ .../ApplicationCommand/OptionChoice.cs | 17 +++ .../ApplicationCommand/OptionChoiceDouble.cs | 14 +++ .../ApplicationCommand/OptionChoiceInteger.cs | 14 +++ .../ApplicationCommand/OptionChoiceString.cs | 14 +++ .../ApplicationCommand/OptionType.cs | 38 ++++++ src/Core/Interactions/Embed/Embed.cs | 88 ++++++++++++++ src/Core/Interactions/Embed/EmbedAuthor.cs | 32 +++++ src/Core/Interactions/Embed/EmbedField.cs | 26 ++++ src/Core/Interactions/Embed/EmbedFooter.cs | 27 +++++ src/Core/Interactions/Embed/EmbedImage.cs | 32 +++++ src/Core/Interactions/Embed/EmbedProvider.cs | 20 ++++ src/Core/Interactions/Embed/EmbedThumbnail.cs | 33 ++++++ src/Core/Interactions/Embed/EmbedTypes.cs | 49 ++++++++ src/Core/Interactions/Embed/EmbedVideo.cs | 32 +++++ .../MessageComponents/ButtonStyle.cs | 31 +++++ .../MessageComponents/Component.cs | 111 ++++++++++++++++++ .../MessageComponents/ComponentEmoji.cs | 33 ++++++ .../MessageComponents/ComponentType.cs | 21 ++++ .../MessageComponents/SelectOption.cs | 38 ++++++ src/Core/Interactions/Request/Interaction.cs | 77 ++++++++++++ .../Interactions/Request/InteractionData.cs | 109 +++++++++++++++++ .../Interactions/Request/InteractionOption.cs | 34 ++++++ .../Request/InteractionResolvedData.cs | 24 ++++ .../Interactions/Request/InteractionType.cs | 10 ++ src/Core/Interactions/Resolved/Attachment.cs | 34 ++++++ src/Core/Interactions/Resolved/Channel.cs | 25 ++++ .../Interactions}/Resolved/ChannelType.cs | 2 +- src/Core/Interactions/Resolved/Emoji.cs | 32 +++++ src/Core/Interactions/Resolved/Member.cs | 27 +++++ src/Core/Interactions/Resolved/Message.cs | 103 ++++++++++++++++ .../Resolved/MessageInteraction.cs | 20 ++++ src/Core/Interactions/Resolved/MessageType.cs | 29 +++++ src/Core/Interactions/Resolved/Reaction.cs | 16 +++ src/Core/Interactions/Resolved/Role.cs | 34 ++++++ src/Core/Interactions/Resolved/RoleTag.cs | 16 +++ .../Interactions/Resolved/ThreadMetadata.cs | 23 ++++ src/Core/Interactions/Resolved/User.cs | 52 ++++++++ .../Response/InteractionResponse.cs | 23 ++++ .../Response/InteractionResponseData.cs | 51 ++++++++ .../Response/InteractionResponseType.cs | 34 ++++++ .../Model/ApplicationCommandOption.cs | 16 --- .../Interactions/Model/Interaction.cs | 22 ---- .../Interactions/Model/InteractionData.cs | 14 --- .../Interactions/Model/InteractionOption.cs | 12 -- .../Model/InteractionResolvedData.cs | 15 --- .../Interactions/Model/InteractionResponse.cs | 13 -- .../Model/InteractionResponseData.cs | 16 --- .../Model/InteractionResponseType.cs | 11 -- .../Interactions/Model/InteractionType.cs | 9 -- .../Model/MessageComponents/Component.cs | 7 -- .../Interactions/Model/Resolved/Channel.cs | 12 -- .../Interactions/Model/Resolved/Member.cs | 16 --- .../Interactions/Model/Resolved/RoleTag.cs | 9 -- .../Interactions/Model/Resolved/Roles.cs | 15 --- .../Model/Resolved/ThreadMetadata.cs | 13 -- .../Interactions/Model/Resolved/User.cs | 21 ---- 59 files changed, 1589 insertions(+), 222 deletions(-) create mode 100644 src/Core/Interactions/ApplicationCommand/Command.cs create mode 100644 src/Core/Interactions/ApplicationCommand/CommandType.cs create mode 100644 src/Core/Interactions/ApplicationCommand/Option.cs create mode 100644 src/Core/Interactions/ApplicationCommand/OptionChoice.cs create mode 100644 src/Core/Interactions/ApplicationCommand/OptionChoiceDouble.cs create mode 100644 src/Core/Interactions/ApplicationCommand/OptionChoiceInteger.cs create mode 100644 src/Core/Interactions/ApplicationCommand/OptionChoiceString.cs create mode 100644 src/Core/Interactions/ApplicationCommand/OptionType.cs create mode 100644 src/Core/Interactions/Embed/Embed.cs create mode 100644 src/Core/Interactions/Embed/EmbedAuthor.cs create mode 100644 src/Core/Interactions/Embed/EmbedField.cs create mode 100644 src/Core/Interactions/Embed/EmbedFooter.cs create mode 100644 src/Core/Interactions/Embed/EmbedImage.cs create mode 100644 src/Core/Interactions/Embed/EmbedProvider.cs create mode 100644 src/Core/Interactions/Embed/EmbedThumbnail.cs create mode 100644 src/Core/Interactions/Embed/EmbedTypes.cs create mode 100644 src/Core/Interactions/Embed/EmbedVideo.cs create mode 100644 src/Core/Interactions/MessageComponents/ButtonStyle.cs create mode 100644 src/Core/Interactions/MessageComponents/Component.cs create mode 100644 src/Core/Interactions/MessageComponents/ComponentEmoji.cs create mode 100644 src/Core/Interactions/MessageComponents/ComponentType.cs create mode 100644 src/Core/Interactions/MessageComponents/SelectOption.cs create mode 100644 src/Core/Interactions/Request/Interaction.cs create mode 100644 src/Core/Interactions/Request/InteractionData.cs create mode 100644 src/Core/Interactions/Request/InteractionOption.cs create mode 100644 src/Core/Interactions/Request/InteractionResolvedData.cs create mode 100644 src/Core/Interactions/Request/InteractionType.cs create mode 100644 src/Core/Interactions/Resolved/Attachment.cs create mode 100644 src/Core/Interactions/Resolved/Channel.cs rename src/{Web/Controllers/Interactions/Model => Core/Interactions}/Resolved/ChannelType.cs (80%) create mode 100644 src/Core/Interactions/Resolved/Emoji.cs create mode 100644 src/Core/Interactions/Resolved/Member.cs create mode 100644 src/Core/Interactions/Resolved/Message.cs create mode 100644 src/Core/Interactions/Resolved/MessageInteraction.cs create mode 100644 src/Core/Interactions/Resolved/MessageType.cs create mode 100644 src/Core/Interactions/Resolved/Reaction.cs create mode 100644 src/Core/Interactions/Resolved/Role.cs create mode 100644 src/Core/Interactions/Resolved/RoleTag.cs create mode 100644 src/Core/Interactions/Resolved/ThreadMetadata.cs create mode 100644 src/Core/Interactions/Resolved/User.cs create mode 100644 src/Core/Interactions/Response/InteractionResponse.cs create mode 100644 src/Core/Interactions/Response/InteractionResponseData.cs create mode 100644 src/Core/Interactions/Response/InteractionResponseType.cs delete mode 100644 src/Web/Controllers/Interactions/Model/ApplicationCommandOption.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Interaction.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionData.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionOption.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionResolvedData.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionResponse.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionResponseData.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionResponseType.cs delete mode 100644 src/Web/Controllers/Interactions/Model/InteractionType.cs delete mode 100644 src/Web/Controllers/Interactions/Model/MessageComponents/Component.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Resolved/Channel.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Resolved/Member.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Resolved/RoleTag.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Resolved/Roles.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Resolved/ThreadMetadata.cs delete mode 100644 src/Web/Controllers/Interactions/Model/Resolved/User.cs diff --git a/src/Core/Interactions/ApplicationCommand/Command.cs b/src/Core/Interactions/ApplicationCommand/Command.cs new file mode 100644 index 0000000..aaf1e74 --- /dev/null +++ b/src/Core/Interactions/ApplicationCommand/Command.cs @@ -0,0 +1,73 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Geekbot.Core.Interactions.ApplicationCommand +{ + /// + public record Command + { + /// + /// unique id of the command + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// the type of command, defaults 1 if not set + /// + [JsonPropertyName("type")] + public CommandType Type { get; set; } + + /// + /// unique id of the parent application + /// + [JsonPropertyName("application_id")] + public string ApplicationId { get; set; } + + /// + /// guild id of the command, if not global + /// + [JsonPropertyName("guild_id")] + public string GuildId { get; set; } + + /// + /// 1-32 character name + /// + /// + /// CHAT_INPUT command names and command option names must match the following regex ^[\w-]{1,32}$ with the unicode flag set. If there is a lowercase variant of any letters used, you must use those. + /// Characters with no lowercase variants and/or uncased letters are still allowed. USER and MESSAGE commands may be mixed case and can include spaces. + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// 1-100 character description for CHAT_INPUT commands, empty string for USER and MESSAGE commands + /// + /// + /// Exclusive: CHAT_INPUT + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// the parameters for the command, max 25 + /// + /// + /// Exclusive: CHAT_INPUT + /// + [JsonPropertyName("options")] + public List