74 lines
1.7 KiB
Go
74 lines
1.7 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
|
|
}
|