package handler import ( "bytes" "encoding/json" "fmt" "net/http" "go.etztech.xyz/lurk/config" "github.com/dghubble/go-twitter/twitter" "go.jolheiser.com/beaver" ) type Twitter struct { Filter config.Filter Stream *twitter.Stream } func (t *Twitter) Run() { beaver.Debugf("setting up stream for %v", t.Filter) demux := twitter.NewSwitchDemux() demux.Tweet = func(tweet *twitter.Tweet) { beaver.Debugf("new tweet for %v", t.Filter) if t.Filter.FollowStrict { var match bool for _, id := range t.Filter.Follows { if id == tweet.User.IDStr { match = true break } } if !match { beaver.Debug("tweet did not match any follow IDs") return } } if err := t.Discord(tweet); err != nil { beaver.Error(err) } } beaver.Debugf("streaming %v", t.Filter) demux.HandleChan(t.Stream.Messages) beaver.Debugf("disconnected from stream: %v", t.Filter) } func (t *Twitter) Discord(tweet *twitter.Tweet) error { e := map[string]string{ "content": fmt.Sprintf("https://twitter.com/%d/status/%d", tweet.User.ID, tweet.ID), } data, err := json.Marshal(e) if err != nil { return err } beaver.Debug(string(data)) if t.Filter.Webhook == "" { return fmt.Errorf("no webhook for %s", t.Filter) } payload := bytes.NewBuffer(data) resp, err := httpClient.Post(t.Filter.Webhook, "application/json", payload) if err != nil { return err } if resp.StatusCode != http.StatusNoContent { return err } return nil }