-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
295 lines (250 loc) · 9.35 KB
/
main.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/dghubble/oauth1"
"github.com/gorilla/mux"
_ "github.com/joho/godotenv/autoload"
)
type TwitterMentionHook struct {
ForUserID string `json:"for_user_id"`
UserHasBlocked bool `json:"user_has_blocked"`
TweetCreateEvents []struct {
CreatedAt string `json:"created_at"`
ID int64 `json:"id"`
IDStr string `json:"id_str"`
Text string `json:"text"`
Source string `json:"source"`
Truncated bool `json:"truncated"`
InReplyToStatusID interface{} `json:"in_reply_to_status_id"`
InReplyToStatusIDStr interface{} `json:"in_reply_to_status_id_str"`
InReplyToUserID interface{} `json:"in_reply_to_user_id"`
InReplyToUserIDStr interface{} `json:"in_reply_to_user_id_str"`
InReplyToScreenName interface{} `json:"in_reply_to_screen_name"`
User struct {
ID int64 `json:"id"`
IDStr string `json:"id_str"`
Name string `json:"name"`
ScreenName string `json:"screen_name"`
Location interface{} `json:"location"`
URL interface{} `json:"url"`
Description interface{} `json:"description"`
TranslatorType string `json:"translator_type"`
Protected bool `json:"protected"`
Verified bool `json:"verified"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ListedCount int `json:"listed_count"`
FavouritesCount int `json:"favourites_count"`
StatusesCount int `json:"statuses_count"`
CreatedAt string `json:"created_at"`
UtcOffset interface{} `json:"utc_offset"`
TimeZone interface{} `json:"time_zone"`
GeoEnabled bool `json:"geo_enabled"`
Lang interface{} `json:"lang"`
ContributorsEnabled bool `json:"contributors_enabled"`
IsTranslator bool `json:"is_translator"`
ProfileBackgroundColor string `json:"profile_background_color"`
ProfileBackgroundImageURL string `json:"profile_background_image_url"`
ProfileBackgroundImageURLHTTPS string `json:"profile_background_image_url_https"`
ProfileBackgroundTile bool `json:"profile_background_tile"`
ProfileLinkColor string `json:"profile_link_color"`
ProfileSidebarBorderColor string `json:"profile_sidebar_border_color"`
ProfileSidebarFillColor string `json:"profile_sidebar_fill_color"`
ProfileTextColor string `json:"profile_text_color"`
ProfileUseBackgroundImage bool `json:"profile_use_background_image"`
ProfileImageURL string `json:"profile_image_url"`
ProfileImageURLHTTPS string `json:"profile_image_url_https"`
DefaultProfile bool `json:"default_profile"`
DefaultProfileImage bool `json:"default_profile_image"`
Following interface{} `json:"following"`
FollowRequestSent interface{} `json:"follow_request_sent"`
Notifications interface{} `json:"notifications"`
WithheldInCountries []interface{} `json:"withheld_in_countries"`
} `json:"user"`
Geo interface{} `json:"geo"`
Coordinates interface{} `json:"coordinates"`
Place interface{} `json:"place"`
Contributors interface{} `json:"contributors"`
IsQuoteStatus bool `json:"is_quote_status"`
QuoteCount int `json:"quote_count"`
ReplyCount int `json:"reply_count"`
RetweetCount int `json:"retweet_count"`
FavoriteCount int `json:"favorite_count"`
Entities struct {
Hashtags []struct {
Text string `json:"text"`
Indices []int `json:"indices"`
} `json:"hashtags"`
Urls []interface{} `json:"urls"`
UserMentions []struct {
ScreenName string `json:"screen_name"`
Name string `json:"name"`
ID int64 `json:"id"`
IDStr string `json:"id_str"`
Indices []int `json:"indices"`
} `json:"user_mentions"`
Symbols []interface{} `json:"symbols"`
} `json:"entities"`
Favorited bool `json:"favorited"`
Retweeted bool `json:"retweeted"`
FilterLevel string `json:"filter_level"`
Lang string `json:"lang"`
TimestampMs string `json:"timestamp_ms"`
} `json:"tweet_create_events"`
}
type DadJoke struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data string `json:"data"`
}
func getRandomDadJoke() (dadJoke DadJoke, err error) {
url := "https://jokes-bapack2-api.herokuapp.com/v1/text/random"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return
}
req.Header.Add("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
if res.StatusCode >= 400 {
err = fmt.Errorf("the request api dadjoke returned status code %d", res.StatusCode)
return
}
if err = json.Unmarshal(body, &dadJoke); err != nil {
return
}
return
}
func crcHandler(rw http.ResponseWriter, r *http.Request) {
crcToken := r.URL.Query()["crc_token"]
if len(crcToken) < 1 {
rw.WriteHeader(http.StatusBadRequest)
rw.Write([]byte("no crc token given"))
return
}
h := hmac.New(sha256.New, []byte(os.Getenv("TWITTER_CONSUMER_SECRET")))
h.Write([]byte(crcToken[0]))
sha := base64.StdEncoding.EncodeToString(h.Sum(nil))
responseToken := fmt.Sprintf("sha256=%s", sha)
js, _ := json.Marshal(map[string]interface{}{
"response_token": responseToken,
})
rw.Header().Set("Content-Type", "application/json")
rw.Write(js)
}
func wehbookHandler(rw http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(rw, "cannot read response body", http.StatusBadRequest)
return
}
var rawData map[string]interface{}
if err := json.Unmarshal(body, &rawData); err != nil {
http.Error(rw, "invalid parsing body response - rawData", http.StatusBadRequest)
return
}
if _, exist := rawData["tweet_create_events"]; !exist {
rw.WriteHeader(http.StatusOK)
return
}
if _, exist := rawData["user_has_blocked"]; !exist {
rw.WriteHeader(http.StatusOK)
return
}
var twitterMentionHook TwitterMentionHook
if err := json.Unmarshal(body, &twitterMentionHook); err != nil {
http.Error(rw, "invalid parsing body response - twitterMentionHook", http.StatusBadRequest)
return
}
replyID := twitterMentionHook.TweetCreateEvents[0].IDStr
username := twitterMentionHook.TweetCreateEvents[0].User.ScreenName
hashtags := twitterMentionHook.TweetCreateEvents[0].Entities.Hashtags
var isDadJokeMatch bool
for _, v := range hashtags {
if v.Text == "dadjoke" {
isDadJokeMatch = true
break
}
}
if isDadJokeMatch {
log.Println("received #dadjoke request")
log.Println(string(body))
res, err := getRandomDadJoke()
if err != nil {
fmt.Println(err.Error())
http.Error(rw, "failed get dadjoke", http.StatusBadRequest)
return
}
status := fmt.Sprintf("@%s 🤖 Automated\n\n%s", username, res.Data)
if err := replyTweet(status, replyID); err != nil {
fmt.Println(err.Error())
http.Error(rw, "failed to reply tweet", http.StatusBadRequest)
return
}
}
// TODO - Other random stuff
rw.Write([]byte("ok"))
}
func twitterClient() (client *http.Client) {
config := oauth1.NewConfig(os.Getenv("TWITTER_CONSUMER_KEY"), os.Getenv("TWITTER_CONSUMER_SECRET"))
token := oauth1.NewToken(os.Getenv("TWITTER_ACCESS_TOKEN"), os.Getenv("TWITTER_ACCESS_TOKEN_SECRET"))
client = config.Client(oauth1.NoContext, token)
return
}
func replyTweet(tweet string, replyID string) (err error) {
path := fmt.Sprintf("%s/statuses/update.json", os.Getenv("TWITTER_BASE_URL"))
params := url.Values{}
params.Set("status", tweet)
params.Set("in_reply_to_status_id", replyID)
client := twitterClient()
resp, err := client.PostForm(path, params)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
var data map[string]interface{}
if err = json.Unmarshal([]byte(body), &data); err != nil {
return
}
if resp.StatusCode >= 400 {
err = fmt.Errorf("the request api reply tweet returned status code: %d", resp.StatusCode)
return
}
return
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("server up and running!"))
})
r.HandleFunc("/webhook/twitter", crcHandler).Methods("GET")
r.HandleFunc("/webhook/twitter", wehbookHandler).Methods("POST")
srv := &http.Server{
Handler: r,
Addr: ":" + os.Getenv("PORT"),
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}