1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package model
- import (
- "aiChat/utility/fsw"
- . "app.yhyue.com/moapp/jybase/common"
- "app.yhyue.com/moapp/jybase/date"
- "app.yhyue.com/moapp/jybase/encrypt"
- "context"
- "fmt"
- "github.com/gogf/gf/v2/encoding/gjson"
- "github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/net/ghttp"
- "github.com/gogf/gf/v2/os/glog"
- "github.com/gogf/gf/v2/util/gconv"
- "time"
- )
- type WsChat struct {
- Ctx context.Context
- }
- func NewMessage(ctx context.Context) *WsChat {
- return &WsChat{
- Ctx: ctx,
- }
- }
- // Handle 处理消息
- func (m *WsChat) Handle(ws *ghttp.WebSocket, msg []byte) {
- defer Catch()
- jSession := SessionCtx.Get(m.Ctx).JSession
- req := &QuestionReq{}
- if err := gjson.Unmarshal(msg, req); err != nil {
- glog.Errorf(m.Ctx, "%d 接收消息Unmarshal出错:%v", jSession.PositionId, err)
- return
- }
- reply, replyId, errMsg := func() (string, int64, error) {
- questionId := ChatHistory.Save(m.Ctx, &ChatRecord{
- Content: req.Prompt,
- Type: 1,
- Refer: req.Href,
- PersonId: jSession.PositionId,
- CreateTime: time.Now().Format(date.Date_Full_Layout),
- })
- var err error
- reply, from := "", 0
- errReply := func() string {
- // 校验是否在黑名单,黑名单不返回内容
- if UserBlackList.CheckBlackList(m.Ctx, jSession.PositionId) {
- return g.Cfg().MustGet(m.Ctx, "limit.blackMsg").String()
- }
- // 校验问答频率
- if ChatLimit.GetBucket(m.Ctx, jSession.PositionId).TakeAvailable(1) == 0 {
- return g.Cfg().MustGet(m.Ctx, "limit.exceedMsg").String()
- }
- // 问题敏感词过滤
- if fsw.Match(req.Prompt) {
- return g.Cfg().MustGet(m.Ctx, "limit.fswMsg").String()
- }
- return ""
- }()
- if errReply != "" {
- reply, from = errReply, -1
- } else {
- reply, from, err = Question.DetailQuestion(m.Ctx, req)
- if err != nil {
- g.Log().Error(m.Ctx, "问答异常", err)
- return "", 0, fmt.Errorf(g.Cfg().MustGet(m.Ctx, "limit.errMsg").String())
- }
- }
- // 记录问答
- replyId := ChatHistory.Save(m.Ctx, &ChatRecord{
- Content: reply,
- Type: 2,
- Actions: gconv.Int(If(errReply == "", 1, 0)),
- QuestionId: questionId,
- PersonId: jSession.PositionId,
- Item: gconv.Int(If(errReply == "", from, -1)),
- CreateTime: time.Now().Format(date.Date_Full_Layout),
- })
- if replyId <= 0 {
- g.Log().Error(m.Ctx, "问答存储存储异常")
- }
- return reply, replyId, nil
- }()
- if errMsg != nil {
- _ = ws.WriteJSON(g.Map{"error_code": -1, "error_msg": errMsg.Error(), "data": nil})
- } else {
- _ = ws.WriteJSON(g.Map{"error_code": 0, "error_msg": "", "data": g.Map{"id": encrypt.SE.Encode2Hex(fmt.Sprintf("%d", replyId)), "reply": reply}})
- }
- }
|