Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stricter rate limiting #76

Merged
merged 1 commit into from
Dec 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions BotNet.Services/BotCommands/OpenAI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using BotNet.Services.MarkdownV2;
Expand Down Expand Up @@ -765,7 +766,8 @@ await botClient.SendTextMessageAsync(
}
}

private static readonly RateLimiter IMAGE_GENERATION_RATE_LIMITER = RateLimiter.PerUser(1, TimeSpan.FromMinutes(3));
private static readonly RateLimiter IMAGE_GENERATION_PER_USER_RATE_LIMITER = RateLimiter.PerUser(1, TimeSpan.FromMinutes(10));
private static readonly RateLimiter IMAGE_GENERATION_PER_CHAT_RATE_LIMITER = RateLimiter.PerUser(2, TimeSpan.FromMinutes(3));
public static async Task StreamChatWithFriendlyBotAsync(
ITelegramBotClient botClient,
IServiceProvider serviceProvider,
Expand Down Expand Up @@ -829,7 +831,11 @@ await serviceProvider.GetRequiredService<FriendlyBot>().StreamChatAsync(
);
break;
case ChatIntent.ImageGeneration:
IMAGE_GENERATION_RATE_LIMITER.ValidateActionRate(
IMAGE_GENERATION_PER_USER_RATE_LIMITER.ValidateActionRate(
chatId: message.Chat.Id,
userId: message.From.Id
);
IMAGE_GENERATION_PER_CHAT_RATE_LIMITER.ValidateActionRate(
chatId: message.Chat.Id,
userId: message.From.Id
);
Expand Down Expand Up @@ -881,6 +887,13 @@ await botClient.SendTextMessageAsync(
),
cancellationToken: cancellationToken);
}
} catch (HttpRequestException exc) when (exc.StatusCode == HttpStatusCode.TooManyRequests) {
await botClient.SendTextMessageAsync(
chatId: message.Chat.Id,
text: "<code>Too many requests.</code>",
parseMode: ParseMode.Html,
replyToMessageId: message.MessageId,
cancellationToken: cancellationToken);
} catch (OperationCanceledException) {
await botClient.SendTextMessageAsync(
chatId: message.Chat.Id,
Expand Down
Loading