Make errorhandler and languagehandler async, await all database actions

This commit is contained in:
runebaas 2018-06-13 22:18:57 +02:00
parent 926a632641
commit 95618b1f8b
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
46 changed files with 181 additions and 137 deletions

View file

@ -35,7 +35,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage) public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage)
{ {
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
guild.WelcomeMessage = welcomeMessage; guild.WelcomeMessage = welcomeMessage;
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
@ -52,7 +52,7 @@ namespace Geekbot.net.Commands.Admin
{ {
var m = await channel.SendMessageAsync("verifying..."); var m = await channel.SendMessageAsync("verifying...");
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
guild.ModChannel = channel.Id.AsLong(); guild.ModChannel = channel.Id.AsLong();
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
@ -65,7 +65,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, "That channel doesn't seem to be valid"); await _errorHandler.HandleCommandException(e, Context, "That channel doesn't seem to be valid");
} }
} }
@ -75,7 +75,7 @@ namespace Geekbot.net.Commands.Admin
{ {
try try
{ {
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
var modChannel = await GetModChannel(guild.ModChannel.AsUlong()); var modChannel = await GetModChannel(guild.ModChannel.AsUlong());
if (modChannel == null) return; if (modChannel == null) return;
@ -89,7 +89,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -99,7 +99,7 @@ namespace Geekbot.net.Commands.Admin
{ {
try try
{ {
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
var modChannel = await GetModChannel(guild.ModChannel.AsUlong()); var modChannel = await GetModChannel(guild.ModChannel.AsUlong());
if (modChannel == null) return; if (modChannel == null) return;
@ -113,7 +113,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -124,15 +124,15 @@ namespace Geekbot.net.Commands.Admin
try try
{ {
var language = languageRaw.ToUpper(); var language = languageRaw.ToUpper();
var success = _translation.SetLanguage(Context.Guild.Id, language); var success = await _translation.SetLanguage(Context.Guild.Id, language);
if (success) if (success)
{ {
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
guild.Language = language; guild.Language = language;
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
var trans = _translation.GetDict(Context); var trans = await _translation.GetDict(Context);
await ReplyAsync(trans["NewLanguageSet"]); await ReplyAsync(trans["NewLanguageSet"]);
return; return;
} }
@ -142,7 +142,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -153,7 +153,7 @@ namespace Geekbot.net.Commands.Admin
try try
{ {
var language = languageRaw.ToLower(); var language = languageRaw.ToLower();
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
guild.WikiLang = language; guild.WikiLang = language;
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
@ -162,7 +162,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -172,7 +172,7 @@ namespace Geekbot.net.Commands.Admin
{ {
try try
{ {
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
guild.Ping = !guild.Ping; guild.Ping = !guild.Ping;
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
@ -180,7 +180,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -190,7 +190,7 @@ namespace Geekbot.net.Commands.Admin
{ {
try try
{ {
var guild = GetGuildSettings(Context.Guild.Id); var guild = await GetGuildSettings(Context.Guild.Id);
guild.Hui = !guild.Hui; guild.Hui = !guild.Hui;
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
@ -198,11 +198,11 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
private GuildSettingsModel GetGuildSettings(ulong guildId) private async Task<GuildSettingsModel> GetGuildSettings(ulong guildId)
{ {
var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong()));
if (guild != null) return guild; if (guild != null) return guild;
@ -212,12 +212,12 @@ namespace Geekbot.net.Commands.Admin
GuildId = guildId.AsLong(), GuildId = guildId.AsLong(),
Hui = false, Hui = false,
Ping = false, Ping = false,
Language = "en", Language = "EN",
ShowDelete = false, ShowDelete = false,
ShowLeave = false, ShowLeave = false,
WikiLang = "en" WikiLang = "en"
}); });
_database.SaveChanges(); await _database.SaveChangesAsync();
return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong()));
} }

View file

@ -40,7 +40,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, await _errorHandler.HandleCommandException(e, Context,
$"I don't have enough permissions do that"); $"I don't have enough permissions do that");
} }
} }

View file

@ -52,14 +52,14 @@ namespace Geekbot.net.Commands.Admin
} }
await ReplyAsync("starting migration"); await ReplyAsync("starting migration");
_globalSettings.SetKey("MigrationStatus", "Running"); await _globalSettings.SetKey("MigrationStatus", "Running");
var redisMigration = new RedisMigration(_database, _redis, _logger, _client); var redisMigration = new RedisMigration(_database, _redis, _logger, _client);
await redisMigration.Migrate(); await redisMigration.Migrate();
_globalSettings.SetKey("MigrationStatus", "Done"); await _globalSettings.SetKey("MigrationStatus", "Done");
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
await ReplyAsync("done"); await ReplyAsync("done");
@ -69,7 +69,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set the youtube api key")] [Summary("Set the youtube api key")]
public async Task SetYoutubeKey([Summary("API Key")] string key) public async Task SetYoutubeKey([Summary("API Key")] string key)
{ {
_globalSettings.SetKey("YoutubeKey", key); await _globalSettings.SetKey("YoutubeKey", key);
await ReplyAsync("Apikey has been set"); await ReplyAsync("Apikey has been set");
} }
@ -77,7 +77,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set the game that the bot is playing")] [Summary("Set the game that the bot is playing")]
public async Task SetGame([Remainder] [Summary("Game")] string key) public async Task SetGame([Remainder] [Summary("Game")] string key)
{ {
_globalSettings.SetKey("Game", key); await _globalSettings.SetKey("Game", key);
await _client.SetGameAsync(key); await _client.SetGameAsync(key);
_logger.Information(LogSource.Geekbot, $"Changed game to {key}"); _logger.Information(LogSource.Geekbot, $"Changed game to {key}");
await ReplyAsync($"Now Playing {key}"); await ReplyAsync($"Now Playing {key}");
@ -109,14 +109,14 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, await _errorHandler.HandleCommandException(e, Context,
"Couldn't complete User Repository, see console for more info"); "Couldn't complete User Repository, see console for more info");
} }
} }
[Command("error", RunMode = RunMode.Async)] [Command("error", RunMode = RunMode.Async)]
[Summary("Throw an error un purpose")] [Summary("Throw an error un purpose")]
public void PurposefulError() public async Task PurposefulError()
{ {
try try
{ {
@ -124,7 +124,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -48,7 +48,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -87,11 +87,11 @@ namespace Geekbot.net.Commands.Admin
} }
catch (HttpException e) catch (HttpException e)
{ {
_errorHandler.HandleHttpException(e, Context); await _errorHandler.HandleHttpException(e, Context);
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -130,7 +130,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -155,7 +155,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -27,7 +27,7 @@ namespace Geekbot.net.Commands.Admin
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -59,7 +59,7 @@ namespace Geekbot.net.Commands.Audio
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
_audioUtils.Cleanup(Context.Guild.Id); _audioUtils.Cleanup(Context.Guild.Id);
} }
} }
@ -92,7 +92,7 @@ namespace Geekbot.net.Commands.Audio
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
_audioUtils.Cleanup(Context.Guild.Id); _audioUtils.Cleanup(Context.Guild.Id);
} }
} }

