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.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace NadekoBot.Classes
{
@ -13,31 +14,24 @@ namespace NadekoBot.Classes
private string FilePath { get; } = "data/nadekobot.sqlite";
public SQLiteConnection Connection { get; set; }
public SQLiteAsyncConnection Connection { get; set; }
static DbHandler() { }
public DbHandler()
{
Connection = new SQLiteConnection(FilePath);
Connection.CreateTable<Stats>();
Connection.CreateTable<Command>();
Connection.CreateTable<Announcement>();
Connection.CreateTable<Request>();
Connection.CreateTable<TypingArticle>();
Connection.CreateTable<CurrencyState>();
Connection.CreateTable<CurrencyTransaction>();
Connection.CreateTable<Donator>();
Connection.CreateTable<UserPokeTypes>();
Connection.CreateTable<UserQuote>();
Connection.CreateTable<Reminder>();
Connection.CreateTable<SongInfo>();
Connection.CreateTable<PlaylistSongInfo>();
Connection.CreateTable<MusicPlaylist>();
Connection.CreateTable<Incident>();
Connection.Execute(Queries.TransactionTriggerQuery);
DbHandlerAsync().GetAwaiter().GetResult();
}
private async Task DbHandlerAsync()
{
Connection = new SQLiteAsyncConnection(FilePath);
await Connection.CreateTablesAsync<Stats, Command, Announcement, Request, TypingArticle>();
await Connection.CreateTablesAsync<CurrencyState, CurrencyTransaction, Donator, UserPokeTypes, UserQuote>();
await Connection.CreateTablesAsync<Reminder, SongInfo, PlaylistSongInfo, MusicPlaylist, Incident>();
await Connection.ExecuteAsync(Queries.TransactionTriggerQuery);
try
{
Connection.Execute(Queries.DeletePlaylistTriggerQuery);
await Connection.ExecuteAsync(Queries.DeletePlaylistTriggerQuery);
}
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()
{
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);
var found = await Connection.FindAsync<T>(id);
if (found != null)
Connection.Delete<T>(found.Id);
await Connection.DeleteAsync(found);
return found;
}
/// <summary>
/// Updates an existing object or creates a new one
/// </summary>
internal void Save<T>(T o) where T : IDataModel, new()
{
var found = Connection.Find<T>(o.Id);
if (found == null)
Connection.Insert(o, typeof(T));
else
Connection.Update(o, typeof(T));
}
internal Task<int> Save<T>(T o) where T : IDataModel, new() => Connection.InsertOrReplaceAsync(o);
/// <summary>
/// Updates an existing object or creates a new one
/// </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)
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();
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>
/// <param name="num">Page number (0+)</param>
/// <returns></returns>
internal List<PlaylistData> GetPlaylistData(int num)
{
return Connection.Query<PlaylistData>(
internal Task<List<PlaylistData>> GetPlaylistData(int num) => Connection.QueryAsync<PlaylistData>(
@"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
ON mp.Id = psi.PlaylistId
@ -124,12 +90,7 @@ Group BY mp.Name
Order By mp.DateAdded desc
Limit 20 OFFSET ?", num * 20);
}
internal IEnumerable<CurrencyState> GetTopRichest(int n = 10)
{
return Connection.Table<CurrencyState>().OrderByDescending(cs => cs.Value).Take(n).ToList();
}
internal async Task<IEnumerable<CurrencyState>> GetTopRichest(int n = 10) => (await Connection.Table<CurrencyState>().OrderByDescending(cs => cs.Value).Take(n).ToListAsync());
}
}

View File

@ -8,14 +8,11 @@ namespace NadekoBot.Classes
{
if (amount <= 0)
return;
await Task.Run(() =>
await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction
{
DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
{
Reason = reason,
UserId = (long)u.Id,
Value = amount,
});
Reason = reason,
UserId = (long)u.Id,
Value = amount,
}).ConfigureAwait(false);
if (silent)
@ -26,27 +23,27 @@ namespace NadekoBot.Classes
await u.SendMessage("👑Congratulations!👑\nYou received: " + flows).ConfigureAwait(false);
}
public static async Task<bool> RemoveFlowers(Discord.User u, string reason, int amount, bool silent=false, string message="👎`Bot owner has taken {0}{1} from you.`")
public static async Task<bool> RemoveFlowers(Discord.User u, string reason, int amount, bool silent = false, string message = "👎`Bot owner has taken {0}{1} from you.`")
{
if (amount <= 0)
return false;
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)
return false;
DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction
{
Reason = reason,
UserId = (long)u.Id,
Value = -amount,
});
}).ConfigureAwait(false);
if (silent)
return true;
await u.SendMessage(string.Format(message,amount,NadekoBot.Config.CurrencySign)).ConfigureAwait(false);
await u.SendMessage(string.Format(message, amount, NadekoBot.Config.CurrencySign)).ConfigureAwait(false);
return true;
}
}

