tw

package module
v0.0.0-...-a01694d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2016 License: MIT Imports: 13 Imported by: 0

README

#tw Codeship GoDoc

A new and simple Twitter API client.

NOTE: This client does not implement the entire Twitter API, even more, it only implements functions for a few endpoints, those that I need in my current project. You're welcome to contribute or ask for features.

Usage

The basic usage is:

Create a new client:

tc := tw.NewClient(ck, cs)

Get access token before any query:

if err := tc.GetBearerAccessToken(); err != nil {
    log.Fatalf("Failed to obtain access token: %s", err)
}

Go for it!

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/rendon/tw"
)

func main() {
	log.SetFlags(log.LstdFlags | log.Llongfile)

	// Create new client
	ck := os.Getenv("TWITTER_CONSUMER_KEY")
	cs := os.Getenv("TWITTER_CONSUMER_SECRET")
	tc := tw.NewClient(ck, cs)

	if err := tc.GetBearerAccessToken(); err != nil {
		log.Fatalf("Failed to obtain access token: %s", err)
	}

	// GET users/show
	user, err := tc.GetUsersShow("twitterdev")
	if err != nil {
		log.Fatalf("Failed to obtain user: %s", err)
	}

	fmt.Printf("User ID: %d\n", user.ID)
	fmt.Printf("User name: %s\n", user.ScreenName)

	// GET statuses/user_timeline
	tweets, err := tc.GetTweets("twitterdev", 5)
	if err != nil {
		log.Fatalf("Failed to obtain tweets: %s", err)
	}

	fmt.Printf("=================== Tweets =================================\n")
	for i := range tweets {
		fmt.Printf("%s\n", tweets[i].Text)
		fmt.Printf("--------------------------------------------------------\n")
	}
	fmt.Println()

	// GET followers/ids
	fmt.Printf("First follower IDs:\n")
	followers := tc.GetFollowersIdsByID(2244994945, 5)
	var ids []int64
	for i := 0; i < 5; i++ {
		err = followers.Next(&ids)
		if err == tw.ErrEndOfList {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		for _, id := range ids {
			fmt.Printf("%d\n", id)
		}
	}
	fmt.Println()

	// GET friends/ids
	fmt.Printf("First friends IDs:\n")
	friends := tc.GetFriendsIdsByID(191541009, 50)
	for i := 0; i < 5; i++ {
		err = friends.Next(&ids)
		if err == tw.ErrEndOfList {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		for _, id := range ids {
			fmt.Printf("%d\n", id)
		}
	}
	fmt.Println()
}

Detecting "Too Many Requests"

You can detect a rate limit error like so:

if err != nil && err.Error() == tw.ErrMsgTooManyRequests {
    // Do something about it
}

Or use type assertion. The actual error in this case is of type tw.RateLimitError, which contains a ResetTime field with the time at which the access will be renewed. You can do something like this in the meanwhile:

time.Sleep(err.ResetTime.Sub(time.Now()))

Originally this client was designed to use multiple sets of keys, rotating keys when detecting Too Many Requests errors. Now the recommended way is to create a list of clients, one per set of credentials and use some sort of balancing algorithm to decide which client to use.

Documentation

Overview

Package tw implements part of the Twitter API, aiming simplicity and flexibility.

Information about the Twitter API can be found at https://dev.twitter.com/rest/public.

Index

Examples

Constants

View Source
const (

	// MaxFollowersCount More info at
	// https://dev.twitter.com/rest/reference/get/followers/ids
	MaxFollowersCount = 5000

	// MaxFriendsCount More info at
	// https://dev.twitter.com/rest/reference/get/friends/ids
	MaxFriendsCount = 5000
)

Variables

View Source
var (
	// ErrMsgTooManyRequests rate limit message.
	ErrMsgTooManyRequests = "Too Many Requests"
	// ErrUnauthorized error for private profiles.
	ErrUnauthorized = errors.New("Authorization Required")
)
View Source
var (
	// ErrEndOfList Indicates  we've reached the  last page for those  queries
	// that fetch data in pages, e.g. get followers, get friends, etc.
	ErrEndOfList = errors.New("No more pages available")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	ConsumerKey       string
	ConsumerSecret    string
	BearerAccessToken string
}

Client Represents a Twitter API client with the necessary access data and methods to query the API.

func NewClient

func NewClient(ck, cs string) *Client

NewClient Returns a new client with credentials set.

Example
log.SetFlags(log.LstdFlags | log.Llongfile)

// Create new client
ck := os.Getenv("TWITTER_CONSUMER_KEY")
cs := os.Getenv("TWITTER_CONSUMER_SECRET")
tc := NewClient(ck, cs)

// Set keys
if err := tc.GetBearerAccessToken(); err != nil {
	log.Fatalf("Failed to obtain access token: %s", err)
}

// GET users/show
user, err := tc.GetUsersShow("twitterdev")
if err != nil {
	log.Fatalf("Failed to obtain user: %s", err)
}

fmt.Printf("User ID: %d\n", user.ID)
fmt.Printf("User name: %s\n", user.ScreenName)

// GET statuses/user_timeline
tweets, err := tc.GetTweets("twitterdev", 5)
if err != nil {
	log.Fatalf("Failed to obtain tweets: %s", err)
}

fmt.Printf("=================== Tweets =================================\n")
for i := range tweets {
	fmt.Printf("%s\n", tweets[i].Text)
	fmt.Printf("--------------------------------------------------------\n")
}
fmt.Println()

// GET followers/ids
fmt.Printf("First follower IDs:\n")
followers := tc.GetFollowersIdsByID(2244994945, 5)
var ids []int64
for i := 0; i < 5; i++ {
	err = followers.Next(&ids)
	if err == ErrEndOfList {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	for _, id := range ids {
		fmt.Printf("%d\n", id)
	}
}
fmt.Println()

// GET friends/ids
fmt.Printf("First friends IDs:\n")
friends := tc.GetFriendsIdsByID(191541009, 50)
for i := 0; i < 5; i++ {
	err = friends.Next(&ids)
	if err == ErrEndOfList {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	for _, id := range ids {
		fmt.Printf("%d\n", id)
	}
}
fmt.Println()
Output:

func (*Client) GetBearerAccessToken

func (c *Client) GetBearerAccessToken() error

GetBearerAccessToken Authenticates with Twitter using the provided consumer key and consumer secret. Details of the algorithmn are available at https://dev.twitter.com/oauth/application-only.

func (*Client) GetFollowersIdsByID

func (c *Client) GetFollowersIdsByID(id int64, count int) *FollowersIterator

GetFollowersIdsByID Returns an iterator which you can call to retrieve pages of followers IDs for the user identified with ID. Count specifies the page size. See https://dev.twitter.com/rest/reference/get/followers/ids.

func (*Client) GetFriendsIdsByID

func (c *Client) GetFriendsIdsByID(id int64, count int) *FriendsIterator

GetFriendsIdsByID Returns an iterator which you can call to retrieve pages of friends IDs for the user identified with ID. Count specifies the page size. See https://dev.twitter.com/rest/reference/get/friends/ids.

func (*Client) GetTweets

func (c *Client) GetTweets(screenName string, count uint) ([]Tweet, error)

GetTweets Retrieves latest tweets, limited by count. For more information see https://dev.twitter.com/rest/reference/get/statuses/user_timeline.

func (*Client) GetTweetsByID

func (c *Client) GetTweetsByID(id int64, count uint) ([]Tweet, error)

GetTweetsByID Retrieves latest tweets by user ID, limited by count. See https://dev.twitter.com/rest/reference/get/statuses/user_timeline.

func (*Client) GetUsersShow

func (c *Client) GetUsersShow(screenName string) (*User, error)

GetUsersShow Retrieves user profile given the user's screen name. For more information see https://dev.twitter.com/rest/reference/get/users/show.

func (*Client) GetUsersShowByID

func (c *Client) GetUsersShowByID(id int64) (*User, error)

GetUsersShowByID Retrieves user profile given it's ID. For more information see https://dev.twitter.com/rest/reference/get/users/show.

type Entities

type Entities struct {
	UserMentions []UserMention `json:"user_mentions"   bson:"user_mentions"`
}

Entities represents a list of mentions in a tweet.

type FollowersIterator

type FollowersIterator struct {
	// contains filtered or unexported fields
}

FollowersIterator Contains the necessary information to retrieve the next page of follower IDs.

func (*FollowersIterator) Next

func (t *FollowersIterator) Next(data *[]int64) error

Next Returns the next page of follower IDs.

type FollowersPage

type FollowersPage struct {
	IDs            []int64 `json:"ids"`
	NextCursor     int64   `json:"next_cursor"`
	PreviousCursor int64   `json:"previous_cursor"`
}

FollowersPage describes a page of follower IDs.

type FriendsIterator

type FriendsIterator struct {
	// contains filtered or unexported fields
}

FriendsIterator Contains the necessary information to retrieve the next page of friends IDs.

func (*FriendsIterator) Next

func (t *FriendsIterator) Next(data *[]int64) error

Next Returns the next page of friends IDs.

type FriendsPage

type FriendsPage struct {
	IDs            []int64 `json:"ids"`
	NextCursor     int64   `json:"next_cursor"`
	PreviousCursor int64   `json:"previous_cursor"`
}

FriendsPage describes a page of friend IDs.

type RateLimitError

type RateLimitError struct {
	ResetTime time.Time
}

RateLimitError indicates a "Too Many Requests" error and associated data.

func (RateLimitError) Error

func (t RateLimitError) Error() string

type RubyDate

type RubyDate struct {
	// contains filtered or unexported fields
}

RubyDate is a custom type to handle Twitter dates.

func (*RubyDate) GetBSON

func (t *RubyDate) GetBSON() (interface{}, error)

GetBSON returns value that can be represented in BSON format.

func (*RubyDate) MarshalJSON

func (t *RubyDate) MarshalJSON() ([]byte, error)

MarshalJSON returns JSON representation of RubyDate type.

func (*RubyDate) SetBSON

func (t *RubyDate) SetBSON(raw bson.Raw) error

SetBSON sets RubyDate value from raw BSON value.

func (*RubyDate) UnmarshalJSON

func (t *RubyDate) UnmarshalJSON(data []byte) error

UnmarshalJSON gets RubyDate value from data.

type Tweet

type Tweet struct {
	ID            int64    `json:"id"                 bson:"id"`
	UserID        int64    `json:"user_id"            bson:"user_id"`
	Text          string   `json:"text"               bson:"text"`
	Retweeted     bool     `json:"retweeted"          bson:"retweeted"`
	IsRetweet     bool     `json:"is_retweet"         bson:"is_retweet"`
	RetweetCount  uint     `json:"retweet_count"      bson:"retweet_count"`
	FavoriteCount uint     `json:"favorite_count"     bson:"favorite_count"`
	Sensitive     bool     `json:"possibly_sensitive" bson:"possibly_sensitive"`
	Entities      Entities `json:"entities"           bson:"entities"`
	CreatedAt     RubyDate `json:"created_at"         bson:"created_at"`
}

Tweet Represents a tweet with some important fields.

type User

type User struct {
	ID              int64     `json:"id"                bson:"_id"`
	Name            string    `json:"name"              bson:"name"`
	ScreenName      string    `json:"screen_name"       bson:"screen_name"`
	Description     string    `json:"description"       bson:"description"`
	ProfileImageURL string    `json:"profile_image_url" bson:"profile_image_url"`
	Location        string    `json:"location"          bson:"location"`
	Lang            string    `json:"lang"              bson:"lang"`
	TimeZone        string    `json:"time_zone"         bson:"time_zone"`
	URL             string    `json:"url"               bson:"url"`
	Protected       bool      `json:"protected"         bson:"protected"`
	Verified        bool      `json:"verified"          bson:"verified"`
	FriendsCount    int       `json:"friends_count"     bson:"friends_count"`
	ListedCount     int       `json:"listed_count"      bson:"listed_count"`
	FavouritesCount int       `json:"favourites_count"  bson:"favourites_count"`
	FollowersCount  int       `json:"followers_count"   bson:"followers_count"`
	StatusesCount   int       `json:"statuses_count"    bson:"statuses_count"`
	CreatedAt       *RubyDate `json:"created_at"        bson:"created_at"`
	RetrievedAt     time.Time `json:"retrieved_at"      bson:"retrieved_at"`
}

User Represents a user with some important fields.

type UserMention

type UserMention struct {
	ID int64 `json:"id" bson:"id"`
}

UserMention represents a mention in a tweet.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL