2022-06-10 22:08:56 +00:00
|
|
|
using App.Metrics;
|
|
|
|
|
2022-01-22 07:47:47 +00:00
|
|
|
using Serilog;
|
|
|
|
|
|
|
|
using Myriad.Gateway;
|
|
|
|
using Myriad.Rest;
|
|
|
|
|
|
|
|
using PluralKit.Core;
|
|
|
|
|
|
|
|
namespace PluralKit.Bot;
|
|
|
|
|
|
|
|
public class PrivateChannelService
|
|
|
|
{
|
2022-06-10 22:08:56 +00:00
|
|
|
private readonly IMetrics _metrics;
|
2022-01-22 07:47:47 +00:00
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly ModelRepository _repo;
|
|
|
|
private readonly DiscordApiClient _rest;
|
2022-06-10 22:08:56 +00:00
|
|
|
public PrivateChannelService(IMetrics metrics, ILogger logger, ModelRepository repo, DiscordApiClient rest)
|
2022-01-22 07:47:47 +00:00
|
|
|
{
|
2022-06-10 22:08:56 +00:00
|
|
|
_metrics = metrics;
|
2022-01-22 07:47:47 +00:00
|
|
|
_logger = logger;
|
|
|
|
_repo = repo;
|
|
|
|
_rest = rest;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task TrySavePrivateChannel(MessageCreateEvent evt)
|
|
|
|
{
|
2022-06-15 03:11:55 +00:00
|
|
|
if (evt.GuildId == null) await SaveDmChannel(evt.Author.Id, evt.ChannelId);
|
2022-01-22 07:47:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<ulong> GetOrCreateDmChannel(ulong userId)
|
|
|
|
{
|
|
|
|
var channelId = await _repo.GetDmChannel(userId);
|
2022-06-15 03:11:55 +00:00
|
|
|
if (channelId != null)
|
2022-01-22 07:47:47 +00:00
|
|
|
{
|
2022-06-15 03:11:55 +00:00
|
|
|
_metrics.Measure.Meter.Mark(BotMetrics.DatabaseDMCacheHits);
|
|
|
|
return channelId.Value;
|
2022-01-22 07:47:47 +00:00
|
|
|
}
|
|
|
|
|
2022-06-15 03:11:55 +00:00
|
|
|
_metrics.Measure.Meter.Mark(BotMetrics.DMCacheMisses);
|
|
|
|
|
|
|
|
var channel = await _rest.CreateDm(userId);
|
2022-06-10 22:08:56 +00:00
|
|
|
|
2022-01-22 07:47:47 +00:00
|
|
|
// spawn off saving the channel as to not block the current thread
|
2022-06-15 03:11:55 +00:00
|
|
|
_ = SaveDmChannel(userId, channel.Id);
|
2022-01-22 07:47:47 +00:00
|
|
|
|
2022-06-15 03:11:55 +00:00
|
|
|
return channel.Id;
|
2022-01-22 07:47:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private async Task SaveDmChannel(ulong userId, ulong channelId)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
await _repo.UpdateAccount(userId, new() { DmChannel = channelId });
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.Error(e, "Failed to save DM channel {ChannelId} for user {UserId}", channelId, userId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|