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

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

View File

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

View File

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

View File

@@ -186,101 +186,105 @@ $@"--
private async Task PotentialAcro(SocketMessage arg)
{
try
await Task.Yield();
var _ = Task.Run(async () =>
{
var msg = arg as SocketUserMessage;
if (msg == null || msg.Author.IsBot || msg.Channel.Id != _channel.Id)
return;
++_spamCount;
var guildUser = (IGuildUser)msg.Author;
var input = msg.Content.ToUpperInvariant().Trim();
if (phase == AcroPhase.Submitting)
try
{
if (_spamCount > 10)
{
_spamCount = 0;
try { await _channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); }
catch { }
}
var inputWords = input.Split(' '); //get all words
if (inputWords.Length != _startingLetters.Length) // number of words must be the same as the number of the starting letters
var msg = arg as SocketUserMessage;
if (msg == null || msg.Author.IsBot || msg.Channel.Id != _channel.Id)
return;
for (int i = 0; i < _startingLetters.Length; i++)
{
var letter = _startingLetters[i];
++_spamCount;
if (!inputWords[i].StartsWith(letter.ToString())) // all first letters must match
var guildUser = (IGuildUser)msg.Author;
var input = msg.Content.ToUpperInvariant().Trim();
if (phase == AcroPhase.Submitting)
{
if (_spamCount > 10)
{
_spamCount = 0;
try { await _channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); }
catch { }
}
var inputWords = input.Split(' '); //get all words
if (inputWords.Length != _startingLetters.Length) // number of words must be the same as the number of the starting letters
return;
}
for (int i = 0; i < _startingLetters.Length; i++)
{
var letter = _startingLetters[i];
if (!inputWords[i].StartsWith(letter.ToString())) // all first letters must match
return;
}
if (!_usersWhoSubmitted.Add(guildUser.Id))
return;
//try adding it to the list of answers
if (!_submissions.TryAdd(input, guildUser))
{
_usersWhoSubmitted.TryRemove(guildUser.Id);
return;
}
// all good. valid input. answer recorded
await _channel.SendConfirmAsync(GetText("acrophobia"),
GetText("acro_submit", guildUser.Mention,
_submissions.Count));
try
{
await msg.DeleteAsync();
}
catch
{
await msg.DeleteAsync(); //try twice
}
}
else if (phase == AcroPhase.Voting)
{
if (_spamCount > 10)
{
_spamCount = 0;
try { await _channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); }
catch { }
}
//if (submissions.TryGetValue(input, out usr) && usr.Id != guildUser.Id)
//{
// if (!usersWhoVoted.Add(guildUser.Id))
// return;
// votes.AddOrUpdate(input, 1, (key, old) => ++old);
// await channel.SendConfirmAsync("Acrophobia", $"{guildUser.Mention} cast their vote!").ConfigureAwait(false);
// await msg.DeleteAsync().ConfigureAwait(false);
// return;
//}
int num;
if (int.TryParse(input, out num) && num > 0 && num <= _submissions.Count)
{
var kvp = _submissions.Skip(num - 1).First();
var usr = kvp.Value;
//can't vote for yourself, can't vote multiple times
if (usr.Id == guildUser.Id || !_usersWhoVoted.Add(guildUser.Id))
if (!_usersWhoSubmitted.Add(guildUser.Id))
return;
_votes.AddOrUpdate(kvp.Key, 1, (key, old) => ++old);
//try adding it to the list of answers
if (!_submissions.TryAdd(input, guildUser))
{
_usersWhoSubmitted.TryRemove(guildUser.Id);
return;
}
// all good. valid input. answer recorded
await _channel.SendConfirmAsync(GetText("acrophobia"),
GetText("acro_vote_cast", Format.Bold(guildUser.ToString()))).ConfigureAwait(false);
await msg.DeleteAsync().ConfigureAwait(false);
GetText("acro_submit", guildUser.Mention,
_submissions.Count));
try
{
await msg.DeleteAsync();
}
catch
{
await msg.DeleteAsync(); //try twice
}
}
else if (phase == AcroPhase.Voting)
{
if (_spamCount > 10)
{
_spamCount = 0;
try { await _channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); }
catch { }
}
//if (submissions.TryGetValue(input, out usr) && usr.Id != guildUser.Id)
//{
// if (!usersWhoVoted.Add(guildUser.Id))
// return;
// votes.AddOrUpdate(input, 1, (key, old) => ++old);
// await channel.SendConfirmAsync("Acrophobia", $"{guildUser.Mention} cast their vote!").ConfigureAwait(false);
// await msg.DeleteAsync().ConfigureAwait(false);
// return;
//}
int num;
if (int.TryParse(input, out num) && num > 0 && num <= _submissions.Count)
{
var kvp = _submissions.Skip(num - 1).First();
var usr = kvp.Value;
//can't vote for yourself, can't vote multiple times
if (usr.Id == guildUser.Id || !_usersWhoVoted.Add(guildUser.Id))
return;
_votes.AddOrUpdate(kvp.Key, 1, (key, old) => ++old);
await _channel.SendConfirmAsync(GetText("acrophobia"),
GetText("acro_vote_cast", Format.Bold(guildUser.ToString()))).ConfigureAwait(false);
await msg.DeleteAsync().ConfigureAwait(false);
}
}
}
}
catch (Exception ex)
{
_log.Warn(ex);
}
catch (Exception ex)
{
_log.Warn(ex);
}
});
}
public async Task End()

