!m save and !m load work properly now, Music is much less spammy

This commit is contained in:
Master Kwoth 2016-04-09 15:21:19 +02:00
parent c7ffb98391
commit 873037a238
9 changed files with 81 additions and 38 deletions

View File

@ -143,13 +143,10 @@ namespace NadekoBot.Classes
{ {
using (var conn = new SQLiteConnection(FilePath)) using (var conn = new SQLiteConnection(FilePath))
{ {
conn.RunInTransaction(() => foreach (var o in ocol)
{ {
foreach (var o in ocol) conn.InsertOrReplace(o, typeof(T));
{ }
conn.InsertOrReplace(o, typeof(T));
}
});
} }
} }

View File

@ -83,10 +83,7 @@ namespace NadekoBot.Classes.Music
else else
await Task.Delay(100, cancelToken); await Task.Delay(100, cancelToken);
else else
{
attempt = 0; attempt = 0;
await Task.Delay(5, cancelToken);
}
await songBuffer.WriteAsync(buffer, read, cancelToken); await songBuffer.WriteAsync(buffer, read, cancelToken);
if (songBuffer.ContentLength > 2.MB()) if (songBuffer.ContentLength > 2.MB())
prebufferingComplete = true; prebufferingComplete = true;
@ -218,6 +215,7 @@ namespace NadekoBot.Classes.Music
Title = Path.GetFileNameWithoutExtension(query), Title = Path.GetFileNameWithoutExtension(query),
Provider = "Local File", Provider = "Local File",
ProviderType = musicType, ProviderType = musicType,
Query = query,
}); });
case MusicType.Radio: case MusicType.Radio:
return new Song(new SongInfo return new Song(new SongInfo
@ -226,6 +224,7 @@ namespace NadekoBot.Classes.Music
Title = $"{query}", Title = $"{query}",
Provider = "Radio Stream", Provider = "Radio Stream",
ProviderType = musicType, ProviderType = musicType,
Query = query
}); });
} }
if (SoundCloud.Default.IsSoundCloudLink(query)) if (SoundCloud.Default.IsSoundCloudLink(query))
@ -240,10 +239,10 @@ namespace NadekoBot.Classes.Music
Query = query, Query = query,
}); });
} }
var links = await SearchHelper.FindYoutubeUrlByKeywords(query); var link = await SearchHelper.FindYoutubeUrlByKeywords(query);
if (links == String.Empty) if (link == String.Empty)
throw new OperationCanceledException("Not a valid youtube query."); throw new OperationCanceledException("Not a valid youtube query.");
var allVideos = await Task.Factory.StartNew(async () => await YouTube.Default.GetAllVideosAsync(links)).Unwrap(); var allVideos = await Task.Factory.StartNew(async () => await YouTube.Default.GetAllVideosAsync(link)).Unwrap();
var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio);
var video = videos var video = videos
.Where(v => v.AudioBitrate < 192) .Where(v => v.AudioBitrate < 192)
@ -257,7 +256,7 @@ namespace NadekoBot.Classes.Music
Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube"
Provider = "YouTube", Provider = "YouTube",
Uri = video.Uri, Uri = video.Uri,
Query = query, Query = link,
ProviderType = musicType, ProviderType = musicType,
}); });
} }

View File

