telegram.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package providers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "git.wenlab.co/joe/beaconfire"
  9. )
  10. const (
  11. TELEGRAM_NAME = "telegram"
  12. _TELEGRAM_DEF_PARSE_MODE = "HTML"
  13. )
  14. type OptionsTelegram struct {
  15. Token string
  16. // Channel []string
  17. // ParseMode string
  18. }
  19. type telegram struct {
  20. opt *OptionsTelegram
  21. }
  22. var _ beaconfire.BeaconFire = &telegram{}
  23. func NewTelegram(opt *OptionsTelegram) *telegram {
  24. return &telegram{
  25. opt: opt,
  26. }
  27. }
  28. func (c *telegram) Name() string {
  29. return TELEGRAM_NAME
  30. }
  31. func (c *telegram) Send(bp *beaconfire.BeaconParam) error {
  32. if len(bp.To) <= 0 {
  33. return beaconfire.ErrNoReceiver
  34. }
  35. u := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", c.opt.Token)
  36. v := url.Values{}
  37. content := bp.FormatHTML()
  38. v.Set("parse_mode", _TELEGRAM_DEF_PARSE_MODE)
  39. v.Set("text", content)
  40. for _, channel := range bp.To {
  41. v.Set("chat_id", channel)
  42. res, err := beaconfire.Request(http.MethodPost, u, []byte(v.Encode()), map[string]string{
  43. "Content-Type": "application/x-www-form-urlencoded",
  44. }, "", "")
  45. if err != nil {
  46. return err
  47. }
  48. var r struct {
  49. Ok bool `json:"ok"`
  50. ErrorCode int `json:"error_code"`
  51. Description string `json:"description"`
  52. }
  53. err = json.Unmarshal(res, &r)
  54. if err != nil {
  55. return err
  56. }
  57. if !r.Ok {
  58. return errors.New(r.Description)
  59. }
  60. }
  61. return nil
  62. }