publisher.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package publisher
  2. import (
  3. "net/url"
  4. "github.com/ChimeraCoder/anaconda"
  5. log "github.com/go-pkgz/lgr"
  6. "github.com/pkg/errors"
  7. "github.com/umputun/rss2twitter/app/rss"
  8. )
  9. // Interface for publishers
  10. type Interface interface {
  11. Publish(event rss.Event, formatter func(rss.Event) string) error
  12. }
  13. // Stdout implements publisher.Interface and sends to stdout
  14. type Stdout struct{}
  15. // Publish to logger
  16. func (s Stdout) Publish(event rss.Event, formatter func(rss.Event) string) error {
  17. log.Printf("[INFO] event - %s", formatter(event))
  18. return nil
  19. }
  20. // Twitter implements publisher.Interface and sends to twitter
  21. type Twitter struct {
  22. ConsumerKey, ConsumerSecret string
  23. AccessToken, AccessSecret string
  24. }
  25. // Publish to twitter
  26. func (t Twitter) Publish(event rss.Event, formatter func(rss.Event) string) error {
  27. log.Printf("[INFO] publish to twitter %+v", event)
  28. api := anaconda.NewTwitterApiWithCredentials(t.AccessToken, t.AccessSecret, t.ConsumerKey, t.ConsumerSecret)
  29. v := url.Values{}
  30. v.Set("tweet_mode", "extended")
  31. msg := formatter(event)
  32. if _, err := api.PostTweet(msg, v); err != nil {
  33. return errors.Wrap(err, "can't send to twitter")
  34. }
  35. log.Printf("[DEBUG] published to twitter %s", msg)
  36. return nil
  37. }