From 42e6589e2a6e9d51921b26d99980aad7867c5720 Mon Sep 17 00:00:00 2001 From: barelyprofessional <150058423+barelyprofessional@users.noreply.github.com> Date: Sun, 9 Feb 2025 16:23:35 +0800 Subject: [PATCH] Original TruncateBytes extension method wasn't working right, seemed to include an extra character which would put us over the limit. Replaced it and new method seems to be working as expected albeit not as nice looking. --- KfChatDotNetBot/ChatBot.cs | 3 +-- KfChatDotNetBot/Extensions.cs | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/KfChatDotNetBot/ChatBot.cs b/KfChatDotNetBot/ChatBot.cs index c1b82a4..272ff54 100644 --- a/KfChatDotNetBot/ChatBot.cs +++ b/KfChatDotNetBot/ChatBot.cs @@ -302,8 +302,6 @@ public class ChatBot if (lengthLimitBehavior == LengthLimitBehavior.TruncateExactly) { - // ReSharper disable once ReplaceSubstringWithRangeIndexer - // The range indexer is a fucking piece of shit that does not work. // TrimEnd in case you end up truncating on a space (happened during testing) as Sneedchat will trim it messageTracker.Message = messageTracker.Message.TruncateBytes(lengthLimit).TrimEnd(); } @@ -311,6 +309,7 @@ public class ChatBot messageTracker.Status = SentMessageTrackerStatus.WaitingForResponse; messageTracker.SentAt = DateTimeOffset.UtcNow; + _logger.Debug($"Message is {messageTracker.Message.Utf8LengthBytes()} bytes"); _sentMessages.Add(messageTracker); await KfClient.SendMessageInstantAsync(messageTracker.Message); return messageTracker; diff --git a/KfChatDotNetBot/Extensions.cs b/KfChatDotNetBot/Extensions.cs index 1b99dab..e3e7e22 100644 --- a/KfChatDotNetBot/Extensions.cs +++ b/KfChatDotNetBot/Extensions.cs @@ -115,10 +115,18 @@ public static class Extensions public static string TruncateBytes(this string s, int limitBytes) { - return Encoding.UTF8.GetString( - Encoding.UTF8.GetBytes(s) - .Take(limitBytes) - .ToArray() - ).TrimEnd(); + if (string.IsNullOrEmpty(s) || limitBytes <= 0) + { + return string.Empty; + } + + if (s.Utf8LengthBytes() <= limitBytes) + { + return s; + } + + var bytes = Encoding.UTF8.GetBytes(s); + var charCount = Encoding.UTF8.GetCharCount(bytes, 0, limitBytes); + return s.Substring(0, charCount); } } \ No newline at end of file