105 lines
2.6 KiB
Go
105 lines
2.6 KiB
Go
package plugin
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/mattermost/mattermost/server/public/model"
|
|
)
|
|
|
|
// ensureBot создает или получает бота для отправки сообщений
|
|
func (p *Plugin) ensureBot() error {
|
|
const botUsername = "sentry"
|
|
|
|
user, appErr := p.API.GetUserByUsername(botUsername)
|
|
if appErr == nil && user != nil {
|
|
if !user.IsBot {
|
|
return fmt.Errorf("user @%s exists but is not a bot", botUsername)
|
|
}
|
|
p.botUserID = user.Id
|
|
return nil
|
|
}
|
|
|
|
bot := &model.Bot{
|
|
Username: botUsername,
|
|
DisplayName: "Sentry",
|
|
Description: "Sentry notifications bot",
|
|
}
|
|
|
|
createdBot, appErr := p.API.CreateBot(bot)
|
|
if appErr != nil {
|
|
p.API.LogError("Failed to create Sentry bot", "error", appErr.Error())
|
|
return appErr
|
|
}
|
|
|
|
p.botUserID = createdBot.UserId
|
|
|
|
// Устанавливаем иконку после создания бота
|
|
if err := p.setBotIcon(); err != nil {
|
|
p.API.LogWarn("Failed to set bot icon", "error", err.Error())
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (p *Plugin) setBotIcon() error {
|
|
if p.botUserID == "" {
|
|
return fmt.Errorf("bot user ID is not set")
|
|
}
|
|
|
|
bundlePath := p.bundlePath
|
|
if bundlePath == "" {
|
|
var err error
|
|
bundlePath, err = p.API.GetBundlePath()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get bundle path: %w", err)
|
|
}
|
|
}
|
|
|
|
iconPath := filepath.Join(bundlePath, "assets", "icon.png")
|
|
|
|
iconData, err := os.ReadFile(iconPath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read icon file: %w", err)
|
|
}
|
|
|
|
if appErr := p.API.SetProfileImage(p.botUserID, iconData); appErr != nil {
|
|
return fmt.Errorf("failed to set profile image: %s", appErr.Error())
|
|
}
|
|
|
|
p.API.LogInfo("Bot icon set successfully")
|
|
return nil
|
|
}
|
|
|
|
// getDirectChannel получает или создает DM канал между ботом и пользователем
|
|
func (p *Plugin) getDirectChannel(userID string) (string, error) {
|
|
if p.botUserID == "" {
|
|
return "", fmt.Errorf("bot user ID is not set")
|
|
}
|
|
|
|
channel, appErr := p.API.GetDirectChannel(p.botUserID, userID)
|
|
if appErr != nil {
|
|
return "", fmt.Errorf("failed to get direct channel: %s", appErr.Error())
|
|
}
|
|
|
|
return channel.Id, nil
|
|
}
|
|
|
|
// sendDMToUser отправляет сообщение пользователю в личные сообщения
|
|
func (p *Plugin) sendDMToUser(userID string, post *model.Post) error {
|
|
dmChannelID, err := p.getDirectChannel(userID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get DM channel: %w", err)
|
|
}
|
|
|
|
post.ChannelId = dmChannelID
|
|
post.UserId = p.botUserID
|
|
|
|
if _, appErr := p.API.CreatePost(post); appErr != nil {
|
|
return fmt.Errorf("failed to create post: %s", appErr.Error())
|
|
}
|
|
|
|
return nil
|
|
}
|