View file

@ -41,7 +41,7 @@ namespace Geekbot.net.Commands.Games
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -30,7 +30,7 @@ namespace Geekbot.net.Commands.Games
var number = new Random().Next(1, 100); var number = new Random().Next(1, 100);
var guess = 1000; var guess = 1000;
int.TryParse(stuff, out guess); int.TryParse(stuff, out guess);
var transDict = _translation.GetDict(Context); var transDict = await _translation.GetDict(Context);
if (guess <= 100 && guess > 0) if (guess <= 100 && guess > 0)
{ {
var prevRoll = _redis.Db.HashGet($"{Context.Guild.Id}:RollsPrevious", Context.Message.Author.Id); var prevRoll = _redis.Db.HashGet($"{Context.Guild.Id}:RollsPrevious", Context.Message.Author.Id);

View file

@ -61,7 +61,7 @@ namespace Geekbot.net.Commands.Integrations.Google
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -64,7 +64,7 @@ namespace Geekbot.net.Commands.Integrations
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -64,7 +64,7 @@ namespace Geekbot.net.Commands.Integrations
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -59,7 +59,7 @@ namespace Geekbot.net.Commands.Integrations.UbranDictionary
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -87,7 +87,7 @@ namespace Geekbot.net.Commands.Integrations
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -51,7 +51,7 @@ namespace Geekbot.net.Commands.Integrations
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -45,7 +45,7 @@ namespace Geekbot.net.Commands.Randomness.Cat
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -51,7 +51,7 @@ namespace Geekbot.net.Commands.Randomness
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -44,7 +44,7 @@ namespace Geekbot.net.Commands.Randomness.Chuck
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -44,7 +44,7 @@ namespace Geekbot.net.Commands.Randomness.Dad
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -45,7 +45,7 @@ namespace Geekbot.net.Commands.Randomness.Dog
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -50,7 +50,7 @@ namespace Geekbot.net.Commands.Randomness
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -31,7 +31,7 @@ namespace Geekbot.net.Commands.Randomness
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -59,7 +59,7 @@ namespace Geekbot.net.Commands.Randomness
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -81,8 +81,8 @@ namespace Geekbot.net.Commands.Randomness
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(things.Count - 1)]}");
UpdateRecieved(user.Id); await UpdateRecieved(user.Id);
UpdateGiven(Context.User.Id); await UpdateGiven(Context.User.Id);
await _database.SaveChangesAsync(); await _database.SaveChangesAsync();
} }
catch (Exception e) catch (Exception e)
@ -91,21 +91,21 @@ namespace Geekbot.net.Commands.Randomness
} }
} }
private void UpdateGiven(ulong userId) private async Task UpdateGiven(ulong userId)
{ {
var user = GetUser(userId); var user = await GetUser(userId);
user.Given++; user.Given++;
_database.Slaps.Update(user); _database.Slaps.Update(user);
} }
private void UpdateRecieved(ulong userId) private async Task UpdateRecieved(ulong userId)
{ {
var user = GetUser(userId); var user = await GetUser(userId);
user.Recieved++; user.Recieved++;
_database.Slaps.Update(user); _database.Slaps.Update(user);
} }
private SlapsModel GetUser(ulong userId) private async Task<SlapsModel> GetUser(ulong userId)
{ {
var user = _database.Slaps.FirstOrDefault(e => var user = _database.Slaps.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
@ -121,7 +121,7 @@ namespace Geekbot.net.Commands.Randomness
Recieved = 0, Recieved = 0,
Given = 0 Given = 0
}); });
_database.SaveChanges(); await _database.SaveChangesAsync();
return _database.Slaps.FirstOrDefault(e => return _database.Slaps.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
e.UserId.Equals(userId.AsLong())); e.UserId.Equals(userId.AsLong()));

