Implemented Discord support. Similar to GambaSesh though doesn't do transcription but does display attachment URLs and device presence data

This commit is contained in:
barelyprofessional
2024-06-30 18:53:53 +08:00
parent 14884c717e
commit f413503d27
3 changed files with 324 additions and 0 deletions

View File

@@ -29,6 +29,8 @@ public class KickBot
private readonly CancellationToken _cancellationToken = new(); private readonly CancellationToken _cancellationToken = new();
private readonly Twitch _twitch; private readonly Twitch _twitch;
private Shuffle _shuffle; private Shuffle _shuffle;
private DiscordService _discord;
private string? _lastDiscordStatus;
private bool _isBmjLive = false; private bool _isBmjLive = false;
private bool _isBmjLiveSynced = false; private bool _isBmjLiveSynced = false;
private Dictionary<string, int> _userIdMapping = new(); private Dictionary<string, int> _userIdMapping = new();
@@ -98,6 +100,7 @@ public class KickBot
} }
BuildShuffle(); BuildShuffle();
BuildDiscord();
_logger.Debug("Blocking the main thread"); _logger.Debug("Blocking the main thread");
var exitEvent = new ManualResetEvent(false); var exitEvent = new ManualResetEvent(false);
@@ -112,6 +115,72 @@ public class KickBot
_shuffle.StartWsClient().Wait(_cancellationToken); _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) private void ShuffleOnWsDisconnection(object sender, DisconnectionInfo e)
{ {
if (e.Type == DisconnectionType.ByServer) if (e.Type == DisconnectionType.ByServer)

View File

@@ -23,4 +23,6 @@ public class ConfigModel
public int? BossmanJackTwitchId { get; set; } = null; public int? BossmanJackTwitchId { get; set; } = null;
// Used for testing // Used for testing
public bool SuppressChatMessages { get; set; } = false; public bool SuppressChatMessages { get; set; } = false;
public string? DiscordToken { get; set; } = null;
public string? DiscordBmjId { get; set; } = "554123642246529046";
} }

View File

@@ -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<ClientWebSocket>(() =>
{
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<DiscordPacketReadModel>(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<DiscordPresenceUpdateModel>() ?? throw new InvalidOperationException());
return;
case "MESSAGE_CREATE":
OnMessageReceived?.Invoke(this,
packet.Data.Deserialize<DiscordMessageModel>() ?? 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<T>
{
[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<object>;
public class DiscordPacketReadModel : DiscordPacketModel<JsonElement>;
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<string, string> 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; }
}