This repository has been archived by the owner on May 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter_sink.go
82 lines (70 loc) · 1.81 KB
/
twitter_sink.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package murmur
import (
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/ChimeraCoder/anaconda"
)
type TwitterSinkConfig struct {
ConsumerKey string `yaml:"consumer_key"`
ConsumerSecret string `yaml:"consumer_secret"`
OAuthToken string `yaml:"oauth_token"`
OAuthTokenSecret string `yaml:"oauth_token_secret"`
}
type TwitterSink struct {
config *TwitterSinkConfig
api *anaconda.TwitterApi
}
func (c *TwitterSinkConfig) NewSink() (Sink, error) {
api := anaconda.NewTwitterApiWithCredentials(
c.OAuthToken, c.OAuthTokenSecret, c.ConsumerKey, c.ConsumerSecret)
api.HttpClient = &http.Client{Timeout: 10 * time.Second}
return &TwitterSink{
config: c,
api: api,
}, nil
}
func (s *TwitterSink) Close() {
s.api.Close()
}
func (s *TwitterSink) RecentUrls() ([]string, error) {
userId := strings.SplitN(s.config.OAuthToken, "-", 2)[0]
if _, err := strconv.ParseInt(userId, 10, 64); err != nil {
return nil, fmt.Errorf("%w", err)
}
v := url.Values{}
v.Set("user_id", userId)
v.Set("count", "200") // TODO: read from the config
timeline, err := s.api.GetUserTimeline(v)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
urls := make([]string, 0, len(timeline)) // heuristic optimization
for _, status := range timeline {
for _, url := range status.Entities.Urls {
urls = append(urls, url.Expanded_url)
}
}
return urls, nil
}
func (s *TwitterSink) Output(item *Item) error {
values := url.Values{}
if _, err := s.api.PostTweet(item.Summary, values); err != nil {
var apiErr *anaconda.ApiError
if errors.As(err, &apiErr) {
for _, err := range apiErr.Decoded.Errors {
if err.Code == anaconda.TwitterErrorStatusIsADuplicate {
return nil
}
}
return fmt.Errorf("%w", apiErr)
} else {
return fmt.Errorf("%w", err)
}
}
return nil
}