- Renamed CustomReaction model to NadekoExpression

- Used structured logging everywhere
This commit is contained in:
Kwoth
2022-01-04 07:35:55 +01:00
parent ef49030841
commit 3aa6a54b6e
30 changed files with 330 additions and 300 deletions

View File

@@ -19,7 +19,7 @@ namespace NadekoBot.Modules.Searches;
public partial class Searches : NadekoModule<SearchesService>
{
private static readonly ConcurrentDictionary<string, string> cachedShortenedLinks = new();
private static readonly ConcurrentDictionary<string, string> _cachedShortenedLinks = new();
private readonly IBotCredentials _creds;
private readonly IGoogleApiService _google;
private readonly IHttpClientFactory _httpFactory;
@@ -141,7 +141,7 @@ public partial class Searches : NadekoModule<SearchesService>
var eb = _eb.Create()
.WithOkColor()
.WithTitle(GetText(strs.time_new))
.WithDescription(Format.Code(data.Time.ToString()))
.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);
@@ -282,20 +282,20 @@ public partial class Searches : NadekoModule<SearchesService>
return;
query = query.Trim();
if (!cachedShortenedLinks.TryGetValue(query, out var shortLink))
if (!_cachedShortenedLinks.TryGetValue(query, out var shortLink))
try
{
using var _http = _httpFactory.CreateClient();
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);
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);
_cachedShortenedLinks.TryAdd(query, data.ResultUrl);
else
return;
@@ -406,7 +406,6 @@ public partial class Searches : NadekoModule<SearchesService>
[Cmd]
public async partial Task Hearthstone([Leftover] string name)
{
var arg = name;
if (!await ValidateQuery(name))
return;
@@ -496,7 +495,8 @@ public partial class Searches : NadekoModule<SearchesService>
.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));
.Select(x => (Sense: x.Senses[0], x.PartOfSpeech))
.ToList();
if (!datas.Any())
{
@@ -505,17 +505,17 @@ 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
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
: data.Sense.Examples[0].Text, Word: word,
WordType: string.IsNullOrWhiteSpace(data.PartOfSpeech) ? "-" : data.PartOfSpeech))
: x.Sense.Examples[0].Text, Word: word,
WordType: string.IsNullOrWhiteSpace(x.PartOfSpeech) ? "-" : x.PartOfSpeech))
.ToList();
Log.Information($"Sending {col.Count} definition for: {word}");
Log.Information("Sending {Count} definition for: {Word}", col.Count, word);
await ctx.SendPaginatedConfirmAsync(0,
page =>
@@ -547,8 +547,6 @@ public partial class Searches : NadekoModule<SearchesService>
{
using var http = _httpFactory.CreateClient();
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);
@@ -563,9 +561,6 @@ public partial class Searches : NadekoModule<SearchesService>
usr = (IGuildUser)ctx.User;
var av = usr.RealAvatarUrl();
if (av is null)
return;
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}");
}
@@ -690,7 +685,7 @@ 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);
}

View File

@@ -68,12 +68,12 @@ public class SearchesService : INService
if (File.Exists("data/wowjokes.json"))
WowJokes = JsonConvert.DeserializeObject<List<WoWJoke>>(File.ReadAllText("data/wowjokes.json"));
else
Log.Warning("data/wowjokes.json is missing. WOW Jokes are not loaded.");
Log.Warning("data/wowjokes.json is missing. WOW Jokes are not loaded");
if (File.Exists("data/magicitems.json"))
MagicItems = JsonConvert.DeserializeObject<List<MagicItem>>(File.ReadAllText("data/magicitems.json"));
else
Log.Warning("data/magicitems.json is missing. Magic items are not loaded.");
Log.Warning("data/magicitems.json is missing. Magic items are not loaded");
if (File.Exists("data/yomama.txt"))
{
@@ -165,14 +165,14 @@ public class SearchesService : INService
+ "appid=42cd627dd60debf25a5739e50a217d74&"
+ "units=metric");
if (data is null)
if (string.IsNullOrWhiteSpace(data))
return null;
return JsonConvert.DeserializeObject<WeatherData>(data);
}
catch (Exception ex)
{
Log.Warning(ex.Message);
Log.Warning(ex, "Error getting weather data");
return null;
}
}
@@ -196,7 +196,7 @@ public class SearchesService : INService
try
{
using var _http = _httpFactory.CreateClient();
using var http = _httpFactory.CreateClient();
var res = await _cache.GetOrAddCachedDataAsync($"geo_{query}",
_ =>
{
@@ -207,7 +207,7 @@ public class SearchesService : INService
+ $"q={Uri.EscapeDataString(query)}&"
+ "format=json";
var res = _http.GetStringAsync(url);
var res = http.GetStringAsync(url);
return res;
},
"",
@@ -227,7 +227,7 @@ public class SearchesService : INService
+ $"key={_creds.TimezoneDbApiKey}&format=json&"
+ "by=position&"
+ $"lat={geoData.Lat}&lng={geoData.Lon}");
using var geoRes = await _http.SendAsync(req);
using var geoRes = await http.SendAsync(req);
var resString = await geoRes.Content.ReadAsStringAsync();
var timeObj = JsonConvert.DeserializeObject<TimeZoneResult>(resString);
@@ -403,7 +403,7 @@ public class SearchesService : INService
}
catch (Exception ex)
{
Log.Error(ex.Message);
Log.Error(ex, "Error getting Hearthstone Card: {ErrorMessage}", ex.Message);
return null;
}
}

View File

@@ -24,7 +24,6 @@ public sealed class StreamNotificationService : INService
private readonly Dictionary<StreamDataKey, Dictionary<ulong, HashSet<FollowedStream>>> _shardTrackedStreams;
private readonly ConcurrentHashSet<ulong> _offlineNotificationServers;
private readonly IBotCredentials _creds;
private readonly IPubSub _pubSub;
private readonly IEmbedBuilderService _eb;
private readonly Timer _notifCleanupTimer;
@@ -49,7 +48,6 @@ public sealed class StreamNotificationService : INService
_db = db;
_client = client;
_strings = strings;
_creds = creds;
_pubSub = pubSub;
_eb = eb;
_streamTracker = new(httpFactory, redis, creds.RedisKey(), client.ShardId == 0);
@@ -123,8 +121,12 @@ public sealed class StreamNotificationService : INService
using var uow = _db.GetDbContext();
foreach (var kvp in deleteGroups)
{
Log.Information($"Deleting {kvp.Value.Count} {kvp.Key} streams because "
+ $"they've been erroring for more than {errorLimit}: {string.Join(", ", kvp.Value)}");
Log.Information(
"Deleting {StreamCount} {Platform} streams because they've been erroring for more than {ErrorLimit}: {RemovedList}",
kvp.Value.Count,
kvp.Key,
errorLimit,
string.Join(", ", kvp.Value));
var toDelete = uow.Set<FollowedStream>()
.AsQueryable()
@@ -140,8 +142,7 @@ public sealed class StreamNotificationService : INService
}
catch (Exception ex)
{
Log.Error("Error cleaning up FollowedStreams");
Log.Error(ex.ToString());
Log.Error(ex, "Error cleaning up FollowedStreams");
}
},
null,