66 lines
1.8 KiB
Go
66 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"ai_scheduler/internal/config"
|
|
"ai_scheduler/internal/services"
|
|
"context"
|
|
|
|
"github.com/go-kratos/kratos/v2/log"
|
|
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
|
|
"github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
|
|
)
|
|
|
|
type DingBotServiceInterface interface {
|
|
GetServiceCfg(cfg map[string]*config.DingTalkBot) (*config.DingTalkBot, string)
|
|
OnChatBotMessageReceived(ctx context.Context, data *chatbot.BotCallbackDataModel) (content []byte, err error)
|
|
}
|
|
|
|
type DingTalkBotServer struct {
|
|
Clients []*client.StreamClient
|
|
}
|
|
|
|
func NewDingTalkBotServer(
|
|
cfg *config.Config,
|
|
services []DingBotServiceInterface,
|
|
) *DingTalkBotServer {
|
|
clients := make([]*client.StreamClient, 0)
|
|
for _, service := range services {
|
|
serviceConf, index := service.GetServiceCfg(cfg.DingTalkBots)
|
|
if serviceConf == nil {
|
|
log.Info("未找到%s配置", index)
|
|
continue
|
|
}
|
|
cli := DingBotServerInit(serviceConf.ClientId, serviceConf.ClientSecret, service)
|
|
if cli == nil {
|
|
log.Info("%s客户端初始失败", index)
|
|
continue
|
|
}
|
|
clients = append(clients, cli)
|
|
}
|
|
return &DingTalkBotServer{
|
|
Clients: clients,
|
|
}
|
|
}
|
|
|
|
func ProvideAllDingBotServices(
|
|
dingBotSvc *services.DingBotService,
|
|
) []DingBotServiceInterface {
|
|
return []DingBotServiceInterface{dingBotSvc}
|
|
}
|
|
|
|
func (d *DingTalkBotServer) Run(ctx context.Context) {
|
|
for name, cli := range d.Clients {
|
|
err := cli.Start(ctx)
|
|
if err != nil {
|
|
log.Info("%s启动失败", name)
|
|
continue
|
|
}
|
|
log.Info("%s启动成功", name)
|
|
}
|
|
}
|
|
func DingBotServerInit(clientId string, clientSecret string, service DingBotServiceInterface) (cli *client.StreamClient) {
|
|
cli = client.NewStreamClient(client.WithAppCredential(client.NewAppCredentialConfig(clientId, clientSecret)))
|
|
cli.RegisterChatBotCallbackRouter(service.OnChatBotMessageReceived)
|
|
return
|
|
}
|