foxcord/Foxcord/Gateway/DiscordGatewayClient.Events.cs

67 lines
2.7 KiB
C#
Raw Permalink Normal View History

using System.Text.Json;
using Foxcord.Gateway.Events.Commands;
using Foxcord.Gateway.Events.Dispatch;
using Foxcord.Rest;
using Foxcord.Rest.Types;
2024-09-03 00:07:12 +02:00
namespace Foxcord.Gateway;
public partial class DiscordGatewayClient
{
private void HandleHeartbeatAck()
{
_lastHeartbeatAck = DateTimeOffset.UtcNow;
_logger.Verbose("Received heartbeat ACK after {Latency}", _lastHeartbeatAck - _lastHeartbeatSend);
}
private async Task HandleHeartbeatRequest(CancellationToken ct = default)
{
_logger.Information("Early heartbeat requested, sending heartbeat");
await SendCommandAsync(new HeartbeatCommand(_lastSequence), ct);
2024-09-03 00:07:12 +02:00
_lastHeartbeatSend = DateTimeOffset.UtcNow;
}
private IDispatch ParseDispatchEvent(string rawType, JsonElement rawPayload)
{
switch (rawType)
{
case DispatchEventTypeName.Ready:
return rawPayload.Deserialize<ReadyEvent>(_jsonSerializerOptions)!;
case DispatchEventTypeName.GuildCreate:
return rawPayload.Deserialize<GuildCreateEvent>(_jsonSerializerOptions)!;
case DispatchEventTypeName.MessageCreate:
return rawPayload.Deserialize<MessageCreateEvent>(_jsonSerializerOptions)!;
default:
throw new ArgumentOutOfRangeException(nameof(rawType), $"Unknown dispatch event '{rawType}'");
}
}
private async Task HandleDispatch(IDispatch dispatch, CancellationToken ct = default)
{
switch (dispatch)
{
case ReadyEvent ready:
_logger.Debug("Received READY! API version: {Version}, user: {UserId}, shard: {Id}/{Total}",
ready.Version, ready.User.Id, ready.Shard.ShardId, ready.Shard.NumShards);
break;
case GuildCreateEvent guildCreate:
_logger.Debug("Received guild create for guild {Id} / {Name}", guildCreate.Id, guildCreate.Name);
break;
case MessageCreateEvent m:
_logger.Debug("Received message create from {User} in {Channel}. Content: {Content}", m.Author.Tag,
m.ChannelId, m.Content);
if (m.Content == "!ping")
{
var rest = new DiscordRestClient(_logger,
new DiscordRestClientOptions { Token = _token["Bot ".Length..] });
await rest.CreateMessageAsync(m.ChannelId,
new CreateMessageParams(Content: $"Pong! Latency: {Latency.TotalMilliseconds}ms"), ct);
}
break;
default:
_logger.Debug("Received dispatch event {DispatchType}", dispatch.GetType().Name);
break;
}
}
2024-09-03 00:07:12 +02:00
}