// Package fakeserver is a small in-memory stand-in for the Telegram Bot API. // Tests and the load script point the bot at it, push updates in and inspect // the calls the bot makes. It speaks real HTTP, so the bot runs through the // same telego code paths as in production, including multipart uploads. package fakeserver import ( "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "regexp" "strconv" "strings" "sync" "time" "unicode/utf16" ) // Token is a syntactically valid bot token accepted by the fake server. const Token = "123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01" // BotID and BotUsername describe the fake bot account. const ( BotID = 123456789 BotUsername = "nr_dl_test_bot" ) // Call is one Bot API request made by the bot. type Call struct { Seq int Method string // Params holds the request parameters as strings. Nested values such as // reply_markup are kept as JSON text. Params map[string]string // Files holds uploaded files by parameter name. Files map[string]File // MessageID is the ID of the message the call created or edited. MessageID int // Failed is true when the server answered with a scripted error. Failed bool } // File is an uploaded file. type File struct { Name string Size int64 } // Button is one inline keyboard button. type Button struct { Text string `json:"text"` Data string `json:"callback_data"` URL string `json:"url"` // WebApp is set on a button that opens a Mini App. WebApp *struct { URL string `json:"url"` } `json:"web_app"` } // Buttons parses the inline keyboard of the call, flattened row by row. func (c Call) Buttons() []Button { var markup struct { InlineKeyboard [][]Button `json:"inline_keyboard"` } if err := json.Unmarshal([]byte(c.Params["reply_markup"]), &markup); err != nil { return nil } var out []Button for _, row := range markup.InlineKeyboard { out = append(out, row...) } return out } // Button returns the button whose callback data starts with prefix. func (c Call) Button(prefix string) (Button, bool) { for _, b := range c.Buttons() { if strings.HasPrefix(b.Data, prefix) { return b, true } } return Button{}, false } // Text returns the text or caption of a send or edit call. func (c Call) Text() string { if t := c.Params["text"]; t != "" { return t } return c.Params["caption"] } // ChatID returns the chat_id parameter as a number. func (c Call) ChatID() int64 { n, _ := strconv.ParseInt(c.Params["chat_id"], 10, 64) return n } type scriptedError struct { code int desc string } // Server is the fake Bot API. type Server struct { HTTP *httptest.Server mu sync.Mutex cond *sync.Cond updates []map[string]any updateID int msgID int fileSeq int seq int calls []Call failures map[string][]scriptedError members map[string]string sent map[int]map[string]any // messages the bot sent, by message ID // confirmed is the highest update ID the bot acknowledged by asking for // a later offset. Like Telegram, confirmed updates are never sent again. confirmed int closed bool } // New starts a fake server on a random local port. func New() *Server { s := NewHandler() s.HTTP = httptest.NewServer(s) return s } // NewHandler returns a fake server that is not listening yet. It is an // http.Handler, so a program can serve it on an address of its choice. func NewHandler() *Server { s := &Server{ msgID: 1000, failures: map[string][]scriptedError{}, members: map[string]string{}, sent: map[int]map[string]any{}, } s.cond = sync.NewCond(&s.mu) return s } // ServeHTTP implements http.Handler. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.handle(w, r) } // URL returns the API root to pass to the bot as TELEGRAM_API_URL. func (s *Server) URL() string { return s.HTTP.URL } // Close stops the server and releases long polls. func (s *Server) Close() { s.mu.Lock() s.closed = true s.cond.Broadcast() s.mu.Unlock() if s.HTTP != nil { s.HTTP.CloseClientConnections() s.HTTP.Close() } } // FailNext makes the next call of a method fail with a Bot API error. func (s *Server) FailNext(method string, code int, description string) { s.mu.Lock() defer s.mu.Unlock() s.failures[method] = append(s.failures[method], scriptedError{code, description}) } // SetMember sets the chat member status getChatMember reports, for example // "administrator". The default is "member". func (s *Server) SetMember(chatID, userID int64, status string) { s.mu.Lock() defer s.mu.Unlock() s.members[fmt.Sprintf("%d:%d", chatID, userID)] = status } // Calls returns the calls of one method, or all calls when method is "". func (s *Server) Calls(method string) []Call { s.mu.Lock() defer s.mu.Unlock() var out []Call for _, c := range s.calls { if method == "" || c.Method == method { out = append(out, c) } } return out } // Seq returns the sequence number of the latest call, to be used as a // starting point for WaitFor. func (s *Server) Seq() int { s.mu.Lock() defer s.mu.Unlock() return s.seq } // WaitFor blocks until a call made after sequence number "after" matches, // and returns it. ok is false when the timeout passes first. method may be // several names separated by "|". func (s *Server) WaitFor(after int, timeout time.Duration, method string, match func(Call) bool) (Call, bool) { methods := strings.Split(method, "|") deadline := time.Now().Add(timeout) timer := time.AfterFunc(timeout, func() { s.mu.Lock() s.cond.Broadcast() s.mu.Unlock() }) defer timer.Stop() s.mu.Lock() defer s.mu.Unlock() for { for _, c := range s.calls { if c.Seq <= after { continue } for _, m := range methods { if c.Method == m && (match == nil || match(c)) { return c, true } } } if time.Now().After(deadline) || s.closed { return Call{}, false } s.cond.Wait() } } // MsgOpt customizes a pushed message. type MsgOpt func(msg map[string]any) // Lang sets the language_code of the sender. func Lang(code string) MsgOpt { return func(msg map[string]any) { msg["from"].(map[string]any)["language_code"] = code } } // ReplyTo makes the message a reply to an earlier message with given text. func ReplyTo(messageID int, text string) MsgOpt { return func(msg map[string]any) { msg["reply_to_message"] = map[string]any{ "message_id": messageID, "date": time.Now().Unix(), "chat": msg["chat"], "from": map[string]any{"id": 4242, "is_bot": false, "first_name": "Other"}, "text": text, "entities": entitiesFor(text), } } } // From sets the first name and username of the sender. func From(firstName, username string) MsgOpt { return func(msg map[string]any) { from := msg["from"].(map[string]any) from["first_name"] = firstName from["username"] = username } } // PushMessage queues a text message update and returns its message ID. // Negative chat IDs are groups, positive ones private chats. func (s *Server) PushMessage(chatID, userID int64, text string, opts ...MsgOpt) int { s.mu.Lock() defer s.mu.Unlock() s.msgID++ msg := map[string]any{ "message_id": s.msgID, "date": time.Now().Unix(), "chat": chatObject(chatID), "from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": "en"}, "text": text, } if ents := entitiesFor(text); len(ents) > 0 { msg["entities"] = ents } for _, o := range opts { o(msg) } s.pushLocked(map[string]any{"message": msg}) return s.msgID } // PushCallback queues a button press on a message. func (s *Server) PushCallback(chatID, userID int64, messageID int, data string) string { s.mu.Lock() defer s.mu.Unlock() id := fmt.Sprintf("cb%d", s.updateID+1) // Like Telegram, the update carries the message the button sits on. msg, known := s.sent[messageID] if !known { msg = map[string]any{ "message_id": messageID, "date": time.Now().Unix(), "chat": chatObject(chatID), "from": botUser(), "text": "card", } } s.pushLocked(map[string]any{"callback_query": map[string]any{ "id": id, "from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": "en"}, "chat_instance": "ci", "data": data, "message": msg, }}) return id } // PushRaw queues an arbitrary update body, for example my_chat_member. func (s *Server) PushRaw(update map[string]any) { s.mu.Lock() defer s.mu.Unlock() s.pushLocked(update) } func (s *Server) pushLocked(update map[string]any) { s.updateID++ update["update_id"] = s.updateID s.updates = append(s.updates, update) s.cond.Broadcast() } func chatObject(chatID int64) map[string]any { if chatID < 0 { return map[string]any{"id": chatID, "type": "supergroup", "title": "Test Group"} } return map[string]any{"id": chatID, "type": "private", "first_name": "User"} } func botUser() map[string]any { return map[string]any{"id": BotID, "is_bot": true, "first_name": "NR Download Bot", "username": BotUsername} } var ( cmdRe = regexp.MustCompile(`^/[A-Za-z0-9_]+(@[A-Za-z0-9_]+)?`) urlRe = regexp.MustCompile(`(?i)(https?://[^\s]+|\b[a-z0-9-]+\.(be|com|org|net|tv)/[^\s]+)`) ) func entitiesFor(text string) []map[string]any { var out []map[string]any u16 := func(byteOff int) int { return len(utf16.Encode([]rune(text[:byteOff]))) } if loc := cmdRe.FindStringIndex(text); loc != nil { out = append(out, map[string]any{"type": "bot_command", "offset": 0, "length": u16(loc[1])}) } for _, loc := range urlRe.FindAllStringIndex(text, -1) { out = append(out, map[string]any{"type": "url", "offset": u16(loc[0]), "length": u16(loc[1]) - u16(loc[0])}) } return out } func (s *Server) handle(w http.ResponseWriter, r *http.Request) { // Path: /bot/ rest, ok := strings.CutPrefix(r.URL.Path, "/bot"+Token+"/") if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"ok": false, "error_code": 401, "description": "Unauthorized"}) return } method := rest params, files, err := readParams(r) if err != nil { writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error_code": 400, "description": "Bad Request: " + err.Error()}) return } if method == "getUpdates" { s.getUpdates(w, params) return } s.mu.Lock() s.seq++ call := Call{Seq: s.seq, Method: method, Params: params, Files: files} if q := s.failures[method]; len(q) > 0 { fail := q[0] s.failures[method] = q[1:] call.Failed = true s.calls = append(s.calls, call) s.cond.Broadcast() s.mu.Unlock() writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error_code": fail.code, "description": fail.desc}) return } result := s.resultLocked(&call) s.calls = append(s.calls, call) s.cond.Broadcast() s.mu.Unlock() writeJSON(w, http.StatusOK, map[string]any{"ok": true, "result": result}) } func (s *Server) getUpdates(w http.ResponseWriter, params map[string]string) { offset, _ := strconv.Atoi(params["offset"]) // Long polls are kept short so tests shut down quickly. deadline := time.Now().Add(150 * time.Millisecond) timer := time.AfterFunc(150*time.Millisecond, func() { s.mu.Lock() s.cond.Broadcast() s.mu.Unlock() }) defer timer.Stop() s.mu.Lock() defer s.mu.Unlock() if offset-1 > s.confirmed { s.confirmed = offset - 1 } for { var out []map[string]any for _, u := range s.updates { if id := u["update_id"].(int); id > s.confirmed && id >= offset { out = append(out, u) } } if len(out) > 0 || time.Now().After(deadline) || s.closed { if out == nil { out = []map[string]any{} } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "result": out}) return } s.cond.Wait() } } // resultLocked builds a plausible result for a call. func (s *Server) resultLocked(c *Call) any { switch c.Method { case "getMe": return botUser() case "getChatMember": status := s.members[c.Params["chat_id"]+":"+c.Params["user_id"]] if status == "" { status = "member" } uid, _ := strconv.ParseInt(c.Params["user_id"], 10, 64) return map[string]any{"status": status, "user": map[string]any{"id": uid, "is_bot": false, "first_name": "User"}} case "sendMessage", "sendPhoto", "sendVideo", "sendAudio", "sendDocument", "sendAnimation": s.msgID++ c.MessageID = s.msgID msg := s.messageLocked(c) s.sent[c.MessageID] = msg return msg case "editMessageText", "editMessageCaption", "editMessageReplyMarkup", "editMessageMedia": c.MessageID, _ = strconv.Atoi(c.Params["message_id"]) return s.messageLocked(c) default: return true } } func (s *Server) messageLocked(c *Call) map[string]any { msg := map[string]any{ "message_id": c.MessageID, "date": time.Now().Unix(), "chat": chatObject(c.ChatID()), "from": botUser(), } if t := c.Params["text"]; t != "" { msg["text"] = t } if t := c.Params["caption"]; t != "" { msg["caption"] = t } media := func(field string) map[string]any { // A string parameter is a file_id or URL and keeps its identity; an // upload gets a fresh file_id. id := c.Params[field] if _, uploaded := c.Files[field]; uploaded || id == "" || strings.HasPrefix(id, "http") { s.fileSeq++ id = fmt.Sprintf("%s-file-%d", field, s.fileSeq) } return map[string]any{"file_id": id, "file_unique_id": "u-" + id} } switch c.Method { case "sendPhoto": ph := media("photo") ph["width"], ph["height"] = 320, 180 msg["photo"] = []any{ph} case "sendVideo": v := media("video") v["width"], v["height"], v["duration"] = 1280, 720, 60 msg["video"] = v case "sendAudio": a := media("audio") a["duration"] = 60 msg["audio"] = a case "sendDocument": msg["document"] = media("document") case "sendAnimation": a := media("animation") a["width"], a["height"], a["duration"] = 320, 180, 3 msg["animation"] = a } return msg } func readParams(r *http.Request) (map[string]string, map[string]File, error) { params := map[string]string{} files := map[string]File{} ct := r.Header.Get("Content-Type") switch { case strings.HasPrefix(ct, "multipart/form-data"): mr, err := r.MultipartReader() if err != nil { return nil, nil, err } for { part, err := mr.NextPart() if err == io.EOF { break } if err != nil { return nil, nil, err } if part.FileName() != "" { n, _ := io.Copy(io.Discard, part) files[part.FormName()] = File{Name: part.FileName(), Size: n} continue } b, _ := io.ReadAll(part) params[part.FormName()] = string(b) } default: body, err := io.ReadAll(r.Body) if err != nil { return nil, nil, err } if len(strings.TrimSpace(string(body))) == 0 { return params, files, nil } var raw map[string]json.RawMessage if err := json.Unmarshal(body, &raw); err != nil { return nil, nil, err } for k, v := range raw { var str string if json.Unmarshal(v, &str) == nil { params[k] = str } else { params[k] = string(v) } } } return params, files, nil } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) }