telegram.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package notification
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "github.com/0xJacky/Nginx-UI/model"
  8. "github.com/nikoksr/notify/service/telegram"
  9. "github.com/uozi-tech/cosy/map2struct"
  10. )
  11. // @external_notifier(Telegram)
  12. type Telegram struct {
  13. BotToken string `json:"bot_token" title:"Bot Token"`
  14. ChatID string `json:"chat_id" title:"Chat ID"`
  15. }
  16. func init() {
  17. RegisterExternalNotifier("telegram", func(ctx context.Context, n *model.ExternalNotify, msg *ExternalMessage) error {
  18. telegramConfig := &Telegram{}
  19. err := map2struct.WeakDecode(n.Config, telegramConfig)
  20. if err != nil {
  21. return err
  22. }
  23. if telegramConfig.BotToken == "" || telegramConfig.ChatID == "" {
  24. return ErrInvalidNotifierConfig
  25. }
  26. telegramService, err := telegram.New(telegramConfig.BotToken)
  27. if err != nil {
  28. return err
  29. }
  30. // ChatID must be an integer for telegram service
  31. chatIDInt, err := strconv.ParseInt(telegramConfig.ChatID, 10, 64)
  32. if err != nil {
  33. return fmt.Errorf("invalid Telegram Chat ID '%s': %w", telegramConfig.ChatID, err)
  34. }
  35. // Check if chatIDInt is 0, which might indicate an empty or invalid input was parsed
  36. if chatIDInt == 0 {
  37. return errors.New("invalid Telegram Chat ID: cannot be zero")
  38. }
  39. telegramService.AddReceivers(chatIDInt)
  40. return telegramService.Send(ctx, msg.GetTitle(n.Language), msg.GetContent(n.Language))
  41. })
  42. }