diff --git a/KfChatDotNetKickBot/KickBot.cs b/KfChatDotNetKickBot/KickBot.cs index ea031d3..06e66a3 100644 --- a/KfChatDotNetKickBot/KickBot.cs +++ b/KfChatDotNetKickBot/KickBot.cs @@ -29,6 +29,8 @@ public class KickBot private readonly CancellationToken _cancellationToken = new(); private readonly Twitch _twitch; private Shuffle _shuffle; + private DiscordService _discord; + private string? _lastDiscordStatus; private bool _isBmjLive = false; private bool _isBmjLiveSynced = false; private Dictionary _userIdMapping = new(); @@ -98,6 +100,7 @@ public class KickBot } BuildShuffle(); + BuildDiscord(); _logger.Debug("Blocking the main thread"); var exitEvent = new ManualResetEvent(false); @@ -112,6 +115,72 @@ public class KickBot _shuffle.StartWsClient().Wait(_cancellationToken); } + private void BuildDiscord() + { + _logger.Debug("Building Discord"); + if (_config.DiscordToken == null) + { + _logger.Info("Not building Discord as the token is not configured"); + return; + } + _discord = new DiscordService(_config.DiscordToken, _config.Proxy); + _discord.OnInvalidCredentials += DiscordOnInvalidCredentials; + _discord.OnWsDisconnection += DiscordOnWsDisconnection; + _discord.OnMessageReceived += DiscordOnMessageReceived; + _discord.OnPresenceUpdated += DiscordOnPresenceUpdated; + _discord.StartWsClient().Wait(_cancellationToken); + } + + private void DiscordOnPresenceUpdated(object sender, DiscordPresenceUpdateModel presence) + { + if (presence.User.Id != _config.DiscordBmjId) + { + return; + } + if (_lastDiscordStatus == presence.Status) + { + _logger.Debug("Ignoring status update as it's the same as the last one"); + return; + } + _lastDiscordStatus = presence.Status; + var clientStatus = presence.ClientStatus.Keys.Aggregate(string.Empty, (current, device) => current + $"{device} is {presence.ClientStatus[device]}; "); + _sendChatMessage($"[img]https://i.postimg.cc/cLmQrp89/discord16.png[/img] BossmanJack has updated his Discord presence: {clientStatus}"); + } + + private void DiscordOnMessageReceived(object sender, DiscordMessageModel message) + { + if (message.Author.Id != _config.DiscordBmjId) + { + return; + } + + var result = $"[img]https://i.postimg.cc/cLmQrp89/discord16.png[/img] BossmanJack: {message.Content}"; + foreach (var attachment in message.Attachments ?? []) + { + result += $"[br]Attachment: {attachment.GetProperty("filename").GetString()} {attachment.GetProperty("url").GetString()}"; + } + _sendChatMessage(result); + } + + private void DiscordOnWsDisconnection(object sender, DisconnectionInfo e) + { + _logger.Error($"Discord dropped, reason {e.Type}"); + // This is raised when the Websocket client is disposed + // Attempting to dispose it again while it is being disposed causes a loop and probably eventually a stack overflow + if (e.Type == DisconnectionType.Exit) + { + return; + } + _discord.Dispose(); + BuildDiscord(); + } + + private void DiscordOnInvalidCredentials(object sender, DiscordPacketReadModel packet) + { + _logger.Error("Credentials failed to validate. Killing service."); + _discord.Dispose(); + } + private void ShuffleOnWsDisconnection(object sender, DisconnectionInfo e) { if (e.Type == DisconnectionType.ByServer) diff --git a/KfChatDotNetKickBot/Models/ConfigModel.cs b/KfChatDotNetKickBot/Models/ConfigModel.cs index 6a575ce..fbac413 100644 --- a/KfChatDotNetKickBot/Models/ConfigModel.cs +++ b/KfChatDotNetKickBot/Models/ConfigModel.cs @@ -23,4 +23,6 @@ public class ConfigModel public int? BossmanJackTwitchId { get; set; } = null; // Used for testing public bool SuppressChatMessages { get; set; } = false; + public string? DiscordToken { get; set; } = null; + public string? DiscordBmjId { get; set; } = "554123642246529046"; } \ No newline at end of file diff --git a/KfChatDotNetKickBot/Services/Discord.cs b/KfChatDotNetKickBot/Services/Discord.cs new file mode 100644 index 0000000..10a6b2d --- /dev/null +++ b/KfChatDotNetKickBot/Services/Discord.cs @@ -0,0 +1,253 @@ +using System.Net; +using System.Net.WebSockets; +using System.Text.Json; +using System.Text.Json.Serialization; +using NLog; +using Websocket.Client; + +namespace KfChatDotNetKickBot.Services; + +public class DiscordService : IDisposable +{ + private readonly Logger _logger = LogManager.GetCurrentClassLogger(); + private WebsocketClient _wsClient; + private readonly Uri _wsUri = new Uri("wss://gateway.discord.gg/?encoding=json&v=9"); + // Not sure what a good value for this would be + private const int ReconnectTimeout = 60; + private readonly string? _proxy; + private readonly string _authorization; + private int _sequence; + private const string UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"; + + public delegate void MessageReceivedEventHandler(object sender, DiscordMessageModel message); + public delegate void PresenceUpdateEventHandler(object sender, DiscordPresenceUpdateModel presence); + public delegate void WsDisconnectionEventHandler(object sender, DisconnectionInfo e); + public delegate void InvalidCredentialsEventHandler(object sender, DiscordPacketReadModel packet); + public event MessageReceivedEventHandler OnMessageReceived; + public event PresenceUpdateEventHandler OnPresenceUpdated; + public event WsDisconnectionEventHandler OnWsDisconnection; + public event InvalidCredentialsEventHandler OnInvalidCredentials; + + private readonly CancellationToken _cancellationToken = CancellationToken.None; + private readonly CancellationTokenSource _pingCts = new(); + private Task? _heartbeatTask; + // Discord tells us the heartbeat interval to use in the op 10 response so this is just a placeholder + private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(40); + + public DiscordService(string authorization, string? proxy = null, CancellationToken? cancellationToken = null) + { + _proxy = proxy; + if (cancellationToken != null) _cancellationToken = cancellationToken.Value; + _authorization = authorization; + _logger.Info("Discord Service created"); + } + + public async Task StartWsClient() + { + _logger.Debug("StartWsClient() called, creating client"); + await CreateWsClient(); + } + + private async Task CreateWsClient() + { + var factory = new Func(() => + { + var clientWs = new ClientWebSocket(); + clientWs.Options.SetRequestHeader("Origin", "https://discord.com"); + clientWs.Options.SetRequestHeader("User-Agent", UserAgent); + if (_proxy == null) return clientWs; + _logger.Debug($"Using proxy address {_proxy}"); + clientWs.Options.Proxy = new WebProxy(_proxy); + return clientWs; + }); + + var client = new WebsocketClient(_wsUri, factory) + { + ReconnectTimeout = TimeSpan.FromSeconds(ReconnectTimeout) + }; + + client.ReconnectionHappened.Subscribe(WsReconnection); + client.MessageReceived.Subscribe(WsMessageReceived); + client.DisconnectionHappened.Subscribe(WsDisconnection); + + _wsClient = client; + + _logger.Debug("Websocket client has been built, about to start"); + await client.Start(); + _logger.Debug("Websocket client started!"); + } + public bool IsConnected() + { + return _wsClient is { IsRunning: true }; + } + + private async Task HeartbeatTimer() + { + using var timer = new PeriodicTimer(_heartbeatInterval); + while (await timer.WaitForNextTickAsync(_pingCts.Token)) + { + if (_wsClient == null) + { + _logger.Debug("_wsClient doesn't exist yet, not going to try ping"); + continue; + } + if (!IsConnected()) + { + _logger.Info("Not connected not going to try send a ping actually"); + continue; + } + + var heartbeatPacket = JsonSerializer.Serialize(new DiscordPacketWriteModel + { + OpCode = 1, + Sequence = _sequence, + }); + _logger.Debug("Sending heartbeat packet"); + _logger.Debug(heartbeatPacket); + await _wsClient.SendInstant(heartbeatPacket); + } + } + + private void WsDisconnection(DisconnectionInfo disconnectionInfo) + { + _logger.Error($"Client disconnected from Discord (or never successfully connected). Type is {disconnectionInfo.Type}"); + _logger.Error(JsonSerializer.Serialize(disconnectionInfo)); + OnWsDisconnection?.Invoke(this, disconnectionInfo); + } + + private void WsReconnection(ReconnectionInfo reconnectionInfo) + { + _logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}"); + } + + private void WsMessageReceived(ResponseMessage message) + { + if (message.Text == null) + { + _logger.Info("Discord sent a null message"); + return; + } + + _logger.Debug($"Received event from Discord: {message.Text}"); + + try + { + var packet = JsonSerializer.Deserialize(message.Text); + if (packet == null) throw new InvalidOperationException("Caught a null when deserializing Discord packet"); + _sequence = packet.Sequence ?? _sequence; + if (packet.OpCode == 9) + { + _logger.Info("Discord sent op code indicating invalid credentials. Raising event."); + OnInvalidCredentials?.Invoke(this, packet); + return; + } + + if (packet.OpCode == 10) + { + _logger.Info("Discord op code 10 (hello) sent. Setting up heartbeat timer and sending init"); + _logger.Info("Sending connection_init"); + var initPayload = + "{\"op\":2,\"d\":{\"token\":\"" + _authorization + "\",\"capabilities\":30717,\"properties\":" + + "{\"os\":\"Linux\",\"browser\":\"Firefox\",\"device\":\"\",\"system_locale\":\"en-US\",\"browser_user_agent\":" + + "\"" + UserAgent + "\",\"browser_version\":\"115.0\",\"os_version\":\"\",\"referrer\":\"\",\"referring_domain\":\"\"," + + "\"referrer_current\":\"\",\"referring_domain_current\":\"\",\"release_channel\":\"stable\"," + + "\"client_build_number\":306208,\"client_event_source\":null,\"design_id\":0},\"presence\":{\"status\":\"unknown\"," + + "\"since\":0,\"activities\":[],\"afk\":false},\"compress\":false,\"client_state\":{\"guild_versions\":{}}}}"; + _logger.Debug(initPayload); + _wsClient.SendInstant(initPayload).Wait(_cancellationToken); + _heartbeatTask?.Dispose(); + _heartbeatInterval = + TimeSpan.FromMilliseconds(packet.Data.GetProperty("heartbeat_interval").GetInt32()); + _heartbeatTask = Task.Run(HeartbeatTimer, _cancellationToken); + return; + } + + if (packet.OpCode != 0) + { + _logger.Info($"Op code {packet.OpCode} was unhandled. JSON follows"); + _logger.Info(message.Text); + return; + } + + switch (packet.DispatchEvent) + { + case null: + throw new InvalidOperationException("t was null"); + case "READY": + _logger.Info("Discord is now ready"); + return; + case "PRESENCE_UPDATE": + OnPresenceUpdated?.Invoke(this, + packet.Data.Deserialize() ?? throw new InvalidOperationException()); + return; + case "MESSAGE_CREATE": + OnMessageReceived?.Invoke(this, + packet.Data.Deserialize() ?? throw new InvalidOperationException()); + return; + default: + _logger.Info($"{packet.DispatchEvent} was unhandled. JSON follows"); + _logger.Info(message.Text); + break; + } + } + catch (Exception e) + { + _logger.Error("Failed to handle message from Discord"); + _logger.Error(e); + _logger.Error("--- JSON Payload ---"); + _logger.Error(message.Text); + _logger.Error("--- End of JSON Payload ---"); + } + } + + public void Dispose() + { + _logger.Info("Disposing Discord"); + _wsClient.Dispose(); + _pingCts.Cancel(); + GC.SuppressFinalize(this); + } +} + +public class DiscordPacketModel +{ + [JsonPropertyName("t")] + public string? DispatchEvent { get; set; } + [JsonPropertyName("op")] + public int OpCode { get; set; } + [JsonPropertyName("d")] + public T? Data { get; set; } + [JsonPropertyName("s")] + public int? Sequence { get; set; } +} + +public class DiscordPacketWriteModel : DiscordPacketModel; +public class DiscordPacketReadModel : DiscordPacketModel; + +public class DiscordPresenceUpdateModel +{ + [JsonPropertyName("user")] + public required DiscordUserModel User { get; set; } + [JsonPropertyName("status")] + public required string Status { get; set; } + [JsonPropertyName("client_status")] + public required Dictionary ClientStatus { get; set; } +} + +public class DiscordUserModel +{ + [JsonPropertyName("id")] + public required string Id { get; set; } + [JsonPropertyName("username")] + public string? Username { get; set; } +} + +public class DiscordMessageModel +{ + [JsonPropertyName("content")] + public string? Content { get; set; } + [JsonPropertyName("author")] + public required DiscordUserModel Author { get; set; } + [JsonPropertyName("attachments")] + public JsonElement[]? Attachments { get; set; } +} \ No newline at end of file