View File

@ -1,11 +1,12 @@
using NadekoBot.DataModels;
using System;
using System.Threading.Tasks;
namespace NadekoBot.Classes
{
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;
Console.ForegroundColor = ConsoleColor.Red;
@ -19,7 +20,7 @@ namespace NadekoBot.Classes
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);
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,
RealOnlineUsers = realOnlineUsers,
@ -255,29 +255,26 @@ namespace NadekoBot
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-----");
#if !NADEKO_RELEASE
await Task.Run(() =>
try
{
try
commandsRan++;
await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Command
{
commandsRan++;
Classes.DbHandler.Instance.Connection.Insert(new DataModels.Command
{
ServerId = (long)(e.Server?.Id ?? 0),
ServerName = e.Server?.Name ?? "--Direct Message--",
ChannelId = (long)e.Channel.Id,
ChannelName = e.Channel.IsPrivate ? "--Direct Message" : e.Channel.Name,
UserId = (long)e.User.Id,
UserName = e.User.Name,
CommandName = e.Command.Text,
DateAdded = DateTime.Now
});
}
catch (Exception ex)
{
Console.WriteLine("Probably unimportant error in ran command DB write.");
Console.WriteLine(ex);
}
}).ConfigureAwait(false);
ServerId = (long)(e.Server?.Id ?? 0),
ServerName = e.Server?.Name ?? "--Direct Message--",
ChannelId = (long)e.Channel.Id,
ChannelName = e.Channel.IsPrivate ? "--Direct Message" : e.Channel.Name,
UserId = (long)e.User.Id,
UserName = e.User.Name,
CommandName = e.Command.Text,
DateAdded = DateTime.Now
}).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine("Probably unimportant error in ran command DB write.");
Console.WriteLine(ex);
}
#endif
}
}

View File

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

View File

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

View File

@ -34,7 +34,7 @@ namespace NadekoBot.Modules.Administration.Commands
NadekoBot.Client.UserJoined += UserJoined;
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;
foreach (var obj in data)

View File

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

View File

