ws.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package model
  2. import (
  3. "aiChat/utility/fsw"
  4. . "app.yhyue.com/moapp/jybase/common"
  5. "app.yhyue.com/moapp/jybase/date"
  6. "app.yhyue.com/moapp/jybase/encrypt"
  7. "context"
  8. "fmt"
  9. "github.com/gogf/gf/v2/encoding/gjson"
  10. "github.com/gogf/gf/v2/frame/g"
  11. "github.com/gogf/gf/v2/net/ghttp"
  12. "github.com/gogf/gf/v2/os/glog"
  13. "github.com/gogf/gf/v2/util/gconv"
  14. "time"
  15. )
  16. type WsChat struct {
  17. Ctx context.Context
  18. }
  19. func NewMessage(ctx context.Context) *WsChat {
  20. return &WsChat{
  21. Ctx: ctx,
  22. }
  23. }
  24. // Handle 处理消息
  25. func (m *WsChat) Handle(ws *ghttp.WebSocket, msg []byte) {
  26. defer Catch()
  27. jSession := SessionCtx.Get(m.Ctx).JSession
  28. req := &QuestionReq{}
  29. if err := gjson.Unmarshal(msg, req); err != nil {
  30. glog.Errorf(m.Ctx, "%d 接收消息Unmarshal出错:%v", jSession.AccountId, err)
  31. return
  32. }
  33. reply, replyId, errMsg := func() (string, int64, error) {
  34. questionId := ChatHistory.Save(m.Ctx, &ChatRecord{
  35. Content: req.Prompt,
  36. Type: 1,
  37. Refer: req.Href,
  38. PersonId: jSession.AccountId,
  39. CreateTime: time.Now().Format(date.Date_Full_Layout),
  40. })
  41. // 校验是否在黑名单,黑名单不返回内容
  42. if UserBlackList.CheckBlackList(m.Ctx, jSession.AccountId) {
  43. return "", 0, nil
  44. }
  45. var err error
  46. reply, from := "", 0
  47. errReply := func() string {
  48. // 校验问答频率
  49. if ChatLimit.GetBucket(m.Ctx, jSession.AccountId).TakeAvailable(1) == 0 {
  50. return g.Cfg().MustGet(m.Ctx, "limit.exceedMsg").String()
  51. }
  52. // 问题敏感词过滤
  53. if fsw.Match(req.Prompt) {
  54. return g.Cfg().MustGet(m.Ctx, "limit.fswMsg", "您的问题可能包含敏感词汇,请修改后再提问!").String()
  55. }
  56. return ""
  57. }()
  58. if errReply != "" {
  59. reply, from = errReply, -1
  60. } else {
  61. reply, from, err = Question.DetailQuestion(m.Ctx, req)
  62. if err != nil {
  63. g.Log().Error(m.Ctx, "问答异常", err)
  64. return "", 0, fmt.Errorf("问答异常")
  65. }
  66. // 回答敏感词过滤
  67. reply = fsw.Repl(reply)
  68. }
  69. // 记录问答
  70. replyId := ChatHistory.Save(m.Ctx, &ChatRecord{
  71. Content: reply,
  72. Type: 2,
  73. Actions: gconv.Int(If(errReply == "", 1, 0)),
  74. QuestionId: questionId,
  75. PersonId: jSession.AccountId,
  76. Item: from,
  77. CreateTime: time.Now().Format(date.Date_Full_Layout),
  78. })
  79. if replyId <= 0 {
  80. g.Log().Error(m.Ctx, "问答存储存储异常")
  81. }
  82. return reply, replyId, nil
  83. }()
  84. if errMsg != nil {
  85. _ = ws.WriteJSON(g.Map{"error_code": -1, "error_msg": errMsg.Error(), "data": nil})
  86. } else {
  87. _ = ws.WriteJSON(g.Map{"error_code": 0, "error_msg": "", "data": g.Map{"id": encrypt.SE.Encode2Hex(fmt.Sprintf("%d", replyId)), "reply": reply}})
  88. }
  89. }