Skip to content

Commit

Permalink
Fix markdown sanitizer
Browse files Browse the repository at this point in the history
  • Loading branch information
ronnygunawan committed Dec 3, 2023
1 parent b3d3069 commit 7a081e8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
5 changes: 4 additions & 1 deletion BotNet.Services/MarkdownV2/MarkdownV2Sanitizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
25 changes: 17 additions & 8 deletions BotNet.Services/OpenAI/OpenAIStreamingClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<OpenAIStreamingClient> logger
) {
private readonly IServiceProvider _serviceProvider = serviceProvider;
private readonly ILogger<OpenAIStreamingClient> _logger = logger;

[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Manually managed")]
public async Task StreamChatAsync(
Expand Down Expand Up @@ -107,6 +110,7 @@ await telegramBotClient.EditMessageTextAsync(
);
} catch (Exception exc) when (exc is not OperationCanceledException) {
// Message might be deleted
_logger.LogError(exc, null);
break;
}
}
Expand All @@ -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<ThreadTracker>();
Expand Down

0 comments on commit 7a081e8

Please sign in to comment.