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.

This commit is contained in:
runebaas 2020-08-14 03:30:54 +02:00
parent 12388fd7d0
commit 90af781c7b
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
40 changed files with 1935 additions and 327 deletions

View file

@ -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<string>();
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<CultureInfo> GetAvailableCultures()
{
var result = new List<CultureInfo>();
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;
}
}
}

View file

@ -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);
}
}

View file

@ -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"
};
}

View file

@ -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<CookiesModel> GetUser(ulong userId)
{
var user = _database.Cookies.FirstOrDefault(u =>u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId);

View file

@ -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);
}
}

View file

@ -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);
}
}
}

View file

@ -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);
}
}
}

View file

@ -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)