- Updated editorconfig rules to hopefully look a bit nicer.

- Removed configureawait(false) from everywhere as it doesnt' do anything in a console app and just makes the code look ugly
- Started using .WhenAll extension instead of Task.WhenAll to make it look nicer when chaining methods
This commit is contained in:
Kwoth
2021-12-28 21:14:26 +01:00
parent d093f7eed7
commit 723447c7d4
171 changed files with 1523 additions and 1594 deletions

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using AngleSharp;
using NadekoBot.Modules.Searches.Services;
using AngleSharp.Html.Dom;
@@ -16,11 +16,11 @@ public partial class Searches
// if (string.IsNullOrWhiteSpace(query))
// return;
//
// var novelData = await _service.GetNovelData(query).ConfigureAwait(false);
// var novelData = await _service.GetNovelData(query);
//
// if (novelData is null)
// {
// await ReplyErrorLocalizedAsync(strs.failed_finding_novel).ConfigureAwait(false);
// await ReplyErrorLocalizedAsync(strs.failed_finding_novel);
// return;
// }
//
@@ -35,7 +35,7 @@ public partial class Searches
// .AddField(GetText(strs.genres), string.Join(" ", novelData.Genres.Any() ? novelData.Genres : new[] { "none" }), true)
// .WithFooter($"{GetText(strs.score)} {novelData.Score}");
//
// await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
// await ctx.Channel.EmbedAsync(embed);
// }
[NadekoCommand, Aliases]
@@ -48,7 +48,7 @@ public partial class Searches
var fullQueryLink = "https://myanimelist.net/profile/" + name;
var config = Configuration.Default.WithDefaultLoader();
using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false);
using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink);
var imageElem = document.QuerySelector("body > div#myanimelist > div.wrapper > div#contentWrapper > div#content > div.content-container > div.container-left > div.user-profile > div.user-image > img");
var imageUrl = ((IHtmlImageElement)imageElem)?.Source ?? "http://icecream.me/uploads/870b03f36b59cc16ebfe314ef2dde781.png";
@@ -103,7 +103,7 @@ public partial class Searches
.WithUrl(fullQueryLink)
.WithImageUrl(imageUrl);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
private static string MalInfoToEmoji(string info)
@@ -135,11 +135,11 @@ public partial class Searches
if (string.IsNullOrWhiteSpace(query))
return;
var animeData = await _service.GetAnimeData(query).ConfigureAwait(false);
var animeData = await _service.GetAnimeData(query);
if (animeData is null)
{
await ReplyErrorLocalizedAsync(strs.failed_finding_anime).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.failed_finding_anime);
return;
}
@@ -153,7 +153,7 @@ public partial class Searches
.AddField(GetText(strs.status), animeData.AiringStatus.ToString(), true)
.AddField(GetText(strs.genres), string.Join(",\n", animeData.Genres.Any() ? animeData.Genres : new[] { "none" }), true)
.WithFooter($"{GetText(strs.score)} {animeData.AverageScore} / 100");
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@@ -163,11 +163,11 @@ public partial class Searches
if (string.IsNullOrWhiteSpace(query))
return;
var mangaData = await _service.GetMangaData(query).ConfigureAwait(false);
var mangaData = await _service.GetMangaData(query);
if (mangaData is null)
{
await ReplyErrorLocalizedAsync(strs.failed_finding_manga).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.failed_finding_manga);
return;
}
@@ -182,7 +182,7 @@ public partial class Searches
.AddField(GetText(strs.genres), string.Join(",\n", mangaData.Genres.Any() ? mangaData.Genres : new[] { "none" }), true)
.WithFooter($"{GetText(strs.score)} {mangaData.AverageScore} / 100");
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
}
}

View File

@@ -69,7 +69,7 @@ public class NotifChecker
entry => entry.AsEnumerable().ToDictionary(x => x.Key.Name, x => x.Value)
);
var newStreamData = await Task.WhenAll(oldStreamDataDict
var newStreamData = await oldStreamDataDict
.Select(x =>
{
// get all stream data for the streams of this type
@@ -80,7 +80,7 @@ public class NotifChecker
// this means there's no provider for this stream data, (and there was before?)
return Task.FromResult(new List<StreamData>());
}));
}).WhenAll();
var newlyOnline = new List<StreamData>();
var newlyOffline = new List<StreamData>();

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Services;
namespace NadekoBot.Modules.Searches;
@@ -15,7 +15,7 @@ public partial class Searches
if (string.IsNullOrWhiteSpace(name))
return;
var (crypto, nearest) = await _service.GetCryptoData(name).ConfigureAwait(false);
var (crypto, nearest) = await _service.GetCryptoData(name);
if (nearest is not null)
{
@@ -23,7 +23,7 @@ public partial class Searches
.WithTitle(GetText(strs.crypto_not_found))
.WithDescription(GetText(strs.did_you_mean(Format.Bold($"{nearest.Name} ({nearest.Symbol})"))));
if (await PromptUserConfirmAsync(embed).ConfigureAwait(false))
if (await PromptUserConfirmAsync(embed))
{
crypto = nearest;
}
@@ -31,7 +31,7 @@ public partial class Searches
if (crypto is null)
{
await ReplyErrorLocalizedAsync(strs.crypto_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.crypto_not_found);
return;
}
@@ -52,7 +52,7 @@ public partial class Searches
.AddField(GetText(strs.price), $"${crypto.Quote.Usd.Price}", true)
.AddField(GetText(strs.volume_24h), $"${crypto.Quote.Usd.Volume_24h:n0}", true)
.AddField(GetText(strs.change_7d_24h), $"{sevenDay}% / {lastDay}%", true)
.WithImageUrl($"https://s3.coinmarketcap.com/generated/sparklines/web/7d/usd/{crypto.Id}.png")).ConfigureAwait(false);
.WithImageUrl($"https://s3.coinmarketcap.com/generated/sparklines/web/7d/usd/{crypto.Id}.png"));
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Services;
using System.Text.RegularExpressions;
@@ -40,7 +40,7 @@ public partial class Searches
channel ??= (ITextChannel)ctx.Channel;
try
{
var feeds = await CodeHollow.FeedReader.FeedReader.ReadAsync(url).ConfigureAwait(false);
var feeds = await CodeHollow.FeedReader.FeedReader.ReadAsync(url);
}
catch (Exception ex)
{
@@ -54,12 +54,12 @@ public partial class Searches
success = _service.AddFeed(ctx.Guild.Id, channel.Id, url);
if (success)
{
await ReplyConfirmLocalizedAsync(strs.feed_added).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.feed_added);
return;
}
}
await ReplyConfirmLocalizedAsync(strs.feed_not_valid).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.feed_not_valid);
}
[NadekoCommand, Aliases]
@@ -69,10 +69,10 @@ public partial class Searches
{
if (_service.RemoveFeed(ctx.Guild.Id, --index))
{
await ReplyConfirmLocalizedAsync(strs.feed_removed).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.feed_removed);
}
else
await ReplyErrorLocalizedAsync(strs.feed_out_of_range).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.feed_out_of_range);
}
[NadekoCommand, Aliases]
@@ -86,8 +86,7 @@ public partial class Searches
{
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithDescription(GetText(strs.feed_no_feed)))
.ConfigureAwait(false);
.WithDescription(GetText(strs.feed_no_feed)));
return;
}
@@ -102,7 +101,7 @@ public partial class Searches
return embed.WithDescription(fs);
}, feeds.Count, 10).ConfigureAwait(false);
}, feeds.Count, 10);
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Services;
namespace NadekoBot.Modules.Searches;
@@ -11,29 +11,29 @@ public partial class Searches
[NadekoCommand, Aliases]
public async Task Yomama()
=> await SendConfirmAsync(await _service.GetYomamaJoke().ConfigureAwait(false)).ConfigureAwait(false);
=> await SendConfirmAsync(await _service.GetYomamaJoke());
[NadekoCommand, Aliases]
public async Task Randjoke()
{
var (setup, punchline) = await _service.GetRandomJoke().ConfigureAwait(false);
await SendConfirmAsync(setup, punchline).ConfigureAwait(false);
var (setup, punchline) = await _service.GetRandomJoke();
await SendConfirmAsync(setup, punchline);
}
[NadekoCommand, Aliases]
public async Task ChuckNorris()
=> await SendConfirmAsync(await _service.GetChuckNorrisJoke().ConfigureAwait(false)).ConfigureAwait(false);
=> await SendConfirmAsync(await _service.GetChuckNorrisJoke());
[NadekoCommand, Aliases]
public async Task WowJoke()
{
if (!_service.WowJokes.Any())
{
await ReplyErrorLocalizedAsync(strs.jokes_not_loaded).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.jokes_not_loaded);
return;
}
var joke = _service.WowJokes[new NadekoRandom().Next(0, _service.WowJokes.Count)];
await SendConfirmAsync(joke.Question, joke.Answer).ConfigureAwait(false);
await SendConfirmAsync(joke.Question, joke.Answer);
}
[NadekoCommand, Aliases]
@@ -41,12 +41,12 @@ public partial class Searches
{
if (!_service.WowJokes.Any())
{
await ReplyErrorLocalizedAsync(strs.magicitems_not_loaded).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.magicitems_not_loaded);
return;
}
var item = _service.MagicItems[new NadekoRandom().Next(0, _service.MagicItems.Count)];
await SendConfirmAsync("✨" + item.Name, item.Description).ConfigureAwait(false);
await SendConfirmAsync("✨" + item.Name, item.Description);
}
}
}

