anaconda

package module
v0.0.0-...-0f727d1 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2014 License: MIT Imports: 9 Imported by: 0

README

Anaconda
====================

[![GoDoc](https://godoc.org/github.com/ChimeraCoder/anaconda?status.png)](https://godoc.org/github.com/ChimeraCoder/anaconda)

Anaconda is a simple, transparent Go package for accessing version 1.1 of the Twitter API. 

Successful API queries return native Go structs that can be used immediately, with no need for type assertions.



Examples
-------------

### Authentication

If you already have the access token (and secret) for your user (Twitter provides this for your own account on the developer portal), creating the client is simple:

````go
anaconda.SetConsumerKey("your-consumer-key")
anaconda.SetConsumerSecret("your-consumer-secret")
api := anaconda.NewTwitterApi("your-access-token", "your-access-token-secret")
````

### Queries

Queries are conducted using a pointer to an authenticated `TwitterApi` struct. In v1.1 of Twitter's API, all requests should be authenticated.

````go
searchResult, _ := api.GetSearch("golang", nil)
for _ , tweet := range searchResult {
    fmt.Println(tweet.Text)
}   
````
Certain endpoints allow separate optional parameter; if desired, these can be passed as the final parameter. 

````go
//Perhaps we want 30 values instead of the default 15
v := url.Values{}
v.Set("count", "30")
result, err := api.GetSearch("golang", v)
````

(Remember that `url.Values` is equivalent to a `map[string][]string`, if you find that more convenient notation when specifying values). Otherwise, `nil` suffices.



Endpoints
------------

Anaconda implements most of the endpoints defined in the [Twitter API documentation](https://dev.twitter.com/docs/api/1.1). For clarity, in most cases, the function name is simply the name of the HTTP method and the endpoint (e.g., the endpoint `GET /friendships/incoming` is provided by the function `GetFriendshipsIncoming`).

In a few cases, a shortened form has been chosen to make life easier (for example, retweeting is simply the function `Retweet`)



Error Handling, Rate Limiting, and Throttling
---------------------------------

###Error Handling

Twitter errors are returned as an `ApiError`, which satisfies the `error` interface and can be treated as a vanilla `error`. However, it also contains the additional information returned by the Twitter API that may be useful in deciding how to proceed after encountering an error.


If you make queries too quickly, you may bump against Twitter's [rate limits](https://dev.twitter.com/docs/rate-limiting/1.1). If this happens, `anaconda` automatically retries the query when the rate limit resets, using the `X-Rate-Limit-Reset` header that Twitter provides to determine how long to wait.

In other words, users of the `anaconda` library should not need to handle rate limiting errors themselves; this is handled seamlessly behind-the-scenes. If an error is returned by a function, another form of error must have occurred (which can be checked by using the fields provided by the `ApiError` struct).


(If desired, this feature can be turned off by calling `ReturnRateLimitError(true)`.)


###Throttling

Anaconda now supports automatic client-side throttling of queries to avoid hitting the Twitter rate-limit.

This is currently *off* by default; however, it may be turned on by default in future versions of the library, as the implementation is improved.


To set a delay between queries, use the `SetDelay` method:

````go
    api.SetDelay(10 * time.Second)
````

Delays are set specific to each `TwitterApi` struct, so queries that use different users' access credentials are completely independent.


To turn off automatic throttling, set the delay to `0`:

````go
    api.SetDelay(0 * time.Second)
````



License
-----------
Anaconda is free software licensed under the MIT/X11 license. Details provided in the LICENSE file.

Documentation

Overview

Package anaconda provides structs and functions for accessing version 1.1 of the Twitter API.

Successful API queries return native Go structs that can be used immediately, with no need for type assertions.

Authentication

If you already have the access token (and secret) for your user (Twitter provides this for your own account on the developer portal), creating the client is simple:

anaconda.SetConsumerKey("your-consumer-key")
anaconda.SetConsumerSecret("your-consumer-secret")
api := anaconda.NewTwitterApi("your-access-token", "your-access-token-secret")

Queries

Executing queries on an authenticated TwitterApi struct is simple.

searchResult, _ := api.GetSearch("golang", nil)
for _ , tweet := range searchResult {
    fmt.Print(tweet.Text)
}

Certain endpoints allow separate optional parameter; if desired, these can be passed as the final parameter.

v := url.Values{}
v.Set("count", "30")
result, err := api.GetSearch("golang", v)

Endpoints

Anaconda implements most of the endpoints defined in the Twitter API documentation: https://dev.twitter.com/docs/api/1.1. For clarity, in most cases, the function name is simply the name of the HTTP method and the endpoint (e.g., the endpoint `GET /friendships/incoming` is provided by the function `GetFriendshipsIncoming`).

In a few cases, a shortened form has been chosen to make life easier (for example, retweeting is simply the function `Retweet`)

More detailed information about the behavior of each particular endpoint can be found at the official Twitter API documentation.

Index

Examples

Constants

View Source
const (
	//Error code defintions match the Twitter documentation
	//https://dev.twitter.com/docs/error-codes-responses
	TwitterErrorCouldNotAuthenticate    = 32
	TwitterErrorDoesNotExist            = 34
	TwitterErrorAccountSuspended        = 64
	TwitterErrorApi1Deprecation         = 68 //This should never be needed
	TwitterErrorRateLimitExceeded       = 88
	TwitterErrorInvalidToken            = 89
	TwitterErrorOverCapacity            = 130
	TwitterErrorInternalError           = 131
	TwitterErrorCouldNotAuthenticateYou = 135
	TwitterErrorStatusIsADuplicate      = 187
	TwitterErrorBadAuthenticationData   = 215
	TwitterErrorUserMustVerifyLogin     = 231
)
View Source
const DEFAULT_CAPACITY = 5
View Source
const DEFAULT_DELAY = 0 * time.Second

Variables

This section is empty.

Functions

func AuthorizationURL

func AuthorizationURL(callback string) (string, *oauth.Credentials, error)

AuthorizationURL generates the authorization URL for the first part of the OAuth handshake. Redirect the user to this URL. This assumes that the consumer key has already been set (using SetConsumerKey).

func GetCredentials

func GetCredentials(tempCred *oauth.Credentials, verifier string) (*oauth.Credentials, url.Values, error)

func SetConsumerKey

func SetConsumerKey(consumer_key string)

SetConsumerKey will set the application-specific consumer_key used in the initial OAuth process This key is listed on https://dev.twitter.com/apps/YOUR_APP_ID/show

func SetConsumerSecret

func SetConsumerSecret(consumer_secret string)

SetConsumerSecret will set the application-specific secret used in the initial OAuth process This secret is listed on https://dev.twitter.com/apps/YOUR_APP_ID/show

Types

type ApiError

type ApiError struct {
	StatusCode int
	Header     http.Header
	Body       string
	Decoded    TwitterErrorResponse
	URL        *url.URL
}

func NewApiError

func NewApiError(resp *http.Response) *ApiError

func (ApiError) Error

func (aerr ApiError) Error() string

ApiError supports the error interface

func (*ApiError) RateLimitCheck

func (aerr *ApiError) RateLimitCheck() (isRateLimitError bool, nextWindow time.Time)

Check to see if an error is a Rate Limiting error. If so, find the next available window in the header. Use like so:

  if aerr, ok := err.(*ApiError); ok {
	  if isRateLimitError, nextWindow := aerr.RateLimitCheck(); isRateLimitError {
     	<-time.After(nextWindow.Sub(time.Now()))
	  }
  }

type Cursor

type Cursor struct {
	Previous_cursor     int64
	Previous_cursor_str string

	Ids []int64

	Next_cursor     int64
	Next_cursor_str string
}

type DirectMessage

type DirectMessage struct {
	CreatedAt           string   `json:"created_at"`
	Entities            Entities `json:"entities"`
	Id                  int64    `json:"id"`
	IdStr               string   `json:"id_str"`
	Recipient           User     `json:"recipient"`
	RecipientId         int64    `json:"recipient_id"`
	RecipientScreenName string   `json:"recipient_screen_name"`
	Sender              User     `json:"sender"`
	SenderId            int64    `json:"sender_id"`
	SenderScreenName    string   `json:"sender_screen_name"`
	Text                string   `json:"text"`
}

type Entities

type Entities struct {
	Hashtags []struct {
		Indices []int
		Text    string
	}
	Urls []struct {
		Indices      []int
		Url          string
		Display_url  string
		Expanded_url string
	}
	User_mentions []struct {
		Name        string
		Indices     []int
		Screen_name string
		Id          int64
		Id_str      string
	}
	Media []struct {
		Id              int64
		Id_str          string
		Media_url       string
		Media_url_https string
		Url             string
		Display_url     string
		Expanded_url    string
		Sizes           MediaSizes
		Type            string
		Indices         []int
	}
}

type FollowersPage

type FollowersPage struct {
	Followers []User
	Error     error
}

type Friendship

type Friendship struct {
	Name        string
	Id_str      string
	Id          int64
	Connections []string
	Screen_name string
}

type MediaSize

type MediaSize struct {
	W      int
	H      int
	Resize string
}

type MediaSizes

type MediaSizes struct {
	Medium MediaSize
	Thumb  MediaSize
	Small  MediaSize
	Large  MediaSize
}

type OEmbed

type OEmbed struct {
	Type          string
	Width         int
	Cache_age     string
	Height        int
	Author_url    string
	Html          string
	Version       string
	Provider_name string
	Provider_url  string
	Url           string
	Author_name   string
}

type Place

type Place struct {
	Attributes  map[string]string `json:"attributes"`
	BoundingBox struct {
		Coordinates [][][]float64 `json:"coordinates"`
		Type        string        `json:"type"`
	} `json:"bounding_box"`
	ContainedWithin []struct {
		Attributes  map[string]string `json:"attributes"`
		BoundingBox struct {
			Coordinates [][][]float64 `json:"coordinates"`
			Type        string        `json:"type"`
		} `json:"bounding_box"`
		Country     string `json:"country"`
		CountryCode string `json:"country_code"`
		FullName    string `json:"full_name"`
		ID          string `json:"id"`
		Name        string `json:"name"`
		PlaceType   string `json:"place_type"`
		URL         string `json:"url"`
	} `json:"contained_within"`
	Country     string `json:"country"`
	CountryCode string `json:"country_code"`
	FullName    string `json:"full_name"`
	Geometry    struct {
		Coordinates [][][]float64 `json:"coordinates"`
		Type        string        `json:"type"`
	} `json:"geometry"`
	ID        string   `json:"id"`
	Name      string   `json:"name"`
	PlaceType string   `json:"place_type"`
	Polylines []string `json:"polylines"`
	URL       string   `json:"url"`
}

type Tweet

type Tweet struct {
	Contributors         []int64     `json:"contributors"`
	Coordinates          interface{} `json:"coordinates"`
	CreatedAt            string      `json:"created_at"`
	Entities             Entities    `json:"entities"`
	FavoriteCount        int         `json:"favorite_count"`
	Favorited            bool        `json:"favorited"`
	Geo                  interface{} `json:"geo"`
	Id                   int64       `json:"id"`
	IdStr                string      `json:"id_str"`
	InReplyToScreenName  string      `json:"in_reply_to_screen_name"`
	InReplyToStatusID    int64       `json:"in_reply_to_status_id"`
	InReplyToStatusIdStr string      `json:"in_reply_to_status_id_str"`
	InReplyToUserID      int64       `json:"in_reply_to_user_id"`
	InReplyToUserIdStr   string      `json:"in_reply_to_user_id_str"`
	Place                Place       `json:"place"`
	PossiblySensitive    bool        `json:"possibly_sensitive"`
	RetweetCount         int         `json:"retweet_count"`
	Retweeted            bool        `json:"retweeted"`
	Source               string      `json:"source"`
	Text                 string      `json:"text"`
	Truncated            bool        `json:"truncated"`
	User                 User        `json:"user"`
}

func (Tweet) CreatedAtTime

func (t Tweet) CreatedAtTime() (time.Time, error)

CreatedAtTime is a convenience wrapper that returns the Created_at time, parsed as a time.Time struct

type TwitterApi

type TwitterApi struct {
	Credentials *oauth.Credentials
	// contains filtered or unexported fields
}

func NewTwitterApi

func NewTwitterApi(access_token string, access_token_secret string) *TwitterApi

NewTwitterApi takes an user-specific access token and secret and returns a TwitterApi struct for that user. The TwitterApi struct can be used for accessing any of the endpoints available.

func (TwitterApi) DeleteTweet

func (a TwitterApi) DeleteTweet(id int64, trimUser bool) (tweet Tweet, err error)

DeleteTweet will destroy (delete) the status (tweet) with the specified ID, assuming that the authenticated user is the author of the status (tweet). If trimUser is set to true, only the user's Id will be provided in the user object returned.

func (*TwitterApi) DisableThrottling

func (c *TwitterApi) DisableThrottling()

Disable query throttling

func (*TwitterApi) EnableThrottling

func (c *TwitterApi) EnableThrottling(rate time.Duration, bufferSize int64)

Enable query throttling using the tokenbucket algorithm

func (*TwitterApi) GetDelay

func (c *TwitterApi) GetDelay() time.Duration

func (TwitterApi) GetDirectMessages

func (a TwitterApi) GetDirectMessages(v url.Values) (messages []DirectMessage, err error)

func (TwitterApi) GetDirectMessagesSent

func (a TwitterApi) GetDirectMessagesSent(v url.Values) (messages []DirectMessage, err error)

func (TwitterApi) GetDirectMessagesShow

func (a TwitterApi) GetDirectMessagesShow(v url.Values) (messages []DirectMessage, err error)

func (TwitterApi) GetFollowersIds

func (a TwitterApi) GetFollowersIds(v url.Values) (c Cursor, err error)

func (TwitterApi) GetFollowersList

func (a TwitterApi) GetFollowersList(v url.Values) (c UserCursor, err error)

func (TwitterApi) GetFollowersListAll

func (a TwitterApi) GetFollowersListAll(v url.Values) (result chan FollowersPage)

Like GetFollowersList, but returns a channel instead of a cursor and pre-fetches the remaining results This channel is closed once all values have been fetched

Example

Fetch a list of all followers without any need for managing cursors (Each page is automatically fetched when the previous one is read)

pages := api.GetFollowersListAll(nil)
for page := range pages {
	//Print the current page of followers
	fmt.Println(page.Followers)
}
Output:

func (TwitterApi) GetFriendsIds

func (a TwitterApi) GetFriendsIds(v url.Values) (c Cursor, err error)

func (TwitterApi) GetFriendsIdsAll

func (a TwitterApi) GetFriendsIdsAll(v url.Values) (c Cursor, err error)

Like GetFriendsIds, but returns a channel instead of a cursor and pre-fetches the remaining results This channel is closed once all values have been fetched

func (TwitterApi) GetFriendshipsIncoming

func (a TwitterApi) GetFriendshipsIncoming(v url.Values) (c Cursor, err error)

func (TwitterApi) GetFriendshipsLookup

func (a TwitterApi) GetFriendshipsLookup(v url.Values) (friendships []Friendship, err error)

func (TwitterApi) GetFriendshipsNoRetweets

func (a TwitterApi) GetFriendshipsNoRetweets() (ids []int64, err error)

GetFriendshipsNoRetweets s a collection of user_ids that the currently authenticated user does not want to receive retweets from. It does not currently support the stringify_ids parameter

func (TwitterApi) GetFriendshipsOutgoing

func (a TwitterApi) GetFriendshipsOutgoing(v url.Values) (c Cursor, err error)

func (TwitterApi) GetHomeTimeline

func (a TwitterApi) GetHomeTimeline() (timeline []Tweet, err error)

func (TwitterApi) GetMentionsTimeline

func (a TwitterApi) GetMentionsTimeline(v url.Values) (timeline []Tweet, err error)

func (TwitterApi) GetOEmbed

func (a TwitterApi) GetOEmbed(v url.Values) (o OEmbed, err error)

No authorization on this endpoint. Its the only one.

func (TwitterApi) GetOEmbedId

func (a TwitterApi) GetOEmbedId(id int64, v url.Values) (o OEmbed, err error)

Calls GetOEmbed with the corresponding id. Convenience wrapper for GetOEmbed()

func (TwitterApi) GetRetweets

func (a TwitterApi) GetRetweets(id int64, v url.Values) (tweets []Tweet, err error)

func (TwitterApi) GetRetweetsOfMe

func (a TwitterApi) GetRetweetsOfMe(v url.Values) (tweets []Tweet, err error)

func (TwitterApi) GetSearch

func (a TwitterApi) GetSearch(queryString string, v url.Values) (timeline []Tweet, err error)
Example
package main

import (
	"fmt"
	"github.com/ChimeraCoder/anaconda"
)

func main() {

	anaconda.SetConsumerKey("your-consumer-key")
	anaconda.SetConsumerSecret("your-consumer-secret")
	api := anaconda.NewTwitterApi("your-access-token", "your-access-token-secret")
	search_result, err := api.GetSearch("golang", nil)
	if err != nil {
		panic(err)
	}
	for _, tweet := range search_result {
		fmt.Print(tweet.Text)
	}
}
Output:

func (TwitterApi) GetSelf

func (a TwitterApi) GetSelf(v url.Values) (u User, err error)

Get the user object for the authenticated user. Requests /account/verify_credentials

func (TwitterApi) GetTweet

func (a TwitterApi) GetTweet(id int64, v url.Values) (tweet Tweet, err error)

func (TwitterApi) GetUserTimeline

func (a TwitterApi) GetUserTimeline(v url.Values) (timeline []Tweet, err error)

func (TwitterApi) GetUsersLookup

func (a TwitterApi) GetUsersLookup(usernames string, v url.Values) (u []User, err error)

func (TwitterApi) GetUsersLookupByIds

func (a TwitterApi) GetUsersLookupByIds(ids []int64, v url.Values) (u []User, err error)

func (TwitterApi) PostTweet

func (a TwitterApi) PostTweet(status string, v url.Values) (tweet Tweet, err error)

PostTweet will create a tweet with the specified status message

func (*TwitterApi) ReturnRateLimitError

func (c *TwitterApi) ReturnRateLimitError(b bool)

ReturnRateLimitError specifies behavior when the Twitter API returns a rate-limit error. If set to true, the query will fail and return the error instead of automatically queuing and retrying the query when the rate limit expires

func (TwitterApi) Retweet

func (a TwitterApi) Retweet(id int64, trimUser bool) (rt Tweet, err error)

Retweet will retweet the status (tweet) with the specified ID. trimUser functions as in DeleteTweet

func (*TwitterApi) SetDelay

func (c *TwitterApi) SetDelay(t time.Duration)

SetDelay will set the delay between throttled queries To turn of throttling, set it to 0 seconds

func (TwitterApi) VerifyCredentials

func (a TwitterApi) VerifyCredentials() (ok bool, err error)

Verify the credentials by making a very small request

type TwitterError

type TwitterError struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

TwitterError represents a single Twitter error messages/code pair

func (TwitterError) Error

func (te TwitterError) Error() string

type TwitterErrorResponse

type TwitterErrorResponse struct {
	Errors []TwitterError `json:"errors"`
}

TwitterErrorResponse has an array of Twitter error messages It satisfies the "error" interface For the most part, Twitter seems to return only a single error message Currently, we assume that this always contains exactly one error message

func (TwitterErrorResponse) Error

func (tr TwitterErrorResponse) Error() string

func (TwitterErrorResponse) First

func (tr TwitterErrorResponse) First() error

type User

type User struct {
	ContributorsEnabled            bool   `json:"contributors_enabled"`
	CreatedAt                      string `json:"created_at"`
	DefaultProfile                 bool   `json:"default_profile"`
	DefaultProfileImage            bool   `json:"default_profile_image"`
	Description                    string `json:"description"`
	FavouritesCount                int    `json:"favourites_count"`
	FollowRequestSent              bool   `json:"follow_request_sent"`
	FollowersCount                 int    `json:"followers_count"`
	Following                      bool   `json:"following"`
	FriendsCount                   int    `json:"friends_count"`
	GeoEnabled                     bool   `json:"geo_enabled"`
	Id                             int64  `json:"id"`
	IdStr                          string `json:"id_str"`
	IsTranslator                   bool   `json:"is_translator"`
	Lang                           string `json:"lang"`
	ListedCount                    int64  `json:"listed_count"`
	Location                       string `json:"location"`
	Name                           string `json:"name"`
	Notifications                  bool   `json:"notifications"`
	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"`
	ProfileImageURL                string `json:"profile_image_url"`
	ProfileImageUrlHttps           string `json:"profile_image_url_https"`
	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"`
	Protected                      bool   `json:"protected"`
	ScreenName                     string `json:"screen_name"`
	ShowAllInlineMedia             bool   `json:"show_all_inline_media"`
	Status                         *Tweet `json:"status"` // Only included if the user is a friend
	StatusesCount                  int64  `json:"statuses_count"`
	TimeZone                       string `json:"time_zone"`
	URL                            string `json:"url"`
	UtcOffset                      int    `json:"utc_offset"`
	Verified                       bool   `json:"verified"`
}

type UserCursor

type UserCursor struct {
	Previous_cursor     int64
	Previous_cursor_str string
	Next_cursor         int64
	Next_cursor_str     string
	Users               []User
}

Jump to

Keyboard shortcuts

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