rewrote database stuff to be async, hopefuly it works properly.

This commit is contained in:
Kwoth 2016-07-29 23:33:21 +02:00
parent f32ff91226
commit 11ed1500ba
15 changed files with 158 additions and 205 deletions

View File

@ -4,6 +4,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks;
namespace NadekoBot.Classes namespace NadekoBot.Classes
{ {
@ -13,31 +14,24 @@ namespace NadekoBot.Classes
private string FilePath { get; } = "data/nadekobot.sqlite"; private string FilePath { get; } = "data/nadekobot.sqlite";
public SQLiteConnection Connection { get; set; } public SQLiteAsyncConnection Connection { get; set; }
static DbHandler() { } static DbHandler() { }
public DbHandler() public DbHandler()
{ {
Connection = new SQLiteConnection(FilePath); DbHandlerAsync().GetAwaiter().GetResult();
Connection.CreateTable<Stats>(); }
Connection.CreateTable<Command>();
Connection.CreateTable<Announcement>(); private async Task DbHandlerAsync()
Connection.CreateTable<Request>(); {
Connection.CreateTable<TypingArticle>(); Connection = new SQLiteAsyncConnection(FilePath);
Connection.CreateTable<CurrencyState>(); await Connection.CreateTablesAsync<Stats, Command, Announcement, Request, TypingArticle>();
Connection.CreateTable<CurrencyTransaction>(); await Connection.CreateTablesAsync<CurrencyState, CurrencyTransaction, Donator, UserPokeTypes, UserQuote>();
Connection.CreateTable<Donator>(); await Connection.CreateTablesAsync<Reminder, SongInfo, PlaylistSongInfo, MusicPlaylist, Incident>();
Connection.CreateTable<UserPokeTypes>(); await Connection.ExecuteAsync(Queries.TransactionTriggerQuery);
Connection.CreateTable<UserQuote>();
Connection.CreateTable<Reminder>();
Connection.CreateTable<SongInfo>();
Connection.CreateTable<PlaylistSongInfo>();
Connection.CreateTable<MusicPlaylist>();
Connection.CreateTable<Incident>();
Connection.Execute(Queries.TransactionTriggerQuery);
try try
{ {
Connection.Execute(Queries.DeletePlaylistTriggerQuery); await Connection.ExecuteAsync(Queries.DeletePlaylistTriggerQuery);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -45,78 +39,50 @@ namespace NadekoBot.Classes
} }
} }
internal T FindOne<T>(Expression<Func<T, bool>> p) where T : IDataModel, new() internal async Task DeleteWhere<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{ {
return Connection.Table<T>().Where(p).FirstOrDefault(); var item = await Connection.Table<T>().Where(p).FirstOrDefaultAsync();
if (item != null)
await Connection.DeleteAsync(item);
} }
internal IList<T> FindAll<T>(Expression<Func<T, bool>> p) where T : IDataModel, new() internal async Task<HashSet<T>> GetAllRows<T>() where T : IDataModel, new() => new HashSet<T>(await Connection.Table<T>().ToListAsync());
internal Task<CurrencyState> GetStateByUserId(long id) => Connection.Table<CurrencyState>().Where(x => x.UserId == id).FirstOrDefaultAsync();
internal async Task<T> Delete<T>(int id) where T : IDataModel, new()
{ {
var found = await Connection.FindAsync<T>(id);
return Connection.Table<T>().Where(p).ToList();
}
internal void DeleteWhere<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{
var id = Connection.Table<T>().Where(p).FirstOrDefault()?.Id;
if (id.HasValue)
Connection.Delete<T>(id);
}
internal HashSet<T> GetAllRows<T>() where T : IDataModel, new()
{
return new HashSet<T>(Connection.Table<T>());
}
internal CurrencyState GetStateByUserId(long id)
{
return Connection.Table<CurrencyState>().Where(x => x.UserId == id).FirstOrDefault();
}
internal T Delete<T>(int id) where T : IDataModel, new()
{
var found = Connection.Find<T>(id);
if (found != null) if (found != null)
Connection.Delete<T>(found.Id); await Connection.DeleteAsync(found);
return found; return found;
} }
/// <summary> /// <summary>
/// Updates an existing object or creates a new one /// Updates an existing object or creates a new one
/// </summary> /// </summary>
internal void Save<T>(T o) where T : IDataModel, new() internal Task<int> Save<T>(T o) where T : IDataModel, new() => Connection.InsertOrReplaceAsync(o);
{
var found = Connection.Find<T>(o.Id);
if (found == null)
Connection.Insert(o, typeof(T));
else
Connection.Update(o, typeof(T));
}
/// <summary> /// <summary>
/// Updates an existing object or creates a new one /// Updates an existing object or creates a new one
/// </summary> /// </summary>
internal void SaveAll<T>(IEnumerable<T> ocol) where T : IDataModel, new() internal async Task SaveAll<T>(IEnumerable<T> ocol) where T : IDataModel, new()
{ {
foreach (var o in ocol) foreach (var o in ocol)
Connection.InsertOrReplace(o); await Connection.InsertOrReplaceAsync(o);
} }
internal T GetRandom<T>(Expression<Func<T, bool>> p) where T : IDataModel, new() internal async Task<T> GetRandom<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{ {
var r = new Random(); var r = new Random();
return Connection.Table<T>().Where(p).ToList().OrderBy(x => r.Next()).FirstOrDefault(); return (await Connection.Table<T>().Where(p).ToListAsync()).OrderBy(x => r.Next()).FirstOrDefault();
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="num">Page number (0+)</param> /// <param name="num">Page number (0+)</param>
/// <returns></returns> /// <returns></returns>
internal List<PlaylistData> GetPlaylistData(int num) internal Task<List<PlaylistData>> GetPlaylistData(int num) => Connection.QueryAsync<PlaylistData>(
{
return Connection.Query<PlaylistData>(
@"SELECT mp.Name as 'Name',mp.Id as 'Id', mp.CreatorName as 'Creator', Count(*) as 'SongCnt' FROM MusicPlaylist as mp @"SELECT mp.Name as 'Name',mp.Id as 'Id', mp.CreatorName as 'Creator', Count(*) as 'SongCnt' FROM MusicPlaylist as mp
INNER JOIN PlaylistSongInfo as psi INNER JOIN PlaylistSongInfo as psi
ON mp.Id = psi.PlaylistId ON mp.Id = psi.PlaylistId
@ -124,12 +90,7 @@ Group BY mp.Name
Order By mp.DateAdded desc Order By mp.DateAdded desc
Limit 20 OFFSET ?", num * 20); Limit 20 OFFSET ?", num * 20);
} internal async Task<IEnumerable<CurrencyState>> GetTopRichest(int n = 10) => (await Connection.Table<CurrencyState>().OrderByDescending(cs => cs.Value).Take(n).ToListAsync());
internal IEnumerable<CurrencyState> GetTopRichest(int n = 10)
{
return Connection.Table<CurrencyState>().OrderByDescending(cs => cs.Value).Take(n).ToList();
}
} }
} }

View File

@ -8,14 +8,11 @@ namespace NadekoBot.Classes
{ {
if (amount <= 0) if (amount <= 0)
return; return;
await Task.Run(() => await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction
{
DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
{ {
Reason = reason, Reason = reason,
UserId = (long)u.Id, UserId = (long)u.Id,
Value = amount, Value = amount,
});
}).ConfigureAwait(false); }).ConfigureAwait(false);
if (silent) if (silent)
@ -31,17 +28,17 @@ namespace NadekoBot.Classes
if (amount <= 0) if (amount <= 0)
return false; return false;
var uid = (long)u.Id; var uid = (long)u.Id;
var state = DbHandler.Instance.FindOne<DataModels.CurrencyState>(cs => cs.UserId == uid); var state = await DbHandler.Instance.Connection.Table<DataModels.CurrencyState>().Where(cs => cs.UserId == uid).FirstOrDefaultAsync();
if (state.Value < amount) if (state.Value < amount)
return false; return false;
DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction
{ {
Reason = reason, Reason = reason,
UserId = (long)u.Id, UserId = (long)u.Id,
Value = -amount, Value = -amount,
}); }).ConfigureAwait(false);
if (silent) if (silent)
return true; return true;

