Files
soft_usite/pkg/models/telegram_agent.go
T
Lizandro GDandClaude Sonnet 4.6 33cfe4fdb0 feat: agente Telegram con IA + Coolify multi-instancia
- Coolify: soporte multi-instancia (CRUD de configs, ?config_id= en todos
  los endpoints, endpoints expandidos para services/databases/teams/envs)
- AiConfig: campos es_agente_bot + telegram_config_id para marcar qué
  config de IA actúa como cerebro del bot administrador
- TelegramAgentHistory + TelegramAgentAuth: historial de conversación por
  chat_id y whitelist de chats autorizados
- Agent Engine: function calling OpenAI-compatible con 25+ herramientas
  (clientes, contratos, contabilidad, proyectos, tickets, tareas,
  Coolify multi-instancia, servidores, monitores URL)
- Webhook POST /webhooks/telegram-agent/:bot_token (público, sin sesión)
- API /api/v2/agent/auth y /api/v2/agent/history para administrar el agente
- AutoMigrate: AiConfig, TelegramAgentHistory, TelegramAgentAuth

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-13 18:29:06 +00:00

84 lines
2.8 KiB
Go

package models
import (
"github.com/sujit-baniya/fiber-boilerplate/app"
"gorm.io/gorm"
)
// TelegramAgentHistory guarda el historial de conversación por chat_id.
// Se usan los últimos N mensajes como contexto en cada llamada al AI.
type TelegramAgentHistory struct {
gorm.Model
ChatID int64 `json:"chat_id" gorm:"column:chat_id;index;not null"`
Role string `json:"role" gorm:"column:role;not null"` // user | assistant | tool
Content string `json:"content" gorm:"column:content;type:text;not null"`
// ToolName y ToolResult se usan para mensajes de tipo "tool"
ToolName string `json:"tool_name" gorm:"column:tool_name"`
ToolResult string `json:"tool_result" gorm:"column:tool_result;type:text"`
}
func (TelegramAgentHistory) TableName() string { return "telegram_agent_history" }
// TelegramAgentChatID guarda qué chat_ids están autorizados a usar el agente.
type TelegramAgentAuth struct {
gorm.Model
ChatID int64 `json:"chat_id" gorm:"column:chat_id;uniqueIndex;not null"`
Nombre string `json:"nombre" gorm:"column:nombre"`
Activo bool `json:"activo" gorm:"column:activo;default:true"`
}
func (TelegramAgentAuth) TableName() string { return "telegram_agent_auth" }
// GetAgentHistory retorna los últimos n mensajes del historial para un chat_id.
func GetAgentHistory(chatID int64, n int) ([]TelegramAgentHistory, error) {
var items []TelegramAgentHistory
err := app.Http.Database.DB.
Where("chat_id = ?", chatID).
Order("created_at DESC").
Limit(n).
Find(&items).Error
// Invertir para orden cronológico
for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
items[i], items[j] = items[j], items[i]
}
return items, err
}
func SaveAgentMessage(chatID int64, role, content, toolName, toolResult string) error {
msg := &TelegramAgentHistory{
ChatID: chatID,
Role: role,
Content: content,
ToolName: toolName,
ToolResult: toolResult,
}
return app.Http.Database.DB.Create(msg).Error
}
// ClearAgentHistory borra el historial de un chat (comando /reset).
func ClearAgentHistory(chatID int64) error {
return app.Http.Database.DB.Where("chat_id = ?", chatID).Delete(&TelegramAgentHistory{}).Error
}
// IsAgentAuthChat verifica si un chat_id está autorizado.
func IsAgentAuthChat(chatID int64) bool {
var auth TelegramAgentAuth
err := app.Http.Database.DB.Where("chat_id = ? AND activo = ?", chatID, true).First(&auth).Error
return err == nil
}
func GetAllAgentAuth() ([]TelegramAgentAuth, error) {
var items []TelegramAgentAuth
err := app.Http.Database.DB.Order("created_at DESC").Find(&items).Error
return items, err
}
func CreateAgentAuth(chatID int64, nombre string) error {
auth := &TelegramAgentAuth{ChatID: chatID, Nombre: nombre, Activo: true}
return app.Http.Database.DB.Create(auth).Error
}
func DeleteAgentAuth(id uint) error {
return app.Http.Database.DB.Delete(&TelegramAgentAuth{}, id).Error
}