telegram.go 1.8 KB

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