View File

@ -1,11 +1,12 @@
using NadekoBot.DataModels; using NadekoBot.DataModels;
using System; using System;
using System.Threading.Tasks;
namespace NadekoBot.Classes namespace NadekoBot.Classes
{ {
internal static class IncidentsHandler internal static class IncidentsHandler
{ {
public static void Add(ulong serverId, ulong channelId, string text) public static Task Add(ulong serverId, ulong channelId, string text)
{ {
var def = Console.ForegroundColor; var def = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
@ -19,7 +20,7 @@ namespace NadekoBot.Classes
Read = false Read = false
}; };
DbHandler.Instance.Connection.Insert(incident, typeof(Incident)); return DbHandler.Instance.Connection.InsertAsync(incident);
} }
} }
} }

View File

@ -195,7 +195,7 @@ namespace NadekoBot
.ConfigureAwait(false); .ConfigureAwait(false);
var connectedServers = NadekoBot.Client.Servers.Count(); var connectedServers = NadekoBot.Client.Servers.Count();
Classes.DbHandler.Instance.Connection.Insert(new DataModels.Stats await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Stats
{ {
OnlineUsers = onlineUsers, OnlineUsers = onlineUsers,
RealOnlineUsers = realOnlineUsers, RealOnlineUsers = realOnlineUsers,
@ -255,12 +255,10 @@ namespace NadekoBot
commandTracker.TryAdd(e.Message.Id, DateTime.UtcNow); commandTracker.TryAdd(e.Message.Id, DateTime.UtcNow);
Console.WriteLine($">>COMMAND STARTED\nCmd: {e.Command.Text}\nMsg: {e.Message.Text}\nUsr: {e.User.Name} [{e.User.Id}]\nSrvr: {e.Server?.Name ?? "PRIVATE"} [{e.Server?.Id}]\n-----"); Console.WriteLine($">>COMMAND STARTED\nCmd: {e.Command.Text}\nMsg: {e.Message.Text}\nUsr: {e.User.Name} [{e.User.Id}]\nSrvr: {e.Server?.Name ?? "PRIVATE"} [{e.Server?.Id}]\n-----");
#if !NADEKO_RELEASE #if !NADEKO_RELEASE
await Task.Run(() =>
{
try try
{ {
commandsRan++; commandsRan++;
Classes.DbHandler.Instance.Connection.Insert(new DataModels.Command await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Command
{ {
ServerId = (long)(e.Server?.Id ?? 0), ServerId = (long)(e.Server?.Id ?? 0),
ServerName = e.Server?.Name ?? "--Direct Message--", ServerName = e.Server?.Name ?? "--Direct Message--",
@ -270,14 +268,13 @@ namespace NadekoBot
UserName = e.User.Name, UserName = e.User.Name,
CommandName = e.Command.Text, CommandName = e.Command.Text,
DateAdded = DateTime.Now DateAdded = DateTime.Now
}); }).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Probably unimportant error in ran command DB write."); Console.WriteLine("Probably unimportant error in ran command DB write.");
Console.WriteLine(ex); Console.WriteLine(ex);
} }
}).ConfigureAwait(false);
#endif #endif
} }
} }

