ws.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package model
  2. import (
  3. "aiChat/utility"
  4. . "app.yhyue.com/moapp/jybase/common"
  5. "app.yhyue.com/moapp/jybase/date"
  6. "app.yhyue.com/moapp/jybase/fsw"
  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. "time"
  14. )
  15. type WsChat struct {
  16. Ctx context.Context
  17. }
  18. func NewMessage(ctx context.Context) *WsChat {
  19. return &WsChat{
  20. Ctx: ctx,
  21. }
  22. }
  23. // Handle 处理消息
  24. func (m *WsChat) Handle(ws *ghttp.WebSocket, msg []byte) {
  25. defer Catch()
  26. jSession := SessionCtx.Get(m.Ctx).JSession
  27. req := &QuestionReq{}
  28. if err := gjson.Unmarshal(msg, req); err != nil {
  29. glog.Errorf(m.Ctx, "%d 接收消息Unmarshal出错:%v", jSession.AccountId, err)
  30. return
  31. }
  32. // 问题敏感词过滤
  33. req.Prompt = fsw.Repl(req.Prompt)
  34. reply, errMsg := func() (string, error) {
  35. reply, from, err := Question.DetailQuestion(m.Ctx, req)
  36. // 回答敏感词过滤
  37. reply = fsw.Repl(reply)
  38. if err != nil {
  39. g.Log().Error(m.Ctx, "问答异常", err)
  40. return "", fmt.Errorf("问答异常")
  41. }
  42. // 记录问答
  43. id := ChatHistroy.Save(m.Ctx, &ChatRecord{
  44. Content: reply,
  45. Type: 2,
  46. Refer: req.Href,
  47. PersonId: jSession.AccountId,
  48. Item: from,
  49. CreateTime: time.Now().Format(date.Date_Full_Layout),
  50. }, &ChatRecord{
  51. Content: req.Prompt,
  52. Type: 1,
  53. Refer: req.Href,
  54. PersonId: jSession.AccountId,
  55. CreateTime: time.Now().Format(date.Date_Full_Layout),
  56. })
  57. if id <= 0 {
  58. g.Log().Error(m.Ctx, "数据存储异常", err)
  59. return "", fmt.Errorf("数据存储异常")
  60. }
  61. if err = utility.ResourcePowerDeduct(m.Ctx, jSession.AccountId, jSession.EntAccountId, fmt.Sprintf("%d", id)); err != nil {
  62. g.Log().Error(m.Ctx, "扣减异常", err)
  63. return "", fmt.Errorf("扣减异常")
  64. }
  65. return reply, nil
  66. }()
  67. if errMsg != nil {
  68. _ = ws.WriteJSON(g.Map{"error_code": -1, "error_msg": errMsg.Error(), "data": nil})
  69. } else {
  70. _ = ws.WriteJSON(g.Map{"error_code": 0, "error_msg": "", "data": reply})
  71. }
  72. }