feat(bots): bot framework polish + store

- /ws/bot endpoint: bot token auth via query param, SHA-256 lookup
- Bot WS actions: SEND_MESSAGE + DELETE_MESSAGE handled in gateway
- Bot messages: bot_id on messages table, bot badge in chat (green + BOT tag)
- Bot store: /bots lists all bots with server count + add-to-server
- Bot manager moved to /bots/manage
- Fix: command routes were double-nested under /bots/{botID}/commands
- Fix: fetchServerCommands route corrected to /bots/servers/...
This commit is contained in:
2026-07-15 12:45:44 -04:00
parent 56af584ede
commit 5bdb758d23
13 changed files with 557 additions and 22 deletions
+209
View File
@@ -2,7 +2,9 @@ package gateway
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"log/slog"
"net/http"
@@ -106,6 +108,9 @@ type Client struct {
Conn *websocket.Conn
UserID string
Username string
IsBot bool
BotID string
BotName string
send chan []byte
}
@@ -184,6 +189,18 @@ func (c *Client) readPump() {
})
}
}
case BotSendMessage:
if !c.IsBot {
c.Hub.logger.Warn("non-bot client sent SEND_MESSAGE", "user_id", c.UserID)
continue
}
c.handleBotSendMessage(event.Data)
case BotDeleteMessage:
if !c.IsBot {
c.Hub.logger.Warn("non-bot client sent DELETE_MESSAGE", "user_id", c.UserID)
continue
}
c.handleBotDeleteMessage(event.Data)
default:
c.Hub.logger.Info("received event from client", "type", event.Type, "user_id", c.UserID)
}
@@ -300,3 +317,195 @@ func ServeWS(db *sql.DB, hub *Hub, logger *slog.Logger, w http.ResponseWriter, r
go client.writePump()
go client.readPump()
}
// ServeBotWS handles websocket requests from bot clients.
// Authenticates via ?token= query param (bot token, hashed lookup).
func ServeBotWS(db *sql.DB, hub *Hub, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token == "" {
http.Error(w, `{"error":"token query param required"}`, http.StatusBadRequest)
return
}
// Hash the token and look up the bot.
tokenHash := hashToken(token)
var botID, botName, ownerID string
err := db.QueryRowContext(r.Context(),
`SELECT id, name, owner_id FROM bots WHERE token = $1`,
tokenHash,
).Scan(&botID, &botName, &ownerID)
if err != nil {
logger.Warn("bot ws auth: invalid token")
http.Error(w, `{"error":"invalid bot token"}`, http.StatusUnauthorized)
return
}
// Verify the bot is added to at least one server.
var serverCount int
err = db.QueryRowContext(r.Context(),
`SELECT COUNT(*) FROM bot_servers WHERE bot_id = $1`, botID,
).Scan(&serverCount)
if err != nil || serverCount == 0 {
logger.Warn("bot ws auth: bot not added to any server", "bot_id", botID)
http.Error(w, `{"error":"bot not added to any server"}`, http.StatusForbidden)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Error("bot websocket upgrade failed", "error", err)
return
}
// Load bot server memberships into hub so BroadcastToServer works.
hub.RefreshUserServers(ownerID)
conn.SetReadDeadline(time.Time{})
conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"ready","bot_id":"`+botID+`"}`))
client := &Client{
Hub: hub,
Conn: conn,
UserID: ownerID,
Username: botName,
IsBot: true,
BotID: botID,
BotName: botName,
send: make(chan []byte, 256),
}
hub.Register(client)
go client.writePump()
go client.readPump()
}
// hashToken returns the SHA-256 hex digest of a token.
func hashToken(token string) string {
h := sha256.Sum256([]byte(token))
return hex.EncodeToString(h[:])
}
// handleBotSendMessage processes a SEND_MESSAGE action from a bot client.
func (c *Client) handleBotSendMessage(data interface{}) {
var payload struct {
ChannelID string `json:"channel_id"`
Content string `json:"content"`
}
raw, ok := data.(json.RawMessage)
if !ok {
return
}
if err := json.Unmarshal(raw, &payload); err != nil || payload.ChannelID == "" || payload.Content == "" {
c.Hub.logger.Warn("bot SEND_MESSAGE: invalid payload")
return
}
if len(payload.Content) > 4000 {
payload.Content = payload.Content[:4000]
}
// Verify the bot is in the server that owns this channel.
serverID, err := c.Hub.ServerIDForChannel(context.Background(), payload.ChannelID)
if err != nil {
c.Hub.logger.Warn("bot SEND_MESSAGE: channel not found", "channel_id", payload.ChannelID)
return
}
var inServer bool
err = c.Hub.db.QueryRowContext(context.Background(),
`SELECT EXISTS(SELECT 1 FROM bot_servers WHERE bot_id = $1 AND server_id = $2)`,
c.BotID, serverID,
).Scan(&inServer)
if err != nil || !inServer {
c.Hub.logger.Warn("bot SEND_MESSAGE: bot not in server", "bot_id", c.BotID, "server_id", serverID)
return
}
// Insert the message with bot_id set.
var msgID, createdAt string
err = c.Hub.db.QueryRowContext(context.Background(),
`INSERT INTO messages (channel_id, author_id, content, bot_id)
VALUES ($1, $2, $3, $4)
RETURNING id, created_at::text`,
payload.ChannelID, c.UserID, payload.Content, c.BotID,
).Scan(&msgID, &createdAt)
if err != nil {
c.Hub.logger.Error("bot SEND_MESSAGE: insert failed", "error", err)
return
}
// Broadcast MESSAGE_CREATE to the server.
c.Hub.BroadcastToServer(serverID, Event{
Type: EventMessageCreate,
Data: map[string]interface{}{
"id": msgID,
"channel_id": payload.ChannelID,
"author_id": c.UserID,
"author_username": c.BotName,
"author_display_name": nil,
"author_bot": true,
"bot_id": c.BotID,
"bot_name": c.BotName,
"content": payload.Content,
"reply_to": nil,
"edited_at": nil,
"pinned": false,
"created_at": createdAt,
"embeds": []interface{}{},
"reactions": []interface{}{},
},
})
}
// handleBotDeleteMessage processes a DELETE_MESSAGE action from a bot client.
func (c *Client) handleBotDeleteMessage(data interface{}) {
var payload struct {
ChannelID string `json:"channel_id"`
MessageID string `json:"message_id"`
}
raw, ok := data.(json.RawMessage)
if !ok {
return
}
if err := json.Unmarshal(raw, &payload); err != nil || payload.ChannelID == "" || payload.MessageID == "" {
c.Hub.logger.Warn("bot DELETE_MESSAGE: invalid payload")
return
}
// Verify the bot is in the server that owns this channel.
serverID, err := c.Hub.ServerIDForChannel(context.Background(), payload.ChannelID)
if err != nil {
return
}
var inServer bool
err = c.Hub.db.QueryRowContext(context.Background(),
`SELECT EXISTS(SELECT 1 FROM bot_servers WHERE bot_id = $1 AND server_id = $2)`,
c.BotID, serverID,
).Scan(&inServer)
if err != nil || !inServer {
return
}
// Delete the message (only if it exists in this channel).
result, err := c.Hub.db.ExecContext(context.Background(),
`DELETE FROM messages WHERE id = $1 AND channel_id = $2`,
payload.MessageID, payload.ChannelID,
)
if err != nil {
c.Hub.logger.Error("bot DELETE_MESSAGE: delete failed", "error", err)
return
}
rows, _ := result.RowsAffected()
if rows == 0 {
return
}
// Broadcast MESSAGE_DELETE.
c.Hub.BroadcastToServer(serverID, Event{
Type: EventMessageDelete,
Data: map[string]string{
"id": payload.MessageID,
"channel_id": payload.ChannelID,
},
})
}
+4
View File
@@ -23,6 +23,10 @@ const (
EventVoiceMute = "VOICE_MUTE"
EventVoiceDeafen = "VOICE_DEAFEN"
EventVoiceWhisper = "VOICE_WHISPER"
// Bot action events (sent by bot clients)
BotSendMessage = "SEND_MESSAGE"
BotDeleteMessage = "DELETE_MESSAGE"
)
// Event represents a WebSocket event sent to clients.