View file

@ -51,7 +51,7 @@ namespace Geekbot.net.Commands.User
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -30,8 +30,8 @@ namespace Geekbot.net.Commands.User
{ {
try try
{ {
var transDict = _translation.GetDict(Context); var transDict = await _translation.GetDict(Context);
var actor = GetUser(Context.User.Id); var actor = await GetUser(Context.User.Id);
if (user.Id == Context.User.Id) if (user.Id == Context.User.Id)
{ {
await ReplyAsync(string.Format(transDict["CannotChangeOwn"], Context.User.Username)); await ReplyAsync(string.Format(transDict["CannotChangeOwn"], Context.User.Username));
@ -43,7 +43,7 @@ namespace Geekbot.net.Commands.User
} }
else else
{ {
var target = GetUser(user.Id); var target = await GetUser(user.Id);
target.Karma = target.Karma + 1; target.Karma = target.Karma + 1;
SetUser(target); SetUser(target);
@ -77,8 +77,8 @@ namespace Geekbot.net.Commands.User
{ {
try try
{ {
var transDict = _translation.GetDict(Context); var transDict = await _translation.GetDict(Context);
var actor = GetUser(Context.User.Id); var actor = await GetUser(Context.User.Id);
if (user.Id == Context.User.Id) if (user.Id == Context.User.Id)
{ {
await ReplyAsync(string.Format(transDict["CannotChangeOwn"], Context.User.Username)); await ReplyAsync(string.Format(transDict["CannotChangeOwn"], Context.User.Username));
@ -90,7 +90,7 @@ namespace Geekbot.net.Commands.User
} }
else else
{ {
var target = GetUser(user.Id); var target = await GetUser(user.Id);
target.Karma = target.Karma - 1; target.Karma = target.Karma - 1;
SetUser(target); SetUser(target);
@ -129,19 +129,18 @@ namespace Geekbot.net.Commands.User
return $"{dt.Minutes} Minutes and {dt.Seconds} Seconds"; return $"{dt.Minutes} Minutes and {dt.Seconds} Seconds";
} }
private KarmaModel GetUser(ulong userId) private async Task<KarmaModel> GetUser(ulong userId)
{ {
var user = _database.Karma.FirstOrDefault(u =>u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? CreateNewRow(userId); var user = _database.Karma.FirstOrDefault(u =>u.GuildId.Equals(Context.Guild.Id.AsLong()) && u.UserId.Equals(userId.AsLong())) ?? await CreateNewRow(userId);
return user; return user;
} }
private bool SetUser(KarmaModel user) private void SetUser(KarmaModel user)
{ {
_database.Karma.Update(user); _database.Karma.Update(user);
return true;
} }
private KarmaModel CreateNewRow(ulong userId) private async Task<KarmaModel> CreateNewRow(ulong userId)
{ {
var user = new KarmaModel() var user = new KarmaModel()
{ {
@ -151,7 +150,7 @@ namespace Geekbot.net.Commands.User
TimeOut = DateTimeOffset.MinValue TimeOut = DateTimeOffset.MinValue
}; };
var newUser = _database.Karma.Add(user).Entity; var newUser = _database.Karma.Add(user).Entity;
_database.SaveChanges(); await _database.SaveChangesAsync();
return newUser; return newUser;
} }
} }

View file

@ -81,6 +81,15 @@ namespace Geekbot.net.Commands.User.Ranking
return; return;
} }
int guildMessages = 0;
if (type == RankType.messages)
{
guildMessages = _database.Messages
.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong()))
.Select(e => e.MessageCount)
.Sum();
}
var highscoreUsers = new Dictionary<RankUserDto, int>(); var highscoreUsers = new Dictionary<RankUserDto, int>();
var failedToRetrieveUser = false; var failedToRetrieveUser = false;
foreach (var user in list) foreach (var user in list)
@ -112,7 +121,7 @@ namespace Geekbot.net.Commands.User.Ranking
} }
if (failedToRetrieveUser) replyBuilder.AppendLine(":warning: Couldn't get all userdata\n"); if (failedToRetrieveUser) replyBuilder.AppendLine(":warning: Couldn't get all userdata\n");
replyBuilder.AppendLine($":bar_chart: **{type} Highscore for {Context.Guild.Name}**"); replyBuilder.AppendLine($":bar_chart: **{type.ToString().CapitalizeFirst()} Highscore for {Context.Guild.Name}**");
var highscorePlace = 1; var highscorePlace = 1;
foreach (var user in highscoreUsers) foreach (var user in highscoreUsers)
{ {
@ -123,8 +132,10 @@ namespace Geekbot.net.Commands.User.Ranking
replyBuilder.Append(user.Key.Username != null replyBuilder.Append(user.Key.Username != null
? $"**{user.Key.Username}#{user.Key.Discriminator}**" ? $"**{user.Key.Username}#{user.Key.Discriminator}**"
: $"**{user.Key.Id}**"); : $"**{user.Key.Id}**");
replyBuilder.Append($" - {user.Value} {type}\n"); replyBuilder.Append(type == RankType.messages
? $" - {user.Value} {type} - {Math.Round((double) (100 * user.Value) / guildMessages, digits: 2)}%\n"
: $" - {user.Value} {type}\n");
highscorePlace++; highscorePlace++;
} }
@ -133,12 +144,17 @@ namespace Geekbot.net.Commands.User.Ranking
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
private Dictionary<ulong, int> GetMessageList(int amount) private Dictionary<ulong, int> GetMessageList(int amount)
{ {
// return _database.Messages
// .Where(k => k.GuildId.Equals(Context.Guild.Id.AsLong()))
// .OrderByDescending(o => o.MessageCount)
// .Take(amount)
// .ToDictionary(key => key.UserId.AsUlong(), key => key.MessageCount);
return _redis.Db return _redis.Db
.HashGetAll($"{Context.Guild.Id}:Messages").ToDictionary().Take(amount + 1) .HashGetAll($"{Context.Guild.Id}:Messages").ToDictionary().Take(amount + 1)
.Where(user => !user.Key.Equals(0)) .Where(user => !user.Key.Equals(0))

View file

@ -39,11 +39,18 @@ namespace Geekbot.net.Commands.User
var age = Math.Floor((DateTime.Now - createdAt).TotalDays); var age = Math.Floor((DateTime.Now - createdAt).TotalDays);
var joinedDayAgo = Math.Floor((DateTime.Now - joinedAt).TotalDays); var joinedDayAgo = Math.Floor((DateTime.Now - joinedAt).TotalDays);
var messages = (int) _redis.Db.HashGet($"{Context.Guild.Id}:Messages", userInfo.Id.ToString()); var messages = _database.Messages.FirstOrDefault(e =>
var guildMessages = (int) _redis.Db.HashGet($"{Context.Guild.Id}:Messages", 0.ToString()); e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
e.UserId.Equals(userInfo.Id.AsLong()))?.MessageCount;
var guildMessages = _database.Messages
.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong()))
.Select(e => e.MessageCount)
.Sum();
var level = _levelCalc.GetLevel(messages); var level = _levelCalc.GetLevel(messages);
var percent = Math.Round((double) (100 * messages) / guildMessages, 2); var percent = Math.Round((double) (100 * messages) / guildMessages, digits: 2);
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()

View file

@ -27,7 +27,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -60,7 +60,7 @@ namespace Geekbot.net.Commands.Utils.Changelog
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -24,14 +24,14 @@ namespace Geekbot.net.Commands.Utils
{ {
try try
{ {
var transDict = _translation.GetDict(Context); var transDict = await _translation.GetDict(Context);
var choicesArray = choices.Split(';'); var choicesArray = choices.Split(';');
var choice = new Random().Next(choicesArray.Length); var choice = new Random().Next(choicesArray.Length);
await ReplyAsync(string.Format(transDict["Choice"], choicesArray[choice])); await ReplyAsync(string.Format(transDict["Choice"], choicesArray[choice]));
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -35,7 +35,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -32,7 +32,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -51,7 +51,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -66,7 +66,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -48,7 +48,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -120,7 +120,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }
@ -148,7 +148,7 @@ namespace Geekbot.net.Commands.Utils
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); await _errorHandler.HandleCommandException(e, Context);
} }
} }

View file

@ -45,7 +45,7 @@ namespace Geekbot.net.Commands.Utils.Quote
} }
catch (Exception e) catch (Exception e)
{ {
_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");
} }
} }
@ -79,7 +79,7 @@ namespace Geekbot.net.Commands.Utils.Quote
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, await _errorHandler.HandleCommandException(e, Context,
"I counldn't find a quote from that user :disappointed:"); "I counldn't find a quote from that user :disappointed:");
} }
} }
@ -112,7 +112,7 @@ namespace Geekbot.net.Commands.Utils.Quote
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, await _errorHandler.HandleCommandException(e, Context,
"I couldn't find a message with that id :disappointed:"); "I couldn't find a message with that id :disappointed:");
} }
} }
@ -131,7 +131,7 @@ namespace Geekbot.net.Commands.Utils.Quote
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, await _errorHandler.HandleCommandException(e, Context,
"I counldn't find a quote from that user :disappointed:"); "I counldn't find a quote from that user :disappointed:");
} }
} }
@ -149,7 +149,7 @@ namespace Geekbot.net.Commands.Utils.Quote
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, await _errorHandler.HandleCommandException(e, Context,
"I couldn't find a message with that id :disappointed:"); "I couldn't find a message with that id :disappointed:");
} }
} }
@ -178,7 +178,7 @@ namespace Geekbot.net.Commands.Utils.Quote
} }
catch (Exception e) catch (Exception e)
{ {
_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:");
} }
} }

