telegram.go 1.4 KB

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