From 0c7d077df12eb9583b10a747d87bd5733ab091e7 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Mon, 24 Oct 2016 23:05:49 +0200 Subject: [PATCH] Playing status fixed? Added a lot of catches to try to fix the error --- .../Modules/Administration/Administration.cs | 4 +- .../Commands/AntiRaidCommands.cs | 32 +++++---- .../Commands/AutoAssignRoleCommands.cs | 26 ++++--- .../Commands/CrossServerTextChannel.cs | 18 ++--- .../Administration/Commands/LogCommand.cs | 69 +++++++++++-------- .../Commands/PlayingRotateCommands.cs | 4 +- .../Commands/VoicePlusTextCommands.cs | 3 +- .../Modules/Gambling/Commands/AnimalRacing.cs | 1 + .../Gambling/Commands/DiceRollCommand.cs | 12 ++-- .../Games/Commands/Trivia/TriviaGame.cs | 2 +- src/NadekoBot/Modules/Music/Classes/Song.cs | 2 +- src/NadekoBot/Modules/Music/Music.cs | 3 +- .../Permissions/Commands/CmdCdsCommands.cs | 8 ++- .../Searches/Commands/AnimeSearchCommands.cs | 4 +- src/NadekoBot/ShardedDiscordClient.cs | 17 +++++ 15 files changed, 125 insertions(+), 80 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 86522f30..28a68c1b 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -749,7 +749,7 @@ namespace NadekoBot.Modules.Administration game = game ?? ""; - await NadekoBot.Client.GetCurrentUser().ModifyStatusAsync(u => u.Game = new Game(game)).ConfigureAwait(false); + await NadekoBot.Client.SetGame(game).ConfigureAwait(false); await channel.SendMessageAsync("`New game set.`").ConfigureAwait(false); } @@ -763,7 +763,7 @@ namespace NadekoBot.Modules.Administration name = name ?? ""; - await NadekoBot.Client.GetCurrentUser().ModifyStatusAsync(u => u.Game = new Game(name, url, StreamType.Twitch)).ConfigureAwait(false); + await NadekoBot.Client.SetStream(name, url).ConfigureAwait(false); await channel.SendMessageAsync("`New stream set.`").ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 1bc1e041..2550a94d 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -101,23 +101,25 @@ namespace NadekoBot.Modules.Administration var t = Task.Run(async () => { - AntiSpamSetting spamSettings; - if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings)) - return; - - var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, new UserSpamStats(msg.Content), - (id, old) => { old.ApplyNextMessage(msg.Content); return old; }); - - if (stats.Count >= spamSettings.MessageThreshold) + try { - if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats)) - { - var log = await PunishUser((IGuildUser)msg.Author, spamSettings.Action, spamSettings.MuteRole, ProtectionType.Spamming) - .ConfigureAwait(false); - try { await channel.Guild.SendMessageToOwnerAsync(log).ConfigureAwait(false); } catch { } - } - } + AntiSpamSetting spamSettings; + if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings)) + return; + var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, new UserSpamStats(msg.Content), + (id, old) => { old.ApplyNextMessage(msg.Content); return old; }); + + if (stats.Count >= spamSettings.MessageThreshold) + { + if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats)) + { + var log = await PunishUser((IGuildUser)msg.Author, spamSettings.Action, spamSettings.MuteRole, ProtectionType.Spamming) + .ConfigureAwait(false); + await channel.Guild.SendMessageToOwnerAsync(log).ConfigureAwait(false); } + } + } + catch { } }); return Task.CompletedTask; }; diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 47abda51..4a159152 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -27,19 +27,23 @@ namespace NadekoBot.Modules.Administration { var t = Task.Run(async () => { - GuildConfig conf; - using (var uow = DbHandler.UnitOfWork()) + try { - conf = uow.GuildConfigs.For(user.Guild.Id); + GuildConfig conf; + using (var uow = DbHandler.UnitOfWork()) + { + conf = uow.GuildConfigs.For(user.Guild.Id); + } + + if (conf.AutoAssignRoleId == 0) + return; + + var role = user.Guild.Roles.FirstOrDefault(r => r.Id == conf.AutoAssignRoleId); + + if (role != null) + await user.AddRolesAsync(role); } - - if (conf.AutoAssignRoleId == 0) - return; - - var role = user.Guild.Roles.FirstOrDefault(r => r.Id == conf.AutoAssignRoleId); - - if (role != null) - try { await user.AddRolesAsync(role); } catch (Exception ex) { _log.Warn(ex); } + catch (Exception ex) { _log.Warn(ex); } }); return Task.CompletedTask; }; diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index b6f3a612..b691e86c 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -36,17 +36,17 @@ namespace NadekoBot.Modules.Administration Task.Run(async () => { - if (msg.Author.Id == NadekoBot.Client.GetCurrentUser().Id) return; - foreach (var subscriber in Subscribers) + if (msg.Author.Id == NadekoBot.Client.GetCurrentUser().Id) return; + foreach (var subscriber in Subscribers) + { + var set = subscriber.Value; + if (!set.Contains(msg.Channel)) + continue; + foreach (var chan in set.Except(new[] { channel })) { - var set = subscriber.Value; - if (!set.Contains(msg.Channel)) - continue; - foreach (var chan in set.Except(new[] { channel })) - { - try { await chan.SendMessageAsync(GetText(channel.Guild, channel, (IGuildUser)msg.Author, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } - } + try { await chan.SendMessageAsync(GetText(channel.Guild, channel, (IGuildUser)msg.Author, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } + } }); return Task.CompletedTask; }; diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index a4fa6baa..24ef2e45 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -90,29 +90,33 @@ namespace NadekoBot.Modules.Administration var task = Task.Run(async () => { - string str = $"🕔`{prettyCurrentTime}`"; - if (before.Username != after.Username) - str += $"**Name Changed**👤`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; - else if (before.Nickname != after.Nickname) - str += $"**Nickname Changed**👤`{before.Username}#{before.Discriminator}`\n\t\t`Old:` {before.Nickname}#{before.Discriminator}\n\t\t`New:` {after.Nickname}#{after.Discriminator}"; - else if (before.AvatarUrl != after.AvatarUrl) - str += $"**Avatar Changed**👤`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; - else if (!before.Roles.SequenceEqual(after.Roles)) + try { - if (before.Roles.Count() < after.Roles.Count()) + string str = $"🕔`{prettyCurrentTime}`"; + if (before.Username != after.Username) + str += $"**Name Changed**👤`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; + else if (before.Nickname != after.Nickname) + str += $"**Nickname Changed**👤`{before.Username}#{before.Discriminator}`\n\t\t`Old:` {before.Nickname}#{before.Discriminator}\n\t\t`New:` {after.Nickname}#{after.Discriminator}"; + else if (before.AvatarUrl != after.AvatarUrl) + str += $"**Avatar Changed**👤`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; + else if (!before.Roles.SequenceEqual(after.Roles)) { - var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => "`" + r.Name + "`"); - str += $"**User's Roles changed ⚔➕**👤`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; - } - else if (before.Roles.Count() > after.Roles.Count()) - { - var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r)).Select(r => "`" + r.Name + "`"); - str += $"**User's Roles changed ⚔➖**👤`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; + if (before.Roles.Count() < after.Roles.Count()) + { + var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => "`" + r.Name + "`"); + str += $"**User's Roles changed ⚔➕**👤`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; + } + else if (before.Roles.Count() > after.Roles.Count()) + { + var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r)).Select(r => "`" + r.Name + "`"); + str += $"**User's Roles changed ⚔➖**👤`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; + } } + else + return; + try { await logChannel.SendMessageAsync(str).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } - else - return; - try { await logChannel.SendMessageAsync(str).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + catch { } }); return Task.CompletedTask; @@ -138,14 +142,18 @@ namespace NadekoBot.Modules.Administration var task = Task.Run(async () => { - if (before.Name != after.Name) - await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Name Changed** `#{after.Name}` ({after.Id}) + try + { + if (before.Name != after.Name) + await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Name Changed** `#{after.Name}` ({after.Id}) `Old:` {before.Name} `New:` {after.Name}").ConfigureAwait(false); - else if ((before as ITextChannel).Topic != (after as ITextChannel).Topic) - await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Topic Changed** `#{after.Name}` ({after.Id}) + else if ((before as ITextChannel).Topic != (after as ITextChannel).Topic) + await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Topic Changed** `#{after.Name}` ({after.Id}) `Old:` {((ITextChannel)before).Topic} `New:` {((ITextChannel)after).Topic}").ConfigureAwait(false); + } + catch { } }); return Task.CompletedTask; @@ -365,11 +373,15 @@ namespace NadekoBot.Modules.Administration var task = Task.Run(async () => { - var str = $@"🕔`{prettyCurrentTime}` **Message** 🚮 `#{channel.Name}` -👤`{msg.Author.Username}`: {msg.Resolve(userHandling:UserMentionHandling.NameAndDiscriminator)}"; - if (msg.Attachments.Any()) - str += $"{Environment.NewLine}`Attachements`: {string.Join(", ", msg.Attachments.Select(a => a.ProxyUrl))}"; - try { await logChannel.SendMessageAsync(str).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try + { + var str = $@"🕔`{prettyCurrentTime}` **Message** 🚮 `#{channel.Name}` +👤`{msg.Author.Username}`: {msg.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator)}"; + if (msg.Attachments.Any()) + str += $"{Environment.NewLine}`Attachements`: {string.Join(", ", msg.Attachments.Select(a => a.ProxyUrl))}"; + await logChannel.SendMessageAsync(str).ConfigureAwait(false); + } + catch (Exception ex) { _log.Warn(ex); } }); return Task.CompletedTask; @@ -377,6 +389,7 @@ namespace NadekoBot.Modules.Administration private Task _client_MessageUpdated(Optional optmsg, IMessage imsg2) { + throw new ArgumentException(); var after = imsg2 as IUserMessage; if (after == null || after.IsAuthor()) return Task.CompletedTask; diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs index bf6030bb..41d7201f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs @@ -58,9 +58,7 @@ namespace NadekoBot.Modules.Administration if (string.IsNullOrWhiteSpace(status)) continue; PlayingPlaceholders.ForEach(e => status = status.Replace(e.Key, e.Value())); - await (await NadekoBot.Client.GetCurrentUserAsync()) - .ModifyStatusAsync(mpp => mpp.Game = new Game(status)) - .ConfigureAwait(false); + await NadekoBot.Client.SetGame(status); } } catch (Exception ex) diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 71414d37..d74b7a9f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -39,9 +39,10 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; var task = Task.Run(async () => { - var botUserPerms = guild.GetCurrentUser().GuildPermissions; try { + var botUserPerms = guild.GetCurrentUser().GuildPermissions; + if (before.VoiceChannel == after.VoiceChannel) return; if (!voicePlusTextCache.Contains(guild.Id)) diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index bf29c2bf..a849f702 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -186,6 +186,7 @@ namespace NadekoBot.Modules.Gambling await Task.Delay(2500); } } + catch { } finally { NadekoBot.Client.MessageReceived -= Client_MessageReceived; diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index e3ca136c..73c650c0 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -35,10 +35,14 @@ namespace NadekoBot.Modules.Gambling var num2 = gen % 10; var imageStream = await Task.Run(() => { - var ms = new MemoryStream(); - new[] { GetDice(num1), GetDice(num2) }.Merge().SaveAsPng(ms); - ms.Position = 0; - return ms; + try + { + var ms = new MemoryStream(); + new[] { GetDice(num1), GetDice(num2) }.Merge().SaveAsPng(ms); + ms.Position = 0; + return ms; + } + catch { return new MemoryStream(); } }); await channel.SendFileAsync(imageStream, "dice.png", $"{umsg.Author.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs index dbc56b74..a52b8122 100644 --- a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs @@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Games.Trivia this.guild = guild; this.channel = channel; WinRequirement = winReq; - Task.Run(StartGame); + Task.Run(async () => { try { await StartGame().ConfigureAwait(false); } catch { } }); } private async Task StartGame() diff --git a/src/NadekoBot/Modules/Music/Classes/Song.cs b/src/NadekoBot/Modules/Music/Classes/Song.cs index 6c8a694c..9e83ff14 100644 --- a/src/NadekoBot/Modules/Music/Classes/Song.cs +++ b/src/NadekoBot/Modules/Music/Classes/Song.cs @@ -306,7 +306,7 @@ namespace NadekoBot.Modules.Music.Classes var link = (await NadekoBot.Google.GetVideosByKeywordsAsync(query).ConfigureAwait(false)).FirstOrDefault(); if (string.IsNullOrWhiteSpace(link)) throw new OperationCanceledException("Not a valid youtube query."); - var allVideos = await Task.Run(async () => await YouTube.Default.GetAllVideosAsync(link).ConfigureAwait(false)).ConfigureAwait(false); + var allVideos = await Task.Run(async () => { try { return await YouTube.Default.GetAllVideosAsync(link).ConfigureAwait(false); } catch { return Enumerable.Empty(); } }).ConfigureAwait(false); var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); var video = videos .Where(v => v.AudioBitrate < 192) diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index 6b58d21b..70af561d 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -799,9 +799,10 @@ namespace NadekoBot.Modules.Music var queuedMessage = await textCh.SendMessageAsync($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); var t = Task.Run(async () => { - await Task.Delay(10000).ConfigureAwait(false); try { + await Task.Delay(10000).ConfigureAwait(false); + await queuedMessage.DeleteAsync().ConfigureAwait(false); } catch { } diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index 6f5b2b4a..9cdd092b 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -112,8 +112,12 @@ namespace NadekoBot.Modules.Permissions }); var t = Task.Run(async () => { - await Task.Delay(cdRule.Seconds * 1000); - activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Text.ToLowerInvariant() && ac.UserId == user.Id); + try + { + await Task.Delay(cdRule.Seconds * 1000); + activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Text.ToLowerInvariant() && ac.UserId == user.Id); + } + catch { } }); } } diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index 27320f0d..5b8d8f5d 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -72,7 +72,7 @@ namespace NadekoBot.Modules.Searches var smallObj = JArray.Parse(res)[0]; var aniData = await http.GetStringAsync("http://anilist.co/api/anime/" + smallObj["id"] + $"?access_token={anilistToken}").ConfigureAwait(false); - return await Task.Run(() => JsonConvert.DeserializeObject(aniData)).ConfigureAwait(false); + return await Task.Run(() => { try { return JsonConvert.DeserializeObject(aniData); } catch { return null; } }).ConfigureAwait(false); } } catch (Exception ex) { @@ -118,7 +118,7 @@ namespace NadekoBot.Modules.Searches var smallObj = JArray.Parse(res)[0]; var aniData = await http.GetStringAsync("http://anilist.co/api/manga/" + smallObj["id"] + $"?access_token={anilistToken}").ConfigureAwait(false); - return await Task.Run(() => JsonConvert.DeserializeObject(aniData)).ConfigureAwait(false); + return await Task.Run(() => { try { return JsonConvert.DeserializeObject(aniData); } catch { return null; } }).ConfigureAwait(false); } } catch (Exception ex) diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index b119df42..afe84ca2 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -9,6 +9,7 @@ using Discord.API; using Discord.Logging; using System.IO; using NLog; +using NadekoBot.Extensions; namespace NadekoBot { @@ -70,6 +71,9 @@ namespace NadekoBot public Task GetCurrentUserAsync() => Clients[0].GetCurrentUserAsync(); + public Task GetAllCurrentUsersAsync() => + Task.WhenAll(Clients.Select(c => c.GetCurrentUserAsync())); + public IReadOnlyCollection GetGuilds() => Clients.SelectMany(c => c.GetGuilds()).ToArray(); @@ -87,5 +91,18 @@ namespace NadekoBot internal Task DownloadAllUsersAsync() => Task.WhenAll(Clients.Select(async c => { await c.DownloadAllUsersAsync(); _log.Info($"Shard #{c.ShardId} downloaded {c.GetGuilds().Sum(g => g.GetUsers().Count)} users."); })); + + public async Task SetGame(string game) + { + await Task.WhenAll((await GetAllCurrentUsersAsync()) + .Select(u => u.ModifyStatusAsync(ms => ms.Game = new Discord.Game(game)))); + } + + public async Task SetStream(string name, string url) + { + await Task.WhenAll((await GetAllCurrentUsersAsync()) + .Select(u => u.ModifyStatusAsync(ms => ms.Game = new Discord.Game(name, url, StreamType.Twitch)))); + + } } }