diff --git a/BotNet.Services/MarkdownV2/MarkdownV2Sanitizer.cs b/BotNet.Services/MarkdownV2/MarkdownV2Sanitizer.cs index 5770bf6..776c00e 100644 --- a/BotNet.Services/MarkdownV2/MarkdownV2Sanitizer.cs +++ b/BotNet.Services/MarkdownV2/MarkdownV2Sanitizer.cs @@ -15,12 +15,15 @@ public static string Sanitize(string input) { // Use StringBuilder for efficient string manipulation StringBuilder sanitized = new(input.Length); + char previousCharacter = '\0'; foreach (char character in input) { // If the character is in our list, append a backslash before it - if (CHARACTERS_TO_ESCAPE.Contains(character)) { + if (CHARACTERS_TO_ESCAPE.Contains(character) + && previousCharacter != '\\') { sanitized.Append('\\'); } sanitized.Append(character); + previousCharacter = character; } return sanitized.ToString(); diff --git a/BotNet.Services/OpenAI/OpenAIStreamingClient.cs b/BotNet.Services/OpenAI/OpenAIStreamingClient.cs index 974151f..d35951c 100644 --- a/BotNet.Services/OpenAI/OpenAIStreamingClient.cs +++ b/BotNet.Services/OpenAI/OpenAIStreamingClient.cs @@ -6,15 +6,18 @@ using BotNet.Services.MarkdownV2; using BotNet.Services.OpenAI.Models; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace BotNet.Services.OpenAI { public sealed class OpenAIStreamingClient( - IServiceProvider serviceProvider + IServiceProvider serviceProvider, + ILogger logger ) { private readonly IServiceProvider _serviceProvider = serviceProvider; + private readonly ILogger _logger = logger; [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Manually managed")] public async Task StreamChatAsync( @@ -107,6 +110,7 @@ await telegramBotClient.EditMessageTextAsync( ); } catch (Exception exc) when (exc is not OperationCanceledException) { // Message might be deleted + _logger.LogError(exc, null); break; } } @@ -120,13 +124,18 @@ await telegramBotClient.EditMessageTextAsync( try { // Finalize message - await telegramBotClient.EditMessageTextAsync( - chatId: chatId, - messageId: incompleteMessage.MessageId, - text: MarkdownV2Sanitizer.Sanitize(lastResult!), - parseMode: ParseMode.MarkdownV2, - cancellationToken: cts.Token - ); + try { + await telegramBotClient.EditMessageTextAsync( + chatId: chatId, + messageId: incompleteMessage.MessageId, + text: MarkdownV2Sanitizer.Sanitize(lastResult!), + parseMode: ParseMode.MarkdownV2, + cancellationToken: cts.Token + ); + } catch (Exception exc) { + _logger.LogError(exc, null); + throw; + } // Track thread ThreadTracker threadTracker = serviceScope.ServiceProvider.GetRequiredService();