浏览代码

Merge branch 'feature/non_friends' into debug

* feature/non_friends:
  fixbug
boweniac 5 天之前
父节点
当前提交
3f0d1b8532
共有 1 个文件被更改,包括 29 次插入14 次删除
  1. 29 14
      crontask/contact_form.go

+ 29 - 14
crontask/contact_form.go

@@ -6,6 +6,7 @@ import (
 	"github.com/google/uuid"
 	"github.com/zeromicro/go-zero/core/logx"
 	"strconv"
+	"strings"
 	"time"
 	"wechat-api/ent/contact"
 	"wechat-api/ent/contactfield"
@@ -227,23 +228,10 @@ func (l *CronTask) openaiRequest(messages string, template []custom_types.Contac
 	if err == nil && resp != nil && len(resp.Choices) > 0 {
 		logx.Info("resp.Choices: ", resp.Choices[0].Message.Content)
 		// 尝试第一层解析成 string
-		var inner string
-		if err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &inner); err == nil {
-			// 成功表示 data 是个被编码过的 JSON 字符串
-			resp.Choices[0].Message.Content = inner
-		}
-		// 解析最终目标
-		var items []ResponseItem
-		err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &items)
+		items, err := parseContent(resp.Choices[0].Message.Content)
 		if err != nil {
 			return nil, err
 		}
-
-		//var items []ResponseItem
-		//err = json.Unmarshal([]byte(resp.Choices[0].Message.Content), &items)
-		//if err != nil {
-		//	return nil, err
-		//}
 		return items, nil
 	} else if resp != nil && len(resp.Choices) == 0 {
 		return nil, err
@@ -453,3 +441,30 @@ func contains(strs []string, target string) bool {
 	}
 	return false
 }
+
+func parseContent(content string) ([]ResponseItem, error) {
+	content = strings.TrimSpace(content)
+
+	// ① 双引号包裹的再来一次:"{\"dataIndex\":...}"
+	if unq, err := strconv.Unquote(content); err == nil {
+		return parseContent(unq) // 尝试递归
+	}
+
+	// ② 数组形式
+	if strings.HasPrefix(content, "[") {
+		var list []ResponseItem
+		if err := json.Unmarshal([]byte(content), &list); err == nil {
+			return list, nil
+		}
+	}
+
+	// ③ 单对象形式
+	if strings.HasPrefix(content, "{") {
+		var item ResponseItem
+		if err := json.Unmarshal([]byte(content), &item); err == nil {
+			return []ResponseItem{item}, nil
+		}
+	}
+
+	return nil, fmt.Errorf("unsupported content format: %q", content)
+}