View File

@@ -119,77 +119,81 @@ namespace NadekoBot.Modules.Games.Hangman
private async Task PotentialGuess(SocketMessage msg)
{
try
await Task.Yield();
var _ = Task.Run(async () =>
{
if (!(msg is SocketUserMessage))
return;
if (msg.Channel != GameChannel)
return; // message's channel has to be the same as game's
if (msg.Content.Length == 1) // message must be 1 char long
try
{
if (++MessagesSinceLastPost > 10)
if (!(msg is SocketUserMessage))
return;
if (msg.Channel != GameChannel)
return; // message's channel has to be the same as game's
if (msg.Content.Length == 1) // message must be 1 char long
{
MessagesSinceLastPost = 0;
try
if (++MessagesSinceLastPost > 10)
{
await GameChannel.SendConfirmAsync("Hangman Game",
ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
MessagesSinceLastPost = 0;
try
{
await GameChannel.SendConfirmAsync("Hangman Game",
ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
}
catch { }
}
catch { }
}
if (!(char.IsLetter(msg.Content[0]) || char.IsDigit(msg.Content[0])))// and a letter or a digit
return;
if (!(char.IsLetter(msg.Content[0]) || char.IsDigit(msg.Content[0])))// and a letter or a digit
return;
var guess = char.ToUpperInvariant(msg.Content[0]);
if (Guesses.Contains(guess))
{
MessagesSinceLastPost = 0;
++Errors;
if (Errors < MaxErrors)
await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author} Letter `{guess}` has already been used.\n" + ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
else
await End().ConfigureAwait(false);
return;
}
Guesses.Add(guess);
if (Term.Word.ToUpperInvariant().Contains(guess))
{
if (GuessedAll)
var guess = char.ToUpperInvariant(msg.Content[0]);
if (Guesses.Contains(guess))
{
try { await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author} guessed a letter `{guess}`!").ConfigureAwait(false); } catch { }
await End().ConfigureAwait(false);
MessagesSinceLastPost = 0;
++Errors;
if (Errors < MaxErrors)
await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author} Letter `{guess}` has already been used.\n" + ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
else
await End().ConfigureAwait(false);
return;
}
MessagesSinceLastPost = 0;
try
Guesses.Add(guess);
if (Term.Word.ToUpperInvariant().Contains(guess))
{
await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author} guessed a letter `{guess}`!\n" + ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
if (GuessedAll)
{
try { await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author} guessed a letter `{guess}`!").ConfigureAwait(false); } catch { }
await End().ConfigureAwait(false);
return;
}
MessagesSinceLastPost = 0;
try
{
await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author} guessed a letter `{guess}`!\n" + ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
}
catch { }
}
catch { }
}
else
{
MessagesSinceLastPost = 0;
++Errors;
if (Errors < MaxErrors)
await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author} Letter `{guess}` does not exist.\n" + ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
else
await End().ConfigureAwait(false);
}
{
MessagesSinceLastPost = 0;
++Errors;
if (Errors < MaxErrors)
await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author} Letter `{guess}` does not exist.\n" + ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
else
await End().ConfigureAwait(false);
}
}
}
}
catch (Exception ex) { _log.Warn(ex); }
catch (Exception ex) { _log.Warn(ex); }
});
}
public string GetHangman() => $@". ┌─────┐

View File

