Applied codestyle to all .cs files

This commit is contained in:
Kwoth
2021-12-29 06:07:16 +01:00
parent 723447c7d4
commit 82000c97a4
543 changed files with 13221 additions and 14059 deletions

View File

@@ -2,6 +2,7 @@
using AngleSharp;
using AngleSharp.Html.Dom;
using Microsoft.Extensions.Caching.Memory;
using NadekoBot.Modules.Administration.Services;
using NadekoBot.Modules.Searches.Common;
using NadekoBot.Modules.Searches.Services;
using Newtonsoft.Json;
@@ -11,20 +12,25 @@ using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.Net;
using NadekoBot.Modules.Administration.Services;
using Color = SixLabors.ImageSharp.Color;
using Configuration = AngleSharp.Configuration;
namespace NadekoBot.Modules.Searches;
public partial class Searches : NadekoModule<SearchesService>
{
private static readonly ConcurrentDictionary<string, string> cachedShortenedLinks = new();
private readonly IBotCredentials _creds;
private readonly IGoogleApiService _google;
private readonly IHttpClientFactory _httpFactory;
private readonly IMemoryCache _cache;
private readonly GuildTimezoneService _tzSvc;
public Searches(IBotCredentials creds, IGoogleApiService google, IHttpClientFactory factory, IMemoryCache cache,
public Searches(
IBotCredentials creds,
IGoogleApiService google,
IHttpClientFactory factory,
IMemoryCache cache,
GuildTimezoneService tzSvc)
{
_creds = creds;
@@ -34,21 +40,21 @@ public partial class Searches : NadekoModule<SearchesService>
_tzSvc = tzSvc;
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Rip([Leftover] IGuildUser usr)
{
var av = usr.RealAvatarUrl();
if (av is null)
return;
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()));
await ctx.Channel.SendFileAsync(picStream,
"rip.png",
$"Rip {Format.Bold(usr.ToString())} \n\t- " + Format.Italics(ctx.User.ToString()));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Weather([Leftover] string query)
{
if (!await ValidateQuery(query))
@@ -59,38 +65,47 @@ public partial class Searches : NadekoModule<SearchesService>
if (data is null)
{
embed.WithDescription(GetText(strs.city_not_found))
.WithErrorColor();
embed.WithDescription(GetText(strs.city_not_found)).WithErrorColor();
}
else
{
var f = StandardConversions.CelsiusToFahrenheit;
var tz = ctx.Guild is null
? TimeZoneInfo.Utc
: _tzSvc.GetTimeZoneOrUtc(ctx.Guild.Id);
var tz = ctx.Guild is null ? TimeZoneInfo.Utc : _tzSvc.GetTimeZoneOrUtc(ctx.Guild.Id);
var sunrise = data.Sys.Sunrise.ToUnixTimestamp();
var sunset = data.Sys.Sunset.ToUnixTimestamp();
sunrise = sunrise.ToOffset(tz.GetUtcOffset(sunrise));
sunset = sunset.ToOffset(tz.GetUtcOffset(sunset));
var timezone = $"UTC{sunrise:zzz}";
embed.AddField("🌍 " + Format.Bold(GetText(strs.location)), $"[{data.Name + ", " + data.Sys.Country}](https://openweathermap.org/city/{data.Id})", true)
embed
.AddField("🌍 " + Format.Bold(GetText(strs.location)),
$"[{data.Name + ", " + data.Sys.Country}](https://openweathermap.org/city/{data.Id})",
true)
.AddField("📏 " + Format.Bold(GetText(strs.latlong)), $"{data.Coord.Lat}, {data.Coord.Lon}", true)
.AddField("☁ " + Format.Bold(GetText(strs.condition)), string.Join(", ", data.Weather.Select(w => w.Main)), true)
.AddField("☁ " + Format.Bold(GetText(strs.condition)),
string.Join(", ", data.Weather.Select(w => w.Main)),
true)
.AddField("😓 " + Format.Bold(GetText(strs.humidity)), $"{data.Main.Humidity}%", true)
.AddField("💨 " + Format.Bold(GetText(strs.wind_speed)), data.Wind.Speed + " m/s", true)
.AddField("🌡 " + Format.Bold(GetText(strs.temperature)), $"{data.Main.Temp:F1}°C / {f(data.Main.Temp):F1}°F", true)
.AddField("🔆 " + Format.Bold(GetText(strs.min_max)), $"{data.Main.TempMin:F1}°C - {data.Main.TempMax:F1}°C\n{f(data.Main.TempMin):F1}°F - {f(data.Main.TempMax):F1}°F", true)
.AddField("🌡 " + Format.Bold(GetText(strs.temperature)),
$"{data.Main.Temp:F1}°C / {f(data.Main.Temp):F1}°F",
true)
.AddField("🔆 " + Format.Bold(GetText(strs.min_max)),
$"{data.Main.TempMin:F1}°C - {data.Main.TempMax:F1}°C\n{f(data.Main.TempMin):F1}°F - {f(data.Main.TempMax):F1}°F",
true)
.AddField("🌄 " + Format.Bold(GetText(strs.sunrise)), $"{sunrise:HH:mm} {timezone}", true)
.AddField("🌇 " + Format.Bold(GetText(strs.sunset)), $"{sunset:HH:mm} {timezone}", true)
.WithOkColor()
.WithFooter("Powered by openweathermap.org", $"http://openweathermap.org/img/w/{data.Weather[0].Icon}.png");
.WithFooter("Powered by openweathermap.org",
$"http://openweathermap.org/img/w/{data.Weather[0].Icon}.png");
}
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Time([Leftover] string query)
{
if (!await ValidateQuery(query))
@@ -117,26 +132,29 @@ public partial class Searches : NadekoModule<SearchesService>
errorKey = strs.error_occured;
break;
}
await ReplyErrorLocalizedAsync(errorKey);
return;
}
else if (string.IsNullOrWhiteSpace(data.TimeZoneName))
if (string.IsNullOrWhiteSpace(data.TimeZoneName))
{
await ReplyErrorLocalizedAsync(strs.timezone_db_api_key);
return;
}
var eb = _eb.Create()
.WithOkColor()
.WithTitle(GetText(strs.time_new))
.WithDescription(Format.Code(data.Time.ToString()))
.AddField(GetText(strs.location), string.Join('\n', data.Address.Split(", ")), true)
.AddField(GetText(strs.timezone), data.TimeZoneName, true);
.WithOkColor()
.WithTitle(GetText(strs.time_new))
.WithDescription(Format.Code(data.Time.ToString()))
.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());
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Youtube([Leftover] string query = null)
{
if (!await ValidateQuery(query))
@@ -152,7 +170,8 @@ public partial class Searches : NadekoModule<SearchesService>
await ctx.Channel.SendMessageAsync(result);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Movie([Leftover] string query = null)
{
if (!await ValidateQuery(query))
@@ -166,37 +185,46 @@ public partial class Searches : NadekoModule<SearchesService>
await ReplyErrorLocalizedAsync(strs.imdb_fail);
return;
}
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle(movie.Title)
.WithUrl($"http://www.imdb.com/title/{movie.ImdbId}/")
.WithDescription(movie.Plot.TrimTo(1000))
.AddField("Rating", movie.ImdbRating, true)
.AddField("Genre", movie.Genre, true)
.AddField("Year", movie.Year, true)
.WithImageUrl(movie.Poster));
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithTitle(movie.Title)
.WithUrl($"http://www.imdb.com/title/{movie.ImdbId}/")
.WithDescription(movie.Plot.TrimTo(1000))
.AddField("Rating", movie.ImdbRating, true)
.AddField("Genre", movie.Genre, true)
.AddField("Year", movie.Year, true)
.WithImageUrl(movie.Poster));
}
[NadekoCommand, Aliases]
public Task RandomCat() => InternalRandomImage(SearchesService.ImageTag.Cats);
[NadekoCommand]
[Aliases]
public Task RandomCat()
=> InternalRandomImage(SearchesService.ImageTag.Cats);
[NadekoCommand, Aliases]
public Task RandomDog() => InternalRandomImage(SearchesService.ImageTag.Dogs);
[NadekoCommand]
[Aliases]
public Task RandomDog()
=> InternalRandomImage(SearchesService.ImageTag.Dogs);
[NadekoCommand, Aliases]
public Task RandomFood() => InternalRandomImage(SearchesService.ImageTag.Food);
[NadekoCommand]
[Aliases]
public Task RandomFood()
=> InternalRandomImage(SearchesService.ImageTag.Food);
[NadekoCommand, Aliases]
public Task RandomBird() => InternalRandomImage(SearchesService.ImageTag.Birds);
[NadekoCommand]
[Aliases]
public Task RandomBird()
=> InternalRandomImage(SearchesService.ImageTag.Birds);
private Task InternalRandomImage(SearchesService.ImageTag tag)
{
var url = _service.GetRandomImageUrl(tag);
return ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithImageUrl(url));
return ctx.Channel.EmbedAsync(_eb.Create().WithOkColor().WithImageUrl(url));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Image([Leftover] string query = null)
{
var oterms = query?.Trim();
@@ -207,20 +235,20 @@ public partial class Searches : NadekoModule<SearchesService>
{
var res = await _google.GetImageAsync(oterms);
var embed = _eb.Create()
.WithOkColor()
.WithAuthor(GetText(strs.image_search_for) + " " + oterms.TrimTo(50),
"http://i.imgur.com/G46fm8J.png",
$"https://www.google.rs/search?q={query}&source=lnms&tbm=isch")
.WithDescription(res.Link)
.WithImageUrl(res.Link)
.WithTitle(ctx.User.ToString());
.WithOkColor()
.WithAuthor(GetText(strs.image_search_for) + " " + oterms.TrimTo(50),
"http://i.imgur.com/G46fm8J.png",
$"https://www.google.rs/search?q={query}&source=lnms&tbm=isch")
.WithDescription(res.Link)
.WithImageUrl(res.Link)
.WithTitle(ctx.User.ToString());
await ctx.Channel.EmbedAsync(embed);
}
catch
{
Log.Warning("Falling back to Imgur");
var fullQueryLink = $"http://imgur.com/search?q={ query }";
var fullQueryLink = $"http://imgur.com/search?q={query}";
var config = Configuration.Default.WithDefaultLoader();
using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink);
var elems = document.QuerySelectorAll("a.image-list-link").ToList();
@@ -228,7 +256,9 @@ public partial class Searches : NadekoModule<SearchesService>
if (!elems.Any())
return;
var img = elems.ElementAtOrDefault(new NadekoRandom().Next(0, elems.Count))?.Children?.FirstOrDefault() as IHtmlImageElement;
var img =
elems.ElementAtOrDefault(new NadekoRandom().Next(0, elems.Count))?.Children?.FirstOrDefault() as
IHtmlImageElement;
if (img?.Source is null)
return;
@@ -236,18 +266,19 @@ public partial class Searches : NadekoModule<SearchesService>
var source = img.Source.Replace("b.", ".", StringComparison.InvariantCulture);
var embed = _eb.Create()
.WithOkColor()
.WithAuthor(GetText(strs.image_search_for) + " " + oterms.TrimTo(50),
"http://s.imgur.com/images/logo-1200-630.jpg?",
fullQueryLink)
.WithDescription(source)
.WithImageUrl(source)
.WithTitle(ctx.User.ToString());
.WithOkColor()
.WithAuthor(GetText(strs.image_search_for) + " " + oterms.TrimTo(50),
"http://s.imgur.com/images/logo-1200-630.jpg?",
fullQueryLink)
.WithDescription(source)
.WithImageUrl(source)
.WithTitle(ctx.User.ToString());
await ctx.Channel.EmbedAsync(embed);
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Lmgtfy([Leftover] string ffs = null)
{
if (!await ValidateQuery(ffs))
@@ -257,15 +288,8 @@ public partial class Searches : NadekoModule<SearchesService>
await SendConfirmAsync($"<{shortenedUrl}>");
}
public class ShortenData
{
[JsonProperty("result_url")]
public string ResultUrl { get; set; }
}
private static readonly ConcurrentDictionary<string, string> cachedShortenedLinks = new();
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Shorten([Leftover] string query)
{
if (!await ValidateQuery(query))
@@ -273,15 +297,11 @@ public partial class Searches : NadekoModule<SearchesService>
query = query.Trim();
if (!cachedShortenedLinks.TryGetValue(query, out var shortLink))
{
try
{
using var _http = _httpFactory.CreateClient();
using var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten");
var formData = new MultipartFormDataContent
{
{ new StringContent(query), "url" }
};
var formData = new MultipartFormDataContent { { new StringContent(query), "url" } };
req.Content = formData;
using var res = await _http.SendAsync(req);
@@ -300,15 +320,15 @@ public partial class Searches : NadekoModule<SearchesService>
Log.Error(ex, "Error shortening a link: {Message}", ex.Message);
return;
}
}
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.AddField(GetText(strs.original_url), $"<{query}>")
.AddField(GetText(strs.short_url), $"<{shortLink}>"));
.WithOkColor()
.AddField(GetText(strs.original_url), $"<{query}>")
.AddField(GetText(strs.short_url), $"<{shortLink}>"));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Google([Leftover] string query = null)
{
query = query?.Trim();
@@ -316,32 +336,32 @@ public partial class Searches : NadekoModule<SearchesService>
return;
_ = ctx.Channel.TriggerTypingAsync();
var data = await _service.GoogleSearchAsync(query);
if (data is null)
{
await ReplyErrorLocalizedAsync(strs.no_results);
return;
}
var desc = data.Results.Take(5).Select(res =>
$@"[**{res.Title}**]({res.Link})
var desc = data.Results.Take(5)
.Select(res => $@"[**{res.Title}**]({res.Link})
{res.Text.TrimTo(400 - res.Title.Length - res.Link.Length)}");
var descStr = string.Join("\n\n", desc);
var embed = _eb.Create()
.WithAuthor(ctx.User.ToString(),
iconUrl: "http://i.imgur.com/G46fm8J.png")
.WithTitle(ctx.User.ToString())
.WithFooter(data.TotalResults)
.WithDescription($"{GetText(strs.search_for)} **{query}**\n\n" +descStr)
.WithOkColor();
.WithAuthor(ctx.User.ToString(), "http://i.imgur.com/G46fm8J.png")
.WithTitle(ctx.User.ToString())
.WithFooter(data.TotalResults)
.WithDescription($"{GetText(strs.search_for)} **{query}**\n\n" + descStr)
.WithOkColor();
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task DuckDuckGo([Leftover] string query = null)
{
query = query?.Trim();
@@ -349,30 +369,31 @@ public partial class Searches : NadekoModule<SearchesService>
return;
_ = ctx.Channel.TriggerTypingAsync();
var data = await _service.DuckDuckGoSearchAsync(query);
if (data is null)
{
await ReplyErrorLocalizedAsync(strs.no_results);
return;
}
var desc = data.Results.Take(5).Select(res =>
$@"[**{res.Title}**]({res.Link})
var desc = data.Results.Take(5)
.Select(res => $@"[**{res.Title}**]({res.Link})
{res.Text.TrimTo(380 - res.Title.Length - res.Link.Length)}");
var descStr = string.Join("\n\n", desc);
var embed = _eb.Create()
.WithAuthor(ctx.User.ToString(),
iconUrl: "https://upload.wikimedia.org/wikipedia/en/9/90/The_DuckDuckGo_Duck.png")
.WithDescription($"{GetText(strs.search_for)} **{query}**\n\n" + descStr)
.WithOkColor();
.WithAuthor(ctx.User.ToString(),
"https://upload.wikimedia.org/wikipedia/en/9/90/The_DuckDuckGo_Duck.png")
.WithDescription($"{GetText(strs.search_for)} **{query}**\n\n" + descStr)
.WithOkColor();
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task MagicTheGathering([Leftover] string search)
{
if (!await ValidateQuery(search))
@@ -387,18 +408,20 @@ public partial class Searches : NadekoModule<SearchesService>
return;
}
var embed = _eb.Create().WithOkColor()
.WithTitle(card.Name)
.WithDescription(card.Description)
.WithImageUrl(card.ImageUrl)
.AddField(GetText(strs.store_url), card.StoreUrl, true)
.AddField(GetText(strs.cost), card.ManaCost, true)
.AddField(GetText(strs.types), card.Types, true);
var embed = _eb.Create()
.WithOkColor()
.WithTitle(card.Name)
.WithDescription(card.Description)
.WithImageUrl(card.ImageUrl)
.AddField(GetText(strs.store_url), card.StoreUrl, true)
.AddField(GetText(strs.cost), card.ManaCost, true)
.AddField(GetText(strs.types), card.Types, true);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Hearthstone([Leftover] string name)
{
var arg = name;
@@ -419,8 +442,8 @@ public partial class Searches : NadekoModule<SearchesService>
await ReplyErrorLocalizedAsync(strs.card_not_found);
return;
}
var embed = _eb.Create().WithOkColor()
.WithImageUrl(card.Img);
var embed = _eb.Create().WithOkColor().WithImageUrl(card.Img);
if (!string.IsNullOrWhiteSpace(card.Flavor))
embed.WithDescription(card.Flavor);
@@ -428,7 +451,8 @@ public partial class Searches : NadekoModule<SearchesService>
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task UrbanDict([Leftover] string query = null)
{
if (!await ValidateQuery(query))
@@ -437,21 +461,25 @@ public partial class Searches : NadekoModule<SearchesService>
await ctx.Channel.TriggerTypingAsync();
using (var http = _httpFactory.CreateClient())
{
var res = await http.GetStringAsync($"http://api.urbandictionary.com/v0/define?term={Uri.EscapeDataString(query)}");
var res = await http.GetStringAsync(
$"http://api.urbandictionary.com/v0/define?term={Uri.EscapeDataString(query)}");
try
{
var items = JsonConvert.DeserializeObject<UrbanResponse>(res).List;
if (items.Any())
{
await ctx.SendPaginatedConfirmAsync(0, p =>
{
var item = items[p];
return _eb.Create().WithOkColor()
.WithUrl(item.Permalink)
.WithAuthor(item.Word)
.WithDescription(item.Definition);
}, items.Length, 1);
await ctx.SendPaginatedConfirmAsync(0,
p =>
{
var item = items[p];
return _eb.Create()
.WithOkColor()
.WithUrl(item.Permalink)
.WithAuthor(item.Word)
.WithDescription(item.Definition);
},
items.Length,
1);
return;
}
}
@@ -459,11 +487,12 @@ public partial class Searches : NadekoModule<SearchesService>
{
}
}
await ReplyErrorLocalizedAsync(strs.ud_error);
await ReplyErrorLocalizedAsync(strs.ud_error);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Define([Leftover] string word)
{
if (!await ValidateQuery(word))
@@ -473,17 +502,21 @@ public partial class Searches : NadekoModule<SearchesService>
string res;
try
{
res = await _cache.GetOrCreateAsync($"define_{word}", e =>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12);
return _http.GetStringAsync("https://api.pearson.com/v2/dictionaries/entries?headword=" + WebUtility.UrlEncode(word));
});
res = await _cache.GetOrCreateAsync($"define_{word}",
e =>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12);
return _http.GetStringAsync("https://api.pearson.com/v2/dictionaries/entries?headword="
+ WebUtility.UrlEncode(word));
});
var data = JsonConvert.DeserializeObject<DefineModel>(res);
var datas = data.Results
.Where(x => x.Senses is not null && x.Senses.Count > 0 && x.Senses[0].Definition is not null)
.Select(x => (Sense: x.Senses[0], x.PartOfSpeech));
.Where(x => x.Senses is not null
&& x.Senses.Count > 0
&& x.Senses[0].Definition is not null)
.Select(x => (Sense: x.Senses[0], x.PartOfSpeech));
if (!datas.Any())
{
@@ -493,33 +526,35 @@ public partial class Searches : NadekoModule<SearchesService>
var col = datas.Select(data => (
Definition: data.Sense.Definition is string
? data.Sense.Definition.ToString()
: ((JArray)JToken.Parse(data.Sense.Definition.ToString())).First.ToString(),
Example: data.Sense.Examples is null || data.Sense.Examples.Count == 0
? string.Empty
: data.Sense.Examples[0].Text,
Word: word,
WordType: string.IsNullOrWhiteSpace(data.PartOfSpeech) ? "-" : data.PartOfSpeech
)).ToList();
Definition: data.Sense.Definition is string
? data.Sense.Definition.ToString()
: ((JArray)JToken.Parse(data.Sense.Definition.ToString())).First.ToString(),
Example: data.Sense.Examples is null || data.Sense.Examples.Count == 0
? string.Empty
: data.Sense.Examples[0].Text, Word: word,
WordType: string.IsNullOrWhiteSpace(data.PartOfSpeech) ? "-" : data.PartOfSpeech))
.ToList();
Log.Information($"Sending {col.Count} definition for: {word}");
await ctx.SendPaginatedConfirmAsync(0, page =>
{
var data = col.Skip(page).First();
var embed = _eb.Create()
.WithDescription(ctx.User.Mention)
.AddField(GetText(strs.word), data.Word, true)
.AddField(GetText(strs._class), data.WordType, true)
.AddField(GetText(strs.definition), data.Definition)
.WithOkColor();
await ctx.SendPaginatedConfirmAsync(0,
page =>
{
var data = col.Skip(page).First();
var embed = _eb.Create()
.WithDescription(ctx.User.Mention)
.AddField(GetText(strs.word), data.Word, true)
.AddField(GetText(strs._class), data.WordType, true)
.AddField(GetText(strs.definition), data.Definition)
.WithOkColor();
if (!string.IsNullOrWhiteSpace(data.Example))
embed.AddField(GetText(strs.example), data.Example);
if (!string.IsNullOrWhiteSpace(data.Example))
embed.AddField(GetText(strs.example), data.Example);
return embed;
}, col.Count, 1);
return embed;
},
col.Count,
1);
}
catch (Exception ex)
{
@@ -527,7 +562,8 @@ public partial class Searches : NadekoModule<SearchesService>
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Catfact()
{
using var http = _httpFactory.CreateClient();
@@ -540,7 +576,8 @@ public partial class Searches : NadekoModule<SearchesService>
}
//done in 3.0
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task Revav([Leftover] IGuildUser usr = null)
{
@@ -555,7 +592,8 @@ public partial class Searches : NadekoModule<SearchesService>
}
//done in 3.0
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Revimg([Leftover] string imageLink = null)
{
imageLink = imageLink?.Trim() ?? "";
@@ -565,7 +603,8 @@ public partial class Searches : NadekoModule<SearchesService>
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}");
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Wiki([Leftover] string query = null)
{
query = query?.Trim();
@@ -574,7 +613,9 @@ public partial class Searches : NadekoModule<SearchesService>
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));
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);
@@ -582,32 +623,28 @@ public partial class Searches : NadekoModule<SearchesService>
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl);
}
[NadekoCommand, Aliases]
public async Task Color(params SixLabors.ImageSharp.Color[] colors)
[NadekoCommand]
[Aliases]
public async Task Color(params Color[] colors)
{
if (!colors.Any())
return;
var colorObjects = colors.Take(10)
.ToArray();
var colorObjects = colors.Take(10).ToArray();
using var img = new Image<Rgba32>(colorObjects.Length * 50, 50);
for (var i = 0; i < colorObjects.Length; i++)
{
var x = i * 50;
img.Mutate(m => m.FillPolygon(colorObjects[i], new PointF[] {
new(x, 0),
new(x + 50, 0),
new(x + 50, 50),
new(x, 50)
}));
img.Mutate(m => m.FillPolygon(colorObjects[i], new(x, 0), new(x + 50, 0), new(x + 50, 50), new(x, 50)));
}
await using var ms = img.ToStream();
await ctx.Channel.SendFileAsync(ms, $"colors.png");
await ctx.Channel.SendFileAsync(ms, "colors.png");
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task Avatar([Leftover] IGuildUser usr = null)
{
@@ -622,13 +659,17 @@ public partial class Searches : NadekoModule<SearchesService>
return;
}
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.AddField("Username", usr.ToString())
.AddField("Avatar Url", avatarUrl)
.WithThumbnailUrl(avatarUrl.ToString()), ctx.User.Mention);
await ctx.Channel.EmbedAsync(
_eb.Create()
.WithOkColor()
.AddField("Username", usr.ToString())
.AddField("Avatar Url", avatarUrl)
.WithThumbnailUrl(avatarUrl.ToString()),
ctx.User.Mention);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Wikia(string target, [Leftover] string query)
{
if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query))
@@ -636,20 +677,21 @@ public partial class Searches : NadekoModule<SearchesService>
await ReplyErrorLocalizedAsync(strs.wikia_input_error);
return;
}
await ctx.Channel.TriggerTypingAsync();
using var http = _httpFactory.CreateClient();
http.DefaultRequestHeaders.Clear();
try
{
var res = await http.GetStringAsync($"https://{Uri.EscapeDataString(target)}.fandom.com/api.php" +
$"?action=query" +
$"&format=json" +
$"&list=search" +
$"&srsearch={Uri.EscapeDataString(query)}" +
$"&srlimit=1");
var res = await http.GetStringAsync($"https://{Uri.EscapeDataString(target)}.fandom.com/api.php"
+ "?action=query"
+ "&format=json"
+ "&list=search"
+ $"&srsearch={Uri.EscapeDataString(query)}"
+ "&srlimit=1");
var items = JObject.Parse(res);
var title = items["query"]?["search"]?.FirstOrDefault()?["title"]?.ToString();
if (string.IsNullOrWhiteSpace(title))
{
await ReplyErrorLocalizedAsync(strs.wikia_error);
@@ -667,7 +709,8 @@ public partial class Searches : NadekoModule<SearchesService>
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task Bible(string book, string chapterAndVerse)
{
@@ -675,27 +718,30 @@ public partial class Searches : NadekoModule<SearchesService>
try
{
using var http = _httpFactory.CreateClient();
var res = await http
.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse);
var res = await http.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse);
obj = JsonConvert.DeserializeObject<BibleVerses>(res);
}
catch
{
}
if (obj.Error != null || obj.Verses is null || obj.Verses.Length == 0)
{
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));
.WithOkColor()
.WithTitle($"{v.BookName} {v.Chapter}:{v.Verse}")
.WithDescription(v.Text));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Steam([Leftover] string query)
{
if (string.IsNullOrWhiteSpace(query))
@@ -725,12 +771,15 @@ public partial class Searches : NadekoModule<SearchesService>
public async Task<bool> ValidateQuery(string query)
{
if (!string.IsNullOrWhiteSpace(query))
{
return true;
}
if (!string.IsNullOrWhiteSpace(query)) return true;
await ErrorLocalizedAsync(strs.specify_search_params);
return false;
}
}
public class ShortenData
{
[JsonProperty("result_url")]
public string ResultUrl { get; set; }
}
}