/
TwitterComm.go
209 lines (181 loc) · 6.15 KB
/
TwitterComm.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"encoding/json"
"fmt"
"github.com/kurrik/oauth1a"
"github.com/kurrik/twittergo"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type twitterComm struct {
client *twittergo.Client
}
func switchClient(twComm *twitterComm) {
// Code removed as it contained my API keys
}
func NewTwitterAppClient() *twitterComm {
config := &oauth1a.ClientConfig{
ConsumerKey: "my-api-key",
ConsumerSecret: "my-api-secret",
}
user := oauth1a.NewAuthorizedConfig("oauth", "sucks")
client := twittergo.NewClient(config, user)
if err := client.FetchAppToken(); err != nil {
if err2 := client.FetchAppToken(); err2 != nil {
fmt.Println("Error occured creating the client.", err)
panic("ERROR CREATING USER CLAY CLIENT")
}
}
return &twitterComm{client}
}
func NewTwitterUserClient() *twitterComm {
config := &oauth1a.ClientConfig{
ConsumerKey: "my-api-key",
ConsumerSecret: "my-api-secret",
}
user := oauth1a.NewAuthorizedConfig("oauth", "sucks")
client := twittergo.NewClient(config, user)
if err := client.FetchAppToken(); err != nil {
fmt.Println("Error occured creating the client.", err)
panic("ERROR CREATING USER CLIENT")
}
return &twitterComm{client}
}
func (twComm *twitterComm) Tweets(userID int64 /* Max 200 */) []map[string]interface{} {
url := fmt.Sprintf("https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=%d&count=200", userID)
data, err := twComm.responseData(url)
tweets := []map[string]interface{}{}
if err != nil {
return tweets
}
if jsonErr := json.Unmarshal(data, &tweets); jsonErr != nil {
fmt.Println("Error in unmarshalling response", jsonErr)
fmt.Println("String is:", string(data))
}
return tweets
}
func (twComm *twitterComm) User(id int64) map[string]interface{} {
url := fmt.Sprintf("https://api.twitter.com/1.1/users/show.json?user_id=%d", id)
data, err := twComm.responseData(url)
responseMap := map[string]interface{}{}
if err != nil {
fmt.Println("Error:", err, ". Returning empty user.")
}
if jsonErr := json.Unmarshal(data, &responseMap); jsonErr != nil {
fmt.Println("Error in unmarshalling response data", jsonErr)
fmt.Println("String is:", string(data))
return twComm.User(id)
}
return responseMap
}
func (twComm *twitterComm) Users(ids []int64) []map[string]interface{} {
if len(ids) == 0 {
return []map[string]interface{}{}
}
url := "https://api.twitter.com/1.1/users/lookup.json?user_id=" // MAX 100
for index, id := range ids {
if index == 100 {
panic("Too many ids passed.")
}
url = url + strconv.FormatInt(id, 10) + ","
}
url = url[:len(url)-1]
data, err := twComm.responseData(url)
users := []map[string]interface{}{}
if err != nil {
println("Error occured on fetching users", ids, err)
return users
}
if jsonErr := json.Unmarshal(data, &users); jsonErr != nil {
fmt.Println("Error unmarshalling response data", jsonErr, url)
fmt.Println("String is:", string(data))
}
return users
}
func (twComm *twitterComm) Favourites(userID int64 /* Max 200 */) []map[string]interface{} {
url := fmt.Sprintf("https://api.twitter.com/1.1/favorites/list.json?user_id=%d&count=200", userID)
data, err := twComm.responseData(url)
favourites := []map[string]interface{}{}
if err != nil {
return favourites
}
if jsonErr := json.Unmarshal(data, &favourites); jsonErr != nil {
fmt.Println("Error in unmarshalling response data", jsonErr)
}
return favourites
}
func (twComm *twitterComm) FollowingIDS(userID int64) []interface{} {
/* Fetches following ids and assigns them to user map*/
url := fmt.Sprintf("https://api.twitter.com/1.1/friends/ids.json?user_id=%d&count=1000", userID)
data, err := twComm.responseData(url)
responseMap := map[string]interface{}{}
if err != nil {
return []interface{}{}
}
if jsonErr := json.Unmarshal(data, &responseMap); jsonErr != nil {
fmt.Println("Error in unmarshalling response data", jsonErr)
fmt.Println("String is:", string(data))
}
if ids, ok := responseMap["ids"]; ok {
idsToReturn := ids.([]interface{})
return idsToReturn
}
fmt.Println("No ids found in response map for following ids. Map:", responseMap)
return []interface{}{}
}
func (twComm *twitterComm) FollowerIDS(userID int64) []interface{} {
url := fmt.Sprintf("https://api.twitter.com/1.1/followers/ids.json?user_id=%d&count=1000", userID)
data, err := twComm.responseData(url)
responseMap := map[string]interface{}{}
if err != nil {
return []interface{}{}
}
if jsonErr := json.Unmarshal(data, &responseMap); jsonErr != nil {
fmt.Println("Error in unmarshalling response data", jsonErr)
fmt.Println("String is:", string(data))
}
if ids, ok := responseMap["ids"]; ok {
idsToReturn := ids.([]interface{})
return idsToReturn
}
fmt.Println("No ids found in response map for follower ids. Map:", responseMap)
return []interface{}{}
}
func (twComm *twitterComm) responseData(url string) ([]byte, error) {
fmt.Println("Getting response for", url)
var req *http.Request
var err error
if req, err = http.NewRequest("GET", url, nil); err != nil {
fmt.Println("Error occured on creating request url", url, err)
return nil, err
}
var resp *twittergo.APIResponse
if resp, err = twComm.client.SendRequest(req); err != nil {
fmt.Println("Error occured on sending request", url, err)
return nil, err
}
defer resp.Body.Close()
var body = []byte{} //need to parse own response for JSON
if body, err = ioutil.ReadAll(resp.Body); err != nil { //read all the data as []byte
fmt.Println("Error in ioutil Reading of response", url, err)
return nil, err
}
if strings.Contains(string(body), "Rate limit exceeded") {
fmt.Println("---------------------------------------------")
fmt.Println("URL: ", url)
fmt.Printf("Rate limit: %v\n", resp.RateLimit())
fmt.Printf("Rate limit remaining: %v\n", resp.RateLimitRemaining())
fmt.Printf("Rate limit reset: %v\n---------------------------------------------\n", resp.RateLimitReset())
twComm.handleRateLimit()
return twComm.responseData(url)
}
return body, nil
}
func (twComm *twitterComm) handleRateLimit() {
fmt.Println("Rate limited. Switching twitter clients after 30 seconds...")
time.Sleep(time.Duration(30 * time.Second))
switchClient(twComm)
}