Skip to content

Commit

Permalink
Merge pull request #100 from teknologi-umum/ddd
Browse files Browse the repository at this point in the history
DDD
  • Loading branch information
ronnygunawan authored Jan 30, 2024
2 parents 7bf0b5b + 6577f07 commit 1bcd84e
Show file tree
Hide file tree
Showing 48 changed files with 711 additions and 619 deletions.
34 changes: 16 additions & 18 deletions BotNet.CommandHandlers/AI/OpenAI/AskCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using BotNet.Commands;
using BotNet.Commands.AI.OpenAI;
using BotNet.Commands.BotUpdate.Message;
using BotNet.Commands.CommandPrioritization;
using BotNet.Commands.ChatAggregate;
using BotNet.Commands.SenderAggregate;
using BotNet.Services.MarkdownV2;
using BotNet.Services.OpenAI;
using BotNet.Services.OpenAI.Models;
Expand All @@ -23,18 +24,18 @@ ILogger<AskCommandHandler> logger
private readonly ITelegramMessageCache _telegramMessageCache = telegramMessageCache;
private readonly ILogger<AskCommandHandler> _logger = logger;

public async Task Handle(AskCommand command, CancellationToken cancellationToken) {
public async Task Handle(AskCommand askCommand, CancellationToken cancellationToken) {
try {
OpenAITextPromptHandler.CHAT_RATE_LIMITER.ValidateActionRate(
chatId: command.ChatId,
userId: command.SenderId
chatId: askCommand.Command.Chat.Id,
userId: askCommand.Command.Sender.Id
);
} catch (RateLimitExceededException exc) {
await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: askCommand.Command.Chat.Id,
text: $"<code>Anda terlalu banyak memanggil AI. Coba lagi {exc.Cooldown}.</code>",
parseMode: ParseMode.Html,
replyToMessageId: command.PromptMessageId,
replyToMessageId: askCommand.Command.MessageId,
cancellationToken: cancellationToken
);
return;
Expand All @@ -44,30 +45,27 @@ await _telegramBotClient.SendTextMessageAsync(
Task _ = Task.Run(async () => {
List<ChatMessage> messages = [
ChatMessage.FromText("system", "The following is a conversation with an AI assistant. The assistant is helpful, creative, direct, concise, and always get to the point."),
ChatMessage.FromText("user", command.Prompt)
ChatMessage.FromText("user", askCommand.Prompt)
];
messages.AddRange(
from message in command.Thread.Take(10).Reverse()
from message in askCommand.Thread.Take(10).Reverse()
select ChatMessage.FromText(
role: message.SenderName switch {
"AI" or "Bot" or "GPT" => "assistant",
_ => "user"
},
role: message.Sender.ChatGPTRole,
text: message.Text
)
);
Message responseMessage = await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: askCommand.Command.Chat.Id,
text: MarkdownV2Sanitizer.Sanitize("… ⏳"),
parseMode: ParseMode.MarkdownV2,
replyToMessageId: command.PromptMessageId
replyToMessageId: askCommand.Command.MessageId
);
string response = await _openAIClient.ChatAsync(
model: command.CommandPriority switch {
CommandPriority.VIPChat or CommandPriority.HomeGroupChat => "gpt-4-1106-preview",
model: askCommand switch {
({ Command: { Sender: VIPSender } or { Chat: HomeGroupChat } }) => "gpt-4-1106-preview",
_ => "gpt-3.5-turbo"
},
messages: messages,
Expand All @@ -78,7 +76,7 @@ select ChatMessage.FromText(
// Finalize message
try {
responseMessage = await telegramBotClient.EditMessageTextAsync(
chatId: command.ChatId,
chatId: askCommand.Command.Chat.Id,
messageId: responseMessage.MessageId,
text: MarkdownV2Sanitizer.Sanitize(response),
parseMode: ParseMode.MarkdownV2,
Expand All @@ -93,7 +91,7 @@ select ChatMessage.FromText(
_telegramMessageCache.Add(
message: AIResponseMessage.FromMessage(
message: responseMessage,
replyToMessageId: command.PromptMessageId,
replyToMessage: askCommand.Command,
callSign: "AI"
)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public Task Handle(OpenAIImageGenerationPrompt command, CancellationToken cancel
} catch (Exception exc) {
_logger.LogError(exc, "Could not generate image");
await _telegramBotClient.EditMessageTextAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
messageId: command.ResponseMessageId,
text: "<code>Failed to generate image.</code>",
parseMode: ParseMode.Html,
Expand All @@ -44,7 +44,7 @@ await _telegramBotClient.EditMessageTextAsync(
// Delete busy message
try {
await _telegramBotClient.DeleteMessageAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
messageId: command.ResponseMessageId,
cancellationToken: cancellationToken
);
Expand All @@ -54,7 +54,7 @@ await _telegramBotClient.DeleteMessageAsync(
// Send generated image
Message responseMessage = await _telegramBotClient.SendPhotoAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
photo: new InputFileUrl(generatedImageUrl),
replyToMessageId: command.PromptMessageId,
cancellationToken: cancellationToken
Expand Down
74 changes: 35 additions & 39 deletions BotNet.CommandHandlers/AI/OpenAI/OpenAITextPromptHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
using BotNet.Commands.AI.OpenAI;
using BotNet.Commands.AI.Stability;
using BotNet.Commands.BotUpdate.Message;
using BotNet.Commands.CommandPrioritization;
using BotNet.Commands.ChatAggregate;
using BotNet.Commands.SenderAggregate;
using BotNet.Services.MarkdownV2;
using BotNet.Services.OpenAI;
using BotNet.Services.OpenAI.Models;
Expand All @@ -29,18 +30,18 @@ ILogger<OpenAITextPromptHandler> logger
private readonly OpenAIClient _openAIClient = openAIClient;
private readonly ILogger<OpenAITextPromptHandler> _logger = logger;

public Task Handle(OpenAITextPrompt command, CancellationToken cancellationToken) {
public Task Handle(OpenAITextPrompt textPrompt, CancellationToken cancellationToken) {
try {
CHAT_RATE_LIMITER.ValidateActionRate(
chatId: command.ChatId,
userId: command.SenderId
chatId: textPrompt.Command.Chat.Id,
userId: textPrompt.Command.Sender.Id
);
} catch (RateLimitExceededException exc) {
return _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: textPrompt.Command.Chat.Id,
text: $"<code>Anda terlalu banyak memanggil AI. Coba lagi {exc.Cooldown}.</code>",
parseMode: ParseMode.Html,
replyToMessageId: command.PromptMessageId,
replyToMessageId: textPrompt.Command.MessageId,
cancellationToken: cancellationToken
);
}
Expand All @@ -52,30 +53,27 @@ public Task Handle(OpenAITextPrompt command, CancellationToken cancellationToken
];
messages.AddRange(
from message in command.Thread.Take(10).Reverse()
from message in textPrompt.Thread.Take(10).Reverse()
select ChatMessage.FromText(
role: message.SenderName switch {
"AI" or "Bot" or "GPT" => "assistant",
_ => "user"
},
role: message.Sender.ChatGPTRole,
text: message.Text
)
);
messages.Add(
ChatMessage.FromText("user", command.Prompt)
ChatMessage.FromText("user", textPrompt.Prompt)
);
Message responseMessage = await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: textPrompt.Command.Chat.Id,
text: MarkdownV2Sanitizer.Sanitize("… ⏳"),
parseMode: ParseMode.MarkdownV2,
replyToMessageId: command.PromptMessageId
replyToMessageId: textPrompt.Command.MessageId
);
string response = await _openAIClient.ChatAsync(
model: command.CommandPriority switch {
CommandPriority.VIPChat or CommandPriority.HomeGroupChat => "gpt-4-1106-preview",
model: textPrompt switch {
({ Command: { Sender: VIPSender } or { Chat: HomeGroupChat } }) => "gpt-4-1106-preview",
_ => "gpt-3.5-turbo"
},
messages: messages,
Expand All @@ -85,52 +83,50 @@ select ChatMessage.FromText(
// Handle image generation intent
if (response.StartsWith("ImageGeneration:")) {
if (command.CommandPriority != CommandPriority.VIPChat) {
if (textPrompt.Command.Sender is not VIPSender) {
try {
ArtCommandHandler.IMAGE_GENERATION_RATE_LIMITER.ValidateActionRate(command.ChatId, command.SenderId);
ArtCommandHandler.IMAGE_GENERATION_RATE_LIMITER.ValidateActionRate(textPrompt.Command.Chat.Id, textPrompt.Command.Sender.Id);
} catch (RateLimitExceededException exc) {
await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: textPrompt.Command.Chat.Id,
text: $"Anda belum mendapat giliran. Coba lagi {exc.Cooldown}.",
parseMode: ParseMode.Html,
replyToMessageId: command.PromptMessageId,
replyToMessageId: textPrompt.Command.MessageId,
cancellationToken: cancellationToken
);
return;
}
}
string imageGenerationPrompt = response.Substring(response.IndexOf(':') + 1).Trim();
switch (command.CommandPriority) {
case CommandPriority.VIPChat:
switch (textPrompt.Command) {
case { Sender: VIPSender }:
await _commandQueue.DispatchAsync(
command: new OpenAIImageGenerationPrompt(
callSign: command.CallSign,
callSign: textPrompt.CallSign,
prompt: imageGenerationPrompt,
promptMessageId: command.PromptMessageId,
responseMessageId: responseMessage.MessageId,
chatId: command.ChatId,
senderId: command.SenderId,
commandPriority: command.CommandPriority
promptMessageId: textPrompt.Command.MessageId,
responseMessageId: new(responseMessage.MessageId),
chat: textPrompt.Command.Chat,
sender: textPrompt.Command.Sender
)
);
break;
case CommandPriority.HomeGroupChat:
case { Chat: HomeGroupChat }:
await _commandQueue.DispatchAsync(
command: new StabilityTextToImagePrompt(
callSign: command.CallSign,
callSign: textPrompt.CallSign,
prompt: imageGenerationPrompt,
promptMessageId: command.PromptMessageId,
responseMessageId: responseMessage.MessageId,
chatId: command.ChatId,
senderId: command.SenderId,
commandPriority: command.CommandPriority
promptMessageId: textPrompt.Command.MessageId,
responseMessageId: new(responseMessage.MessageId),
chat: textPrompt.Command.Chat,
sender: textPrompt.Command.Sender
)
);
break;
default:
await _telegramBotClient.EditMessageTextAsync(
chatId: command.ChatId,
chatId: textPrompt.Command.Chat.Id,
messageId: responseMessage.MessageId,
text: MarkdownV2Sanitizer.Sanitize("Image generation tidak bisa dipakai di sini."),
parseMode: ParseMode.MarkdownV2,
Expand All @@ -144,7 +140,7 @@ await _telegramBotClient.EditMessageTextAsync(
// Finalize message
try {
responseMessage = await telegramBotClient.EditMessageTextAsync(
chatId: command.ChatId,
chatId: textPrompt.Command.Chat.Id,
messageId: responseMessage.MessageId,
text: MarkdownV2Sanitizer.Sanitize(response),
parseMode: ParseMode.MarkdownV2,
Expand All @@ -159,8 +155,8 @@ await _telegramBotClient.EditMessageTextAsync(
_telegramMessageCache.Add(
message: AIResponseMessage.FromMessage(
message: responseMessage,
replyToMessageId: command.PromptMessageId,
callSign: command.CallSign
replyToMessage: textPrompt.Command,
callSign: textPrompt.CallSign
)
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public Task Handle(StabilityTextToImagePrompt command, CancellationToken cancell
);
} catch (ContentFilteredException exc) {
await _telegramBotClient.EditMessageTextAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
messageId: command.ResponseMessageId,
text: $"<code>{exc.Message ?? "Content filtered."}</code>",
parseMode: ParseMode.Html,
Expand All @@ -38,7 +38,7 @@ await _telegramBotClient.EditMessageTextAsync(
return;
} catch {
await _telegramBotClient.EditMessageTextAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
messageId: command.ResponseMessageId,
text: "<code>Failed to generate image.</code>",
parseMode: ParseMode.Html,
Expand All @@ -50,7 +50,7 @@ await _telegramBotClient.EditMessageTextAsync(
// Delete busy message
try {
await _telegramBotClient.DeleteMessageAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
messageId: command.ResponseMessageId,
cancellationToken: cancellationToken
);
Expand All @@ -61,7 +61,7 @@ await _telegramBotClient.DeleteMessageAsync(
// Send generated image
using MemoryStream generatedImageStream = new(generatedImage);
Message responseMessage = await _telegramBotClient.SendPhotoAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
photo: new InputFileStream(generatedImageStream, "art.png"),
replyToMessageId: command.PromptMessageId,
cancellationToken: cancellationToken
Expand Down
33 changes: 16 additions & 17 deletions BotNet.CommandHandlers/Art/ArtCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
using BotNet.Commands.AI.OpenAI;
using BotNet.Commands.AI.Stability;
using BotNet.Commands.Art;
using BotNet.Commands.CommandPrioritization;
using BotNet.Commands.ChatAggregate;
using BotNet.Commands.SenderAggregate;
using BotNet.Services.MarkdownV2;
using BotNet.Services.RateLimit;
using Telegram.Bot;
Expand All @@ -21,10 +22,10 @@ ICommandQueue commandQueue

public Task Handle(ArtCommand command, CancellationToken cancellationToken) {
try {
IMAGE_GENERATION_RATE_LIMITER.ValidateActionRate(command.ChatId, command.SenderId);
IMAGE_GENERATION_RATE_LIMITER.ValidateActionRate(command.Chat.Id, command.Sender.Id);
} catch (RateLimitExceededException exc) {
return _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
text: $"Anda belum mendapat giliran. Coba lagi {exc.Cooldown}.",
parseMode: ParseMode.Html,
replyToMessageId: command.PromptMessageId,
Expand All @@ -35,10 +36,10 @@ public Task Handle(ArtCommand command, CancellationToken cancellationToken) {
// Fire and forget
Task.Run(async () => {
try {
switch (command.CommandPriority) {
case CommandPriority.VIPChat: {
switch (command) {
case { Sender: VIPSender }: {
Message busyMessage = await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
text: "Generating image… ⏳",
parseMode: ParseMode.Markdown,
replyToMessageId: command.PromptMessageId,
Expand All @@ -50,17 +51,16 @@ await _commandQueue.DispatchAsync(
callSign: "AI",
prompt: command.Prompt,
promptMessageId: command.PromptMessageId,
responseMessageId: busyMessage.MessageId,
chatId: command.ChatId,
senderId: command.SenderId,
commandPriority: command.CommandPriority
responseMessageId: new(busyMessage.MessageId),
chat: command.Chat,
sender: command.Sender
)
);
}
break;
case CommandPriority.HomeGroupChat: {
case { Chat: HomeGroupChat }: {
Message busyMessage = await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
text: "Generating image… ⏳",
parseMode: ParseMode.Markdown,
replyToMessageId: command.PromptMessageId,
Expand All @@ -72,17 +72,16 @@ await _commandQueue.DispatchAsync(
callSign: "AI",
prompt: command.Prompt,
promptMessageId: command.PromptMessageId,
responseMessageId: busyMessage.MessageId,
chatId: command.ChatId,
senderId: command.SenderId,
commandPriority: command.CommandPriority
responseMessageId: new(busyMessage.MessageId),
chat: command.Chat,
sender: command.Sender
)
);
}
break;
default:
await _telegramBotClient.SendTextMessageAsync(
chatId: command.ChatId,
chatId: command.Chat.Id,
text: MarkdownV2Sanitizer.Sanitize("Image generation tidak bisa dipakai di sini."),
parseMode: ParseMode.MarkdownV2,
replyToMessageId: command.PromptMessageId,
Expand Down
Loading

0 comments on commit 1bcd84e

Please sign in to comment.