//go:build simbot package main import ( "encoding/json" "flag" "log" "net/url" "os" "os/signal" "syscall" "time" "github.com/gorilla/websocket" ) const ( gatewayURL = "ws://localhost:3333/sync" apiKey = "gateway" // must match the mod's channel id used by your mod simulator channelID = "123456789" ) type Handshake struct { Type string `json:"type"` Data json.RawMessage `json:"data"` } type BotHandshake struct { ChannelId string `json:"channel_id"` // match gateway field exactly } type GatewayAck struct { Status string `json:"status"` Type string `json:"type"` } type User struct { ID string `json:"id"` Name string `json:"name"` } type Destination struct { ID string `json:"channel_id,omitempty"` } type GatewayMessageIn struct { ID string `json:"id"` MsgID string `json:"msg_id"` Destination Destination `json:"destination,omitempty"` Author User `json:"author"` Content string `json:"content"` Meta map[string]interface{} `json:"meta,omitempty"` Ts time.Time `json:"ts,omitempty"` ReceivedAt time.Time `json:"-"` } func main() { var ( botID = flag.String("bot", "sim-bot-1", "bot id") sendAfter = flag.Duration("send-after", 0, "optional: send a bot->mod message after this delay (e.g. 2s)") sendMsg = flag.String("msg", "Hello from bot!", "optional bot->mod test message content") ) flag.Parse() interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) u, err := url.Parse(gatewayURL) if err != nil { log.Fatalf("Failed to parse URL: %v", err) } q := u.Query() q.Set("api_key", apiKey) u.RawQuery = q.Encode() log.Printf("Connecting to %s", u.String()) conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatalf("Failed to connect: %v", err) } // we intentionally don't defer conn.Close() here immediately; we'll do on shutdown log.Println("Connected to gateway") // handle server pings by replying a Pong (safe) conn.SetPingHandler(func(appData string) error { log.Println("Received ping from server, sending pong") return conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(5*time.Second)) }) // send bot handshake (must at least include bot_id) bhs := BotHandshake{ChannelId: channelID} data, err := json.Marshal(bhs) if err != nil { _ = conn.Close() log.Fatalf("Failed to marshal bot handshake: %v", err) } hs := Handshake{Type: "bot", Data: data} if err := conn.WriteJSON(hs); err != nil { _ = conn.Close() log.Fatalf("Failed to send handshake: %v", err) } log.Println("Handshake sent (bot)") // Instead of ReadJSON, read raw message so we can see whatever the server returns (or why it closes). // This avoids a silent parsing failure if server returns non-JSON or closes immediately. conn.SetReadDeadline(time.Now().Add(10 * time.Second)) msgType, raw, err := conn.ReadMessage() if err != nil { _ = conn.Close() log.Fatalf("Failed to read handshake response: %v", err) } _ = conn.SetReadDeadline(time.Time{}) // clear deadline if msgType == websocket.TextMessage || msgType == websocket.BinaryMessage { log.Printf("Raw handshake reply: %s", string(raw)) var ack GatewayAck if err := json.Unmarshal(raw, &ack); err != nil { log.Printf("Handshake reply is not JSON or unmarshal failed: %v", err) } else { log.Printf("Parsed ack: status=%q, type=%q", ack.Status, ack.Type) } } else { log.Printf("Handshake reply was control frame or unexpected type=%d", msgType) } // From here, start the normal read loop. done := make(chan struct{}) go func() { defer close(done) for { msgType, message, err := conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) { log.Printf("WebSocket error: %v", err) } else { log.Printf("Connection closed or read error: %v", err) } return } if msgType == websocket.TextMessage || msgType == websocket.BinaryMessage { log.Printf("Received from gateway: %s", string(message)) } } }() // optionally send a bot->mod message after a delay if *sendAfter > 0 { go func() { time.Sleep(*sendAfter) msg := GatewayMessageIn{ MsgID: "bot-msg-001", ID: channelID, // bot reports channel id as ID Author: User{ ID: *botID, Name: "SimBot", }, Content: *sendMsg, Ts: time.Now().UTC(), } // set a write deadline _ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) if err := conn.WriteJSON(msg); err != nil { log.Printf("Failed to send bot->mod test message: %v", err) return } log.Printf("Sent bot->mod test message (channel=%s)", channelID) _ = conn.SetWriteDeadline(time.Time{}) }() } log.Println("Bot simulator running. Press Ctrl+C to exit.") // Wait for interrupt or read loop done for { select { case <-done: log.Println("Connection closed by server") _ = conn.Close() return case <-interrupt: log.Println("Interrupt received, closing connection...") // politely close _ = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) select { case <-done: case <-time.After(time.Second): } _ = conn.Close() return } } }