View File

@@ -39,8 +39,7 @@ public partial class Searches
return;
using var http = _httpFactory.CreateClient("memelist");
var res = await http.GetAsync("https://api.memegen.link/templates/")
.ConfigureAwait(false);
var res = await http.GetAsync("https://api.memegen.link/templates/");
var rawJson = await res.Content.ReadAsStringAsync();
@@ -58,7 +57,7 @@ public partial class Searches
.WithDescription(templates);
return embed;
}, data.Count, 15).ConfigureAwait(false);
}, data.Count, 15);
}
[NadekoCommand, Aliases]
@@ -75,8 +74,7 @@ public partial class Searches
}
}
memeUrl += ".png";
await ctx.Channel.SendMessageAsync(memeUrl)
.ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(memeUrl);
}
private static string Replace(string input)

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Common;
using Newtonsoft.Json;
@@ -33,19 +33,18 @@ public partial class Searches
{
if (string.IsNullOrWhiteSpace(_creds.OsuApiKey))
{
await ReplyErrorLocalizedAsync(strs.osu_api_key).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.osu_api_key);
return;
}
var smode = ResolveGameMode(modeNumber);
var userReq = $"https://osu.ppy.sh/api/get_user?k={_creds.OsuApiKey}&u={user}&m={modeNumber}";
var userResString = await http.GetStringAsync(userReq)
.ConfigureAwait(false);
var userResString = await http.GetStringAsync(userReq);
var objs = JsonConvert.DeserializeObject<List<OsuUserData>>(userResString);
if (objs.Count == 0)
{
await ReplyErrorLocalizedAsync(strs.osu_user_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.osu_user_not_found);
return;
}
@@ -67,11 +66,11 @@ public partial class Searches
}
catch (ArgumentOutOfRangeException)
{
await ReplyErrorLocalizedAsync(strs.osu_user_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.osu_user_not_found);
}
catch (Exception ex)
{
await ReplyErrorLocalizedAsync(strs.osu_failed).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.osu_failed);
Log.Warning(ex, "Osu command failed");
}
}
@@ -86,18 +85,16 @@ public partial class Searches
var modeStr = ResolveGameMode(modeNumber);
var resString = await http
.GetStringAsync($"https://api.gatari.pw/user/stats?u={user}&mode={modeNumber}")
.ConfigureAwait(false);
.GetStringAsync($"https://api.gatari.pw/user/stats?u={user}&mode={modeNumber}");
var statsResponse = JsonConvert.DeserializeObject<GatariUserStatsResponse>(resString);
if (statsResponse.Code != 200 || statsResponse.Stats.Id == 0)
{
await ReplyErrorLocalizedAsync(strs.osu_user_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.osu_user_not_found);
return;
}
var usrResString = await http.GetStringAsync($"https://api.gatari.pw/users/get?u={user}")
.ConfigureAwait(false);
var usrResString = await http.GetStringAsync($"https://api.gatari.pw/users/get?u={user}");
var userData = JsonConvert.DeserializeObject<GatariUserResponse>(usrResString).Users[0];
var userStats = statsResponse.Stats;
@@ -122,13 +119,13 @@ public partial class Searches
{;
if (string.IsNullOrWhiteSpace(_creds.OsuApiKey))
{
await SendErrorAsync("An osu! API key is required.").ConfigureAwait(false);
await SendErrorAsync("An osu! API key is required.");
return;
}
if (string.IsNullOrWhiteSpace(user))
{
await SendErrorAsync("Please provide a username.").ConfigureAwait(false);
await SendErrorAsync("Please provide a username.");
return;
}
@@ -146,7 +143,7 @@ public partial class Searches
$"&limit=5" +
$"&m={m}";
var resString = await http.GetStringAsync(reqString).ConfigureAwait(false);
var resString = await http.GetStringAsync(reqString);
var obj = JsonConvert.DeserializeObject<List<OsuUserBests>>(resString);
var mapTasks = obj.Select(async item =>
@@ -155,7 +152,7 @@ public partial class Searches
$"?k={_creds.OsuApiKey}" +
$"&b={item.BeatmapId}";
var mapResString = await http.GetStringAsync(mapReqString).ConfigureAwait(false);
var mapResString = await http.GetStringAsync(mapReqString);
var map = JsonConvert.DeserializeObject<List<OsuMapData>>(mapResString).FirstOrDefault();
if (map is null)
return default;
@@ -179,13 +176,13 @@ public partial class Searches
.WithOkColor()
.WithTitle($"Top 5 plays for {user}");
var mapData = await Task.WhenAll(mapTasks);
var mapData = await mapTasks.WhenAll();
foreach (var (title, desc) in mapData.Where(x => x != default))
{
eb.AddField(title, desc, false);
}
await ctx.Channel.EmbedAsync(eb).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(eb);
}
//https://osu.ppy.sh/wiki/Accuracy

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Common;
using NadekoBot.Modules.Searches.Services;
using Newtonsoft.Json;
@@ -32,7 +32,7 @@ public partial class Searches
if (string.IsNullOrWhiteSpace(usr))
{
await SendErrorAsync("Please provide an account name.").ConfigureAwait(false);
await SendErrorAsync("Please provide an account name.");
return;
}
@@ -41,7 +41,7 @@ public partial class Searches
try
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"{_poeURL}{usr}").ConfigureAwait(false);
var res = await http.GetStringAsync($"{_poeURL}{usr}");
characters = JsonConvert.DeserializeObject<List<Account>>(res);
}
catch
@@ -50,7 +50,7 @@ public partial class Searches
.WithDescription(GetText(strs.account_not_found))
.WithErrorColor();
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
return;
}
@@ -89,7 +89,7 @@ public partial class Searches
return embed;
}
}, characters.Count, 9, true).ConfigureAwait(false);
}, characters.Count, 9, true);
}
[NadekoCommand, Aliases]
@@ -100,7 +100,7 @@ public partial class Searches
try
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync("http://api.pathofexile.com/leagues?type=main&compact=1").ConfigureAwait(false);
var res = await http.GetStringAsync("http://api.pathofexile.com/leagues?type=main&compact=1");
leagues = JsonConvert.DeserializeObject<List<Leagues>>(res);
}
catch
@@ -109,7 +109,7 @@ public partial class Searches
.WithDescription(GetText(strs.leagues_not_found))
.WithErrorColor();
await ctx.Channel.EmbedAsync(eembed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(eembed);
return;
}
@@ -131,7 +131,7 @@ public partial class Searches
embed.WithDescription(sb.ToString());
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@@ -139,12 +139,12 @@ public partial class Searches
{
if (string.IsNullOrWhiteSpace(leagueName))
{
await SendErrorAsync("Please provide league name.").ConfigureAwait(false);
await SendErrorAsync("Please provide league name.");
return;
}
if (string.IsNullOrWhiteSpace(currencyName))
{
await SendErrorAsync("Please provide currency name.").ConfigureAwait(false);
await SendErrorAsync("Please provide currency name.");
return;
}
@@ -155,7 +155,7 @@ public partial class Searches
{
var res = $"{_ponURL}{leagueName}";
using var http = _httpFactory.CreateClient();
var obj = JObject.Parse(await http.GetStringAsync(res).ConfigureAwait(false));
var obj = JObject.Parse(await http.GetStringAsync(res));
var chaosEquivalent = 0.0F;
var conversionEquivalent = 0.0F;
@@ -193,7 +193,7 @@ public partial class Searches
.AddField($"{cleanConvert} Equivalent", chaosEquivalent / conversionEquivalent, true)
.WithOkColor();
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
catch
{
@@ -201,7 +201,7 @@ public partial class Searches
.WithDescription(GetText(strs.ninja_not_found))
.WithErrorColor();
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Searches;
public partial class Searches
@@ -24,8 +24,7 @@ public partial class Searches
[NadekoCommand, Aliases]
public async Task Placelist()
=> await SendConfirmAsync(GetText(strs.list_of_place_tags(Prefix)),
_typesStr)
.ConfigureAwait(false);
_typesStr);
[NadekoCommand, Aliases]
public async Task Place(PlaceType placeType, uint width = 0, uint height = 0)
@@ -67,7 +66,7 @@ public partial class Searches
url += $"/{width}/{height}";
await ctx.Channel.SendMessageAsync(url).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(url);
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Services;
using NadekoBot.Common.Pokemon;
@@ -35,11 +35,11 @@ public partial class Searches
.WithThumbnailUrl($"https://assets.pokemon.com/assets/cms2/img/pokedex/detail/{p.Id.ToString("000")}.png")
.AddField(GetText(strs.types), string.Join("\n", p.Types), true)
.AddField(GetText(strs.height_weight), GetText(strs.height_weight_val(p.HeightM, p.WeightKg)), true)
.AddField(GetText(strs.abilities), string.Join("\n", p.Abilities.Select(a => a.Value)), true)).ConfigureAwait(false);
.AddField(GetText(strs.abilities), string.Join("\n", p.Abilities.Select(a => a.Value)), true));
return;
}
}
await ReplyErrorLocalizedAsync(strs.pokemon_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.pokemon_none);
}
[NadekoCommand, Aliases]
@@ -61,7 +61,7 @@ public partial class Searches
return;
}
}
await ReplyErrorLocalizedAsync(strs.pokemon_ability_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.pokemon_ability_none);
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using AngleSharp;
using AngleSharp.Html.Dom;
using Microsoft.Extensions.Caching.Memory;
@@ -40,23 +40,22 @@ public partial class Searches : NadekoModule<SearchesService>
var av = usr.RealAvatarUrl();
if (av is null)
return;
await using var picStream = await _service.GetRipPictureAsync(usr.Nickname ?? usr.Username, av).ConfigureAwait(false);
await using var picStream = await _service.GetRipPictureAsync(usr.Nickname ?? usr.Username, av);
await ctx.Channel.SendFileAsync(
picStream,
"rip.png",
$"Rip {Format.Bold(usr.ToString())} \n\t- " +
Format.Italics(ctx.User.ToString()))
.ConfigureAwait(false);
Format.Italics(ctx.User.ToString()));
}
[NadekoCommand, Aliases]
public async Task Weather([Leftover] string query)
{
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
var embed = _eb.Create();
var data = await _service.GetWeatherDataAsync(query).ConfigureAwait(false);
var data = await _service.GetWeatherDataAsync(query);
if (data is null)
{
@@ -88,18 +87,18 @@ public partial class Searches : NadekoModule<SearchesService>
.WithOkColor()
.WithFooter("Powered by openweathermap.org", $"http://openweathermap.org/img/w/{data.Weather[0].Icon}.png");
}
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
public async Task Time([Leftover] string query)
{
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var (data, err) = await _service.GetTimeDataAsync(query).ConfigureAwait(false);
var (data, err) = await _service.GetTimeDataAsync(query);
if (err is not null)
{
LocStr errorKey;
@@ -118,12 +117,12 @@ public partial class Searches : NadekoModule<SearchesService>
errorKey = strs.error_occured;
break;
}
await ReplyErrorLocalizedAsync(errorKey).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(errorKey);
return;
}
else if (string.IsNullOrWhiteSpace(data.TimeZoneName))
{
await ReplyErrorLocalizedAsync(strs.timezone_db_api_key).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.timezone_db_api_key);
return;
}
@@ -134,37 +133,37 @@ public partial class Searches : NadekoModule<SearchesService>
.AddField(GetText(strs.location), string.Join('\n', data.Address.Split(", ")), true)
.AddField(GetText(strs.timezone), data.TimeZoneName, true);
await ctx.Channel.SendMessageAsync(embed: eb.Build()).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(embed: eb.Build());
}
[NadekoCommand, Aliases]
public async Task Youtube([Leftover] string query = null)
{
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
var result = (await _google.GetVideoLinksByKeywordAsync(query).ConfigureAwait(false)).FirstOrDefault();
var result = (await _google.GetVideoLinksByKeywordAsync(query)).FirstOrDefault();
if (string.IsNullOrWhiteSpace(result))
{
await ReplyErrorLocalizedAsync(strs.no_results).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_results);
return;
}
await ctx.Channel.SendMessageAsync(result).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(result);
}
[NadekoCommand, Aliases]
public async Task Movie([Leftover] string query = null)
{
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var movie = await _service.GetMovieDataAsync(query).ConfigureAwait(false);
var movie = await _service.GetMovieDataAsync(query);
if (movie is null)
{
await ReplyErrorLocalizedAsync(strs.imdb_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.imdb_fail);
return;
}
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
@@ -174,7 +173,7 @@ public partial class Searches : NadekoModule<SearchesService>
.AddField("Rating", movie.ImdbRating, true)
.AddField("Genre", movie.Genre, true)
.AddField("Year", movie.Year, true)
.WithImageUrl(movie.Poster)).ConfigureAwait(false);
.WithImageUrl(movie.Poster));
}
[NadekoCommand, Aliases]
@@ -201,12 +200,12 @@ public partial class Searches : NadekoModule<SearchesService>
public async Task Image([Leftover] string query = null)
{
var oterms = query?.Trim();
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
query = WebUtility.UrlEncode(oterms).Replace(' ', '+');
try
{
var res = await _google.GetImageAsync(oterms).ConfigureAwait(false);
var res = await _google.GetImageAsync(oterms);
var embed = _eb.Create()
.WithOkColor()
.WithAuthor(GetText(strs.image_search_for) + " " + oterms.TrimTo(50),
@@ -215,7 +214,7 @@ public partial class Searches : NadekoModule<SearchesService>
.WithDescription(res.Link)
.WithImageUrl(res.Link)
.WithTitle(ctx.User.ToString());
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
catch
{
@@ -223,7 +222,7 @@ public partial class Searches : NadekoModule<SearchesService>
var fullQueryLink = $"http://imgur.com/search?q={ query }";
var config = Configuration.Default.WithDefaultLoader();
using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false);
using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink);
var elems = document.QuerySelectorAll("a.image-list-link").ToList();
if (!elems.Any())
@@ -244,14 +243,14 @@ public partial class Searches : NadekoModule<SearchesService>
.WithDescription(source)
.WithImageUrl(source)
.WithTitle(ctx.User.ToString());
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
}
[NadekoCommand, Aliases]
public async Task Lmgtfy([Leftover] string ffs = null)
{
if (!await ValidateQuery(ffs).ConfigureAwait(false))
if (!await ValidateQuery(ffs))
return;
var shortenedUrl = await _google.ShortenUrl($"http://lmgtfy.com/?q={Uri.EscapeDataString(ffs)}");
@@ -269,7 +268,7 @@ public partial class Searches : NadekoModule<SearchesService>
[NadekoCommand, Aliases]
public async Task Shorten([Leftover] string query)
{
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
query = query.Trim();
@@ -285,7 +284,7 @@ public partial class Searches : NadekoModule<SearchesService>
};
req.Content = formData;
using var res = await _http.SendAsync(req).ConfigureAwait(false);
using var res = await _http.SendAsync(req);
var content = await res.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ShortenData>(content);
@@ -313,7 +312,7 @@ public partial class Searches : NadekoModule<SearchesService>
public async Task Google([Leftover] string query = null)
{
query = query?.Trim();
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
_ = ctx.Channel.TriggerTypingAsync();
@@ -339,14 +338,14 @@ public partial class Searches : NadekoModule<SearchesService>
.WithDescription($"{GetText(strs.search_for)} **{query}**\n\n" +descStr)
.WithOkColor();
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
public async Task DuckDuckGo([Leftover] string query = null)
{
query = query?.Trim();
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
_ = ctx.Channel.TriggerTypingAsync();
@@ -370,7 +369,7 @@ public partial class Searches : NadekoModule<SearchesService>
.WithDescription($"{GetText(strs.search_for)} **{query}**\n\n" + descStr)
.WithOkColor();
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@@ -379,12 +378,12 @@ public partial class Searches : NadekoModule<SearchesService>
if (!await ValidateQuery(search))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
var card = await _service.GetMtgCardAsync(search).ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var card = await _service.GetMtgCardAsync(search);
if (card is null)
{
await ReplyErrorLocalizedAsync(strs.card_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.card_not_found);
return;
}
@@ -396,28 +395,28 @@ public partial class Searches : NadekoModule<SearchesService>
.AddField(GetText(strs.cost), card.ManaCost, true)
.AddField(GetText(strs.types), card.Types, true);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
public async Task Hearthstone([Leftover] string name)
{
var arg = name;
if (!await ValidateQuery(name).ConfigureAwait(false))
if (!await ValidateQuery(name))
return;
if (string.IsNullOrWhiteSpace(_creds.RapidApiKey))
{
await ReplyErrorLocalizedAsync(strs.mashape_api_missing).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mashape_api_missing);
return;
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
var card = await _service.GetHearthstoneCardDataAsync(name).ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var card = await _service.GetHearthstoneCardDataAsync(name);
if (card is null)
{
await ReplyErrorLocalizedAsync(strs.card_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.card_not_found);
return;
}
var embed = _eb.Create().WithOkColor()
@@ -426,19 +425,19 @@ public partial class Searches : NadekoModule<SearchesService>
if (!string.IsNullOrWhiteSpace(card.Flavor))
embed.WithDescription(card.Flavor);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
public async Task UrbanDict([Leftover] string query = null)
{
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
using (var http = _httpFactory.CreateClient())
{
var res = await http.GetStringAsync($"http://api.urbandictionary.com/v0/define?term={Uri.EscapeDataString(query)}").ConfigureAwait(false);
var res = await http.GetStringAsync($"http://api.urbandictionary.com/v0/define?term={Uri.EscapeDataString(query)}");
try
{
var items = JsonConvert.DeserializeObject<UrbanResponse>(res).List;
@@ -452,7 +451,7 @@ public partial class Searches : NadekoModule<SearchesService>
.WithUrl(item.Permalink)
.WithAuthor(item.Word)
.WithDescription(item.Definition);
}, items.Length, 1).ConfigureAwait(false);
}, items.Length, 1);
return;
}
}
@@ -460,14 +459,14 @@ public partial class Searches : NadekoModule<SearchesService>
{
}
}
await ReplyErrorLocalizedAsync(strs.ud_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.ud_error);
}
[NadekoCommand, Aliases]
public async Task Define([Leftover] string word)
{
if (!await ValidateQuery(word).ConfigureAwait(false))
if (!await ValidateQuery(word))
return;
using var _http = _httpFactory.CreateClient();
@@ -478,7 +477,7 @@ public partial class Searches : NadekoModule<SearchesService>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12);
return _http.GetStringAsync("https://api.pearson.com/v2/dictionaries/entries?headword=" + WebUtility.UrlEncode(word));
}).ConfigureAwait(false);
});
var data = JsonConvert.DeserializeObject<DefineModel>(res);
@@ -489,7 +488,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (!datas.Any())
{
Log.Warning("Definition not found: {Word}", word);
await ReplyErrorLocalizedAsync(strs.define_unknown).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.define_unknown);
}
@@ -532,12 +531,12 @@ public partial class Searches : NadekoModule<SearchesService>
public async Task Catfact()
{
using var http = _httpFactory.CreateClient();
var response = await http.GetStringAsync("https://catfact.ninja/fact").ConfigureAwait(false);
var response = await http.GetStringAsync("https://catfact.ninja/fact");
if (response is null)
return;
var fact = JObject.Parse(response)["fact"].ToString();
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact).ConfigureAwait(false);
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact);
}
//done in 3.0
@@ -552,7 +551,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (av is null)
return;
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}").ConfigureAwait(false);
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}");
}
//done in 3.0
@@ -563,7 +562,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (string.IsNullOrWhiteSpace(imageLink))
return;
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}").ConfigureAwait(false);
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}");
}
[NadekoCommand, Aliases]
@@ -571,16 +570,16 @@ public partial class Searches : NadekoModule<SearchesService>
{
query = query?.Trim();
if (!await ValidateQuery(query).ConfigureAwait(false))
if (!await ValidateQuery(query))
return;
using var http = _httpFactory.CreateClient();
var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)).ConfigureAwait(false);
var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query));
var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result);
if (data.Query.Pages[0].Missing || string.IsNullOrWhiteSpace(data.Query.Pages[0].FullUrl))
await ReplyErrorLocalizedAsync(strs.wiki_page_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.wiki_page_not_found);
else
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl);
}
[NadekoCommand, Aliases]
@@ -605,7 +604,7 @@ public partial class Searches : NadekoModule<SearchesService>
}
await using var ms = img.ToStream();
await ctx.Channel.SendFileAsync(ms, $"colors.png").ConfigureAwait(false);
await ctx.Channel.SendFileAsync(ms, $"colors.png");
}
[NadekoCommand, Aliases]
@@ -619,14 +618,14 @@ public partial class Searches : NadekoModule<SearchesService>
if (avatarUrl is null)
{
await ReplyErrorLocalizedAsync(strs.avatar_none(usr.ToString())).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.avatar_none(usr.ToString()));
return;
}
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.AddField("Username", usr.ToString())
.AddField("Avatar Url", avatarUrl)
.WithThumbnailUrl(avatarUrl.ToString()), ctx.User.Mention).ConfigureAwait(false);
.WithThumbnailUrl(avatarUrl.ToString()), ctx.User.Mention);
}
[NadekoCommand, Aliases]
@@ -634,10 +633,10 @@ public partial class Searches : NadekoModule<SearchesService>
{
if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query))
{
await ReplyErrorLocalizedAsync(strs.wikia_input_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.wikia_input_error);
return;
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
using var http = _httpFactory.CreateClient();
http.DefaultRequestHeaders.Clear();
try
@@ -647,24 +646,24 @@ public partial class Searches : NadekoModule<SearchesService>
$"&format=json" +
$"&list=search" +
$"&srsearch={Uri.EscapeDataString(query)}" +
$"&srlimit=1").ConfigureAwait(false);
$"&srlimit=1");
var items = JObject.Parse(res);
var title = items["query"]?["search"]?.FirstOrDefault()?["title"]?.ToString();
if (string.IsNullOrWhiteSpace(title))
{
await ReplyErrorLocalizedAsync(strs.wikia_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.wikia_error);
return;
}
var url = Uri.EscapeDataString($"https://{target}.fandom.com/wiki/{title}");
var response = $@"`{GetText(strs.title)}` {title.SanitizeMentions()}
`{GetText(strs.url)}:` {url}";
await ctx.Channel.SendMessageAsync(response).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(response);
}
catch
{
await ReplyErrorLocalizedAsync(strs.wikia_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.wikia_error);
}
}
@@ -677,7 +676,7 @@ public partial class Searches : NadekoModule<SearchesService>
{
using var http = _httpFactory.CreateClient();
var res = await http
.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse).ConfigureAwait(false);
.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse);
obj = JsonConvert.DeserializeObject<BibleVerses>(res);
}
@@ -685,14 +684,14 @@ public partial class Searches : NadekoModule<SearchesService>
{
}
if (obj.Error != null || obj.Verses is null || obj.Verses.Length == 0)
await SendErrorAsync(obj.Error ?? "No verse found.").ConfigureAwait(false);
await SendErrorAsync(obj.Error ?? "No verse found.");
else
{
var v = obj.Verses[0];
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithTitle($"{v.BookName} {v.Chapter}:{v.Verse}")
.WithDescription(v.Text)).ConfigureAwait(false);
.WithDescription(v.Text));
}
}
@@ -702,12 +701,12 @@ public partial class Searches : NadekoModule<SearchesService>
if (string.IsNullOrWhiteSpace(query))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var appId = await _service.GetSteamAppIdByName(query).ConfigureAwait(false);
var appId = await _service.GetSteamAppIdByName(query);
if (appId == -1)
{
await ReplyErrorLocalizedAsync(strs.not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.not_found);
return;
}
@@ -721,7 +720,7 @@ public partial class Searches : NadekoModule<SearchesService>
// .AddField(GetText(strs.price), gameData.IsFree ? GetText(strs.FREE) : game, true)
// .AddField(GetText(strs.links), gameData.GetGenresString(), true)
// .WithFooter(GetText(strs.recommendations(gameData.TotalRecommendations)));
await ctx.Channel.SendMessageAsync($"https://store.steampowered.com/app/{appId}").ConfigureAwait(false);
await ctx.Channel.SendMessageAsync($"https://store.steampowered.com/app/{appId}");
}
public async Task<bool> ValidateQuery(string query)
@@ -731,7 +730,7 @@ public partial class Searches : NadekoModule<SearchesService>
return true;
}
await ErrorLocalizedAsync(strs.specify_search_params).ConfigureAwait(false);
await ErrorLocalizedAsync(strs.specify_search_params);
return false;
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using AngleSharp;
using AngleSharp.Html.Dom;
using NadekoBot.Modules.Searches.Common;
@@ -26,14 +26,14 @@ public class AnimeSearchService : INService
var link = "https://aniapi.nadeko.bot/anime/" + Uri.EscapeDataString(query.Replace("/", " ", StringComparison.InvariantCulture));
link = link.ToLowerInvariant();
var (ok, data) = await _cache.TryGetAnimeDataAsync(link).ConfigureAwait(false);
var (ok, data) = await _cache.TryGetAnimeDataAsync(link);
if (!ok)
{
using (var http = _httpFactory.CreateClient())
{
data = await http.GetStringAsync(link).ConfigureAwait(false);
data = await http.GetStringAsync(link);
}
await _cache.SetAnimeDataAsync(link, data).ConfigureAwait(false);
await _cache.SetAnimeDataAsync(link, data);
}
@@ -58,11 +58,11 @@ public class AnimeSearchService : INService
.Replace("/", " ")
);
link = link.ToLowerInvariant();
var (ok, data) = await _cache.TryGetNovelDataAsync(link).ConfigureAwait(false);
var (ok, data) = await _cache.TryGetNovelDataAsync(link);
if (!ok)
{
var config = Configuration.Default.WithDefaultLoader();
using var document = await BrowsingContext.New(config).OpenAsync(link).ConfigureAwait(false);
using var document = await BrowsingContext.New(config).OpenAsync(link);
var imageElem = document.QuerySelector("div.seriesimg > img");
if (imageElem is null)
return null;
@@ -109,7 +109,7 @@ public class AnimeSearchService : INService
};
await _cache.SetNovelDataAsync(link,
JsonConvert.SerializeObject(obj)).ConfigureAwait(false);
JsonConvert.SerializeObject(obj));
return obj;
}
@@ -132,14 +132,14 @@ public class AnimeSearchService : INService
var link = "https://aniapi.nadeko.bot/manga/" + Uri.EscapeDataString(query.Replace("/", " ", StringComparison.InvariantCulture));
link = link.ToLowerInvariant();
var (ok, data) = await _cache.TryGetAnimeDataAsync(link).ConfigureAwait(false);
var (ok, data) = await _cache.TryGetAnimeDataAsync(link);
if (!ok)
{
using (var http = _httpFactory.CreateClient())
{
data = await http.GetStringAsync(link).ConfigureAwait(false);
data = await http.GetStringAsync(link);
}
await _cache.SetAnimeDataAsync(link, data).ConfigureAwait(false);
await _cache.SetAnimeDataAsync(link, data);
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Common;
using Newtonsoft.Json;
@@ -25,7 +25,7 @@ public class CryptoService : INService
}
name = name.ToUpperInvariant();
var cryptos = await CryptoData().ConfigureAwait(false);
var cryptos = await CryptoData();
if (cryptos is null)
return (null, null);

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using CodeHollow.FeedReader.Feeds;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
@@ -52,7 +52,7 @@ public class FeedsService : INService
var rssUrl = kvp.Key;
try
{
var feed = await CodeHollow.FeedReader.FeedReader.ReadAsync(rssUrl).ConfigureAwait(false);
var feed = await CodeHollow.FeedReader.FeedReader.ReadAsync(rssUrl);
var items = feed
.Items
@@ -143,7 +143,7 @@ public class FeedsService : INService
.Where(x => x != null)
.Select(x => x.EmbedAsync(embed));
allSendTasks.Add(Task.WhenAll(feedSendTasks));
allSendTasks.Add(feedSendTasks.WhenAll());
}
}
catch
@@ -151,7 +151,7 @@ public class FeedsService : INService
}
}
await Task.WhenAll(Task.WhenAll(allSendTasks), Task.Delay(10000)).ConfigureAwait(false);
await Task.WhenAll(Task.WhenAll(allSendTasks), Task.Delay(10000));
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@@ -75,7 +75,7 @@ public class SearchesService : INService
var data = await _cache.GetOrAddCachedDataAsync($"nadeko_rip_{text}_{imgUrl}",
GetRipPictureFactory,
(text, imgUrl),
TimeSpan.FromDays(1)).ConfigureAwait(false);
TimeSpan.FromDays(1));
return data.ToStream();
}
@@ -149,7 +149,7 @@ public class SearchesService : INService
var data = await http.GetStringAsync($"http://api.openweathermap.org/data/2.5/weather?" +
$"q={query}&" +
$"appid=42cd627dd60debf25a5739e50a217d74&" +
$"units=metric").ConfigureAwait(false);
$"units=metric");
if (data is null)
return null;
@@ -288,7 +288,7 @@ public class SearchesService : INService
// using (var http = _httpFactory.CreateClient())
// {
// var response = await http.GetStringAsync(new Uri("http://api.yomomma.info/")).ConfigureAwait(false);
// var response = await http.GetStringAsync(new Uri("http://api.yomomma.info/"));
// return JObject.Parse(response)["joke"].ToString() + " 😆";
// }
}
@@ -304,7 +304,7 @@ public class SearchesService : INService
public async Task<string> GetChuckNorrisJoke()
{
using var http = _httpFactory.CreateClient();
var response = await http.GetStringAsync(new Uri("http://api.icndb.com/jokes/random/")).ConfigureAwait(false);
var response = await http.GetStringAsync(new Uri("http://api.icndb.com/jokes/random/"));
return JObject.Parse(response)["value"]["joke"].ToString() + " 😆";
}
@@ -314,7 +314,7 @@ public class SearchesService : INService
var data = await _cache.GetOrAddCachedDataAsync($"nadeko_mtg_{search}",
GetMtgCardFactory,
search,
TimeSpan.FromDays(1)).ConfigureAwait(false);
TimeSpan.FromDays(1));
if (data is null || data.Length == 0)
return null;
@@ -333,7 +333,7 @@ public class SearchesService : INService
$"newSearch=false&" +
$"ProductType=All&" +
$"IsProductNameExact=false&" +
$"ProductName={Uri.EscapeDataString(card.Name)}").ConfigureAwait(false);
$"ProductName={Uri.EscapeDataString(card.Name)}");
}
catch { storeUrl = "<url can't be found>"; }
@@ -350,26 +350,18 @@ public class SearchesService : INService
using var http = _httpFactory.CreateClient();
http.DefaultRequestHeaders.Clear();
var response = await http.GetStringAsync($"https://api.magicthegathering.io/v1/cards?name={Uri.EscapeDataString(search)}")
.ConfigureAwait(false);
var response = await http.GetStringAsync($"https://api.magicthegathering.io/v1/cards?name={Uri.EscapeDataString(search)}");
var responseObject = JsonConvert.DeserializeObject<MtgResponse>(response);
if (responseObject is null)
return new MtgData[0];
return Array.Empty<MtgData>();
var cards = responseObject.Cards.Take(5).ToArray();
if (cards.Length == 0)
return new MtgData[0];
return Array.Empty<MtgData>();
var tasks = new List<Task<MtgData>>(cards.Length);
for (var i = 0; i < cards.Length; i++)
{
var card = cards[i];
tasks.Add(GetMtgDataAsync(card));
}
return await Task.WhenAll(tasks).ConfigureAwait(false);
return await cards.Select(GetMtgDataAsync)
.WhenAll();
}
public Task<HearthstoneCardData> GetHearthstoneCardDataAsync(string name)
@@ -389,7 +381,7 @@ public class SearchesService : INService
try
{
var response = await http.GetStringAsync($"https://omgvamp-hearthstone-v1.p.rapidapi.com/" +
$"cards/search/{Uri.EscapeDataString(name)}").ConfigureAwait(false);
$"cards/search/{Uri.EscapeDataString(name)}");
var objs = JsonConvert.DeserializeObject<HearthstoneCardData[]>(response);
if (objs is null || objs.Length == 0)
return null;
@@ -400,7 +392,7 @@ public class SearchesService : INService
return null;
if (!string.IsNullOrWhiteSpace(data.Img))
{
data.Img = await _google.ShortenUrl(data.Img).ConfigureAwait(false);
data.Img = await _google.ShortenUrl(data.Img);
}
if (!string.IsNullOrWhiteSpace(data.Text))
{
@@ -429,11 +421,11 @@ public class SearchesService : INService
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync(string.Format("https://omdbapi.nadeko.bot/?t={0}&y=&plot=full&r=json",
name.Trim().Replace(' ', '+'))).ConfigureAwait(false);
name.Trim().Replace(' ', '+')));
var movie = JsonConvert.DeserializeObject<OmdbMovie>(res);
if (movie?.Title is null)
return null;
movie.Poster = await _google.ShortenUrl(movie.Poster).ConfigureAwait(false);
movie.Poster = await _google.ShortenUrl(movie.Poster);
return movie;
}
@@ -442,7 +434,7 @@ public class SearchesService : INService
var redis = _cache.Redis;
var db = redis.GetDatabase();
const string STEAM_GAME_IDS_KEY = "steam_names_to_appid";
var exists = await db.KeyExistsAsync(STEAM_GAME_IDS_KEY).ConfigureAwait(false);
var exists = await db.KeyExistsAsync(STEAM_GAME_IDS_KEY);
// if we didn't get steam name to id map already, get it
//if (!exists)
@@ -450,12 +442,12 @@ public class SearchesService : INService
// using (var http = _httpFactory.CreateClient())
// {
// // https://api.steampowered.com/ISteamApps/GetAppList/v2/
// var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/").ConfigureAwait(false);
// var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/");
// var apps = JsonConvert.DeserializeAnonymousType(gamesStr, new { applist = new { apps = new List<SteamGameId>() } }).applist.apps;
// //await db.HashSetAsync("steam_game_ids", apps.Select(app => new HashEntry(app.Name.Trim().ToLowerInvariant(), app.AppId)).ToArray()).ConfigureAwait(false);
// //await db.HashSetAsync("steam_game_ids", apps.Select(app => new HashEntry(app.Name.Trim().ToLowerInvariant(), app.AppId)).ToArray());
// await db.StringSetAsync("steam_game_ids", gamesStr, TimeSpan.FromHours(24));
// //await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget).ConfigureAwait(false);
// //await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget);
// }
//}
@@ -463,16 +455,16 @@ public class SearchesService : INService
{
using var http = _httpFactory.CreateClient();
// https://api.steampowered.com/ISteamApps/GetAppList/v2/
var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/").ConfigureAwait(false);
var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/");
var apps = JsonConvert.DeserializeAnonymousType(gamesStr, new { applist = new { apps = new List<SteamGameId>() } }).applist.apps;
return apps
.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase)
.GroupBy(x => x.Name)
.ToDictionary(x => x.Key, x => x.First().AppId);
//await db.HashSetAsync("steam_game_ids", apps.Select(app => new HashEntry(app.Name.Trim().ToLowerInvariant(), app.AppId)).ToArray()).ConfigureAwait(false);
//await db.HashSetAsync("steam_game_ids", apps.Select(app => new HashEntry(app.Name.Trim().ToLowerInvariant(), app.AppId)).ToArray());
//await db.StringSetAsync("steam_game_ids", gamesStr, TimeSpan.FromHours(24));
//await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget).ConfigureAwait(false);
//await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget);
}, default(string), TimeSpan.FromHours(24));
if (gamesMap is null)
@@ -506,7 +498,7 @@ public class SearchesService : INService
// now that we have appid, get the game info with that appid
//var gameData = await _cache.GetOrAddCachedDataAsync($"steam_game:{appid}", SteamGameDataFactory, appid, TimeSpan.FromHours(12))
// .ConfigureAwait(false);
//;
//return gameData;
}
@@ -516,7 +508,7 @@ public class SearchesService : INService
// using (var http = _httpFactory.CreateClient())
// {
// // https://store.steampowered.com/api/appdetails?appids=
// var responseStr = await http.GetStringAsync($"https://store.steampowered.com/api/appdetails?appids={appid}").ConfigureAwait(false);
// var responseStr = await http.GetStringAsync($"https://store.steampowered.com/api/appdetails?appids={appid}");
// var data = JsonConvert.DeserializeObject<Dictionary<int, SteamGameData.Container>>(responseStr);
// if (!data.ContainsKey(appid) || !data[appid].Success)
// return null; // for some reason we can't get the game with valid appid. SHould never happen