@@ -109,38 +109,42 @@ namespace NadekoBot.Modules.Games.Models
private async Task AnswerReceived(SocketMessage imsg)
{
try
await Task.Yield();
var _ = Task.Run(async () =>
{
if (imsg.Author.IsBot)
return;
var msg = imsg as SocketUserMessage;
if (msg == null)
return;
if (this.Channel == null || this.Channel.Id != msg.Channel.Id) return;
var guess = msg.Content;
var distance = CurrentSentence.LevenshteinDistance(guess);
var decision = Judge(distance, guess.Length);
if (decision && !finishedUserIds.Contains(msg.Author.Id))
try
{
var elapsed = sw.Elapsed;
var wpm = CurrentSentence.Length / WORD_VALUE / elapsed.TotalSeconds * 60;
finishedUserIds.Add(msg.Author.Id);
await this.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle($"{msg.Author} finished the race!")
.AddField(efb => efb.WithName("Place").WithValue($"#{finishedUserIds.Count}").WithIsInline(true))
.AddField(efb => efb.WithName("WPM").WithValue($"{wpm:F1} *[{elapsed.TotalSeconds:F2}sec]*").WithIsInline(true))
.AddField(efb => efb.WithName("Errors").WithValue(distance.ToString()).WithIsInline(true)))
.ConfigureAwait(false);
if (finishedUserIds.Count % 4 == 0)
if (imsg.Author.IsBot)
return;
var msg = imsg as SocketUserMessage;
if (msg == null)
return;
if (this.Channel == null || this.Channel.Id != msg.Channel.Id) return;
var guess = msg.Content;
var distance = CurrentSentence.LevenshteinDistance(guess);
var decision = Judge(distance, guess.Length);
if (decision && !finishedUserIds.Contains(msg.Author.Id))
{
await this.Channel.SendConfirmAsync($":exclamation: A lot of people finished, here is the text for those still typing:\n\n**{Format.Sanitize(CurrentSentence.Replace(" ", " \x200B")).SanitizeMentions()}**").ConfigureAwait(false);
var elapsed = sw.Elapsed;
var wpm = CurrentSentence.Length / WORD_VALUE / elapsed.TotalSeconds * 60;
finishedUserIds.Add(msg.Author.Id);
await this.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle($"{msg.Author} finished the race!")
.AddField(efb => efb.WithName("Place").WithValue($"#{finishedUserIds.Count}").WithIsInline(true))
.AddField(efb => efb.WithName("WPM").WithValue($"{wpm:F1} *[{elapsed.TotalSeconds:F2}sec]*").WithIsInline(true))
.AddField(efb => efb.WithName("Errors").WithValue(distance.ToString()).WithIsInline(true)))
.ConfigureAwait(false);
if (finishedUserIds.Count % 4 == 0)
{
await this.Channel.SendConfirmAsync($":exclamation: A lot of people finished, here is the text for those still typing:\n\n**{Format.Sanitize(CurrentSentence.Replace(" ", " \x200B")).SanitizeMentions()}**").ConfigureAwait(false);
}
}
}
}
catch (Exception ex) { _log.Warn(ex); }
catch (Exception ex) { _log.Warn(ex); }
});
}
private bool Judge(int errors, int textLength) => errors <= textLength / 25;

View File

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

View File