View File

@ -818,14 +818,11 @@ namespace NadekoBot.Modules.Administration
.Description("List of lovely people who donated to keep this project alive.") .Description("List of lovely people who donated to keep this project alive.")
.Do(async e => .Do(async e =>
{ {
await Task.Run(async () => var rows = await DbHandler.Instance.GetAllRows<Donator>().ConfigureAwait(false);
{
var rows = DbHandler.Instance.GetAllRows<Donator>();
var donatorsOrdered = rows.OrderByDescending(d => d.Amount); var donatorsOrdered = rows.OrderByDescending(d => d.Amount);
string str = $"**Thanks to the people listed below for making this project happen!**\n"; string str = $"**Thanks to the people listed below for making this project happen!**\n";
await e.Channel.SendMessage(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false); await e.Channel.SendMessage(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false);
}).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "donadd") cgb.CreateCommand(Prefix + "donadd")
@ -834,24 +831,21 @@ namespace NadekoBot.Modules.Administration
.Parameter("amount") .Parameter("amount")
.AddCheck(SimpleCheckers.OwnerOnly()) .AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e => .Do(async e =>
{
await Task.Run(() =>
{ {
var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault(); var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault();
var amount = int.Parse(e.GetArg("amount")); var amount = int.Parse(e.GetArg("amount"));
if (donator == null) return; if (donator == null) return;
try try
{ {
DbHandler.Instance.Connection.Insert(new Donator await DbHandler.Instance.Connection.InsertAsync(new Donator
{ {
Amount = amount, Amount = amount,
UserName = donator.Name, UserName = donator.Name,
UserId = (long)donator.Id UserId = (long)donator.Id
}); }).ConfigureAwait(false);
e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false); await e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false);
} }
catch { } catch { }
}).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "announce") cgb.CreateCommand(Prefix + "announce")

View File

@ -19,8 +19,8 @@ namespace NadekoBot.Modules.Administration.Commands
.Do(async e => .Do(async e =>
{ {
var sid = (long)e.Server.Id; var sid = (long)e.Server.Id;
var incs = DbHandler.Instance.FindAll<Incident>(i => i.ServerId == sid && i.Read == false); var incs = await DbHandler.Instance.Connection.Table<Incident>().Where(i => i.ServerId == sid && i.Read == false).ToListAsync();
DbHandler.Instance.Connection.UpdateAll(incs.Select(i => { i.Read = true; return i; })); await DbHandler.Instance.Connection.UpdateAllAsync(incs.Select(i => { i.Read = true; return i; }));
await e.User.SendMessage(string.Join("\n----------------------", incs.Select(i => i.Text))); await e.User.SendMessage(string.Join("\n----------------------", incs.Select(i => i.Text)));
}); });
@ -32,8 +32,8 @@ namespace NadekoBot.Modules.Administration.Commands
.Do(async e => .Do(async e =>
{ {
var sid = (long)e.Server.Id; var sid = (long)e.Server.Id;
var incs = DbHandler.Instance.FindAll<Incident>(i => i.ServerId == sid); var incs = await DbHandler.Instance.Connection.Table<Incident>().Where(i => i.ServerId == sid).ToListAsync();
DbHandler.Instance.Connection.UpdateAll(incs.Select(i => { i.Read = true; return i; })); await DbHandler.Instance.Connection.UpdateAllAsync(incs.Select(i => { i.Read = true; return i; }));
var data = string.Join("\n----------------------\n", incs.Select(i => i.Text)); var data = string.Join("\n----------------------\n", incs.Select(i => i.Text));
MemoryStream ms = new MemoryStream(); MemoryStream ms = new MemoryStream();
var sw = new StreamWriter(ms); var sw = new StreamWriter(ms);

View File

@ -34,7 +34,7 @@ namespace NadekoBot.Modules.Administration.Commands
NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserJoined += UserJoined;
NadekoBot.Client.UserLeft += UserLeft; NadekoBot.Client.UserLeft += UserLeft;
var data = Classes.DbHandler.Instance.GetAllRows<DataModels.Announcement>(); var data = Classes.DbHandler.Instance.GetAllRows<DataModels.Announcement>().GetAwaiter().GetResult();
if (!data.Any()) return; if (!data.Any()) return;
foreach (var obj in data) foreach (var obj in data)

View File

@ -40,14 +40,13 @@ namespace NadekoBot.Modules.Conversations
var text = e.GetArg("text"); var text = e.GetArg("text");
if (string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
return; return;
await Task.Run(() => await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.UserQuote()
Classes.DbHandler.Instance.Connection.Insert(new DataModels.UserQuote()
{ {
DateAdded = DateTime.Now, DateAdded = DateTime.Now,
Keyword = e.GetArg("keyword").ToLowerInvariant(), Keyword = e.GetArg("keyword").ToLowerInvariant(),
Text = text, Text = text,
UserName = e.User.Name, UserName = e.User.Name,
})).ConfigureAwait(false); }).ConfigureAwait(false);
await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false); await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false);
}); });
@ -62,7 +61,7 @@ namespace NadekoBot.Modules.Conversations
return; return;
var quote = var quote =
Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>( await Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>(
uqm => uqm.Keyword == keyword); uqm => uqm.Keyword == keyword);
if (quote != null) if (quote != null)
@ -80,13 +79,10 @@ namespace NadekoBot.Modules.Conversations
var text = e.GetArg("quote")?.Trim(); var text = e.GetArg("quote")?.Trim();
if (string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
return; return;
await Task.Run(() =>
{
if (NadekoBot.IsOwner(e.User.Id)) if (NadekoBot.IsOwner(e.User.Id))
Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text); await Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text);
else else
Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name); await Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name);
}).ConfigureAwait(false);
await e.Channel.SendMessage("`Done.`").ConfigureAwait(false); await e.Channel.SendMessage("`Done.`").ConfigureAwait(false);
}); });

