-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter_notification.go
66 lines (61 loc) · 1.84 KB
/
twitter_notification.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
package notification
import (
"bytes"
"context"
"fmt"
"html"
"net/http"
"strings"
"github.com/dghubble/go-twitter/twitter"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/pkg/errors"
)
type twitterRepository struct {
l log.Logger
c *twitter.Client
tu *twitter.User
}
// NewTwitterRepository initializes a new Twitter notifier repository
func NewTwitterRepository(l log.Logger, c *twitter.Client, tu *twitter.User) *twitterRepository {
return &twitterRepository{
l: l,
c: c,
tu: tu,
}
}
func (s *twitterRepository) Post(ctx context.Context, text string, author string, url string) error {
// We split into words, and add as many words so we stay routhly under 100 characters for the Tweet
var length int
var summaryTokens []string
for _, t := range strings.Split(text, " ") {
runes := bytes.Runes([]byte(t))
// If length of tweet is below 100, we add tokens to the list
if length <= 100 {
length += len(runes)
summaryTokens = append(summaryTokens, t)
} else {
// Only if the word is shorter than 5 do we also still add it to the list
if len(runes) < 5 {
summaryTokens = append(summaryTokens, t)
length += len(runes)
break
} else {
break
}
}
}
tweetBody := html.UnescapeString("”" + strings.Join(summaryTokens, " ") + "...“" + "\n\n" + url)
t, resp, err := s.c.Statuses.Update(tweetBody, &twitter.StatusUpdateParams{
TweetMode: "extended",
})
if err != nil {
return errors.Wrap(err, "posting status update")
}
if resp.StatusCode != http.StatusOK {
level.Error(s.l).Log("err", "unexpected status code from twitter", "status_code", resp.StatusCode)
return errors.New("unexpected status code from twitter")
}
level.Info(s.l).Log("msg", "tweet successfully sent", "id", t.IDStr, "url", fmt.Sprintf("https://twitter.com/%s/status/%s", s.tu.ScreenName, t.IDStr))
return nil
}