1
0

telegram.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package notification
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "github.com/0xJacky/Nginx-UI/model"
  10. tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
  11. "github.com/nikoksr/notify/service/telegram"
  12. "github.com/uozi-tech/cosy/map2struct"
  13. )
  14. // @external_notifier(Telegram)
  15. type Telegram struct {
  16. BotToken string `json:"bot_token" title:"Bot Token"`
  17. ChatID string `json:"chat_id" title:"Chat ID"`
  18. HTTPProxy string `json:"http_proxy" title:"HTTP Proxy"`
  19. }
  20. func init() {
  21. RegisterExternalNotifier("telegram", func(ctx context.Context, n *model.ExternalNotify, msg *ExternalMessage) error {
  22. telegramConfig := &Telegram{}
  23. err := map2struct.WeakDecode(n.Config, telegramConfig)
  24. if err != nil {
  25. return err
  26. }
  27. if telegramConfig.BotToken == "" || telegramConfig.ChatID == "" {
  28. return ErrInvalidNotifierConfig
  29. }
  30. client := http.DefaultClient
  31. if telegramConfig.HTTPProxy != "" {
  32. proxyURL, err := url.Parse(telegramConfig.HTTPProxy)
  33. if err != nil {
  34. return err
  35. }
  36. client = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
  37. }
  38. botAPI, err := tgbotapi.NewBotAPIWithClient(telegramConfig.BotToken, client)
  39. if err != nil {
  40. return err
  41. }
  42. telegramService, err := telegram.New(telegramConfig.BotToken)
  43. if err != nil {
  44. return err
  45. }
  46. telegramService.SetClient(botAPI)
  47. // ChatID must be an integer for telegram service
  48. chatIDInt, err := strconv.ParseInt(telegramConfig.ChatID, 10, 64)
  49. if err != nil {
  50. return fmt.Errorf("invalid Telegram Chat ID '%s': %w", telegramConfig.ChatID, err)
  51. }
  52. // Check if chatIDInt is 0, which might indicate an empty or invalid input was parsed
  53. if chatIDInt == 0 {
  54. return errors.New("invalid Telegram Chat ID: cannot be zero")
  55. }
  56. telegramService.AddReceivers(chatIDInt)
  57. return telegramService.Send(ctx, msg.GetTitle(n.Language), msg.GetContent(n.Language))
  58. })
  59. }