View File

@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Gambling.Commands
if (!int.TryParse(e.GetArg("amount"), out amount) || amount < 0) if (!int.TryParse(e.GetArg("amount"), out amount) || amount < 0)
amount = 0; amount = 0;
var userFlowers = GamblingModule.GetUserFlowers(e.User.Id); var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount) if (userFlowers < amount)
{ {

View File

@ -43,7 +43,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1) if (!int.TryParse(amountstr, out amount) || amount < 1)
return; return;
var userFlowers = GamblingModule.GetUserFlowers(e.User.Id); var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount) if (userFlowers < amount)
{ {
@ -57,11 +57,13 @@ namespace NadekoBot.Modules.Gambling
var guess = guessStr == "HEADS" || guessStr == "H"; var guess = guessStr == "HEADS" || guessStr == "H";
bool result = false; bool result = false;
if (rng.Next(0, 2) == 1) { if (rng.Next(0, 2) == 1)
{
await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
result = true; result = true;
} }
else { else
{
await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
} }

View File

@ -9,6 +9,7 @@ using NadekoBot.Modules.Permissions.Classes;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Gambling namespace NadekoBot.Modules.Gambling
{ {
@ -57,7 +58,7 @@ namespace NadekoBot.Modules.Gambling
.Do(async e => .Do(async e =>
{ {
var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User;
var pts = GetUserFlowers(usr.Id); var pts = await GetUserFlowers(usr.Id).ConfigureAwait(false);
var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}";
await e.Channel.SendMessage(str).ConfigureAwait(false); await e.Channel.SendMessage(str).ConfigureAwait(false);
}); });
@ -79,7 +80,7 @@ namespace NadekoBot.Modules.Gambling
if (mentionedUser == null) if (mentionedUser == null)
return; return;
var userFlowers = GetUserFlowers(e.User.Id); var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount) if (userFlowers < amount)
{ {
@ -150,7 +151,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1) if (!int.TryParse(amountstr, out amount) || amount < 1)
return; return;
var userFlowers = GetUserFlowers(e.User.Id); var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount) if (userFlowers < amount)
{ {
@ -176,7 +177,8 @@ namespace NadekoBot.Modules.Gambling
str += $"Congratulations! You won {amount * 3}{NadekoBot.Config.CurrencySign} for rolling above 90."; str += $"Congratulations! You won {amount * 3}{NadekoBot.Config.CurrencySign} for rolling above 90.";
await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 3, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 3, true).ConfigureAwait(false);
} }
else { else
{
str += $"👑 Congratulations! You won {amount * 10}{NadekoBot.Config.CurrencySign} for rolling **100**. 👑"; str += $"👑 Congratulations! You won {amount * 10}{NadekoBot.Config.CurrencySign} for rolling **100**. 👑";
await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false);
} }
@ -190,7 +192,7 @@ namespace NadekoBot.Modules.Gambling
.Description($"Displays bot currency leaderboard | {Prefix}lb") .Description($"Displays bot currency leaderboard | {Prefix}lb")
.Do(async e => .Do(async e =>
{ {
var richestTemp = DbHandler.Instance.GetTopRichest(); var richestTemp = await DbHandler.Instance.GetTopRichest().ConfigureAwait(false);
var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray();
if (richest.Length == 0) if (richest.Length == 0)
return; return;
@ -208,7 +210,7 @@ namespace NadekoBot.Modules.Gambling
}); });
} }
public static long GetUserFlowers(ulong userId) => public static async Task<long> GetUserFlowers(ulong userId) =>
Classes.DbHandler.Instance.GetStateByUserId((long)userId)?.Value ?? 0; (await Classes.DbHandler.Instance.GetStateByUserId((long)userId))?.Value ?? 0;
} }
} }

