telegram.go 1.4 KB

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