-
Notifications
You must be signed in to change notification settings - Fork 0
/
rules.go
83 lines (70 loc) · 1.77 KB
/
rules.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
83
package main
import (
"context"
"encoding/json"
"github.com/g8rswimmer/go-twitter/v2"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type rule struct {
name string
// for query examples,
// see: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule#examples
query string
}
func rules(ctx context.Context,
logger *logrus.Logger,
client *twitter.Client,
r rule,
dryRun bool,
) (string, error) {
streamRule := twitter.TweetSearchStreamRule{
Value: r.query,
Tag: r.name,
}
// check if tag is already there
var (
resp any
err error
)
resp, err = client.TweetSearchStreamRules(context.Background(), []twitter.TweetSearchStreamRuleID{})
if err != nil {
return "", errors.Errorf("tweet search stream rule callout error: %v", err)
}
ruleID := findRuleID(resp, r)
if ruleID == "" {
resp, err = client.TweetSearchStreamAddRule(ctx, []twitter.TweetSearchStreamRule{streamRule}, dryRun)
if err != nil {
return "", err
}
ruleID = findRuleID(resp, r)
}
enc, err := json.MarshalIndent(resp, "", " ")
if err != nil {
//return errors.Wrap(err,"could not marshall twitter rule response")
logger.Warnf("could not marshall twitter rule response %+v", err)
return ruleID, nil
}
logger.Infof("applied rules %v", string(enc))
return ruleID, nil
}
func findRuleID(resp any, r rule) string {
var rules []*twitter.TweetSearchStreamRuleEntity
switch v := resp.(type) {
case *twitter.TweetSearchStreamAddRuleResponse:
rules = v.Rules
case *twitter.TweetSearchStreamRulesResponse:
rules = v.Rules
default:
// should not happen
return ""
}
var ruleID string
for _, rule := range rules {
if rule.Tag == r.name || rule.Value == r.query {
ruleID = string(rule.ID)
break
}
}
return ruleID
}