View File

@ -15,9 +15,9 @@ namespace NadekoBot.Modules.Games.Commands
public static class SentencesProvider public static class SentencesProvider
{ {
internal static string GetRandomSentence() internal static async Task<string> GetRandomSentence()
{ {
var data = DbHandler.Instance.GetAllRows<TypingArticle>(); var data = await DbHandler.Instance.GetAllRows<TypingArticle>();
try try
{ {
return data.ToList()[new Random().Next(0, data.Count())].Text; return data.ToList()[new Random().Next(0, data.Count())].Text;
@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Games.Commands
{ {
if (IsActive) return; // can't start running game if (IsActive) return; // can't start running game
IsActive = true; IsActive = true;
CurrentSentence = SentencesProvider.GetRandomSentence(); CurrentSentence = await SentencesProvider.GetRandomSentence().ConfigureAwait(false);
var i = (int)(CurrentSentence.Length / WORD_VALUE * 1.7f); var i = (int)(CurrentSentence.Length / WORD_VALUE * 1.7f);
await channel.SendMessage($":clock2: Next contest will last for {i} seconds. Type the bolded text as fast as you can.").ConfigureAwait(false); await channel.SendMessage($":clock2: Next contest will last for {i} seconds. Type the bolded text as fast as you can.").ConfigureAwait(false);
@ -182,11 +182,11 @@ namespace NadekoBot.Modules.Games.Commands
{ {
if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text"))) return; if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text"))) return;
DbHandler.Instance.Connection.Insert(new TypingArticle await DbHandler.Instance.Connection.InsertAsync(new TypingArticle
{ {
Text = e.GetArg("text"), Text = e.GetArg("text"),
DateAdded = DateTime.Now DateAdded = DateTime.Now
}); }).ConfigureAwait(false);
await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false); await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false);
}); });

View File

@ -612,13 +612,13 @@ namespace NadekoBot.Modules.Music
CreatorName = e.User.Name, CreatorName = e.User.Name,
Name = name.ToLowerInvariant(), Name = name.ToLowerInvariant(),
}; };
DbHandler.Instance.SaveAll(songInfos); await DbHandler.Instance.SaveAll(songInfos).ConfigureAwait(false);
DbHandler.Instance.Save(playlist); await DbHandler.Instance.Save(playlist).ConfigureAwait(false);
DbHandler.Instance.Connection.InsertAll(songInfos.Select(s => new PlaylistSongInfo await DbHandler.Instance.Connection.InsertAllAsync(songInfos.Select(s => new PlaylistSongInfo
{ {
PlaylistId = playlist.Id.Value, PlaylistId = playlist.Id.Value,
SongInfoId = s.Id.Value SongInfoId = s.Id.Value
}), typeof(PlaylistSongInfo)); })).ConfigureAwait(false);
await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false); await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false);
@ -650,7 +650,7 @@ namespace NadekoBot.Modules.Music
if (!int.TryParse(parts[1], out playlistNumber)) if (!int.TryParse(parts[1], out playlistNumber))
return; return;
var playlist = DbHandler.Instance.FindOne<MusicPlaylist>( var playlist = DbHandler.Instance.Connection.FindAsync<MusicPlaylist>(
p => p.Id == playlistNumber); p => p.Id == playlistNumber);
if (playlist == null) if (playlist == null)
@ -659,11 +659,11 @@ namespace NadekoBot.Modules.Music
return; return;
} }
var psis = DbHandler.Instance.FindAll<PlaylistSongInfo>(psi => var psis = await DbHandler.Instance.Connection.Table<PlaylistSongInfo>().Where(psi =>
psi.PlaylistId == playlist.Id); psi.PlaylistId == playlist.Id).ToListAsync().ConfigureAwait(false);
var songInfos = psis.Select(psi => DbHandler.Instance var songInfos = await Task.WhenAll(psis.Select(async psi => await DbHandler.Instance
.FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId)); .Connection.FindAsync<DataModels.SongInfo>(si => si.Id == psi.SongInfoId))).ConfigureAwait(false);
await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false); await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
foreach (var si in songInfos) foreach (var si in songInfos)
@ -687,17 +687,17 @@ namespace NadekoBot.Modules.Music
.Alias(Prefix + "pls") .Alias(Prefix + "pls")
.Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`") .Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`")
.Parameter("num", ParameterType.Optional) .Parameter("num", ParameterType.Optional)
.Do(e => .Do(async e =>
{ {
int num = 0; int num = 0;
int.TryParse(e.GetArg("num"), out num); int.TryParse(e.GetArg("num"), out num);
if (num < 0) if (num < 0)
return; return;
var result = DbHandler.Instance.GetPlaylistData(num); var result = await DbHandler.Instance.GetPlaylistData(num);
if (result.Count == 0) if (result.Count == 0)
e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false); await e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false);
else else
e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false); await e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "deleteplaylist") cgb.CreateCommand(Prefix + "deleteplaylist")
@ -711,9 +711,9 @@ namespace NadekoBot.Modules.Music
return; return;
var plnum = int.Parse(pl); var plnum = int.Parse(pl);
if (NadekoBot.IsOwner(e.User.Id)) if (NadekoBot.IsOwner(e.User.Id))
DbHandler.Instance.Delete<MusicPlaylist>(plnum); await DbHandler.Instance.Delete<MusicPlaylist>(plnum).ConfigureAwait(false);
else else
DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId); await DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId).ConfigureAwait(false);
await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false); await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false);
}); });
@ -773,11 +773,13 @@ namespace NadekoBot.Modules.Music
{ {
await e.Channel.SendMessage("Could not select song, likely wrong index"); await e.Channel.SendMessage("Could not select song, likely wrong index");
} else }
else
{ {
await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false); await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
} }
} else }
else
{ {
var curSong = musicPlayer.CurrentSong; var curSong = musicPlayer.CurrentSong;
if (curSong == null) if (curSong == null)

View File

@ -9,6 +9,7 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Pokemon namespace NadekoBot.Modules.Pokemon
{ {
@ -39,10 +40,10 @@ namespace NadekoBot.Modules.Pokemon
return damage; return damage;
} }
private PokemonType GetPokeType(ulong id) private async Task<PokemonType> GetPokeType(ulong id)
{ {
var db = DbHandler.Instance.GetAllRows<UserPokeTypes>(); var db = await DbHandler.Instance.GetAllRows<UserPokeTypes>().ConfigureAwait(false);
Dictionary<long, string> setTypes = db.ToDictionary(x => x.UserId, y => y.type); Dictionary<long, string> setTypes = db.ToDictionary(x => x.UserId, y => y.type);
if (setTypes.ContainsKey((long)id)) if (setTypes.ContainsKey((long)id))
{ {
@ -134,7 +135,7 @@ namespace NadekoBot.Modules.Pokemon
} }
//Check whether move can be used //Check whether move can be used
PokemonType userType = GetPokeType(e.User.Id); PokemonType userType = await GetPokeType(e.User.Id).ConfigureAwait(false);
var enabledMoves = userType.Moves; var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant())) if (!enabledMoves.Contains(move.ToLowerInvariant()))
@ -144,7 +145,7 @@ namespace NadekoBot.Modules.Pokemon
} }
//get target type //get target type
PokemonType targetType = GetPokeType(target.Id); PokemonType targetType = await GetPokeType(target.Id).ConfigureAwait(false);
//generate damage //generate damage
int damage = GetDamage(userType, targetType); int damage = GetDamage(userType, targetType);
//apply damage to target //apply damage to target
@ -199,7 +200,7 @@ namespace NadekoBot.Modules.Pokemon
.Description($"Lists the moves you are able to use | `{Prefix}ml`") .Description($"Lists the moves you are able to use | `{Prefix}ml`")
.Do(async e => .Do(async e =>
{ {
var userType = GetPokeType(e.User.Id); var userType = await GetPokeType(e.User.Id).ConfigureAwait(false);
var movesList = userType.Moves; var movesList = userType.Moves;
var str = $"**Moves for `{userType.Name}` type.**"; var str = $"**Moves for `{userType.Name}` type.**";
foreach (string m in movesList) foreach (string m in movesList)
@ -235,7 +236,7 @@ namespace NadekoBot.Modules.Pokemon
} }
//Payment~ //Payment~
var amount = 1; var amount = 1;
var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; var pts = (await Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0;
if (pts < amount) if (pts < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
@ -276,7 +277,7 @@ namespace NadekoBot.Modules.Pokemon
await e.Channel.SendMessage("No such person.").ConfigureAwait(false); await e.Channel.SendMessage("No such person.").ConfigureAwait(false);
return; return;
} }
var pType = GetPokeType(usr.Id); var pType = await GetPokeType(usr.Id).ConfigureAwait(false);
await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
}); });
@ -295,7 +296,7 @@ namespace NadekoBot.Modules.Pokemon
await e.Channel.SendMessage("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false); await e.Channel.SendMessage("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false);
return; return;
} }
if (targetType == GetPokeType(e.User.Id)) if (targetType == await GetPokeType(e.User.Id).ConfigureAwait(false))
{ {
await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
return; return;
@ -303,7 +304,7 @@ namespace NadekoBot.Modules.Pokemon
//Payment~ //Payment~
var amount = 1; var amount = 1;
var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; var pts = (await DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0;
if (pts < amount) if (pts < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
@ -311,19 +312,19 @@ namespace NadekoBot.Modules.Pokemon
} }
await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false); await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false);
//Actually changing the type here //Actually changing the type here
var preTypes = DbHandler.Instance.GetAllRows<UserPokeTypes>(); var preTypes = await DbHandler.Instance.GetAllRows<UserPokeTypes>().ConfigureAwait(false);
Dictionary<long, int> Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id.Value); Dictionary<long, int> Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id.Value);
if (Dict.ContainsKey((long)e.User.Id)) if (Dict.ContainsKey((long)e.User.Id))
{ {
//delete previous type //delete previous type
DbHandler.Instance.Delete<UserPokeTypes>(Dict[(long)e.User.Id]); await DbHandler.Instance.Delete<UserPokeTypes>(Dict[(long)e.User.Id]).ConfigureAwait(false);
} }
DbHandler.Instance.Connection.Insert(new UserPokeTypes await DbHandler.Instance.Connection.InsertAsync(new UserPokeTypes
{ {
UserId = (long)e.User.Id, UserId = (long)e.User.Id,
type = targetType.Name type = targetType.Name
}, typeof(UserPokeTypes)); }).ConfigureAwait(false);
//Now for the response //Now for the response

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Utility.Commands
public Remind(DiscordModule module) : base(module) public Remind(DiscordModule module) : base(module)
{ {
var remList = DbHandler.Instance.GetAllRows<Reminder>(); var remList = DbHandler.Instance.GetAllRows<Reminder>().GetAwaiter().GetResult();
reminders = remList.Select(StartNewReminder).ToList(); reminders = remList.Select(StartNewReminder).ToList();
} }
@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Utility.Commands
} }
finally finally
{ {
DbHandler.Instance.Delete<Reminder>(r.Id.Value); await DbHandler.Instance.Delete<Reminder>(r.Id.Value).ConfigureAwait(false);
t.Stop(); t.Stop();
t.Dispose(); t.Dispose();
} }
@ -171,7 +171,7 @@ namespace NadekoBot.Modules.Utility.Commands
UserId = (long)e.User.Id, UserId = (long)e.User.Id,
ServerId = (long)e.Server.Id ServerId = (long)e.Server.Id
}; };
DbHandler.Instance.Connection.Insert(rem); await DbHandler.Instance.Connection.InsertAsync(rem).ConfigureAwait(false);
reminders.Add(StartNewReminder(rem)); reminders.Add(StartNewReminder(rem));