@ -20,7 +20,7 @@ namespace NadekoBot.Modules.Gambling
.Do(FlipCoinFunc());
cgb.CreateCommand(Module.Prefix + "betflip")
.Alias(Prefix+"bf")
.Alias(Prefix + "bf")
.Description($"Bet to guess will the result be heads or tails. Guessing award you double flowers you've bet. | `{Prefix}bf 5 heads` or `{Prefix}bf 3 t`")
.Parameter("amount", ParameterType.Required)
.Parameter("guess", ParameterType.Required)
@ -43,7 +43,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1)
return;
var userFlowers = GamblingModule.GetUserFlowers(e.User.Id);
var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount)
{
@ -57,11 +57,13 @@ namespace NadekoBot.Modules.Gambling
var guess = guessStr == "HEADS" || guessStr == "H";
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);
result = true;
}
else {
else
{
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.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Gambling
{
@ -57,13 +58,13 @@ namespace NadekoBot.Modules.Gambling
.Do(async e =>
{
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}";
await e.Channel.SendMessage(str).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "give")
.Description(string.Format("Give someone a certain amount of {0}s", NadekoBot.Config.CurrencyName)+ $"|`{Prefix}give 1 \"@SomeGuy\"`")
.Description(string.Format("Give someone a certain amount of {0}s", NadekoBot.Config.CurrencyName) + $"|`{Prefix}give 1 \"@SomeGuy\"`")
.Parameter("amount", ParameterType.Required)
.Parameter("receiver", ParameterType.Unparsed)
.Do(async e =>
@ -79,7 +80,7 @@ namespace NadekoBot.Modules.Gambling
if (mentionedUser == null)
return;
var userFlowers = GetUserFlowers(e.User.Id);
var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount)
{
@ -141,7 +142,7 @@ namespace NadekoBot.Modules.Gambling
cgb.CreateCommand(Prefix + "betroll")
.Alias(Prefix + "br")
.Description($"Bets a certain amount of {NadekoBot.Config.CurrencyName}s and rolls a dice. Rolling over 66 yields x2 flowers, over 90 - x3 and 100 x10. | `{Prefix}br 5`")
.Parameter("amount",ParameterType.Required)
.Parameter("amount", ParameterType.Required)
.Do(async e =>
{
var amountstr = e.GetArg("amount").Trim();
@ -150,7 +151,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1)
return;
var userFlowers = GetUserFlowers(e.User.Id);
var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false);
if (userFlowers < amount)
{
@ -176,13 +177,14 @@ namespace NadekoBot.Modules.Gambling
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);
}
else {
else
{
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 e.Channel.SendMessage(str).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "leaderboard")
@ -190,7 +192,7 @@ namespace NadekoBot.Modules.Gambling
.Description($"Displays bot currency leaderboard | {Prefix}lb")
.Do(async e =>
{
var richestTemp = DbHandler.Instance.GetTopRichest();
var richestTemp = await DbHandler.Instance.GetTopRichest().ConfigureAwait(false);
var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray();
if (richest.Length == 0)
return;
@ -208,7 +210,7 @@ namespace NadekoBot.Modules.Gambling
});
}
public static long GetUserFlowers(ulong userId) =>
Classes.DbHandler.Instance.GetStateByUserId((long)userId)?.Value ?? 0;
public static async Task<long> GetUserFlowers(ulong userId) =>
(await Classes.DbHandler.Instance.GetStateByUserId((long)userId))?.Value ?? 0;
}
}

View File

@ -15,9 +15,9 @@ namespace NadekoBot.Modules.Games.Commands
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
{
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
IsActive = true;
CurrentSentence = SentencesProvider.GetRandomSentence();
CurrentSentence = await SentencesProvider.GetRandomSentence().ConfigureAwait(false);
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);
@ -182,11 +182,11 @@ namespace NadekoBot.Modules.Games.Commands
{
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"),
DateAdded = DateTime.Now
});
}).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,
Name = name.ToLowerInvariant(),
};
DbHandler.Instance.SaveAll(songInfos);
DbHandler.Instance.Save(playlist);
DbHandler.Instance.Connection.InsertAll(songInfos.Select(s => new PlaylistSongInfo
await DbHandler.Instance.SaveAll(songInfos).ConfigureAwait(false);
await DbHandler.Instance.Save(playlist).ConfigureAwait(false);
await DbHandler.Instance.Connection.InsertAllAsync(songInfos.Select(s => new PlaylistSongInfo
{
PlaylistId = playlist.Id.Value,
SongInfoId = s.Id.Value
}), typeof(PlaylistSongInfo));
})).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))
return;
var playlist = DbHandler.Instance.FindOne<MusicPlaylist>(
var playlist = DbHandler.Instance.Connection.FindAsync<MusicPlaylist>(
p => p.Id == playlistNumber);
if (playlist == null)
@ -659,11 +659,11 @@ namespace NadekoBot.Modules.Music
return;
}
var psis = DbHandler.Instance.FindAll<PlaylistSongInfo>(psi =>
psi.PlaylistId == playlist.Id);
var psis = await DbHandler.Instance.Connection.Table<PlaylistSongInfo>().Where(psi =>
psi.PlaylistId == playlist.Id).ToListAsync().ConfigureAwait(false);
var songInfos = psis.Select(psi => DbHandler.Instance
.FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId));
var songInfos = await Task.WhenAll(psis.Select(async psi => await DbHandler.Instance
.Connection.FindAsync<DataModels.SongInfo>(si => si.Id == psi.SongInfoId))).ConfigureAwait(false);
await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
foreach (var si in songInfos)
@ -687,17 +687,17 @@ namespace NadekoBot.Modules.Music
.Alias(Prefix + "pls")
.Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`")
.Parameter("num", ParameterType.Optional)
.Do(e =>
.Do(async e =>
{
int num = 0;
int.TryParse(e.GetArg("num"), out num);
if (num < 0)
return;
var result = DbHandler.Instance.GetPlaylistData(num);
var result = await DbHandler.Instance.GetPlaylistData(num);
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
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")
@ -711,9 +711,9 @@ namespace NadekoBot.Modules.Music
return;
var plnum = int.Parse(pl);
if (NadekoBot.IsOwner(e.User.Id))
DbHandler.Instance.Delete<MusicPlaylist>(plnum);
await DbHandler.Instance.Delete<MusicPlaylist>(plnum).ConfigureAwait(false);
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);
});
@ -771,20 +771,22 @@ namespace NadekoBot.Modules.Music
var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1);
if (selSong == null)
{
await e.Channel.SendMessage("Could not select song, likely wrong index");
} else
await e.Channel.SendMessage("Could not select song, likely wrong index");
}
else
{
await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
}
} else
}
else
{
var curSong = musicPlayer.CurrentSong;
if (curSong == null)
return;
await e.Channel.SendMessage($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false);
}
});
cgb.CreateCommand(Prefix + "autoplay")

View File

@ -9,6 +9,7 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Pokemon
{
@ -39,10 +40,10 @@ namespace NadekoBot.Modules.Pokemon
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);
if (setTypes.ContainsKey((long)id))
{
@ -134,7 +135,7 @@ namespace NadekoBot.Modules.Pokemon
}
//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;
if (!enabledMoves.Contains(move.ToLowerInvariant()))
@ -144,7 +145,7 @@ namespace NadekoBot.Modules.Pokemon
}
//get target type
PokemonType targetType = GetPokeType(target.Id);
PokemonType targetType = await GetPokeType(target.Id).ConfigureAwait(false);
//generate damage
int damage = GetDamage(userType, targetType);
//apply damage to target
@ -199,7 +200,7 @@ namespace NadekoBot.Modules.Pokemon
.Description($"Lists the moves you are able to use | `{Prefix}ml`")
.Do(async e =>
{
var userType = GetPokeType(e.User.Id);
var userType = await GetPokeType(e.User.Id).ConfigureAwait(false);
var movesList = userType.Moves;
var str = $"**Moves for `{userType.Name}` type.**";
foreach (string m in movesList)
@ -235,7 +236,7 @@ namespace NadekoBot.Modules.Pokemon
}
//Payment~
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)
{
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);
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);
});
@ -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);
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);
return;
@ -303,7 +304,7 @@ namespace NadekoBot.Modules.Pokemon
//Payment~
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)
{
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);
//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);
if (Dict.ContainsKey((long)e.User.Id))
{
//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,
type = targetType.Name
}, typeof(UserPokeTypes));
}).ConfigureAwait(false);
//Now for the response

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Utility.Commands
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();
}
@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Utility.Commands
}
finally
{
DbHandler.Instance.Delete<Reminder>(r.Id.Value);
await DbHandler.Instance.Delete<Reminder>(r.Id.Value).ConfigureAwait(false);
t.Stop();
t.Dispose();
}
@ -171,7 +171,7 @@ namespace NadekoBot.Modules.Utility.Commands
UserId = (long)e.User.Id,
ServerId = (long)e.Server.Id
};
DbHandler.Instance.Connection.Insert(rem);
await DbHandler.Instance.Connection.InsertAsync(rem).ConfigureAwait(false);
reminders.Add(StartNewReminder(rem));