-
Notifications
You must be signed in to change notification settings - Fork 17
/
twitter.go
100 lines (81 loc) · 2.14 KB
/
twitter.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
package main
// Handles optional posting to twitter of everything your markov-bot says
//
// YOU WILL WANT TO BE VERY CAREFUL ABOUT THIS
// It will/may contain internal links, names, other identifying info from what people
// tend to think is private data
//
// Requires a consumer key and secret and then an associated access token and secret
// You can get these from https://dev.twitter.com/apps/new
import (
"encoding/json"
"github.com/mrjones/oauth"
"io/ioutil"
"net/http"
)
type Twitter struct {
consumerKey string
consumerSecret string
accessToken oauth.AccessToken
client oauth.Consumer
}
type User struct {
ID uint64 `json:"id"`
ScreenName string `json:"screen_name"`
}
func NewTwitter(consumerKey string, consumerSecret string, accessToken string, accessTokenSecret string) *Twitter {
c := oauth.NewConsumer(
consumerKey,
consumerSecret,
oauth.ServiceProvider{
RequestTokenUrl: "https://api.twitter.com/oauth/request_token",
AuthorizeTokenUrl: "https://api.twitter.com/oauth/authorize",
AccessTokenUrl: "https://api.twitter.com/oauth/access_token",
})
return &Twitter{
consumerKey: consumerKey,
consumerSecret: consumerSecret,
accessToken: oauth.AccessToken{
Token: accessToken,
Secret: accessTokenSecret,
},
client: *c,
}
}
func (t *Twitter) GetMe() (*User, error) {
resp, err := t.client.Get(
"https://api.twitter.com/1.1/account/verify_credentials.json",
map[string]string{},
&t.accessToken)
if err != nil {
return nil, err
}
// Make sure we close the body stream no matter what
defer resp.Body.Close()
// Read body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// parse into json
var user User
err = json.Unmarshal(body, &user)
if err != nil {
return nil, err
}
return &user, nil
}
func (t *Twitter) Post(status string) (*http.Response, error) {
resp, err := t.client.Post(
"https://api.twitter.com/1.1/statuses/update.json",
map[string]string{
"status": status,
},
&t.accessToken)
if err != nil {
return resp, err
}
// Make sure we close the body stream no matter what
defer resp.Body.Close()
return resp, nil
}