-
Notifications
You must be signed in to change notification settings - Fork 0
/
Searches.cs
615 lines (524 loc) · 21.5 KB
/
Searches.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#nullable disable
using Microsoft.Extensions.Caching.Memory;
using NadekoBot.Modules.Administration.Services;
using NadekoBot.Modules.Searches.Common;
using NadekoBot.Modules.Searches.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Nadeko.Common;
using Color = SixLabors.ImageSharp.Color;
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,
GuildTimezoneService tzSvc)
{
_creds = creds;
_google = google;
_httpFactory = factory;
_cache = cache;
_tzSvc = tzSvc;
}
[Cmd]
public async Task Rip([Leftover] IGuildUser usr)
{
var av = usr.RealAvatarUrl();
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()));
}
[Cmd]
public async Task Weather([Leftover] string query)
{
if (!await ValidateQuery(query))
return;
var embed = _eb.Create();
var data = await _service.GetWeatherDataAsync(query);
if (data is null)
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 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)
.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.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.sunrise)), $"{sunrise:HH:mm} {timezone}", true)
.AddField("🌇 " + Format.Bold(GetText(strs.sunset)), $"{sunset:HH:mm} {timezone}", true)
.WithOkColor()
.WithFooter("Powered by openweathermap.org",
$"https://openweathermap.org/img/w/{data.Weather[0].Icon}.png");
}
await ctx.Channel.EmbedAsync(embed);
}
[Cmd]
public async Task Time([Leftover] string query)
{
if (!await ValidateQuery(query))
return;
await ctx.Channel.TriggerTypingAsync();
var (data, err) = await _service.GetTimeDataAsync(query);
if (err is not null)
{
LocStr errorKey;
switch (err)
{
case TimeErrors.ApiKeyMissing:
errorKey = strs.api_key_missing;
break;
case TimeErrors.InvalidInput:
errorKey = strs.invalid_input;
break;
case TimeErrors.NotFound:
errorKey = strs.not_found;
break;
default:
errorKey = strs.error_occured;
break;
}
await ReplyErrorLocalizedAsync(errorKey);
return;
}
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(Culture)))
.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());
}
[Cmd]
public async Task Movie([Leftover] string query = null)
{
if (!await ValidateQuery(query))
return;
await ctx.Channel.TriggerTypingAsync();
var movie = await _service.GetMovieDataAsync(query);
if (movie is null)
{
await ReplyErrorLocalizedAsync(strs.imdb_fail);
return;
}
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithTitle(movie.Title)
.WithUrl($"https://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));
}
[Cmd]
public Task RandomCat()
=> InternalRandomImage(SearchesService.ImageTag.Cats);
[Cmd]
public Task RandomDog()
=> InternalRandomImage(SearchesService.ImageTag.Dogs);
[Cmd]
public Task RandomFood()
=> InternalRandomImage(SearchesService.ImageTag.Food);
[Cmd]
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));
}
[Cmd]
public async Task Lmgtfy([Leftover] string ffs = null)
{
if (!await ValidateQuery(ffs))
return;
var shortenedUrl = await _google.ShortenUrl($"https://lmgtfy.com/?q={Uri.EscapeDataString(ffs)}");
await SendConfirmAsync($"<{shortenedUrl}>");
}
[Cmd]
public async Task Shorten([Leftover] string query)
{
if (!await ValidateQuery(query))
return;
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" }
};
req.Content = formData;
using var res = await http.SendAsync(req);
var content = await res.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ShortenData>(content);
if (!string.IsNullOrWhiteSpace(data?.ResultUrl))
_cachedShortenedLinks.TryAdd(query, data.ResultUrl);
else
return;
shortLink = data.ResultUrl;
}
catch (Exception ex)
{
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}>"));
}
[Cmd]
public async Task MagicTheGathering([Leftover] string search)
{
if (!await ValidateQuery(search))
return;
await ctx.Channel.TriggerTypingAsync();
var card = await _service.GetMtgCardAsync(search);
if (card is null)
{
await ReplyErrorLocalizedAsync(strs.card_not_found);
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);
await ctx.Channel.EmbedAsync(embed);
}
[Cmd]
public async Task Hearthstone([Leftover] string name)
{
if (!await ValidateQuery(name))
return;
if (string.IsNullOrWhiteSpace(_creds.RapidApiKey))
{
await ReplyErrorLocalizedAsync(strs.mashape_api_missing);
return;
}
await ctx.Channel.TriggerTypingAsync();
var card = await _service.GetHearthstoneCardDataAsync(name);
if (card is null)
{
await ReplyErrorLocalizedAsync(strs.card_not_found);
return;
}
var embed = _eb.Create().WithOkColor().WithImageUrl(card.Img);
if (!string.IsNullOrWhiteSpace(card.Flavor))
embed.WithDescription(card.Flavor);
await ctx.Channel.EmbedAsync(embed);
}
[Cmd]
public async Task UrbanDict([Leftover] string query = null)
{
if (!await ValidateQuery(query))
return;
await ctx.Channel.TriggerTypingAsync();
using (var http = _httpFactory.CreateClient())
{
var res = await http.GetStringAsync(
$"https://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);
return;
}
}
catch
{
}
}
await ReplyErrorLocalizedAsync(strs.ud_error);
}
[Cmd]
public async Task Define([Leftover] string word)
{
if (!await ValidateQuery(word))
return;
using var http = _httpFactory.CreateClient();
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));
});
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))
.ToList();
if (!datas.Any())
{
Log.Warning("Definition not found: {Word}", word);
await ReplyErrorLocalizedAsync(strs.define_unknown);
}
var col = datas.Select(x => (
Definition: x.Sense.Definition is string
? x.Sense.Definition.ToString()
: ((JArray)JToken.Parse(x.Sense.Definition.ToString())).First.ToString(),
Example: x.Sense.Examples is null || x.Sense.Examples.Count == 0
? string.Empty
: x.Sense.Examples[0].Text, Word: word,
WordType: string.IsNullOrWhiteSpace(x.PartOfSpeech) ? "-" : x.PartOfSpeech))
.ToList();
Log.Information("Sending {Count} definition for: {Word}", col.Count, word);
await ctx.SendPaginatedConfirmAsync(0,
page =>
{
var model = col.Skip(page).First();
var embed = _eb.Create()
.WithDescription(ctx.User.Mention)
.AddField(GetText(strs.word), model.Word, true)
.AddField(GetText(strs._class), model.WordType, true)
.AddField(GetText(strs.definition), model.Definition)
.WithOkColor();
if (!string.IsNullOrWhiteSpace(model.Example))
embed.AddField(GetText(strs.example), model.Example);
return embed;
},
col.Count,
1);
}
catch (Exception ex)
{
Log.Error(ex, "Error retrieving definition data for: {Word}", word);
}
}
[Cmd]
public async Task Catfact()
{
using var http = _httpFactory.CreateClient();
var response = await http.GetStringAsync("https://catfact.ninja/fact");
var fact = JObject.Parse(response)["fact"].ToString();
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact);
}
//done in 3.0
[Cmd]
[RequireContext(ContextType.Guild)]
public async Task Revav([Leftover] IGuildUser usr = null)
{
if (usr is null)
usr = (IGuildUser)ctx.User;
var av = usr.RealAvatarUrl();
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}");
}
//done in 3.0
[Cmd]
public async Task Revimg([Leftover] string imageLink = null)
{
imageLink = imageLink?.Trim() ?? "";
if (string.IsNullOrWhiteSpace(imageLink))
return;
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}");
}
[Cmd]
public async Task Wiki([Leftover] string query = null)
{
query = query?.Trim();
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));
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);
else
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl);
}
[Cmd]
public async Task Color(params Color[] colors)
{
if (!colors.Any())
return;
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(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");
}
[Cmd]
[RequireContext(ContextType.Guild)]
public async Task Avatar([Leftover] IGuildUser usr = null)
{
if (usr is null)
usr = (IGuildUser)ctx.User;
var avatarUrl = usr.RealAvatarUrl(2048);
await ctx.Channel.EmbedAsync(
_eb.Create()
.WithOkColor()
.AddField("Username", usr.ToString())
.AddField("Avatar Url", avatarUrl)
.WithThumbnailUrl(avatarUrl.ToString()),
ctx.User.Mention);
}
[Cmd]
public async Task Wikia(string target, [Leftover] string query)
{
if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query))
{
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 items = JObject.Parse(res);
var title = items["query"]?["search"]?.FirstOrDefault()?["title"]?.ToString();
if (string.IsNullOrWhiteSpace(title))
{
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);
}
catch
{
await ReplyErrorLocalizedAsync(strs.wikia_error);
}
}
[Cmd]
[RequireContext(ContextType.Guild)]
public async Task Bible(string book, string chapterAndVerse)
{
var obj = new BibleVerses();
try
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"https://bible-api.com/{book} {chapterAndVerse}");
obj = JsonConvert.DeserializeObject<BibleVerses>(res);
}
catch
{
}
if (obj.Error is not 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));
}
}
[Cmd]
public async Task Steam([Leftover] string query)
{
if (string.IsNullOrWhiteSpace(query))
return;
await ctx.Channel.TriggerTypingAsync();
var appId = await _service.GetSteamAppIdByName(query);
if (appId == -1)
{
await ReplyErrorLocalizedAsync(strs.not_found);
return;
}
//var embed = _eb.Create()
// .WithOkColor()
// .WithDescription(gameData.ShortDescription)
// .WithTitle(gameData.Name)
// .WithUrl(gameData.Link)
// .WithImageUrl(gameData.HeaderImage)
// .AddField(GetText(strs.genres), gameData.TotalEpisodes.ToString(), true)
// .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}");
}
private async Task<bool> ValidateQuery([MaybeNullWhen(false)] string query)
{
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; }
}
}