View file

@ -44,7 +44,7 @@
<PackageReference Include="NLog" Version="4.5.6" /> <PackageReference Include="NLog" Version="4.5.6" />
<PackageReference Include="NLog.Config" Version="4.5.6" /> <PackageReference Include="NLog.Config" Version="4.5.6" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.0" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.1" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="2.0.0-preview1" />
<PackageReference Include="PokeApi.NET" Version="1.1.0" /> <PackageReference Include="PokeApi.NET" Version="1.1.0" />
<PackageReference Include="SharpRaven" Version="2.4.0" /> <PackageReference Include="SharpRaven" Version="2.4.0" />
<PackageReference Include="SumoLogic.Logging.NLog" Version="1.0.0.7" /> <PackageReference Include="SumoLogic.Logging.NLog" Version="1.0.0.7" />

View file

@ -11,6 +11,7 @@ using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository; using Geekbot.net.Lib.UserRepository;
using Microsoft.EntityFrameworkCore;
namespace Geekbot.net namespace Geekbot.net
{ {
@ -93,29 +94,33 @@ namespace Geekbot.net
} }
} }
public Task UpdateStats(SocketMessage message) public async Task UpdateStats(SocketMessage message)
{ {
try try
{ {
if (message == null) return Task.CompletedTask; if (message == null) return;
if (message.Channel.Name.StartsWith('@')) if (message.Channel.Name.StartsWith('@'))
{ {
_logger.Information(LogSource.Message, $"[DM-Channel] {message.Content}", SimpleConextConverter.ConvertSocketMessage(message)); _logger.Information(LogSource.Message, $"[DM-Channel] {message.Content}", SimpleConextConverter.ConvertSocketMessage(message));
return Task.CompletedTask; return;
} }
var channel = (SocketGuildChannel) message.Channel; var channel = (SocketGuildChannel) message.Channel;
// await _database.Database.ExecuteSqlCommandAsync("UPDATE \"Messages\" " +
// $"SET \"MessageCount\" = \"MessageCount\" + {1} " +
// $"WHERE \"GuildId\" = '{channel.Guild.Id.AsLong()}' " +
// $"AND \"UserId\" = '{message.Author.Id.AsLong()}'");
//
await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", message.Author.Id.ToString());
await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString());
_redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", message.Author.Id.ToString()); if (message.Author.IsBot) return;
_redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString());
if (message.Author.IsBot) return Task.CompletedTask;
_logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message)); _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message));
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(LogSource.Message, "Could not process message stats", e); _logger.Error(LogSource.Message, "Could not process message stats", e);
} }
return Task.CompletedTask;
} }
// //

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Net; using System.Net;
using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.Net; using Discord.Net;
using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Localization;
@ -34,11 +35,11 @@ namespace Geekbot.net.Lib.ErrorHandling
} }
} }
public void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def") public async Task HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def")
{ {
try try
{ {
var errorString = errorMessage == "def" ? _translation.GetString(context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage; var errorString = errorMessage == "def" ? await _translation.GetString(context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage;
var errorObj = SimpleConextConverter.ConvertContext(context); var errorObj = SimpleConextConverter.ConvertContext(context);
if (e.Message.Contains("50007")) return; if (e.Message.Contains("50007")) return;
if (e.Message.Contains("50013")) return; if (e.Message.Contains("50013")) return;
@ -86,9 +87,9 @@ namespace Geekbot.net.Lib.ErrorHandling
} }
} }
public async void HandleHttpException(HttpException e, ICommandContext context) public async Task HandleHttpException(HttpException e, ICommandContext context)
{ {
var errorStrings = _translation.GetDict(context, "httpErrors"); var errorStrings = await _translation.GetDict(context, "httpErrors");
switch(e.HttpCode) switch(e.HttpCode)
{ {
case HttpStatusCode.Forbidden: case HttpStatusCode.Forbidden:

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.Net; using Discord.Net;
@ -6,7 +7,7 @@ namespace Geekbot.net.Lib.ErrorHandling
{ {
public interface IErrorHandler public interface IErrorHandler
{ {
void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def"); Task HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def");
void HandleHttpException(HttpException e, ICommandContext context); Task HandleHttpException(HttpException e, ICommandContext context);
} }
} }

View file

@ -0,0 +1,12 @@
using System.Linq;
namespace Geekbot.net.Lib.Extensions
{
public static class StringExtensions
{
public static string CapitalizeFirst(this string source)
{
return source.First().ToString().ToUpper() + source.Substring(1);
}
}
}

View file

@ -1,4 +1,5 @@
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.Models; using Geekbot.net.Database.Models;
@ -13,7 +14,7 @@ namespace Geekbot.net.Lib.GlobalSettings
_database = database; _database = database;
} }
public bool SetKey(string keyName, string value) public async Task<bool> SetKey(string keyName, string value)
{ {
try try
{ {
@ -25,13 +26,13 @@ namespace Geekbot.net.Lib.GlobalSettings
Name = keyName, Name = keyName,
Value = value Value = value
}); });
_database.SaveChanges(); await _database.SaveChangesAsync();
return true; return true;
} }
key.Value = value; key.Value = value;
_database.Globals.Update(key); _database.Globals.Update(key);
_database.SaveChanges(); await _database.SaveChangesAsync();
return true; return true;
} }
catch catch

