Browse Source

如果内容为空,则由openai生成内容

DESKTOP-TH1UEOC\Rowan 1 year ago
parent
commit
726052080f
3 changed files with 123 additions and 0 deletions
  1. 2 0
      go.mod
  2. 4 0
      go.sum
  3. 117 0
      internal/mqs/amq/handler/amq/wxhook/say_morning.go

+ 2 - 0
go.mod

@@ -40,6 +40,7 @@ require (
 	github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
 	github.com/gofrs/uuid/v5 v5.0.0 // indirect
 	github.com/gogo/protobuf v1.3.2 // indirect
+	github.com/golang-module/carbon/v2 v2.3.10 // indirect
 	github.com/golang/mock v1.6.0 // indirect
 	github.com/golang/protobuf v1.5.4 // indirect
 	github.com/google/gnostic-models v0.6.8 // indirect
@@ -56,6 +57,7 @@ require (
 	github.com/json-iterator/go v1.1.12 // indirect
 	github.com/klauspost/compress v1.17.7 // indirect
 	github.com/lib/pq v1.10.9 // indirect
+	github.com/liujiawm/gocalendar v1.1.0 // indirect
 	github.com/mailru/easyjson v0.7.7 // indirect
 	github.com/mattn/go-colorable v0.1.13 // indirect
 	github.com/mattn/go-isatty v0.0.20 // indirect

+ 4 - 0
go.sum

@@ -76,6 +76,8 @@ github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M=
 github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
 github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
 github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
+github.com/golang-module/carbon/v2 v2.3.10 h1:C25x4A4UrIch6bisV3j37eU+op5+cp4gw/Fffv5c/FA=
+github.com/golang-module/carbon/v2 v2.3.10/go.mod h1:XDALX7KgqmHk95xyLeaqX9/LJGbfLATyruTziq68SZ8=
 github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
 github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
 github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
@@ -134,6 +136,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
 github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
 github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
+github.com/liujiawm/gocalendar v1.1.0 h1:rDxY+NaeFAbjxtJ54B0U2Dr3Y4bzjF3BJPdlVXFhW8k=
+github.com/liujiawm/gocalendar v1.1.0/go.mod h1:7k6xFVwvjZTCZVX+GGzYkYLDSg1xaY1PnjX8ZNdLAkk=
 github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
 github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
 github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=

+ 117 - 0
internal/mqs/amq/handler/amq/wxhook/say_morning.go

@@ -5,7 +5,9 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"github.com/golang-module/carbon/v2"
 	"github.com/imroc/req/v3"
+	"github.com/liujiawm/gocalendar"
 	"github.com/suyuan32/simple-admin-common/i18n"
 	"github.com/suyuan32/simple-admin-job/ent/task"
 	"github.com/suyuan32/simple-admin-job/internal/enum/taskresult"
@@ -64,6 +66,14 @@ func (l *SayMorningHandler) ProcessTask(ctx context.Context, t *asynq.Task) erro
 
 	for _, v := range p {
 
+		if v.Msg == "" {
+			v.Msg, _ = l.GetMorningMsg()
+			if v.Msg == "" {
+				logx.Error("failed to get morning msg")
+				continue
+			}
+		}
+
 		logx.Info("send text message", logx.Field("wxid", v.Wxid), logx.Field("msg", v.Msg))
 
 		resp, err := client.R().SetBody(&SendTextMsgReq{
@@ -94,3 +104,110 @@ func (l *SayMorningHandler) ProcessTask(ctx context.Context, t *asynq.Task) erro
 
 	return nil
 }
+
+// 通过openai获取早安问候语
+func (l *SayMorningHandler) GetMorningMsg() (helloStr string, err error) {
+	client := req.C().DevMode()
+	client.SetCommonRetryCount(2).
+		SetCommonRetryBackoffInterval(1*time.Second, 5*time.Second).
+		SetCommonRetryFixedInterval(2 * time.Second).SetTimeout(30 * time.Second)
+
+	type OpenAIChatCompletionsMsg struct {
+		Role    string `json:"role"`
+		Content string `json:"content"`
+	}
+
+	type OpenAIChatCompletionsReq struct {
+		Model    string                     `json:"model"`
+		Messages []OpenAIChatCompletionsMsg `json:"messages"`
+	}
+
+	systemMsg := OpenAIChatCompletionsMsg{
+		Role:    "system",
+		Content: "您是一个特别会打招呼的客服助手,你每天都会根据当前日期和当天的情况采用不同问候,问候分为以下类型,你会在不同的时间选择不同类型的问候\n节日问候\n节气问候\n普通问候(利用中国传统文化元素,如诗词、语等)\n\n然后紧接着,你会进行自我价值介绍,突出了客服助手的在线服务、专业解答以及随时待命的特点,同时也表达了对客户的关心与回应的承诺。\n\n\n生成规则如下:\n当天是节日或者节气时生成节日或节气相关的问候语\n当天既不是节日也不是节气时生成普通问候语\n当节日和节气是同一天时优先生成节日的问候\n\n问候语和自我价值介绍组成一条完整的打招呼话术\n问候语后加{太阳}的表情\n自我价值介绍后加{咖啡}的表情\n\n话术最后,以 ”你可以随时@我“ 做为结尾\n\n你只需要回复最终生成的话术,不需要回复其他任何东西,不需要前后上下文\n\n",
+	}
+
+	now := carbon.SetTimezone(carbon.Shanghai).Now()
+	c := gocalendar.NewCalendar(gocalendar.CalendarConfig{
+		TimeZoneName:    "Asia/Shanghai",
+		SolarTerms:      true,
+		Lunar:           true,
+		HeavenlyEarthly: true,
+		StarSign:        true,
+	})
+	items := c.GenerateWithDate(now.Year(), now.Month(), now.Day())
+	ask := "今天是 " + now.ToDateString()
+	for _, item := range items {
+		if item.IsToday == 1 {
+			ask += ", " + item.LunarDate.String()
+			//ask += ", " + item.StarSign.Name + "座"
+
+			if item.SolarTerm != nil {
+				ask += ", " + item.SolarTerm.Name
+			}
+
+			if len(item.Festival.Show) > 0 {
+				for _, f := range item.Festival.Show {
+					ask += ", " + f
+				}
+			}
+			if len(item.Festival.Secondary) > 0 {
+				for _, f := range item.Festival.Secondary {
+					ask += ", " + f
+				}
+			}
+		}
+	}
+
+	userMsg := OpenAIChatCompletionsMsg{
+		Role:    "user",
+		Content: ask,
+	}
+
+	helloReq := OpenAIChatCompletionsReq{
+		Model:    "gpt-4-turbo-preview",
+		Messages: []OpenAIChatCompletionsMsg{systemMsg, userMsg},
+	}
+
+	type OpenAIChatCompletionsResp struct {
+		ID      string `json:"id"`
+		Object  string `json:"object"`
+		Created int    `json:"created"`
+		Model   string `json:"model"`
+		Choices []struct {
+			Index   int `json:"index"`
+			Message struct {
+				Role    string `json:"role"`
+				Content string `json:"content"`
+			} `json:"message"`
+			Logprobs     interface{} `json:"logprobs"`
+			FinishReason string      `json:"finish_reason"`
+		} `json:"choices"`
+		Usage struct {
+			PromptTokens     int `json:"prompt_tokens"`
+			CompletionTokens int `json:"completion_tokens"`
+			TotalTokens      int `json:"total_tokens"`
+		} `json:"usage"`
+		SystemFingerprint string `json:"system_fingerprint"`
+	}
+
+	var helloResp OpenAIChatCompletionsResp
+
+	resp, err := client.R().
+		SetHeader("Content-Type", "application/json").
+		SetHeader("Authorization", "Bearer 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").
+		SetBody(&helloReq).
+		SetSuccessResult(&helloResp).
+		Post("https://api.openai.com/v1/chat/completions")
+	if err != nil {
+		return
+	}
+
+	if resp.IsSuccessState() { // Status code is between 200 and 299.
+		helloStr = helloResp.Choices[0].Message.Content
+		return
+	} else {
+		err = errors.New("failed to get morning msg")
+		return
+	}
+}