package global import ( "context" "enterprise/common/config" "enterprise/common/dao" "github.com/ArtisanCloud/PowerWeChat/v3/src/work" "github.com/ArtisanCloud/PowerWeChat/v3/src/work/message/request" "github.com/gogap/errors" log "github.com/sirupsen/logrus" "github.com/smbrave/goutil" "github.com/spf13/cast" "strings" "sync" ) var ( wxEnterprise *work.Work corpEnterprise map[int64]*work.Work corpEnterpriseMutex sync.Mutex ) func init() { corpEnterprise = make(map[int64]*work.Work) } func initWxWork() (*work.Work, error) { cfg := config.GetConfig() client, err := work.NewWork(&work.UserConfig{ CorpID: cfg.QyWeixin.Corpid, AgentID: cast.ToInt(cfg.QyWeixin.EnterpriseAgent), Secret: cfg.QyWeixin.EnterpriseSecret, OAuth: work.OAuth{ Callback: "https://wecom.artisan-cloud.com/callback", Scopes: nil, }, }) if err != nil { log.Errorf("config[%s] init error : %s", goutil.EncodeJSON(cfg), err.Error()) return nil, err } return client, nil } func getWxWork(corpId int64) (*work.Work, error) { if c, ok := corpEnterprise[corpId]; ok { return c, nil } corp, err := dao.NewCorpDao().Get(corpId) if err != nil { return nil, err } if corp == nil { return nil, errors.New("corp not exist") } cfg := corp.GetConfig() client, err := work.NewWork(&work.UserConfig{ CorpID: cfg.CorpId, AgentID: cast.ToInt(cfg.EnterpriseAgent), Secret: cfg.EnterpriseSecret, OAuth: work.OAuth{ Callback: "https://wecom.artisan-cloud.com/callback", Scopes: nil, }, }) if err != nil { log.Errorf("config[%s] init error : %s", goutil.EncodeJSON(cfg), err.Error()) return nil, err } corpEnterpriseMutex.Lock() corpEnterprise[corpId] = client corpEnterpriseMutex.Unlock() return client, nil } func SendMessage(user []string, content string) error { if wxEnterprise == nil { wxM, err := initWxWork() if err != nil { return err } wxEnterprise = wxM } cfg := config.GetConfig() receivers := user message := &request.RequestMessageSendText{} message.ToUser = strings.Join(receivers, "|") message.MsgType = "text" message.AgentID = cast.ToInt(cfg.QyWeixin.EnterpriseAgent) message.Text = &request.RequestText{Content: content} if _, err := wxEnterprise.Message.SendText(context.Background(), message); err != nil { log.Errorf("send message [%s] error : %s", goutil.EncodeJSON(message), err) return err } return nil } func SendCorpMessage(corpId int64, user []string, content string) error { client, _ := getWxWork(corpId) if client == nil { return errors.New("client error ") } corp, _ := dao.NewCorpDao().Get(corpId) receivers := user message := &request.RequestMessageSendText{} message.ToUser = strings.Join(receivers, "|") message.MsgType = "text" message.AgentID = cast.ToInt(corp.GetConfig().EnterpriseAgent) message.Text = &request.RequestText{Content: content} if _, err := client.Message.SendText(context.Background(), message); err != nil { log.Errorf("send message [%s] error : %s", goutil.EncodeJSON(message), err) return err } return nil }