1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-01-31 09:09:00 +03:00
Octobot/src/Responders/GuildUnloadedResponder.cs
Octol1ttle cf7007f269
Handle guild data load errors better (#172)
Previously, any errors in guild data load will cause the bot to be
unusable in that guild. It didn't help that the end users had no
information that something was wrong! Now, any errors will be logged
better (with the full path to the file that couldn't be loaded), and the
users will receive a message saying that functionality is degraded

The old way to save objects was to serialize them directly into streams
opened by `File#Create`. This can cause problems if the serialization
isn't completed, because `File#Create` overwrites the file with an empty
one on the spot. Now, objects are first deserialized into a temporary
file, then the original is replaced by the temporary, then the temporary
is deleted.

Errors during guild data load would sometimes cause the bot to replace
the corrupted file with a default one whenever a save is triggered. Now,
guilds with load errors won't have their data saved to aid in debugging

---------

Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com>
Signed-off-by: mctaylors <mctaylxrs@outlook.com>
2023-10-26 18:14:27 +03:00

38 lines
1.1 KiB
C#

using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
using Octobot.Data;
using Octobot.Services;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.Gateway.Responders;
using Remora.Results;
namespace Octobot.Responders;
/// <summary>
/// Handles removing guild ID from <see cref="GuildData" /> if the guild becomes unavailable.
/// </summary>
[UsedImplicitly]
public class GuildUnloadedResponder : IResponder<IGuildDelete>
{
private readonly GuildDataService _guildData;
private readonly ILogger<GuildUnloadedResponder> _logger;
public GuildUnloadedResponder(
GuildDataService guildData, ILogger<GuildUnloadedResponder> logger)
{
_guildData = guildData;
_logger = logger;
}
public Task<Result> RespondAsync(IGuildDelete gatewayEvent, CancellationToken ct = default)
{
var guildId = gatewayEvent.ID;
var isDataRemoved = _guildData.UnloadGuildData(guildId);
if (isDataRemoved)
{
_logger.LogInformation("Unloaded guild {GuildId}", guildId);
}
return Task.FromResult(Result.FromSuccess());
}
}