Made events run async where needed, fixed .startevent flowerreaction and running commands in DMs

This commit is contained in:
Master Kwoth 2017-06-06 00:46:58 +02:00
parent ec5a5c42a9
commit fa29131818
26 changed files with 1089 additions and 931 deletions

View File

@ -0,0 +1,34 @@
[16:25-2017-06-05]
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: The server name or address could not be resolved
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext()
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClient.<FinishSendAsync>d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClient.<GetContentAsync>d__32`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at NadekoBot.Modules.Searches.Searches.JokeCommands.<Randjoke>d__3.MoveNext() in C:\Users\Kwoth\Documents\projekti\NadekoBot1.0\src\NadekoBot\Modules\Searches\Commands\JokeCommands.cs:line 40
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Discord.Commands.ModuleClassBuilder.<>c__DisplayClass6_1.<<BuildCommand>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Discord.Commands.CommandInfo.<ExecuteAsyncInternal>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Discord.Commands.CommandInfo.<ExecuteAsyncInternal>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Discord.Commands.CommandInfo.<ExecuteAsync>d__37.MoveNext()
------

View File

@ -16,8 +16,6 @@ namespace NadekoBot.Modules.Administration
[Group] [Group]
public class LocalizationCommands : NadekoSubmodule public class LocalizationCommands : NadekoSubmodule
{ {
//Română, România
//Bahasa Indonesia, Indonesia
private static ImmutableDictionary<string, string> supportedLocales { get; } = new Dictionary<string, string>() private static ImmutableDictionary<string, string> supportedLocales { get; } = new Dictionary<string, string>()
{ {
{"ar", "العربية" }, {"ar", "العربية" },

View File

@ -255,7 +255,7 @@ namespace NadekoBot.Modules.Gambling
return Task.CompletedTask; return Task.CompletedTask;
if ((msg.Author.Id == _client.CurrentUser.Id) || !(imsg.Channel is ITextChannel) || imsg.Channel != _raceChannel) if ((msg.Author.Id == _client.CurrentUser.Id) || !(imsg.Channel is ITextChannel) || imsg.Channel != _raceChannel)
return Task.CompletedTask; return Task.CompletedTask;
_messagesSinceGameStarted++; Interlocked.Increment(ref _messagesSinceGameStarted);
return Task.CompletedTask; return Task.CompletedTask;
} }

View File

@ -194,10 +194,10 @@ namespace NadekoBot.Modules.Gambling
StartingMessage = umsg; StartingMessage = umsg;
_client.MessageDeleted += MessageDeletedEventHandler; _client.MessageDeleted += MessageDeletedEventHandler;
try { await StartingMessage.AddReactionAsync(Emote.Parse("🌸")).ConfigureAwait(false); } try { await StartingMessage.AddReactionAsync(new Emoji("🌸")).ConfigureAwait(false); }
catch catch
{ {
try { await StartingMessage.AddReactionAsync(Emote.Parse("🌸")).ConfigureAwait(false); } try { await StartingMessage.AddReactionAsync(new Emoji("🌸")).ConfigureAwait(false); }
catch catch
{ {
try { await StartingMessage.DeleteAsync().ConfigureAwait(false); } try { await StartingMessage.DeleteAsync().ConfigureAwait(false); }

View File

@ -185,6 +185,9 @@ $@"--
} }
private async Task PotentialAcro(SocketMessage arg) private async Task PotentialAcro(SocketMessage arg)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -281,6 +284,7 @@ $@"--
{ {
_log.Warn(ex); _log.Warn(ex);
} }
});
} }
public async Task End() public async Task End()

View File

@ -118,6 +118,9 @@ namespace NadekoBot.Modules.Games.Hangman
} }
private async Task PotentialGuess(SocketMessage msg) private async Task PotentialGuess(SocketMessage msg)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -190,6 +193,7 @@ namespace NadekoBot.Modules.Games.Hangman
} }
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
} }
public string GetHangman() => $@". ┌─────┐ public string GetHangman() => $@". ┌─────┐

View File

@ -108,6 +108,9 @@ namespace NadekoBot.Modules.Games.Models
} }
private async Task AnswerReceived(SocketMessage imsg) private async Task AnswerReceived(SocketMessage imsg)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -141,6 +144,7 @@ namespace NadekoBot.Modules.Games.Models
} }
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
} }
private bool Judge(int errors, int textLength) => errors <= textLength / 25; private bool Judge(int errors, int textLength) => errors <= textLength / 25;

View File

@ -237,7 +237,7 @@ namespace NadekoBot.Modules.Games
return true; return true;
} }
private Task Client_MessageReceived(Discord.WebSocket.SocketMessage msg) private Task Client_MessageReceived(SocketMessage msg)
{ {
var _ = Task.Run(async () => var _ = Task.Run(async () =>
{ {

View File

@ -179,6 +179,9 @@ namespace NadekoBot.Modules.Games.Trivia
} }
private async Task PotentialGuess(SocketMessage imsg) private async Task PotentialGuess(SocketMessage imsg)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -238,6 +241,7 @@ namespace NadekoBot.Modules.Games.Trivia
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
} }
public string GetLeaderboard() public string GetLeaderboard()

View File

@ -4,13 +4,9 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using NadekoBot.Attributes; using NadekoBot.Attributes;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using NadekoBot.Modules.Searches.Models; using NadekoBot.Services.Searches;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -21,37 +17,11 @@ namespace NadekoBot.Modules.Searches
[Group] [Group]
public class AnimeSearchCommands : NadekoSubmodule public class AnimeSearchCommands : NadekoSubmodule
{ {
private static readonly Timer anilistTokenRefresher; private readonly AnimeSearchService _service;
private static string anilistToken { get; set; }
static AnimeSearchCommands() public AnimeSearchCommands(AnimeSearchService service)
{ {
anilistTokenRefresher = new Timer(async (state) => _service = service;
{
try
{
var headers = new Dictionary<string, string>
{
{"grant_type", "client_credentials"},
{"client_id", "kwoth-w0ki9"},
{"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"},
};
using (var http = new HttpClient())
{
//http.AddFakeHeaders();
http.DefaultRequestHeaders.Clear();
var formContent = new FormUrlEncodedContent(headers);
var response = await http.PostAsync("https://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false);
var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
anilistToken = JObject.Parse(stringContent)["access_token"].ToString();
}
}
catch
{
// ignored
}
}, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(29));
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
@ -171,7 +141,7 @@ namespace NadekoBot.Modules.Searches
if (string.IsNullOrWhiteSpace(query)) if (string.IsNullOrWhiteSpace(query))
return; return;
var animeData = await GetAnimeData(query).ConfigureAwait(false); var animeData = await _service.GetAnimeData(query).ConfigureAwait(false);
if (animeData == null) if (animeData == null)
{ {
@ -198,7 +168,7 @@ namespace NadekoBot.Modules.Searches
if (string.IsNullOrWhiteSpace(query)) if (string.IsNullOrWhiteSpace(query))
return; return;
var mangaData = await GetMangaData(query).ConfigureAwait(false); var mangaData = await _service.GetMangaData(query).ConfigureAwait(false);
if (mangaData == null) if (mangaData == null)
{ {
@ -218,52 +188,6 @@ namespace NadekoBot.Modules.Searches
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
} }
private async Task<AnimeResult> GetAnimeData(string query)
{
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
try
{
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
using (var http = new HttpClient())
{
var res = await http.GetStringAsync(link + $"?access_token={anilistToken}").ConfigureAwait(false);
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(() => { try { return JsonConvert.DeserializeObject<AnimeResult>(aniData); } catch { return null; } }).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_log.Warn(ex, "Failed anime search for {0}", query);
return null;
}
}
private async Task<MangaResult> GetMangaData(string query)
{
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
try
{
using (var http = new HttpClient())
{
var res = await http.GetStringAsync("http://anilist.co/api/manga/search/" + Uri.EscapeUriString(query) + $"?access_token={anilistToken}").ConfigureAwait(false);
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(() => { try { return JsonConvert.DeserializeObject<MangaResult>(aniData); } catch { return null; } }).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_log.Warn(ex, "Failed anime search for {0}", query);
return null;
}
}
} }
} }
} }

View File

@ -132,6 +132,7 @@ namespace NadekoBot
#region Searches #region Searches
var searchesService = new SearchesService(Client, GoogleApi, Db); var searchesService = new SearchesService(Client, GoogleApi, Db);
var streamNotificationService = new StreamNotificationService(Db, Client, Strings); var streamNotificationService = new StreamNotificationService(Db, Client, Strings);
var animeSearchService = new AnimeSearchService();
#endregion #endregion
var clashService = new ClashOfClansService(Client, Db, Localization, Strings); var clashService = new ClashOfClansService(Client, Db, Localization, Strings);
@ -184,6 +185,7 @@ namespace NadekoBot
.Add(converterService) .Add(converterService)
.Add<SearchesService>(searchesService) .Add<SearchesService>(searchesService)
.Add(streamNotificationService) .Add(streamNotificationService)
.Add(animeSearchService)
.Add<ClashOfClansService>(clashService) .Add<ClashOfClansService>(clashService)
.Add<MusicService>(musicService) .Add<MusicService>(musicService)
.Add<GreetSettingsService>(greetSettingsService) .Add<GreetSettingsService>(greetSettingsService)

View File

@ -31,6 +31,9 @@
<ItemGroup> <ItemGroup>
<Compile Remove="data\**\*;credentials.json" /> <Compile Remove="data\**\*;credentials.json" />
<Compile Remove="Modules\Utility\Models\**" />
<EmbeddedResource Remove="Modules\Utility\Models\**" />
<None Remove="Modules\Utility\Models\**" />
<None Update="credentials_example.json"> <None Update="credentials_example.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
@ -87,6 +90,5 @@
<ItemGroup> <ItemGroup>
<Folder Include="Modules\Music\Classes\" /> <Folder Include="Modules\Music\Classes\" />
<Folder Include="Modules\Utility\Models\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -5,6 +5,7 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Services.Administration namespace NadekoBot.Services.Administration
{ {
@ -25,7 +26,9 @@ namespace NadekoBot.Services.Administration
gcs.Where(x => x.AutoAssignRoleId != 0) gcs.Where(x => x.AutoAssignRoleId != 0)
.ToDictionary(k => k.GuildId, v => v.AutoAssignRoleId)); .ToDictionary(k => k.GuildId, v => v.AutoAssignRoleId));
_client.UserJoined += async (user) => _client.UserJoined += (user) =>
{
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -40,6 +43,8 @@ namespace NadekoBot.Services.Administration
await user.AddRoleAsync(role).ConfigureAwait(false); await user.AddRoleAsync(role).ConfigureAwait(false);
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
return Task.CompletedTask;
}; };
} }
} }

View File

@ -95,6 +95,9 @@ namespace NadekoBot.Services.Administration
_strings.GetText(key, guild.Id, "Administration".ToLowerInvariant(), replacements); _strings.GetText(key, guild.Id, "Administration".ToLowerInvariant(), replacements);
private async Task _client_UserUpdated(SocketUser before, SocketUser uAfter) private async Task _client_UserUpdated(SocketUser before, SocketUser uAfter)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -160,9 +163,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) private async Task _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -204,9 +211,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async void MuteCommands_UserMuted(IGuildUser usr, MuteType muteType) private async void MuteCommands_UserMuted(IGuildUser usr, MuteType muteType)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -243,9 +254,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async void MuteCommands_UserUnmuted(IGuildUser usr, MuteType muteType) private async void MuteCommands_UserUnmuted(IGuildUser usr, MuteType muteType)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -283,9 +298,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
public async Task TriggeredAntiProtection(PunishmentAction action, ProtectionType protection, params IGuildUser[] users) public async Task TriggeredAntiProtection(PunishmentAction action, ProtectionType protection, params IGuildUser[] users)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -328,9 +347,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_GuildUserUpdated(SocketGuildUser before, SocketGuildUser after) private async Task _client_GuildUserUpdated(SocketGuildUser before, SocketGuildUser after)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -373,9 +396,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_ChannelUpdated(IChannel cbefore, IChannel cafter) private async Task _client_ChannelUpdated(IChannel cbefore, IChannel cafter)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -420,9 +447,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_ChannelDestroyed(IChannel ich) private async Task _client_ChannelDestroyed(IChannel ich)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -455,9 +486,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_ChannelCreated(IChannel ich) private async Task _client_ChannelCreated(IChannel ich)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -486,9 +521,13 @@ namespace NadekoBot.Services.Administration
.WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false); .WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false);
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
} }
private async Task _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) private async Task _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -536,9 +575,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_UserPresenceUpdated(Optional<SocketGuild> optGuild, SocketUser usr, SocketPresence before, SocketPresence after) private async Task _client_UserPresenceUpdated(Optional<SocketGuild> optGuild, SocketUser usr, SocketPresence before, SocketPresence after)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -575,9 +618,13 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_UserLeft(IGuildUser usr) private async Task _client_UserLeft(IGuildUser usr)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -601,9 +648,12 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
private async Task _client_UserJoined(IGuildUser usr) private Task _client_UserJoined(IGuildUser usr)
{
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -624,9 +674,14 @@ namespace NadekoBot.Services.Administration
.WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false); .WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false);
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
return Task.CompletedTask;
} }
private async Task _client_UserUnbanned(IUser usr, IGuild guild) private async Task _client_UserUnbanned(IUser usr, IGuild guild)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -647,9 +702,13 @@ namespace NadekoBot.Services.Administration
.WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false); .WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false);
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
} }
private async Task _client_UserBanned(IUser usr, IGuild guild) private async Task _client_UserBanned(IUser usr, IGuild guild)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -669,11 +728,14 @@ namespace NadekoBot.Services.Administration
.WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false); .WithFooter(efb => efb.WithText(CurrentTime))).ConfigureAwait(false);
} }
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
});
} }
private async Task _client_MessageDeleted(Cacheable<IMessage, ulong> optMsg, ISocketMessageChannel ch) private async Task _client_MessageDeleted(Cacheable<IMessage, ulong> optMsg, ISocketMessageChannel ch)
{ {
await Task.Yield();
var _ = Task.Run(async () =>
{
try try
{ {
var msg = (optMsg.HasValue ? optMsg.Value : null) as IUserMessage; var msg = (optMsg.HasValue ? optMsg.Value : null) as IUserMessage;
@ -709,9 +771,13 @@ namespace NadekoBot.Services.Administration
_log.Warn(ex); _log.Warn(ex);
// ignored // ignored
} }
});
} }
private async Task _client_MessageUpdated(Cacheable<IMessage, ulong> optmsg, SocketMessage imsg2, ISocketMessageChannel ch) private async Task _client_MessageUpdated(Cacheable<IMessage, ulong> optmsg, SocketMessage imsg2, ISocketMessageChannel ch)
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -754,6 +820,7 @@ namespace NadekoBot.Services.Administration
{ {
// ignored // ignored
} }
});
} }
public enum LogType public enum LogType

View File

@ -71,20 +71,21 @@ namespace NadekoBot.Services.Administration
_client.UserJoined += Client_UserJoined; _client.UserJoined += Client_UserJoined;
} }
private async Task Client_UserJoined(IGuildUser usr) private Task Client_UserJoined(IGuildUser usr)
{ {
try try
{ {
MutedUsers.TryGetValue(usr.Guild.Id, out ConcurrentHashSet<ulong> muted); MutedUsers.TryGetValue(usr.Guild.Id, out ConcurrentHashSet<ulong> muted);
if (muted == null || !muted.Contains(usr.Id)) if (muted == null || !muted.Contains(usr.Id))
return; return Task.CompletedTask;
await MuteUser(usr).ConfigureAwait(false); Task.Run(() => MuteUser(usr).ConfigureAwait(false));
} }
catch (Exception ex) catch (Exception ex)
{ {
LogManager.GetCurrentClassLogger().Warn(ex); _log.Warn(ex);
} }
return Task.CompletedTask;
} }
public async Task MuteUser(IGuildUser usr, MuteType type = MuteType.All) public async Task MuteUser(IGuildUser usr, MuteType type = MuteType.All)

View File

@ -258,7 +258,7 @@ namespace NadekoBot.Services
break; break;
} }
} }
var prefix = GetPrefix(guild.Id); var prefix = GetPrefix(guild?.Id);
// execute the command and measure the time it took // execute the command and measure the time it took
if (messageContent.StartsWith(prefix)) if (messageContent.StartsWith(prefix))
{ {

View File

@ -99,6 +99,7 @@ namespace NadekoBot.Services.Games
private async Task PotentialFlowerGeneration(SocketMessage imsg) private async Task PotentialFlowerGeneration(SocketMessage imsg)
{ {
await Task.Yield();
var msg = imsg as SocketUserMessage; var msg = imsg as SocketUserMessage;
if (msg == null || msg.Author.IsBot) if (msg == null || msg.Author.IsBot)
return; return;
@ -110,6 +111,8 @@ namespace NadekoBot.Services.Games
if (!GenerationChannels.Contains(channel.Id)) if (!GenerationChannels.Contains(channel.Id))
return; return;
var _ = Task.Run(async () =>
{
try try
{ {
var lastGeneration = LastGenerations.GetOrAdd(channel.Id, DateTime.MinValue); var lastGeneration = LastGenerations.GetOrAdd(channel.Id, DateTime.MinValue);
@ -151,6 +154,7 @@ namespace NadekoBot.Services.Games
{ {
LogManager.GetCurrentClassLogger().Warn(ex); LogManager.GetCurrentClassLogger().Warn(ex);
} }
});
return; return;
} }
} }

View File

@ -0,0 +1,98 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NadekoBot.Services.Searches
{
public class AnimeSearchService
{
private readonly Timer _anilistTokenRefresher;
private readonly Logger _log;
private static string anilistToken { get; set; }
public AnimeSearchService()
{
_log = LogManager.GetCurrentClassLogger();
_anilistTokenRefresher = new Timer(async (state) =>
{
try
{
var headers = new Dictionary<string, string>
{
{"grant_type", "client_credentials"},
{"client_id", "kwoth-w0ki9"},
{"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"},
};
using (var http = new HttpClient())
{
//http.AddFakeHeaders();
http.DefaultRequestHeaders.Clear();
var formContent = new FormUrlEncodedContent(headers);
var response = await http.PostAsync("https://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false);
var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
anilistToken = JObject.Parse(stringContent)["access_token"].ToString();
}
}
catch
{
// ignored
}
}, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(29));
}
public async Task<AnimeResult> GetAnimeData(string query)
{
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
try
{
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
using (var http = new HttpClient())
{
var res = await http.GetStringAsync(link + $"?access_token={anilistToken}").ConfigureAwait(false);
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(() => { try { return JsonConvert.DeserializeObject<AnimeResult>(aniData); } catch { return null; } }).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_log.Warn(ex, "Failed anime search for {0}", query);
return null;
}
}
public async Task<MangaResult> GetMangaData(string query)
{
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
try
{
using (var http = new HttpClient())
{
var res = await http.GetStringAsync("http://anilist.co/api/manga/search/" + Uri.EscapeUriString(query) + $"?access_token={anilistToken}").ConfigureAwait(false);
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(() => { try { return JsonConvert.DeserializeObject<MangaResult>(aniData); } catch { return null; } }).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_log.Warn(ex, "Failed anime search for {0}", query);
return null;
}
}
}
}

View File

@ -1,6 +1,6 @@
using NadekoBot.Extensions; using NadekoBot.Extensions;
namespace NadekoBot.Modules.Searches.Models namespace NadekoBot.Services.Searches
{ {
public class AnimeResult public class AnimeResult
{ {

View File

@ -1,4 +1,4 @@
namespace NadekoBot.Modules.Searches.Models namespace NadekoBot.Services.Searches
{ {
public class MangaResult public class MangaResult
{ {

View File

@ -40,6 +40,9 @@ namespace NadekoBot.Services.Searches
//translate commands //translate commands
_client.MessageReceived += async (msg) => _client.MessageReceived += async (msg) =>
{
await Task.Yield();
var _ = Task.Run(async () =>
{ {
try try
{ {
@ -56,8 +59,7 @@ namespace NadekoBot.Services.Searches
ChannelId = umsg.Channel.Id, ChannelId = umsg.Channel.Id,
}; };
string langs; if (!UserLanguages.TryGetValue(key, out string langs))
if (!UserLanguages.TryGetValue(key, out langs))
return; return;
var text = await Translate(langs, umsg.Resolve(TagHandling.Ignore)) var text = await Translate(langs, umsg.Resolve(TagHandling.Ignore))
@ -67,6 +69,7 @@ namespace NadekoBot.Services.Searches
await umsg.Channel.SendConfirmAsync($"{umsg.Author.Mention} `:` " + text.Replace("<@ ", "<@").Replace("<@! ", "<@!")).ConfigureAwait(false); await umsg.Channel.SendConfirmAsync($"{umsg.Author.Mention} `:` " + text.Replace("<@ ", "<@").Replace("<@! ", "<@!")).ConfigureAwait(false);
} }
catch { } catch { }
});
}; };
//pokemon commands //pokemon commands

View File

@ -21,8 +21,9 @@ namespace NadekoBot.Services.Utility
_client.MessageReceived += Client_MessageReceived; _client.MessageReceived += Client_MessageReceived;
} }
private async Task Client_MessageReceived(SocketMessage imsg) private Task Client_MessageReceived(SocketMessage imsg)
{ {
var _ = Task.Run(async () => {
try try
{ {
if (imsg.Author.IsBot) if (imsg.Author.IsBot)
@ -57,6 +58,9 @@ namespace NadekoBot.Services.Utility
{ {
// ignored // ignored
} }
});
return Task.CompletedTask;
} }
private string GetMessage(ITextChannel channel, IGuildUser user, IUserMessage message) => private string GetMessage(ITextChannel channel, IGuildUser user, IUserMessage message) =>