From 2e4616c7366c54e9bfc0f5f3b21d31899b944ccb Mon Sep 17 00:00:00 2001 From: barelyprofessional <150058423+barelyprofessional@users.noreply.github.com> Date: Thu, 27 Jun 2024 11:30:41 +0800 Subject: [PATCH] Added a feature to reconnect if the bot somehow gets stuck (either not joined to a channel or stuck in a disconnected state) --- KfChatDotNetKickBot/KickBot.cs | 11 +++++++++++ KfChatDotNetWsClient/ChatClient.cs | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/KfChatDotNetKickBot/KickBot.cs b/KfChatDotNetKickBot/KickBot.cs index e32d16f..7eba511 100644 --- a/KfChatDotNetKickBot/KickBot.cs +++ b/KfChatDotNetKickBot/KickBot.cs @@ -31,6 +31,7 @@ public class KickBot private bool _isBmjLive = false; private bool _isBmjLiveSynced = false; private Dictionary _userIdMapping = new(); + private DateTime _lastKfEvent = DateTime.Now; public KickBot() { @@ -189,6 +190,13 @@ public class KickBot _kfClient.SendMessage("/ping"); _kickClient.SendPusherPing(); if (_initialStartCooldown) _initialStartCooldown = false; + var inactivityTime = DateTime.Now - _lastKfEvent; + _logger.Debug($"Last KF event was {inactivityTime:g} ago"); + if (inactivityTime.TotalMinutes > 10) + { + _logger.Error("Forcing reconnection as bot is completely dead"); + _kfClient.Reconnect().Wait(_cancellationToken); + } } } @@ -212,6 +220,7 @@ public class KickBot private void OnKfChatMessage(object sender, List messages, MessagesJsonModel jsonPayload) { + _lastKfEvent = DateTime.Now; _logger.Debug($"Received {messages.Count} message(s)"); foreach (var message in messages) { @@ -298,6 +307,7 @@ public class KickBot private void OnUsersJoined(object sender, List users, UsersJsonModel jsonPayload) { + _lastKfEvent = DateTime.Now; _logger.Debug($"Received {users.Count} user join events"); foreach (var user in users) { @@ -316,6 +326,7 @@ public class KickBot private void OnUsersParted(object sender, List userIds) { + _lastKfEvent = DateTime.Now; if (userIds.Contains(_config.GambaSeshUserId) && _config.EnableGambaSeshDetect) { _logger.Info("GambaSesh is no longer present"); diff --git a/KfChatDotNetWsClient/ChatClient.cs b/KfChatDotNetWsClient/ChatClient.cs index c7fce27..2fd413f 100644 --- a/KfChatDotNetWsClient/ChatClient.cs +++ b/KfChatDotNetWsClient/ChatClient.cs @@ -51,6 +51,11 @@ public class ChatClient _wsClient.Stop(WebSocketCloseStatus.NormalClosure, "Closing websocket").Wait(); } + public async Task Reconnect() + { + await _wsClient.Reconnect(); + } + private async Task CreateWsClient() { var factory = new Func(() =>