@@ -180,64 +180,68 @@ namespace NadekoBot.Modules.Games.Trivia
private async Task PotentialGuess(SocketMessage imsg)
{
try
await Task.Yield();
var _ = Task.Run(async () =>
{
if (imsg.Author.IsBot)
return;
var umsg = imsg as SocketUserMessage;
var textChannel = umsg?.Channel as ITextChannel;
if (textChannel == null || textChannel.Guild != Guild)
return;
var guildUser = (IGuildUser)umsg.Author;
var guess = false;
await _guessLock.WaitAsync().ConfigureAwait(false);
try
{
if (GameActive && CurrentQuestion.IsAnswerCorrect(umsg.Content) && !triviaCancelSource.IsCancellationRequested)
{
Users.AddOrUpdate(guildUser, 1, (gu, old) => ++old);
guess = true;
}
}
finally { _guessLock.Release(); }
if (!guess) return;
triviaCancelSource.Cancel();
if (imsg.Author.IsBot)
return;
var umsg = imsg as SocketUserMessage;
if (Users[guildUser] == WinRequirement)
{
ShouldStopGame = true;
var textChannel = umsg?.Channel as ITextChannel;
if (textChannel == null || textChannel.Guild != Guild)
return;
var guildUser = (IGuildUser)umsg.Author;
var guess = false;
await _guessLock.WaitAsync().ConfigureAwait(false);
try
{
await Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle(GetText("trivia_game"))
.WithDescription(GetText("trivia_win",
guildUser.Mention,
Format.Bold(CurrentQuestion.Answer)))
.WithImageUrl(CurrentQuestion.AnswerImageUrl))
.ConfigureAwait(false);
if (GameActive && CurrentQuestion.IsAnswerCorrect(umsg.Content) && !triviaCancelSource.IsCancellationRequested)
{
Users.AddOrUpdate(guildUser, 1, (gu, old) => ++old);
guess = true;
}
}
catch
{
// ignored
}
var reward = _bc.TriviaCurrencyReward;
if (reward > 0)
await _cs.AddAsync(guildUser, "Won trivia", reward, true).ConfigureAwait(false);
return;
}
finally { _guessLock.Release(); }
if (!guess) return;
triviaCancelSource.Cancel();
await Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle(GetText("trivia_game"))
.WithDescription(GetText("trivia_guess", guildUser.Mention, Format.Bold(CurrentQuestion.Answer)))
.WithImageUrl(CurrentQuestion.AnswerImageUrl))
.ConfigureAwait(false);
}
catch (Exception ex) { _log.Warn(ex); }
if (Users[guildUser] == WinRequirement)
{
ShouldStopGame = true;
try
{
await Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle(GetText("trivia_game"))
.WithDescription(GetText("trivia_win",
guildUser.Mention,
Format.Bold(CurrentQuestion.Answer)))
.WithImageUrl(CurrentQuestion.AnswerImageUrl))
.ConfigureAwait(false);
}
catch
{
// ignored
}
var reward = _bc.TriviaCurrencyReward;
if (reward > 0)
await _cs.AddAsync(guildUser, "Won trivia", reward, true).ConfigureAwait(false);
return;
}
await Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle(GetText("trivia_game"))
.WithDescription(GetText("trivia_guess", guildUser.Mention, Format.Bold(CurrentQuestion.Answer)))
.WithImageUrl(CurrentQuestion.AnswerImageUrl))
.ConfigureAwait(false);
}
catch (Exception ex) { _log.Warn(ex); }
});
}
public string GetLeaderboard()

View File

@@ -4,13 +4,9 @@ using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Modules.Searches.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NadekoBot.Services.Searches;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -21,37 +17,11 @@ namespace NadekoBot.Modules.Searches
[Group]
public class AnimeSearchCommands : NadekoSubmodule
{
private static readonly Timer anilistTokenRefresher;
private static string anilistToken { get; set; }
private readonly AnimeSearchService _service;
static AnimeSearchCommands()
public AnimeSearchCommands(AnimeSearchService service)
{
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));
_service = service;
}
[NadekoCommand, Usage, Description, Aliases]
@@ -171,7 +141,7 @@ namespace NadekoBot.Modules.Searches
if (string.IsNullOrWhiteSpace(query))
return;
var animeData = await GetAnimeData(query).ConfigureAwait(false);
var animeData = await _service.GetAnimeData(query).ConfigureAwait(false);
if (animeData == null)
{
@@ -198,7 +168,7 @@ namespace NadekoBot.Modules.Searches
if (string.IsNullOrWhiteSpace(query))
return;
var mangaData = await GetMangaData(query).ConfigureAwait(false);
var mangaData = await _service.GetMangaData(query).ConfigureAwait(false);
if (mangaData == null)
{
@@ -218,52 +188,6 @@ namespace NadekoBot.Modules.Searches
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

@@ -1,20 +0,0 @@
using NadekoBot.Extensions;
namespace NadekoBot.Modules.Searches.Models
{
public class AnimeResult
{
public int id;
public string AiringStatus => airing_status.ToTitleCase();
public string airing_status;
public string title_english;
public int total_episodes;
public string description;
public string image_url_lge;
public string[] Genres;
public string average_score;
public string Link => "http://anilist.co/anime/" + id;
public string Synopsis => description?.Substring(0, description.Length > 500 ? 500 : description.Length) + "...";
}
}

View File

@@ -1,17 +0,0 @@
namespace NadekoBot.Modules.Searches.Models
{
public class MangaResult
{
public int id;
public string publishing_status;
public string image_url_lge;
public string title_english;
public int total_chapters;
public int total_volumes;
public string description;
public string[] Genres;
public string average_score;
public string Link => "http://anilist.co/manga/" + id;
public string Synopsis => description?.Substring(0, description.Length > 500 ? 500 : description.Length) + "...";
}
}