View File

@@ -227,15 +227,14 @@ public sealed class StreamNotificationService : INService
var key = stream.CreateKey();
if (_shardTrackedStreams.TryGetValue(key, out var fss))
{
var sendTasks = fss
await fss
// send offline stream notifications only to guilds which enable it with .stoff
.SelectMany(x => x.Value)
.Where(x => _offlineNotificationServers.Contains(x.GuildId))
.Select(fs => _client.GetGuild(fs.GuildId)
?.GetTextChannel(fs.ChannelId)
?.EmbedAsync(GetEmbed(fs.GuildId, stream)));
await Task.WhenAll(sendTasks);
?.EmbedAsync(GetEmbed(fs.GuildId, stream)))
.WhenAll();
}
}
}
@@ -247,7 +246,7 @@ public sealed class StreamNotificationService : INService
var key = stream.CreateKey();
if (_shardTrackedStreams.TryGetValue(key, out var fss))
{
var sendTasks = fss
await fss
.SelectMany(x => x.Value)
.Select(fs =>
{
@@ -266,9 +265,8 @@ public sealed class StreamNotificationService : INService
: rep.Replace(fs.Message);
return textChannel.EmbedAsync(GetEmbed(fs.GuildId, stream), message);
});
await Task.WhenAll(sendTasks);
})
.WhenAll();
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net;
using LinqToDB;
using LinqToDB.EntityFrameworkCore;
@@ -102,7 +102,7 @@ public sealed class TranslateService : ITranslateService, ILateExecutor, IReadyE
if (string.IsNullOrWhiteSpace(text))
throw new ArgumentException("Text is empty or null", nameof(text));
var res = await _google.Translate(text, source, target).ConfigureAwait(false);
var res = await _google.Translate(text, source, target);
return res.SanitizeMentions(true);
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Searches.Services;
// public class YtTrackService : INService
@@ -31,7 +31,7 @@ namespace NadekoBot.Modules.Searches.Services;
// await Task.Delay(10000);
// using (var http = httpClientFactory.CreateClient())
// {
// await Task.WhenAll(followedChannels.Select(kvp => CheckChannel(kvp.Key, kvp.Value.SelectMany(x => x.Value).ToList())));
// await followedChannels.Select(kvp => CheckChannel(kvp.Key, kvp.Value.SelectMany(x => x.Value).ToList())).WhenAll();
// }
// }
// }

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Modules.Searches.Services;
using NadekoBot.Db;
@@ -27,12 +27,12 @@ public partial class Searches
var data = await _service.FollowStream(ctx.Guild.Id, ctx.Channel.Id, link);
if (data is null)
{
await ReplyErrorLocalizedAsync(strs.stream_not_added).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.stream_not_added);
return;
}
var embed = _service.GetEmbed(ctx.Guild.Id, data);
await ctx.Channel.EmbedAsync(embed, GetText(strs.stream_tracked)).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed, GetText(strs.stream_tracked));
}
[NadekoCommand, Aliases]
@@ -47,7 +47,7 @@ public partial class Searches
var fs = await _service.UnfollowStreamAsync(ctx.Guild.Id, index);
if (fs is null)
{
await ReplyErrorLocalizedAsync(strs.stream_no).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.stream_no);
return;
}
@@ -123,7 +123,7 @@ public partial class Searches
}
return eb;
}, streams.Count, 12).ConfigureAwait(false);
}, streams.Count, 12);
}
[NadekoCommand, Aliases]
@@ -134,11 +134,11 @@ public partial class Searches
var newValue = _service.ToggleStreamOffline(ctx.Guild.Id);
if (newValue)
{
await ReplyConfirmLocalizedAsync(strs.stream_off_enabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.stream_off_enabled);
}
else
{
await ReplyConfirmLocalizedAsync(strs.stream_off_disabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.stream_off_disabled);
}
}
@@ -152,7 +152,7 @@ public partial class Searches
if (!_service.SetStreamMessage(ctx.Guild.Id, index, message, out var fs))
{
await ReplyConfirmLocalizedAsync(strs.stream_not_following).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.stream_not_following);
return;
}
@@ -188,10 +188,10 @@ public partial class Searches
{
try
{
var data = await _service.GetStreamDataAsync(url).ConfigureAwait(false);
var data = await _service.GetStreamDataAsync(url);
if (data is null)
{
await ReplyErrorLocalizedAsync(strs.no_channel_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_channel_found);
return;
}
@@ -208,7 +208,7 @@ public partial class Searches
}
catch
{
await ReplyErrorLocalizedAsync(strs.no_channel_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_channel_found);
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Searches;
public partial class Searches
@@ -11,8 +11,8 @@ public partial class Searches
{
try
{
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
var translation = await _service.Translate(from, to, text).ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var translation = await _service.Translate(from, to, text);
var embed = _eb.Create(ctx)
.WithOkColor()
@@ -23,7 +23,7 @@ public partial class Searches
}
catch
{
await ReplyErrorLocalizedAsync(strs.bad_input_format).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.bad_input_format);
}
}
@@ -43,11 +43,11 @@ public partial class Searches
var toggle = await _service.ToggleAtl(ctx.Guild.Id, ctx.Channel.Id, autoDelete == AutoDeleteAutoTranslate.Del);
if (toggle)
{
await ReplyConfirmLocalizedAsync(strs.atl_started).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.atl_started);
}
else
{
await ReplyConfirmLocalizedAsync(strs.atl_stopped).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.atl_stopped);
}
}
@@ -57,7 +57,7 @@ public partial class Searches
{
if (await _service.UnregisterUser(ctx.Channel.Id, ctx.User.Id))
{
await ReplyConfirmLocalizedAsync(strs.atl_removed).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.atl_removed);
}
}
@@ -78,7 +78,7 @@ public partial class Searches
if (succ is false)
{
await ReplyErrorLocalizedAsync(strs.invalid_lang).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.invalid_lang);
return;
}
@@ -88,6 +88,6 @@ public partial class Searches
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Translangs()
=> await ctx.Channel.SendTableAsync(_service.GetLanguages(), str => $"{str,-15}", 3).ConfigureAwait(false);
=> await ctx.Channel.SendTableAsync(_service.GetLanguages(), str => $"{str,-15}", 3);
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Newtonsoft.Json;
namespace NadekoBot.Modules.Searches;
@@ -23,27 +23,26 @@ public partial class Searches
try
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"{_xkcdUrl}/info.0.json").ConfigureAwait(false);
var res = await http.GetStringAsync($"{_xkcdUrl}/info.0.json");
var comic = JsonConvert.DeserializeObject<XkcdComic>(res);
var embed = _eb.Create().WithOkColor()
.WithImageUrl(comic.ImageLink)
.WithAuthor(comic.Title, "https://xkcd.com/s/919f27.ico", $"{_xkcdUrl}/{comic.Num}")
.AddField(GetText(strs.comic_number), comic.Num.ToString(), true)
.AddField(GetText(strs.date), $"{comic.Month}/{comic.Year}", true);
var sent = await ctx.Channel.EmbedAsync(embed)
.ConfigureAwait(false);
var sent = await ctx.Channel.EmbedAsync(embed);
await Task.Delay(10000).ConfigureAwait(false);
await Task.Delay(10000);
await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build()).ConfigureAwait(false);
await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build());
}
catch (HttpRequestException)
{
await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.comic_not_found);
}
return;
}
await Xkcd(new NadekoRandom().Next(1, 1750)).ConfigureAwait(false);
await Xkcd(new NadekoRandom().Next(1, 1750));
}
[NadekoCommand, Aliases]
@@ -55,7 +54,7 @@ public partial class Searches
try
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"{_xkcdUrl}/{num}/info.0.json").ConfigureAwait(false);
var res = await http.GetStringAsync($"{_xkcdUrl}/{num}/info.0.json");
var comic = JsonConvert.DeserializeObject<XkcdComic>(res);
var embed = _eb.Create()
@@ -65,16 +64,15 @@ public partial class Searches
.AddField(GetText(strs.comic_number), comic.Num.ToString(), true)
.AddField(GetText(strs.date), $"{comic.Month}/{comic.Year}", true);
var sent = await ctx.Channel.EmbedAsync(embed)
.ConfigureAwait(false);
var sent = await ctx.Channel.EmbedAsync(embed);
await Task.Delay(10000).ConfigureAwait(false);
await Task.Delay(10000);
await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build()).ConfigureAwait(false);
await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build());
}
catch (HttpRequestException)
{
await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.comic_not_found);
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Searches;
public partial class Searches
@@ -13,11 +13,11 @@ public partial class Searches
// var succ = await _service.ToggleChannelFollowAsync(ctx.Guild.Id, ctx.Channel.Id, ytChannelId, uploadMessage);
// if(succ)
// {
// await ReplyConfirmLocalizedAsync(strs.yt_follow_added).ConfigureAwait(false);
// await ReplyConfirmLocalizedAsync(strs.yt_follow_added);
// }
// else
// {
// await ReplyConfirmLocalizedAsync(strs.yt_follow_fail).ConfigureAwait(false);
// await ReplyConfirmLocalizedAsync(strs.yt_follow_fail);
// }
// }
//
@@ -28,11 +28,11 @@ public partial class Searches
// //var succ = await _service.ToggleChannelTrackingAsync(ctx.Guild.Id, ctx.Channel.Id, ytChannelId, uploadMessage);
// //if (succ)
// //{
// // await ReplyConfirmLocalizedAsync(strs.yt_track_added).ConfigureAwait(false);
// // await ReplyConfirmLocalizedAsync(strs.yt_track_added);
// //}
// //else
// //{
// // await ReplyConfirmLocalizedAsync(strs.yt_track_fail).ConfigureAwait(false);
// // await ReplyConfirmLocalizedAsync(strs.yt_track_fail);
// //}
// }
//
@@ -43,11 +43,11 @@ public partial class Searches
// //var succ = await _service.ToggleChannelTrackingAsync(ctx.Guild.Id, ctx.Channel.Id, ytChannelId, uploadMessage);
// //if (succ)
// //{
// // await ReplyConfirmLocalizedAsync(strs.yt_track_added).ConfigureAwait(false);
// // await ReplyConfirmLocalizedAsync(strs.yt_track_added);
// //}
// //else
// //{
// // await ReplyConfirmLocalizedAsync(strs.yt_track_fail).ConfigureAwait(false);
// // await ReplyConfirmLocalizedAsync(strs.yt_track_fail);
// //}
// }
// }