enterprise/common/global/message.go

59 lines
1.4 KiB
Go
Raw Normal View History

2023-08-04 19:29:13 +08:00
package global
import (
"context"
"enterprise/common/config"
"github.com/ArtisanCloud/PowerWeChat/v3/src/work"
"github.com/ArtisanCloud/PowerWeChat/v3/src/work/message/request"
log "github.com/sirupsen/logrus"
"github.com/smbrave/goutil"
"github.com/spf13/cast"
"strings"
)
var (
wxEnterprise *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 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
}