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

This reverts commit 11ed1500ba.
This commit is contained in:
Kwoth 2016-07-30 01:21:48 +02:00
parent 11ed1500ba
commit 670a8ddf82
15 changed files with 205 additions and 158 deletions

View File

@ -4,7 +4,6 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace NadekoBot.Classes
{
@ -14,24 +13,31 @@ namespace NadekoBot.Classes
private string FilePath { get; } = "data/nadekobot.sqlite";
public SQLiteAsyncConnection Connection { get; set; }
public SQLiteConnection Connection { get; set; }
static DbHandler() { }
public DbHandler()
{
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);
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);
try
{
await Connection.ExecuteAsync(Queries.DeletePlaylistTriggerQuery);
Connection.Execute(Queries.DeletePlaylistTriggerQuery);
}
catch (Exception ex)
{
@ -39,50 +45,78 @@ namespace NadekoBot.Classes
}
}
internal async Task DeleteWhere<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
internal T FindOne<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{
var item = await Connection.Table<T>().Where(p).FirstOrDefaultAsync();
if (item != null)
await Connection.DeleteAsync(item);
return Connection.Table<T>().Where(p).FirstOrDefault();
}
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()
internal IList<T> FindAll<T>(Expression<Func<T, bool>> p) 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)
await Connection.DeleteAsync(found);
Connection.Delete<T>(found.Id);
return found;
}
/// <summary>
/// Updates an existing object or creates a new one
/// </summary>
internal Task<int> Save<T>(T o) where T : IDataModel, new() => Connection.InsertOrReplaceAsync(o);
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));
}
/// <summary>
/// Updates an existing object or creates a new one
/// </summary>
internal async Task SaveAll<T>(IEnumerable<T> ocol) where T : IDataModel, new()
internal void SaveAll<T>(IEnumerable<T> ocol) where T : IDataModel, new()
{
foreach (var o in ocol)
await Connection.InsertOrReplaceAsync(o);
Connection.InsertOrReplace(o);
}
internal async Task<T> GetRandom<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
internal T GetRandom<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{
var r = new Random();
return (await Connection.Table<T>().Where(p).ToListAsync()).OrderBy(x => r.Next()).FirstOrDefault();
return Connection.Table<T>().Where(p).ToList().OrderBy(x => r.Next()).FirstOrDefault();
}
/// <summary>
///
/// </summary>
/// <param name="num">Page number (0+)</param>
/// <returns></returns>
internal Task<List<PlaylistData>> GetPlaylistData(int num) => Connection.QueryAsync<PlaylistData>(
internal List<PlaylistData> GetPlaylistData(int num)
{
return Connection.Query<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
@ -90,7 +124,12 @@ Group BY mp.Name
Order By mp.DateAdded desc
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,11 +8,14 @@ namespace NadekoBot.Classes
{
if (amount <= 0)
return;
await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction
await Task.Run(() =>
{
Reason = reason,
UserId = (long)u.Id,
Value = amount,
DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
{
Reason = reason,
UserId = (long)u.Id,
Value = amount,
});
}).ConfigureAwait(false);
if (silent)
@ -23,27 +26,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 = await DbHandler.Instance.Connection.Table<DataModels.CurrencyState>().Where(cs => cs.UserId == uid).FirstOrDefaultAsync();
var state = DbHandler.Instance.FindOne<DataModels.CurrencyState>(cs => cs.UserId == uid);
if (state.Value < amount)
return false;
await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction
DbHandler.Instance.Connection.Insert(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,12 +1,11 @@
using NadekoBot.DataModels;
using System;
using System.Threading.Tasks;
namespace NadekoBot.Classes
{
internal static class IncidentsHandler
{
public static Task Add(ulong serverId, ulong channelId, string text)
public static void Add(ulong serverId, ulong channelId, string text)
{
var def = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
@ -20,7 +19,7 @@ namespace NadekoBot.Classes
Read = false
};
return DbHandler.Instance.Connection.InsertAsync(incident);
DbHandler.Instance.Connection.Insert(incident, typeof(Incident));
}
}
}

View File

@ -195,7 +195,7 @@ namespace NadekoBot
.ConfigureAwait(false);
var connectedServers = NadekoBot.Client.Servers.Count();
await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Stats
Classes.DbHandler.Instance.Connection.Insert(new DataModels.Stats
{
OnlineUsers = onlineUsers,
RealOnlineUsers = realOnlineUsers,
@ -255,26 +255,29 @@ 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
try
await Task.Run(() =>
{
commandsRan++;
await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Command
try
{
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);
}
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);
#endif
}
}

View File

@ -818,11 +818,14 @@ namespace NadekoBot.Modules.Administration
.Description("List of lovely people who donated to keep this project alive.")
.Do(async e =>
{
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 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";
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")
@ -832,20 +835,23 @@ namespace NadekoBot.Modules.Administration
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e =>
{
var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault();
var amount = int.Parse(e.GetArg("amount"));
if (donator == null) return;
try
await Task.Run(() =>
{
await DbHandler.Instance.Connection.InsertAsync(new Donator
var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault();
var amount = int.Parse(e.GetArg("amount"));
if (donator == null) return;
try
{
Amount = amount,
UserName = donator.Name,
UserId = (long)donator.Id
}).ConfigureAwait(false);
await e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false);
}
catch { }
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);
});
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 = 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; }));
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; }));
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 = 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 incs = DbHandler.Instance.FindAll<Incident>(i => i.ServerId == sid);
DbHandler.Instance.Connection.UpdateAll(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>().GetAwaiter().GetResult();
var data = Classes.DbHandler.Instance.GetAllRows<DataModels.Announcement>();
if (!data.Any()) return;
foreach (var obj in data)

View File

@ -40,13 +40,14 @@ namespace NadekoBot.Modules.Conversations
var text = e.GetArg("text");
if (string.IsNullOrWhiteSpace(text))
return;
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 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 e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false);
});
@ -61,7 +62,7 @@ namespace NadekoBot.Modules.Conversations
return;
var quote =
await Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>(
Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>(
uqm => uqm.Keyword == keyword);
if (quote != null)
@ -79,10 +80,13 @@ namespace NadekoBot.Modules.Conversations
var text = e.GetArg("quote")?.Trim();
if (string.IsNullOrWhiteSpace(text))
return;
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 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);
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 = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false);
var userFlowers = GamblingModule.GetUserFlowers(e.User.Id);
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 = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false);
var userFlowers = GamblingModule.GetUserFlowers(e.User.Id);
if (userFlowers < amount)
{
@ -57,13 +57,11 @@ 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,7 +9,6 @@ using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Gambling
{
@ -58,13 +57,13 @@ namespace NadekoBot.Modules.Gambling
.Do(async e =>
{
var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User;
var pts = await GetUserFlowers(usr.Id).ConfigureAwait(false);
var pts = GetUserFlowers(usr.Id);
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 =>
@ -80,7 +79,7 @@ namespace NadekoBot.Modules.Gambling
if (mentionedUser == null)
return;
var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false);
var userFlowers = GetUserFlowers(e.User.Id);
if (userFlowers < amount)
{
@ -142,7 +141,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();
@ -151,7 +150,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1)
return;
var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false);
var userFlowers = GetUserFlowers(e.User.Id);
if (userFlowers < amount)
{
@ -177,14 +176,13 @@ 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")
@ -192,7 +190,7 @@ namespace NadekoBot.Modules.Gambling
.Description($"Displays bot currency leaderboard | {Prefix}lb")
.Do(async e =>
{
var richestTemp = await DbHandler.Instance.GetTopRichest().ConfigureAwait(false);
var richestTemp = DbHandler.Instance.GetTopRichest();
var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray();
if (richest.Length == 0)
return;
@ -210,7 +208,7 @@ namespace NadekoBot.Modules.Gambling
});
}
public static async Task<long> GetUserFlowers(ulong userId) =>
(await Classes.DbHandler.Instance.GetStateByUserId((long)userId))?.Value ?? 0;
public static long GetUserFlowers(ulong userId) =>
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 async Task<string> GetRandomSentence()
internal static string GetRandomSentence()
{
var data = await DbHandler.Instance.GetAllRows<TypingArticle>();
var data = 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 = await SentencesProvider.GetRandomSentence().ConfigureAwait(false);
CurrentSentence = SentencesProvider.GetRandomSentence();
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;
await DbHandler.Instance.Connection.InsertAsync(new TypingArticle
DbHandler.Instance.Connection.Insert(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(),
};
await DbHandler.Instance.SaveAll(songInfos).ConfigureAwait(false);
await DbHandler.Instance.Save(playlist).ConfigureAwait(false);
await DbHandler.Instance.Connection.InsertAllAsync(songInfos.Select(s => new PlaylistSongInfo
DbHandler.Instance.SaveAll(songInfos);
DbHandler.Instance.Save(playlist);
DbHandler.Instance.Connection.InsertAll(songInfos.Select(s => new PlaylistSongInfo
{
PlaylistId = playlist.Id.Value,
SongInfoId = s.Id.Value
})).ConfigureAwait(false);
}), typeof(PlaylistSongInfo));
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.Connection.FindAsync<MusicPlaylist>(
var playlist = DbHandler.Instance.FindOne<MusicPlaylist>(
p => p.Id == playlistNumber);
if (playlist == null)
@ -659,11 +659,11 @@ namespace NadekoBot.Modules.Music
return;
}
var psis = await DbHandler.Instance.Connection.Table<PlaylistSongInfo>().Where(psi =>
psi.PlaylistId == playlist.Id).ToListAsync().ConfigureAwait(false);
var psis = DbHandler.Instance.FindAll<PlaylistSongInfo>(psi =>
psi.PlaylistId == playlist.Id);
var songInfos = await Task.WhenAll(psis.Select(async psi => await DbHandler.Instance
.Connection.FindAsync<DataModels.SongInfo>(si => si.Id == psi.SongInfoId))).ConfigureAwait(false);
var songInfos = psis.Select(psi => DbHandler.Instance
.FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId));
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(async e =>
.Do(e =>
{
int num = 0;
int.TryParse(e.GetArg("num"), out num);
if (num < 0)
return;
var result = await DbHandler.Instance.GetPlaylistData(num);
var result = DbHandler.Instance.GetPlaylistData(num);
if (result.Count == 0)
await e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false);
e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false);
else
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);
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))
await DbHandler.Instance.Delete<MusicPlaylist>(plnum).ConfigureAwait(false);
DbHandler.Instance.Delete<MusicPlaylist>(plnum);
else
await DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId).ConfigureAwait(false);
DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId);
await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false);
});
@ -771,22 +771,20 @@ 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,7 +9,6 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Pokemon
{
@ -40,10 +39,10 @@ namespace NadekoBot.Modules.Pokemon
return damage;
}
private async Task<PokemonType> GetPokeType(ulong id)
private PokemonType GetPokeType(ulong id)
{
var db = await DbHandler.Instance.GetAllRows<UserPokeTypes>().ConfigureAwait(false);
var db = DbHandler.Instance.GetAllRows<UserPokeTypes>();
Dictionary<long, string> setTypes = db.ToDictionary(x => x.UserId, y => y.type);
if (setTypes.ContainsKey((long)id))
{
@ -135,7 +134,7 @@ namespace NadekoBot.Modules.Pokemon
}
//Check whether move can be used
PokemonType userType = await GetPokeType(e.User.Id).ConfigureAwait(false);
PokemonType userType = GetPokeType(e.User.Id);
var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant()))
@ -145,7 +144,7 @@ namespace NadekoBot.Modules.Pokemon
}
//get target type
PokemonType targetType = await GetPokeType(target.Id).ConfigureAwait(false);
PokemonType targetType = GetPokeType(target.Id);
//generate damage
int damage = GetDamage(userType, targetType);
//apply damage to target
@ -200,7 +199,7 @@ namespace NadekoBot.Modules.Pokemon
.Description($"Lists the moves you are able to use | `{Prefix}ml`")
.Do(async e =>
{
var userType = await GetPokeType(e.User.Id).ConfigureAwait(false);
var userType = GetPokeType(e.User.Id);
var movesList = userType.Moves;
var str = $"**Moves for `{userType.Name}` type.**";
foreach (string m in movesList)
@ -236,7 +235,7 @@ namespace NadekoBot.Modules.Pokemon
}
//Payment~
var amount = 1;
var pts = (await Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0;
var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.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);
@ -277,7 +276,7 @@ namespace NadekoBot.Modules.Pokemon
await e.Channel.SendMessage("No such person.").ConfigureAwait(false);
return;
}
var pType = await GetPokeType(usr.Id).ConfigureAwait(false);
var pType = GetPokeType(usr.Id);
await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
});
@ -296,7 +295,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 == await GetPokeType(e.User.Id).ConfigureAwait(false))
if (targetType == GetPokeType(e.User.Id))
{
await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
return;
@ -304,7 +303,7 @@ namespace NadekoBot.Modules.Pokemon
//Payment~
var amount = 1;
var pts = (await DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0;
var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.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);
@ -312,19 +311,19 @@ namespace NadekoBot.Modules.Pokemon
}
await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false);
//Actually changing the type here
var preTypes = await DbHandler.Instance.GetAllRows<UserPokeTypes>().ConfigureAwait(false);
var preTypes = DbHandler.Instance.GetAllRows<UserPokeTypes>();
Dictionary<long, int> Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id.Value);
if (Dict.ContainsKey((long)e.User.Id))
{
//delete previous type
await DbHandler.Instance.Delete<UserPokeTypes>(Dict[(long)e.User.Id]).ConfigureAwait(false);
DbHandler.Instance.Delete<UserPokeTypes>(Dict[(long)e.User.Id]);
}
await DbHandler.Instance.Connection.InsertAsync(new UserPokeTypes
DbHandler.Instance.Connection.Insert(new UserPokeTypes
{
UserId = (long)e.User.Id,
type = targetType.Name
}).ConfigureAwait(false);
}, typeof(UserPokeTypes));
//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>().GetAwaiter().GetResult();
var remList = DbHandler.Instance.GetAllRows<Reminder>();
reminders = remList.Select(StartNewReminder).ToList();
}
@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Utility.Commands
}
finally
{
await DbHandler.Instance.Delete<Reminder>(r.Id.Value).ConfigureAwait(false);
DbHandler.Instance.Delete<Reminder>(r.Id.Value);
t.Stop();
t.Dispose();
}
@ -171,7 +171,7 @@ namespace NadekoBot.Modules.Utility.Commands
UserId = (long)e.User.Id,
ServerId = (long)e.Server.Id
};
await DbHandler.Instance.Connection.InsertAsync(rem).ConfigureAwait(false);
DbHandler.Instance.Connection.Insert(rem);
reminders.Add(StartNewReminder(rem));