feat: 增加 SafeW 已监控群列表接口
通过 getUpdates 将群写入 Redis,供创建/编辑渠道时选择 chat_id,避免前端重复传递 token。
This commit is contained in:
+181
-1
@@ -90,11 +90,73 @@ func (s *SafeWSender) Send(title, content string, config json.RawMessage) error
|
||||
}
|
||||
|
||||
func (s *SafeWSender) endpoint(token string) string {
|
||||
return s.methodURL(token, "sendMessage")
|
||||
}
|
||||
|
||||
func (s *SafeWSender) methodURL(token, method string) string {
|
||||
base := s.apiBase
|
||||
if base == "" {
|
||||
base = safewAPIBase
|
||||
}
|
||||
return strings.TrimRight(base, "/") + "/bot" + token + "/sendMessage"
|
||||
return strings.TrimRight(base, "/") + "/bot" + token + "/" + method
|
||||
}
|
||||
|
||||
type SafewAuthError struct {
|
||||
Description string
|
||||
}
|
||||
|
||||
func (e *SafewAuthError) Error() string {
|
||||
if e.Description == "" {
|
||||
return "safew unauthorized"
|
||||
}
|
||||
return e.Description
|
||||
}
|
||||
|
||||
func (s *SafeWSender) PollGroupChats(token string, offset int64, timeout int) ([]SafewChat, int64, error) {
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" {
|
||||
return nil, offset, fmt.Errorf("safew: token is required")
|
||||
}
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"timeout": timeout,
|
||||
"offset": offset,
|
||||
"limit": 100,
|
||||
})
|
||||
resp, err := http.Post(s.methodURL(token, "getUpdates"), "application/json", bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, offset, fmt.Errorf("safew getUpdates: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, offset, fmt.Errorf("safew getUpdates read: %w", err)
|
||||
}
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
return nil, offset, &SafewAuthError{Description: safewErrorDescription(respBody)}
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
desc := safewErrorDescription(respBody)
|
||||
if desc != "" {
|
||||
return nil, offset, fmt.Errorf("safew getUpdates status %d: %s", resp.StatusCode, desc)
|
||||
}
|
||||
return nil, offset, fmt.Errorf("safew getUpdates status %d", resp.StatusCode)
|
||||
}
|
||||
var api safewAPIResponse
|
||||
if err := json.Unmarshal(respBody, &api); err == nil && !api.OK {
|
||||
if resp.StatusCode == 401 || strings.Contains(strings.ToLower(api.Description), "token") {
|
||||
return nil, offset, &SafewAuthError{Description: api.Description}
|
||||
}
|
||||
return nil, offset, fmt.Errorf("safew: %s", api.Description)
|
||||
}
|
||||
chats, maxID, err := GroupsFromUpdates(respBody)
|
||||
if err != nil {
|
||||
return nil, offset, err
|
||||
}
|
||||
next := offset
|
||||
if maxID > 0 {
|
||||
next = maxID + 1
|
||||
}
|
||||
return chats, next, nil
|
||||
}
|
||||
|
||||
func parseSafewChatID(raw json.RawMessage) (string, error) {
|
||||
@@ -136,3 +198,121 @@ func escapeMarkdownV2(s string) string {
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type SafewChat struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Username *string `json:"username"`
|
||||
}
|
||||
|
||||
func GroupsFromUpdates(body []byte) ([]SafewChat, int64, error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.UseNumber()
|
||||
var wrap struct {
|
||||
OK bool `json:"ok"`
|
||||
Result []json.RawMessage `json:"result"`
|
||||
}
|
||||
if err := dec.Decode(&wrap); err != nil {
|
||||
return nil, 0, fmt.Errorf("safew updates decode: %w", err)
|
||||
}
|
||||
seen := map[string]SafewChat{}
|
||||
var maxID int64
|
||||
for _, item := range wrap.Result {
|
||||
id, chat, err := parseUpdateItem(item)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if id > maxID {
|
||||
maxID = id
|
||||
}
|
||||
if chat == nil {
|
||||
continue
|
||||
}
|
||||
if chat.Type != "group" && chat.Type != "supergroup" {
|
||||
continue
|
||||
}
|
||||
seen[chat.ID] = *chat
|
||||
}
|
||||
out := make([]SafewChat, 0, len(seen))
|
||||
for _, c := range seen {
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, maxID, nil
|
||||
}
|
||||
|
||||
func parseUpdateItem(item json.RawMessage) (int64, *SafewChat, error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(item))
|
||||
dec.UseNumber()
|
||||
var u map[string]json.RawMessage
|
||||
if err := dec.Decode(&u); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
var updateID int64
|
||||
if raw, ok := u["update_id"]; ok {
|
||||
var n json.Number
|
||||
if err := json.Unmarshal(raw, &n); err == nil {
|
||||
updateID, _ = n.Int64()
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"message", "edited_message", "channel_post", "edited_channel_post", "my_chat_member", "chat_member"} {
|
||||
raw, ok := u[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
chat := chatFromNested(raw)
|
||||
if chat != nil {
|
||||
return updateID, chat, nil
|
||||
}
|
||||
}
|
||||
return updateID, nil, nil
|
||||
}
|
||||
|
||||
func chatFromNested(raw json.RawMessage) *SafewChat {
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.UseNumber()
|
||||
var obj map[string]json.RawMessage
|
||||
if err := dec.Decode(&obj); err != nil {
|
||||
return nil
|
||||
}
|
||||
chatRaw, ok := obj["chat"]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
dec = json.NewDecoder(bytes.NewReader(chatRaw))
|
||||
dec.UseNumber()
|
||||
var c struct {
|
||||
ID json.Number `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Username *string `json:"username"`
|
||||
}
|
||||
if err := dec.Decode(&c); err != nil {
|
||||
return nil
|
||||
}
|
||||
id := strings.TrimSpace(c.ID.String())
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
return &SafewChat{ID: id, Type: c.Type, Title: c.Title, Username: c.Username}
|
||||
}
|
||||
|
||||
func FilterSafewChats(chats []SafewChat, q string) []SafewChat {
|
||||
q = strings.TrimSpace(strings.ToLower(q))
|
||||
if q == "" {
|
||||
return chats
|
||||
}
|
||||
var out []SafewChat
|
||||
for _, c := range chats {
|
||||
uname := ""
|
||||
if c.Username != nil {
|
||||
uname = *c.Username
|
||||
}
|
||||
if strings.Contains(strings.ToLower(c.Title), q) ||
|
||||
strings.Contains(strings.ToLower(uname), q) ||
|
||||
strings.Contains(strings.ToLower(c.ID), q) {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGroupsFromUpdatesKeepsGroupsDropsPrivate(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"ok": true,
|
||||
"result": [
|
||||
{"update_id": 100000001, "message": {"chat": {"id": 10000778141, "type": "group", "title": "测试AI"}}},
|
||||
{"update_id": 100000002, "message": {"chat": {"id": 11, "type": "private", "first_name": "u"}}},
|
||||
{"update_id": 100000003, "my_chat_member": {"chat": {"id": 22, "type": "supergroup", "title": "SG", "username": "sg_name"}}}
|
||||
]
|
||||
}`)
|
||||
chats, maxID, err := GroupsFromUpdates(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if maxID != 100000003 {
|
||||
t.Fatalf("maxID=%d", maxID)
|
||||
}
|
||||
if len(chats) != 2 {
|
||||
t.Fatalf("len=%d want 2: %#v", len(chats), chats)
|
||||
}
|
||||
byID := map[string]SafewChat{}
|
||||
for _, c := range chats {
|
||||
byID[c.ID] = c
|
||||
}
|
||||
g := byID["10000778141"]
|
||||
if g.Type != "group" || g.Title != "测试AI" {
|
||||
t.Fatalf("group: %#v", g)
|
||||
}
|
||||
raw, _ := json.Marshal(g)
|
||||
var m map[string]any
|
||||
_ = json.Unmarshal(raw, &m)
|
||||
if _, ok := m["id"].(string); !ok {
|
||||
t.Fatalf("id JSON type = %T, want string", m["id"])
|
||||
}
|
||||
sg := byID["22"]
|
||||
if sg.Username == nil || *sg.Username != "sg_name" {
|
||||
t.Fatalf("username: %#v", sg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSafewChats(t *testing.T) {
|
||||
chats := []SafewChat{
|
||||
{ID: "10000778141", Type: "group", Title: "测试AI"},
|
||||
{ID: "99", Type: "group", Title: "ops"},
|
||||
}
|
||||
got := FilterSafewChats(chats, "测试")
|
||||
if len(got) != 1 || got[0].ID != "10000778141" {
|
||||
t.Fatalf("%#v", got)
|
||||
}
|
||||
got = FilterSafewChats(chats, "10000778141")
|
||||
if len(got) != 1 || got[0].Title != "测试AI" {
|
||||
t.Fatalf("%#v", got)
|
||||
}
|
||||
got = FilterSafewChats(chats, "")
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("empty q should keep all, got %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollGroupChatsSuccess(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/bottok/getUpdates" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
if body["timeout"] != float64(0) {
|
||||
t.Errorf("timeout=%v", body["timeout"])
|
||||
}
|
||||
if body["offset"] != float64(5) {
|
||||
t.Errorf("offset=%v", body["offset"])
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"ok":true,"result":[{"update_id":10,"message":{"chat":{"id":10000778141,"type":"group","title":"测试AI"}}}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
s := &SafeWSender{apiBase: srv.URL}
|
||||
chats, next, err := s.PollGroupChats("tok", 5, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next != 11 {
|
||||
t.Fatalf("next=%d want 11", next)
|
||||
}
|
||||
if len(chats) != 1 || chats[0].ID != "10000778141" {
|
||||
t.Fatalf("%#v", chats)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollGroupChatsUnauthorized(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"ok":false,"error_code":401,"description":"BOT_TOKEN_INVALID"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
s := &SafeWSender{apiBase: srv.URL}
|
||||
_, _, err := s.PollGroupChats("bad", 0, 0)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
ae, ok := err.(*SafewAuthError)
|
||||
if !ok {
|
||||
t.Fatalf("type %T %v", err, err)
|
||||
}
|
||||
if !strings.Contains(ae.Description, "BOT_TOKEN_INVALID") {
|
||||
t.Fatalf("%q", ae.Description)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user