@ -1,10 +1,12 @@
using SQLite; using SQLite;
using System; using System;
namespace NadekoBot.Classes._DataModels { namespace NadekoBot.Classes._DataModels
internal abstract class IDataModel { {
internal abstract class IDataModel
{
[PrimaryKey, AutoIncrement] [PrimaryKey, AutoIncrement]
public int Id { get; set; } public int? Id { get; set; }
[Newtonsoft.Json.JsonProperty("createdAt")] [Newtonsoft.Json.JsonProperty("createdAt")]
public DateTime DateAdded { get; set; } = DateTime.Now; public DateTime DateAdded { get; set; } = DateTime.Now;
public IDataModel() { } public IDataModel() { }

View File

@ -1,4 +1,6 @@
namespace NadekoBot.Classes._DataModels using SQLite;
namespace NadekoBot.Classes._DataModels
{ {
internal class SongInfo : IDataModel internal class SongInfo : IDataModel
{ {
@ -6,6 +8,7 @@
public int ProviderType { get; internal set; } public int ProviderType { get; internal set; }
public string Title { get; internal set; } public string Title { get; internal set; }
public string Uri { get; internal set; } public string Uri { get; internal set; }
[Unique]
public string Query { get; internal set; } public string Query { get; internal set; }
} }
} }

View File

@ -63,7 +63,7 @@ namespace NadekoBot.Modules.Administration.Commands
} }
finally finally
{ {
DbHandler.Instance.Delete<Reminder>(r.Id); DbHandler.Instance.Delete<Reminder>(r.Id.Value);
t.Stop(); t.Stop();
t.Dispose(); t.Dispose();
} }

View File

@ -49,7 +49,7 @@ namespace NadekoBot.Modules
manager.CreateCommands(Prefix, cgb => manager.CreateCommands(Prefix, cgb =>
{ {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb)); commands.ForEach(cmd => cmd.Init(cgb));
@ -113,6 +113,11 @@ namespace NadekoBot.Modules
.Do(async e => .Do(async e =>
{ {
await QueueSong(e.Channel, e.User.VoiceChannel, e.GetArg("query")); await QueueSong(e.Channel, e.User.VoiceChannel, e.GetArg("query"));
if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
{
await Task.Delay(10000);
await e.Message.Delete();
}
}); });
cgb.CreateCommand("lq") cgb.CreateCommand("lq")
@ -272,7 +277,7 @@ namespace NadekoBot.Modules
cgb.CreateCommand("lopl") cgb.CreateCommand("lopl")
.Description("Queues up to 50 songs from a directory. **Owner Only!**\n**Usage**: `!m lopl C:/music/classical`") .Description("Queues up to 50 songs from a directory. **Owner Only!**\n**Usage**: `!m lopl C:/music/classical`")
.Parameter("directory", ParameterType.Unparsed) .Parameter("directory", ParameterType.Unparsed)
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e => .Do(async e =>
{ {
var arg = e.GetArg("directory"); var arg = e.GetArg("directory");
@ -301,12 +306,17 @@ namespace NadekoBot.Modules
return; return;
} }
await QueueSong(e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio); await QueueSong(e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio);
if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
{
await Task.Delay(10000);
await e.Message.Delete();
}
}); });
cgb.CreateCommand("lo") cgb.CreateCommand("lo")
.Description("Queues a local file by specifying a full path. **Owner Only!**\n**Usage**: `!m ra C:/music/mysong.mp3`") .Description("Queues a local file by specifying a full path. **Owner Only!**\n**Usage**: `!m ra C:/music/mysong.mp3`")
.Parameter("path", ParameterType.Unparsed) .Parameter("path", ParameterType.Unparsed)
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e => .Do(async e =>
{ {
var arg = e.GetArg("path"); var arg = e.GetArg("path");
@ -350,9 +360,9 @@ namespace NadekoBot.Modules
} }
if (num <= 0 || num > musicPlayer.Playlist.Count) if (num <= 0 || num > musicPlayer.Playlist.Count)
return; return;
var song = (musicPlayer.Playlist as List<Song>)?[num - 1];
musicPlayer.RemoveSongAt(num - 1); musicPlayer.RemoveSongAt(num - 1);
await e.Channel.SendMessage($"🎵**Track at position `#{num}` has been removed.**"); await e.Channel.SendMessage($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**");
}); });
cgb.CreateCommand("cleanup") cgb.CreateCommand("cleanup")
@ -434,8 +444,8 @@ namespace NadekoBot.Modules
ProviderType = (int)s.SongInfo.ProviderType, ProviderType = (int)s.SongInfo.ProviderType,
Title = s.SongInfo.Title, Title = s.SongInfo.Title,
Uri = s.SongInfo.Uri, Uri = s.SongInfo.Uri,
Query = s.SongInfo.Query Query = s.SongInfo.Query,
}); }).ToList();
var playlist = new MusicPlaylist var playlist = new MusicPlaylist
{ {
@ -443,19 +453,28 @@ namespace NadekoBot.Modules
CreatorName = e.User.Name, CreatorName = e.User.Name,
Name = name.ToLowerInvariant(), Name = name.ToLowerInvariant(),
}; };
DbHandler.Instance.SaveAll(songInfos); DbHandler.Instance.SaveAll(songInfos);
DbHandler.Instance.Save(playlist); DbHandler.Instance.Save(playlist);
DbHandler.Instance.InsertMany(songInfos.Select(s => new PlaylistSongInfo DbHandler.Instance.InsertMany(songInfos.Select(s => new PlaylistSongInfo
{ {
PlaylistId = playlist.Id, PlaylistId = playlist.Id.Value,
SongInfoId = s.Id SongInfoId = s.Id.Value
})); }));
await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`"); await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`");
}); });
//cgb.CreateCommand("info")
// .Description("Prints music info (queued/finished/playing) only to this channel")
// .Do(async e =>
// {
// MusicPlayer musicPlayer;
// if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
// return;
// musicPlayer
// });
cgb.CreateCommand("load") cgb.CreateCommand("load")
.Description("Loads a playlist under a certain name. \n**Usage**: `!m load classical-1`") .Description("Loads a playlist under a certain name. \n**Usage**: `!m load classical-1`")
.Parameter("name", ParameterType.Unparsed) .Parameter("name", ParameterType.Unparsed)
@ -531,11 +550,19 @@ namespace NadekoBot.Modules
if (DefaultMusicVolumes.TryGetValue(server.Id, out throwAway)) if (DefaultMusicVolumes.TryGetValue(server.Id, out throwAway))
vol = throwAway; vol = throwAway;
var mp = new MusicPlayer(voiceCh, vol); var mp = new MusicPlayer(voiceCh, vol);
Message playingMessage = null;
Message lastFinishedMessage = null;
mp.OnCompleted += async (s, song) => mp.OnCompleted += async (s, song) =>
{ {
try try
{ {
await textCh.SendMessage($"🎵`Finished`{song.PrettyName}"); if (lastFinishedMessage != null)
await lastFinishedMessage.Delete();
if (playingMessage != null)
await playingMessage.Delete();
lastFinishedMessage = await textCh.SendMessage($"🎵`Finished`{song.PrettyName}");
} }
catch { } catch { }
}; };
@ -547,7 +574,7 @@ namespace NadekoBot.Modules
try try
{ {
var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`"; var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`";
await textCh.SendMessage(msgTxt); playingMessage = await textCh.SendMessage(msgTxt);
} }
catch { } catch { }
}; };
@ -555,9 +582,23 @@ namespace NadekoBot.Modules
}); });
var resolvedSong = await Song.ResolveSong(query, musicType); var resolvedSong = await Song.ResolveSong(query, musicType);
resolvedSong.MusicPlayer = musicPlayer; resolvedSong.MusicPlayer = musicPlayer;
if (!silent)
await textCh.Send($"🎵`Queued`{resolvedSong.PrettyName}");
musicPlayer.AddSong(resolvedSong); musicPlayer.AddSong(resolvedSong);
if (!silent)
{
var queuedMessage = await textCh.SendMessage($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count}`");
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(async () =>
{
await Task.Delay(10000);
try
{
await queuedMessage.Delete();
}
catch { }
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
} }
} }
} }

View File

@ -20,7 +20,7 @@ namespace NadekoBot.Modules.Pokemon
public PokemonModule() public PokemonModule()
{ {
} }
private int GetDamage(PokemonType usertype, PokemonType targetType) private int GetDamage(PokemonType usertype, PokemonType targetType)
@ -35,7 +35,7 @@ namespace NadekoBot.Modules.Pokemon
damage = (int)(damage * multiplier); damage = (int)(damage * multiplier);
} }
} }
return damage; return damage;
} }
@ -50,12 +50,12 @@ namespace NadekoBot.Modules.Pokemon
} }
int count = NadekoBot.Config.PokemonTypes.Count; int count = NadekoBot.Config.PokemonTypes.Count;
int remainder = Math.Abs((int)(id % (ulong) count)); int remainder = Math.Abs((int)(id % (ulong)count));
return NadekoBot.Config.PokemonTypes[remainder]; return NadekoBot.Config.PokemonTypes[remainder];
} }
private PokemonType stringToPokemonType(string v) private PokemonType stringToPokemonType(string v)
{ {
@ -311,7 +311,7 @@ namespace NadekoBot.Modules.Pokemon
FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount); FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount);
//Actually changing the type here //Actually changing the type here
var preTypes = DbHandler.Instance.GetAllRows<UserPokeTypes>(); var preTypes = DbHandler.Instance.GetAllRows<UserPokeTypes>();
Dictionary<long, int> Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id); 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

View File

@ -167,7 +167,7 @@ namespace NadekoBot
modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None);
modules.Add(new GamesModule(), "Games", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None);
//modules.Add(new Music(), "Music", ModuleFilter.None); modules.Add(new Music(), "Music", ModuleFilter.None);
modules.Add(new Searches(), "Searches", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None);
modules.Add(new NSFW(), "NSFW", ModuleFilter.None); modules.Add(new NSFW(), "NSFW", ModuleFilter.None);
modules.Add(new ClashOfClans(), "ClashOfClans", ModuleFilter.None); modules.Add(new ClashOfClans(), "ClashOfClans", ModuleFilter.None);

View File

@ -1,6 +1,7 @@
{ {
"Username": "myemail@email.com", "Username": "myemail@email.com",
"Password": "xxxxxxx", "Password": "xxxxxxx",
"Token": "",
"BotId": 1231231231231, "BotId": 1231231231231,
"GoogleAPIKey": "", "GoogleAPIKey": "",
"OwnerIds": [ "OwnerIds": [