github.com/wtfutil/wtf@v0.43.0/modules/twitter/client.go (about) 1 package twitter 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "net/http" 8 "strconv" 9 10 "golang.org/x/oauth2" 11 "golang.org/x/oauth2/clientcredentials" 12 ) 13 14 /* NOTE: Currently single application ONLY 15 * bearer tokens are only supported for applications, not single-users 16 */ 17 18 // Client represents the data required to connect to the Twitter API 19 type Client struct { 20 apiBase string 21 count int 22 screenName string 23 httpClient *http.Client 24 } 25 26 // NewClient creates and returns a new Twitter client 27 func NewClient(settings *Settings) *Client { 28 var httpClient *http.Client 29 // If a bearer token is supplied, use that directly. Otherwise, let the Oauth client fetch a token 30 // using the consumer key and secret. 31 if settings.bearerToken == "" { 32 conf := &clientcredentials.Config{ 33 ClientID: settings.consumerKey, 34 ClientSecret: settings.consumerSecret, 35 TokenURL: "https://api.twitter.com/oauth2/token", 36 } 37 httpClient = conf.Client(context.Background()) 38 } else { 39 ctx := context.Background() 40 httpClient = oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{ 41 AccessToken: settings.bearerToken, 42 TokenType: "Bearer", 43 })) 44 } 45 46 client := Client{ 47 apiBase: "https://api.twitter.com/1.1/", 48 count: settings.count, 49 screenName: "", 50 httpClient: httpClient, 51 } 52 53 return &client 54 } 55 56 /* -------------------- Public Functions -------------------- */ 57 58 // Tweets returns a list of tweets of a user 59 func (client *Client) Tweets() []Tweet { 60 tweets, err := client.getTweets() 61 if err != nil { 62 return []Tweet{} 63 } 64 65 return tweets 66 } 67 68 /* -------------------- Private Functions -------------------- */ 69 70 // tweets is the private interface for retrieving the list of user tweets 71 func (client *Client) getTweets() (tweets []Tweet, err error) { 72 apiURL := fmt.Sprintf( 73 "%s/statuses/user_timeline.json?screen_name=%s&count=%s", 74 client.apiBase, 75 client.screenName, 76 strconv.Itoa(client.count), 77 ) 78 79 data, err := Request(client.httpClient, apiURL) 80 if err != nil { 81 return tweets, err 82 } 83 err = json.Unmarshal(data, &tweets) 84 85 return 86 }