ai_scheduler/internal/pkg/dingtalk/robot_client.go

66 lines
1.7 KiB
Go

package dingtalk
import (
errorcode "ai_scheduler/internal/data/error"
"encoding/json"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
robot "github.com/alibabacloud-go/dingtalk/robot_1_0"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
type RobotClient struct {
cli *robot.Client
oauth2Client *Oauth2Client
}
func NewRobotClient(oauth2Client *Oauth2Client) (*RobotClient, error) {
cfg := &openapi.Config{
Protocol: tea.String("https"),
RegionId: tea.String("central"),
}
c, err := robot.NewClient(cfg)
if err != nil {
return nil, err
}
return &RobotClient{cli: c, oauth2Client: oauth2Client}, nil
}
type SendGroupMessagesReq struct {
MsgKey string
MsgParam map[string]any
OpenConversationId string
RobotCode string
}
func (c *RobotClient) SendGroupMessages(appKey AppKey, req *SendGroupMessagesReq) (string, error) {
// 获取token
accessToken, err := c.oauth2Client.GetAccessToken(appKey)
if err != nil {
return "", err
}
msgParamBytes, _ := json.Marshal(req.MsgParam)
msgParamJson := string(msgParamBytes)
resp, err := c.cli.OrgGroupSendWithOptions(
&robot.OrgGroupSendRequest{
MsgKey: tea.String(req.MsgKey),
MsgParam: tea.String(msgParamJson),
OpenConversationId: tea.String(req.OpenConversationId),
RobotCode: tea.String(req.RobotCode),
},
&robot.OrgGroupSendHeaders{XAcsDingtalkAccessToken: tea.String(accessToken)},
&util.RuntimeOptions{},
)
if err != nil {
return "", err
}
if resp.Body == nil {
return "", errorcode.ParamErrf("empty response body")
}
return *resp.Body.ProcessQueryKey, nil
}