send_text_msg_logic.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package Wxhook
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/suyuan32/simple-admin-common/enum/errorcode"
  6. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  7. "time"
  8. "wechat-api/ent/predicate"
  9. "wechat-api/ent/wx"
  10. "wechat-api/hook"
  11. "wechat-api/internal/svc"
  12. "wechat-api/internal/types"
  13. "github.com/zeromicro/go-zero/core/logx"
  14. )
  15. type SendTextMsgLogic struct {
  16. logx.Logger
  17. ctx context.Context
  18. svcCtx *svc.ServiceContext
  19. }
  20. func NewSendTextMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendTextMsgLogic {
  21. return &SendTextMsgLogic{
  22. Logger: logx.WithContext(ctx),
  23. ctx: ctx,
  24. svcCtx: svcCtx}
  25. }
  26. func (l *SendTextMsgLogic) SendTextMsg(req *types.SendTextMsgReq) (resp *types.BaseMsgResp, err error) {
  27. //根据wx实体的wxid查询
  28. var predicates []predicate.Wx
  29. if req.WxWxid != nil {
  30. predicates = append(predicates, wx.WxidContains(*req.WxWxid))
  31. }
  32. wxInfo, err := l.svcCtx.DB.Wx.Query().Where(predicates...).Only(l.ctx)
  33. //根据wx实体的主键ID查询
  34. //wxInfo, err := l.svcCtx.DB.Wx.Get(l.ctx, *req.AgentWxId)
  35. l.Infof("wxInfo = %v", wxInfo)
  36. if err != nil {
  37. l.Error("查询微信信息失败", err)
  38. return
  39. }
  40. privateIP := ""
  41. adminPort := ""
  42. port := ""
  43. if wxInfo.ServerID != 0 {
  44. serverInfo, err := l.svcCtx.DB.Server.Get(l.ctx, wxInfo.ServerID)
  45. if err != nil {
  46. l.Error("查询服务器信息失败", err)
  47. return nil, err
  48. }
  49. privateIP = serverInfo.PrivateIP
  50. adminPort = serverInfo.AdminPort
  51. port = wxInfo.Port
  52. }
  53. var ctype uint64
  54. if req.Ctype != nil && *req.Ctype != 0 {
  55. ctype = *req.Ctype
  56. }
  57. var hookClient *hook.Hook
  58. if ctype == 3 {
  59. hookClient = hook.NewWecomHook("", adminPort, port)
  60. } else {
  61. hookClient = hook.NewHook(privateIP, adminPort, port)
  62. }
  63. msgId := time.Now().UnixNano() / int64(time.Microsecond)
  64. l.svcCtx.Rds.Set(l.ctx, fmt.Sprintf("MsgId_FriendId:%d", msgId), *req.Wxid, 10*time.Minute)
  65. err = hookClient.SendTextMsg(*req.Wxid, *req.Msg, wxInfo.Wxid, msgId)
  66. if err != nil {
  67. l.Errorf("发送微信文本消息失败:%v\n", err)
  68. return nil, err
  69. }
  70. resp = &types.BaseMsgResp{
  71. Msg: errormsg.Success,
  72. Code: errorcode.OK,
  73. }
  74. return resp, nil
  75. }