package providers import ( "encoding/json" "errors" "fmt" "net/http" "net/url" "git.wenlab.co/joe/beaconfire" ) const ( _TELEGRAM_DEF_PARSE_MODE = "HTML" BEACON_NAME_TELEGRAM = "telegram" ) type OptionsTelegram struct { Token string To []string // userId // Channel []string // ParseMode string } type telegram struct { opt *OptionsTelegram } var _ beaconfire.BeaconFire = &telegram{} func NewTelegram(opt *OptionsTelegram) *telegram { return &telegram{ opt: opt, } } func (c *telegram) Name() string { return BEACON_NAME_TELEGRAM } func (c *telegram) Send(bp *beaconfire.BeaconMessage) error { if len(c.opt.To) <= 0 { return beaconfire.ErrNoReceiver } u := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", c.opt.Token) v := url.Values{} content := bp.FormatHTML() v.Set("parse_mode", _TELEGRAM_DEF_PARSE_MODE) v.Set("text", content) for _, channel := range c.opt.To { v.Set("chat_id", channel) res, err := beaconfire.Request(http.MethodPost, u, []byte(v.Encode()), map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }, "", "") if err != nil { return err } var r struct { Ok bool `json:"ok"` ErrorCode int `json:"error_code"` Description string `json:"description"` } err = json.Unmarshal(res, &r) if err != nil { return err } if !r.Ok { return errors.New(r.Description) } } return nil }