View file

@ -1,10 +1,11 @@
using Geekbot.net.Database.Models; using System.Threading.Tasks;
using Geekbot.net.Database.Models;
namespace Geekbot.net.Lib.GlobalSettings namespace Geekbot.net.Lib.GlobalSettings
{ {
public interface IGlobalSettings public interface IGlobalSettings
{ {
bool SetKey(string keyName, string value); Task<bool> SetKey(string keyName, string value);
string GetKey(string keyName); string GetKey(string keyName);
GlobalsModel GetKeyFull(string keyName); GlobalsModel GetKeyFull(string keyName);
} }

View file

@ -2,6 +2,6 @@
{ {
public interface ILevelCalc public interface ILevelCalc
{ {
int GetLevel(int experience); int GetLevel(int? experience);
} }
} }

View file

@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Levels
_levels = levels.ToArray(); _levels = levels.ToArray();
} }
public int GetLevel(int messages) public int GetLevel(int? messages)
{ {
var returnVal = 1; var returnVal = 1;
foreach (var level in _levels) foreach (var level in _levels)

View file

@ -1,14 +1,15 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
namespace Geekbot.net.Lib.Localization namespace Geekbot.net.Lib.Localization
{ {
public interface ITranslationHandler public interface ITranslationHandler
{ {
string GetString(ulong guildId, string command, string stringName); Task<string> GetString(ulong guildId, string command, string stringName);
Dictionary<string, string> GetDict(ICommandContext context); Task<Dictionary<string, string>> GetDict(ICommandContext context);
Dictionary<string, string> GetDict(ICommandContext context, string command); Task<Dictionary<string, string>> GetDict(ICommandContext context, string command);
bool SetLanguage(ulong guildId, string language); Task<bool> SetLanguage(ulong guildId, string language);
List<string> SupportedLanguages { get; } List<string> SupportedLanguages { get; }
} }
} }

View file

@ -2,8 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.Models; using Geekbot.net.Database.Models;
using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Extensions;
@ -78,7 +78,7 @@ namespace Geekbot.net.Lib.Localization
} }
} }
private string GetServerLanguage(ulong guildId) private async Task<string> GetServerLanguage(ulong guildId)
{ {
try try
{ {
@ -94,7 +94,7 @@ namespace Geekbot.net.Lib.Localization
} }
catch catch
{ {
lang = GetGuild(guildId).Language ?? "EN"; lang = (await GetGuild(guildId)).Language ?? "EN";
_serverLanguages[guildId] = lang; _serverLanguages[guildId] = lang;
return lang; return lang;
} }
@ -106,9 +106,9 @@ namespace Geekbot.net.Lib.Localization
} }
} }
public string GetString(ulong guildId, string command, string stringName) public async Task<string> GetString(ulong guildId, string command, string stringName)
{ {
var translation = _translations[GetServerLanguage(guildId)][command][stringName]; var translation = _translations[await GetServerLanguage(guildId)][command][stringName];
if (!string.IsNullOrWhiteSpace(translation)) return translation; if (!string.IsNullOrWhiteSpace(translation)) return translation;
translation = _translations[command][stringName]["EN"]; translation = _translations[command][stringName]["EN"];
if (string.IsNullOrWhiteSpace(translation)) if (string.IsNullOrWhiteSpace(translation))
@ -118,12 +118,12 @@ namespace Geekbot.net.Lib.Localization
return translation; return translation;
} }
public Dictionary<string, string> GetDict(ICommandContext context) public async Task<Dictionary<string, string>> GetDict(ICommandContext context)
{ {
try try
{ {
var command = context.Message.Content.Split(' ').First().TrimStart('!').ToLower(); var command = context.Message.Content.Split(' ').First().TrimStart('!').ToLower();
return _translations[GetServerLanguage(context.Guild.Id)][command]; return _translations[await GetServerLanguage(context.Guild.Id)][command];
} }
catch (Exception e) catch (Exception e)
{ {
@ -132,11 +132,11 @@ namespace Geekbot.net.Lib.Localization
} }
} }
public Dictionary<string, string> GetDict(ICommandContext context, string command) public async Task<Dictionary<string, string>> GetDict(ICommandContext context, string command)
{ {
try try
{ {
return _translations[GetServerLanguage(context.Guild.Id)][command]; return _translations[await GetServerLanguage(context.Guild.Id)][command];
} }
catch (Exception e) catch (Exception e)
{ {
@ -145,12 +145,12 @@ namespace Geekbot.net.Lib.Localization
} }
} }
public bool SetLanguage(ulong guildId, string language) public async Task<bool> SetLanguage(ulong guildId, string language)
{ {
try try
{ {
if (!_supportedLanguages.Contains(language)) return false; if (!_supportedLanguages.Contains(language)) return false;
var guild = GetGuild(guildId); var guild = await GetGuild(guildId);
guild.Language = language; guild.Language = language;
_database.GuildSettings.Update(guild); _database.GuildSettings.Update(guild);
_serverLanguages[guildId] = language; _serverLanguages[guildId] = language;
@ -165,7 +165,7 @@ namespace Geekbot.net.Lib.Localization
public List<string> SupportedLanguages => _supportedLanguages; public List<string> SupportedLanguages => _supportedLanguages;
private GuildSettingsModel GetGuild(ulong guildId) private async Task<GuildSettingsModel> GetGuild(ulong guildId)
{ {
var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong()));
if (guild != null) return guild; if (guild != null) return guild;
@ -173,7 +173,7 @@ namespace Geekbot.net.Lib.Localization
{ {
GuildId = guildId.AsLong() GuildId = guildId.AsLong()
}); });
_database.SaveChanges(); await _database.SaveChangesAsync();
return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong())); return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong()));
} }
} }