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