telegram-ollama-reply-bot/bot/message_history.go
Alexey Skobkin 40b20b1b50
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Raising the limit of history container size
2024-10-30 16:12:39 +00:00

94 lines
1.6 KiB
Go

package bot
import (
"github.com/mymmrac/telego"
"log/slog"
)
const HistoryLength = 150
type Message struct {
Name string
Text string
IsMe bool
}
type MessageRingBuffer struct {
messages []Message
capacity int
}
func NewMessageBuffer(capacity int) *MessageRingBuffer {
return &MessageRingBuffer{
messages: make([]Message, 0, capacity),
capacity: capacity,
}
}
func (b *MessageRingBuffer) Push(element Message) {
if len(b.messages) >= b.capacity {
b.messages = b.messages[1:]
}
b.messages = append(b.messages, element)
}
func (b *MessageRingBuffer) GetAll() []Message {
return b.messages
}
func (b *Bot) saveChatMessageToHistory(message *telego.Message) {
chatId := message.Chat.ID
slog.Info(
"history-message-save",
"chat", chatId,
"from_id", message.From.ID,
"from_name", message.From.FirstName,
"text", message.Text,
)
_, ok := b.history[chatId]
if !ok {
b.history[chatId] = NewMessageBuffer(HistoryLength)
}
b.history[chatId].Push(Message{
Name: message.From.FirstName,
Text: message.Text,
IsMe: false,
})
}
func (b *Bot) saveBotReplyToHistory(message *telego.Message, reply string) {
chatId := message.Chat.ID
slog.Info(
"history-reply-save",
"chat", chatId,
"to_id", message.From.ID,
"to_name", message.From.FirstName,
"text", reply,
)
_, ok := b.history[chatId]
if !ok {
b.history[chatId] = NewMessageBuffer(HistoryLength)
}
b.history[chatId].Push(Message{
Name: b.profile.Username,
Text: reply,
IsMe: true,
})
}
func (b *Bot) getChatHistory(chatId int64) []Message {
_, ok := b.history[chatId]
if !ok {
return make([]Message, 0)
}
return b.history[chatId].GetAll()
}