anaconda

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

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

Go to latest
Published: Dec 5, 2019 License: MIT Imports: 19 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.Statuses {
    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)
````

###Query Queue Persistence

If your code creates a NewTwitterApi in a regularly called function, you'll need to call `.Close()` on the API struct to clear the queryQueue and allow the goroutine to exit. Otherwise you could see goroutine and therefor heap memory leaks in long-running applications.

### Google App Engine

Since Google App Engine doesn't make the standard `http.Transport` available, it's necessary to tell Anaconda to use a different client context.

````go
	api = anaconda.NewTwitterApi("", "")
	c := appengine.NewContext(r)
	api.HttpClient.Transport = &urlfetch.Transport{Context: c}
````


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.Statuses {
    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

	// Undocumented by Twitter, but may be returned instead of 34
	TwitterErrorDoesNotExist2 = 144
)
View Source
const (
	BaseUrlUserStream = "https://userstream.twitter.com/1.1"
	BaseUrlSiteStream = "https://sitestream.twitter.com/1.1"
	BaseUrlStream     = "https://stream.twitter.com/1.1"
)
View Source
const (
	BaseUrlV1     = "https://api.twitter.com/1"
	BaseUrl       = "https://api.twitter.com/1.1"
	UploadBaseUrl = "https://upload.twitter.com/1.1"
)
View Source
const (
	AdsUrl = "https://ads-api.twitter.com/5"
)
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 NewHTTP420ErrBackoff

func NewHTTP420ErrBackoff() backoff.Interface

Back off exponentially for HTTP 420 errors.

Start with a 1 minute wait and double each attempt.
Note that every HTTP 420 received increases the time you must
wait until rate limiting will no longer will be in effect for your account.

func NewHTTPErrBackoff

func NewHTTPErrBackoff() backoff.Interface

Back off exponentially for HTTP errors for which reconnecting would be appropriate.

Start with a 5 second wait, doubling each attempt, up to 320 seconds.

func NewTCPIPErrBackoff

func NewTCPIPErrBackoff() backoff.Interface

Back off linearly for TCP/IP level network errors.

These problems are generally temporary and tend to clear quickly.
Increase the delay in reconnects by 250ms each attempt, up to 16 seconds.

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 Account

type Account struct {
	Data AccountModel `json:"data"`
	Pagination
}

type AccountModel

type AccountModel struct {
	Id               string       `json:"id"`
	Name             string       `json:"name"`
	ApprovalStatus   string       `json:"approval_status"`
	Salt             string       `json:"salt"`
	Deleted          bool         `json:"deleted"`
	Timezone         string       `json:"timezone"`
	TimezoneSwitchAt sql.NullTime `json:"timezone_switch_at"`
	CreatedAt        time.Time    `json:"created_at"`
	UpdatedAt        time.Time    `json:"updated_at"`
}

type AccountVideo

type AccountVideo struct {
	Data VideoModel `json:"data"`
	Pagination
}

type AccountVideos

type AccountVideos struct {
	Data []VideoModel `json:"data"`
	Pagination
}

type Accounts

type Accounts struct {
	Data []AccountModel `json:"data"`
	Pagination
}

type AddUserToListResponse

type AddUserToListResponse struct {
	Users []User `json:"users"`
}

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 Campaign

type Campaign struct {
	Data CampaignModel `json:"data"`
	Pagination
}

type CampaignModel

type CampaignModel struct {
	Id                  string       `json:"id"`
	Name                string       `json:"name"`
	AccountId           string       `json:"account_id"`
	FundingInstrumentId string       `json:"funding_instrument_id"`
	Currency            string       `json:"currency"`
	Paused              bool         `json:"paused"`
	Deleted             bool         `json:"deleted"`
	StandardDelivery    bool         `json:"standard_delivery"`
	TotalBudget         int64        `json:"total_budget_amount_local_micro"`
	DailyBudget         int64        `json:"daily_budget_amount_local_micro"`
	StartTime           time.Time    `json:"start_time"`
	EndTime             sql.NullTime `json:"end_time"`
	CreatedAt           time.Time    `json:"created_at"`
	UpdatedAt           time.Time    `json:"updated_at"`
}

type Campaigns

type Campaigns struct {
	Data []CampaignModel `json:"data"`
	Pagination
}

type ChunkedMedia

type ChunkedMedia struct {
	MediaID          int64  `json:"media_id"`
	MediaIDString    string `json:"media_id_string"`
	ExpiresAfterSecs int    `json:"expires_after_secs"`
}

type Configuration

type Configuration struct {
	CharactersReservedPerMedia int      `json:"characters_reserved_per_media"`
	MaxMediaPerUpload          int      `json:"max_media_per_upload"`
	NonUsernamePaths           []string `json:"non_username_paths"`
	PhotoSizeLimit             int      `json:"photo_size_limit"`
	PhotoSizes                 struct {
		Thumb  photoSize `json:"thumb"`
		Small  photoSize `json:"small"`
		Medium photoSize `json:"medium"`
		Large  photoSize `json:"large"`
	} `json:"photo_sizes"`
	ShortUrlLength      int `json:"short_url_length"`
	ShortUrlLengthHttps int `json:"short_url_length_https"`
}

type Contributor

type Contributor struct {
	Id         int64  `json:"id"`
	IdStr      string `json:"id_str"`
	ScreenName string `json:"screen_name"`
}

Could also use User, since the fields match, but only these fields are possible in Contributor

type ConversionType

type ConversionType struct {
	Metric        []int64 `json:"metric"`
	OrderQuantity []int64 `json:"order_quantity"`
	SaleAmount    []int64 `json:"sale_amount"`
}

type Coordinates

type Coordinates struct {
	Coordinates [2]float64 `json:"coordinates"` // Coordinate always has to have exactly 2 values
	Type        string     `json:"type"`
}

type Cursor

type Cursor struct {
	Previous_cursor     int64
	Previous_cursor_str string

	Ids []int64

	Next_cursor     int64
	Next_cursor_str string
}

type Data

type Data struct {
	Id               int64         `json:"id"`
	AccountId        string        `json:"account_id"`
	URL              string        `json:"url"`
	Entity           string        `json:"entity"`
	EntityIds        []json.Number `json:"entity_ids"`
	Placement        string        `json:"placement"`
	Granularity      string        `json:"granularity"`
	SegmentationType string        `json:"segmentation_type"`
	Country          string        `json:"country"`
	Platform         string        `json:"platform"`
	Status           string        `json:"status"`
	MetricGroups     []string      `json:"metric_groups"`
	StartTime        time.Time     `json:"start_time"`
	EndTime          time.Time     `json:"end_time"`
}

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 DisconnectMessage

type DisconnectMessage struct {
	Code       int64  `json:"code"`
	StreamName string `json:"stream_name"`
	Reason     string `json:"reason"`
}

type Entities

type Entities struct {
	Hashtags []struct {
		Indices []int
		Text    string
	}
	Urls []struct {
		Indices      []int
		Url          string
		Display_url  string
		Expanded_url string
	}
	Url           UrlEntity
	User_mentions []struct {
		Name        string
		Indices     []int
		Screen_name string
		Id          int64
		Id_str      string
	}
	Media []EntityMedia
}

type EntityMedia

type EntityMedia struct {
	Id                   int64
	Id_str               string
	Media_url            string
	Media_url_https      string
	Url                  string
	Display_url          string
	Expanded_url         string
	Sizes                MediaSizes
	Source_status_id     int64
	Source_status_id_str string
	Type                 string
	Indices              []int
	VideoInfo            VideoInfo `json:"video_info"`
}

type Event

type Event struct {
	Target    *User  `json:"target"`
	Source    *User  `json:"source"`
	Event     string `json:"event"`
	CreatedAt string `json:"created_at"`
}

type EventList

type EventList struct {
	Event
	TargetObject *List `json:"target_object"`
}

type EventTweet

type EventTweet struct {
	Event
	TargetObject *Tweet `json:"target_object"`
}

type FollowersIdsPage

type FollowersIdsPage struct {
	Ids   []int64
	Error error
}

FIXME: Might want to consolidate this with FriendsIdsPage and just

have "UserIdsPage".

type FollowersPage

type FollowersPage struct {
	Followers []User
	Error     error
}

type FriendsIdsCursor

type FriendsIdsCursor struct {
	Previous_cursor     int64
	Previous_cursor_str string
	Next_cursor         int64
	Next_cursor_str     string
	Ids                 []int64
}

type FriendsIdsPage

type FriendsIdsPage struct {
	Ids   []int64
	Error error
}

type FriendsList

type FriendsList []int64

type FriendsPage

type FriendsPage struct {
	Friends []User
	Error   error
}

type Friendship

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

type FundingInstrument

type FundingInstrument struct {
	Data     FundingModel `json:"data"`
	DataType string       `json:"data_type"`
	Request  interface{}  `json:"request"`
}

type FundingInstruments

type FundingInstruments struct {
	Data []FundingModel `json:"data"`
	Pagination
}

type FundingModel

type FundingModel struct {
	Id           string       `json:"id"`
	AccountId    string       `json:"account_id"`
	Currency     string       `json:"currency"`
	Type         string       `json:"type"`
	Description  string       `json:"description"`
	CreditLimit  int64        `json:"credit_limit_local_micro"`
	FundedAmount int64        `json:"funded_amount_local_micro"`
	Deleted      bool         `json:"deleted"`
	Cancelled    bool         `json:"cancelled"`
	StartTime    time.Time    `json:"start_time"`
	EndTime      sql.NullTime `json:"end_time"`
	CreatedAt    time.Time    `json:"created_at"`
	UpdatedAt    time.Time    `json:"updated_at"`
}

type GeoSearchResult

type GeoSearchResult struct {
	Result struct {
		Places []struct {
			ID              string `json:"id"`
			URL             string `json:"url"`
			PlaceType       string `json:"place_type"`
			Name            string `json:"name"`
			FullName        string `json:"full_name"`
			CountryCode     string `json:"country_code"`
			Country         string `json:"country"`
			ContainedWithin []struct {
				ID          string    `json:"id"`
				URL         string    `json:"url"`
				PlaceType   string    `json:"place_type"`
				Name        string    `json:"name"`
				FullName    string    `json:"full_name"`
				CountryCode string    `json:"country_code"`
				Country     string    `json:"country"`
				Centroid    []float64 `json:"centroid"`
				BoundingBox struct {
					Type        string        `json:"type"`
					Coordinates [][][]float64 `json:"coordinates"`
				} `json:"bounding_box"`
				Attributes struct {
				} `json:"attributes"`
			} `json:"contained_within"`
			Centroid    []float64 `json:"centroid"`
			BoundingBox struct {
				Type        string        `json:"type"`
				Coordinates [][][]float64 `json:"coordinates"`
			} `json:"bounding_box"`
			Attributes struct {
			} `json:"attributes"`
		} `json:"places"`
	} `json:"result"`
	Query struct {
		URL    string `json:"url"`
		Type   string `json:"type"`
		Params struct {
			Accuracy     float64 `json:"accuracy"`
			Granularity  string  `json:"granularity"`
			Query        string  `json:"query"`
			Autocomplete bool    `json:"autocomplete"`
			TrimPlace    bool    `json:"trim_place"`
		} `json:"params"`
	} `json:"query"`
}

type Image

type Image struct {
	W         int    `json:"w"`
	H         int    `json:"h"`
	ImageType string `json:"image_type"`
}

type Job

type Job struct {
	Data Data `json:"data"`
	Pagination
}

type Jobs

type Jobs struct {
	Data []Data `json:"data"`
	Pagination
}

type LimitNotice

type LimitNotice struct {
	Track int64 `json:"track"`
}

type LineItem

type LineItem struct {
	Data LineItemModel `json:"data"`
	Pagination
}

type LineItemModel

type LineItemModel struct {
	Id                     string    `json:"id"`
	Name                   string    `json:"name"`
	AccountId              string    `json:"account_id"`
	CampaignId             string    `json:"campaign_id"`
	BidType                string    `json:"bid_type"`
	Placements             []string  `json:"placements"`
	ProductType            string    `json:"product_type"`
	BidAmount              int64     `json:"bid_amount_local_micro"`
	AutomaticallySelectBid bool      `json:"automatically_select_bid"`
	AdvertiserDomain       string    `json:"advertiser_domain"`
	PrimaryWebEventTag     string    `json:"primary_web_event_tag"`
	ChargeBy               string    `json:"charge_by"`
	BidUnit                string    `json:"bid_unit"`
	TotalBudget            int64     `json:"total_budget_amount_local_micro"`
	Objective              string    `json:"objective"`
	Paused                 bool      `json:"paused"`
	Deleted                bool      `json:"deleted"`
	Optimization           string    `json:"optimization"`
	Categories             []string  `json:"categories"`
	Currency               string    `json:"currency"`
	IncludeSentiment       string    `json:"include_sentiment"`
	CreatedAt              time.Time `json:"created_at"`
	UpdatedAt              time.Time `json:"updated_at"`
}

type LineItems

type LineItems struct {
	Data []LineItemModel `json:"data"`
	Pagination
}

type List

type List struct {
	Slug            string `json:"slug"`
	Name            string `json:"name"`
	URL             string `json:"uri"`
	CreatedAt       string `json:"created_at"`
	Id              int64  `json:"id"`
	SubscriberCount int64  `json:"subscriber_count"`
	MemberCount     int64  `json:"member_count"`
	Mode            string `json:"mode"`
	FullName        string `json:"full_name"`
	Description     string `json:"description"`
	User            User   `json:"user"`
	Following       bool   `json:"following"`
}

type ListResponse

type ListResponse struct {
	PreviousCursor int    `json:"previous_cursor"`
	NextCursor     int    `json:"next_cursor"`
	Lists          []List `json:"lists"`
}

type Location

type Location struct {
	Name  string `json:"name"`
	Woeid int    `json:"woeid"`
}

type LocationDeletionNotice

type LocationDeletionNotice struct {
	UserId          int64  `json:"user_id"`
	UserIdStr       string `json:"user_id_str"`
	UpToStatusId    int64  `json:"up_to_status_id"`
	UpToStatusIdStr string `json:"up_to_status_id_str"`
}

type Logger

type Logger interface {
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})

	Panic(args ...interface{})
	Panicf(format string, args ...interface{})

	// Log functions
	Critical(args ...interface{})
	Criticalf(format string, args ...interface{})

	Error(args ...interface{})
	Errorf(format string, args ...interface{})

	Warning(args ...interface{})
	Warningf(format string, args ...interface{})

	Notice(args ...interface{})
	Noticef(format string, args ...interface{})

	Info(args ...interface{})
	Infof(format string, args ...interface{})

	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
}

The Logger interface provides optional logging ability for the streaming API. It can also be used to log the rate limiting headers if desired.

var BasicLogger Logger

BasicLogger is the equivalent of using log from the standard library to print to STDERR.

type Media

type Media struct {
	MediaID       int64  `json:"media_id"`
	MediaIDString string `json:"media_id_string"`
	Size          int    `json:"size"`
	Image         Image  `json:"image"`
}

type MediaCreative

type MediaCreative struct {
	Data MediaCreativeModel `json:"data"`
	Pagination
}

type MediaCreativeModel

type MediaCreativeModel struct {
	Id             string    `json:"id"`
	LineItemId     string    `json:"line_item_id"`
	AccountMediaId string    `json:"account_media_id"`
	LandingUrl     string    `json:"landing_url"`
	Deleted        bool      `json:"deleted"`
	ApprovalStatus string    `json:"approval_status"`
	ServingStatus  string    `json:"serving_status"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

type MediaCreatives

type MediaCreatives struct {
	Data []MediaCreativeModel `json:"data"`
	Pagination
}

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 Metric

type Metric struct {
	AppClicks            []int64 `json:"app_clicks"`
	BilledCharge         []int64 `json:"billed_charge_local_micro"`
	BilledEngagements    []int64 `json:"billed_engagements"`
	CardEngagements      []int64 `json:"card_engagements"`
	CarouselSwipes       []int64 `json:"carousel_swipes"`
	Clicks               []int64 `json:"clicks"`
	Engagements          []int64 `json:"engagements"`
	Follows              []int64 `json:"follows"`
	Impressions          []int64 `json:"impressions"`
	Likes                []int64 `json:"likes"`
	MediaEngagements     []int64 `json:"media_engagements"`
	MediaViews           []int64 `json:"media_views"`
	PollCardVote         []int64 `json:"poll_card_vote"`
	QualifiedImpressions []int64 `json:"qualified_impressions"`
	Replies              []int64 `json:"replies"`
	Retweets             []int64 `json:"retweets"`
	TweetsSend           []int64 `json:"tweets_send"`
	Unfollows            []int64 `json:"unfollows"`
	UrlClicks            []int64 `json:"url_clicks"`

	// video metrics
	ContentStarts []int64 `json:"video_content_starts"`
	CtaClicks     []int64 `json:"video_cta_clicks"`
	MrcViews      []int64 `json:"video_mrc_views"`
	TotalViews    []int64 `json:"video_total_views"`
	Views25       []int64 `json:"video_views_25"`
	Views50       []int64 `json:"video_views_50"`
	Views75       []int64 `json:"video_views_75"`
	Views100      []int64 `json:"video_views_100"`
	Views3s100Pct []int64 `json:"video_3s100pct_views"`

	MobileMetrics
	WebMetrics
}

type Metrics

type Metrics struct {
	Metric  Metric       `json:"metrics"`
	Segment *SegmentType `json:"segment,omitempty"`
}

type MobileConversion

type MobileConversion struct {
	Assisted       []int64 `json:"assisted"`
	OrderQuantity  []int64 `json:"order_quantity"`
	PostEngagement []int64 `json:"post_engagement"`
	PostView       []int64 `json:"post_view"`
	SaleAmount     []int64 `json:"sale_amount"`
}

type MobileMetrics

type MobileMetrics struct {
	AchievementsUnlocked MobileConversion `json:"mobile_conversion_achievements_unlocked"`
	AddToCarts           MobileConversion `json:"mobile_conversion_add_to_carts"`
	AddToWishLists       MobileConversion `json:"mobile_conversion_add_to_wishlists"`
	CheckoutsInitiated   MobileConversion `json:"mobile_conversion_checkouts_initiated"`
	ContentViews         MobileConversion `json:"mobile_conversion_content_views"`
	Downloads            MobileConversion `json:"mobile_conversion_downloads"`
	Installs             MobileConversion `json:"mobile_conversion_installs"`
	Invites              MobileConversion `json:"mobile_conversion_invites"`
	KeyPageViews         MobileConversion `json:"mobile_conversion_key_page_views"`
	LevelsAchieved       MobileConversion `json:"mobile_conversion_levels_achieved"`
	Logins               MobileConversion `json:"mobile_conversion_logins"`
	PaymentInfoAdditions MobileConversion `json:"mobile_conversion_payment_info_additions"`
	Purchases            MobileConversion `json:"mobile_conversion_purchases"`
	Rates                MobileConversion `json:"mobile_conversion_rates"`
	ReEngages            MobileConversion `json:"mobile_conversion_re_engages"`
	Reservations         MobileConversion `json:"mobile_conversion_reservations"`
	Searches             MobileConversion `json:"mobile_conversion_searches"`
	Shares               MobileConversion `json:"mobile_conversion_shares"`
	SignUps              MobileConversion `json:"mobile_conversion_sign_ups"`
	SiteVisits           MobileConversion `json:"mobile_conversion_site_visits"`
	SpentCredits         MobileConversion `json:"mobile_conversion_spent_credits"`
	TutorialsCompleted   MobileConversion `json:"mobile_conversion_tutorials_completed"`
	Updates              MobileConversion `json:"mobile_conversion_updates"`
}

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 Pagination

type Pagination struct {
	DataType   string      `json:"data_type"`
	NextCursor string      `json:"next_cursor"`
	TotalCount int64       `json:"total_count"`
	Request    interface{} `json:"request"`
}

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 PromotedTweet

type PromotedTweet struct {
	Data PromotedTweetModel `json:"data"`
	Pagination
}

type PromotedTweetModel

type PromotedTweetModel struct {
	Id             string    `json:"id"`
	TweetId        string    `json:"tweet_id"`
	LineItemId     string    `json:"line_item_id"`
	Paused         bool      `json:"paused"`
	Deleted        bool      `json:"deleted"`
	Cancelled      bool      `json:"cancelled"`
	ApprovalStatus string    `json:"approval_status"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

type PromotedTweets

type PromotedTweets struct {
	Data []PromotedTweetModel `json:"data"`
	Pagination
}

type Relationship

type Relationship struct {
	Target Target `json:"target"`
	Source Source `json:"source"`
}

type RelationshipResponse

type RelationshipResponse struct {
	Relationship Relationship `json:"relationship"`
}

type SearchMetadata

type SearchMetadata struct {
	CompletedIn   float32 `json:"completed_in"`
	MaxId         int64   `json:"max_id"`
	MaxIdString   string  `json:"max_id_str"`
	Query         string  `json:"query"`
	RefreshUrl    string  `json:"refresh_url"`
	Count         int     `json:"count"`
	SinceId       int64   `json:"since_id"`
	SinceIdString string  `json:"since_id_str"`
	NextResults   string  `json:"next_results"`
}

type SearchResponse

type SearchResponse struct {
	Statuses []Tweet        `json:"statuses"`
	Metadata SearchMetadata `json:"search_metadata"`
}

func (*SearchResponse) GetNext

func (sr *SearchResponse) GetNext(a *TwitterApi) (SearchResponse, error)

type SegmentType

type SegmentType struct {
	SegmentName  string `json:"segment_name"`
	SegmentValue string `json:"segment_value"`
}

type Settings

type Settings struct {
	AlwaysUseHTTPS           bool            `json:"always_use_https"`
	DiscoverableByEmail      bool            `json:"discoverable_by_email"`
	GeoEnabled               bool            `json:"geo_enabled"`
	Language                 string          `json:"language"`
	Protected                bool            `json:"protected"`
	ScreenName               string          `json:"screen_name"`
	ShowAllInlineMedia       bool            `json:"show_all_inline_media"`
	SleepTime                SleepTime       `json:"sleep_time"`
	TimeZone                 TimeZone        `json:"time_zone"`
	Locations                []TrendLocation `json:"trend_location"`
	UseCookiePersonalization bool            `json:"use_cookie_personalization"`
	AllowContributorRequest  string          `json:"allow_contributor_request"`
}

type SleepTime

type SleepTime struct {
	Enabled   bool         `json:"enabled"`
	EndTime   sql.NullTime `json:"end_time"`
	StartTime sql.NullTime `json:"start_time"`
}

type Source

type Source struct {
	Id                    int64
	Id_str                string
	Screen_name           string
	Following             bool
	Followed_by           bool
	Can_dm                bool
	Blocking              bool
	Muting                bool
	Marked_spam           bool
	All_replies           bool
	Want_retweets         bool
	Notifications_enabled bool
}

type StallWarning

type StallWarning struct {
	Code        string `json:"code"`
	Message     string `json:"message"`
	PercentFull int64  `json:"percent_full"`
}

type Stats

type Stats struct {
	Data             []StatsModel `json:"data"`
	DataType         string       `json:"data_type"`
	NextCursor       string       `json:"next_cursor"`
	TimeSeriesLength int64        `json:"time_series_length"`
	Request          StatsRequest `json:"request"`
}

type StatsModel

type StatsModel struct {
	Id     string    `json:"id"`
	IdData []Metrics `json:"id_data"`
}

type StatsParams

type StatsParams struct {
	Entity       string        `json:"entity"`
	EntityIds    []json.Number `json:"entity_ids"`
	Segmentation string        `json:"segmentation_type"`
	Placement    string        `json:"placement"`
	Granularity  string        `json:"granularity"`
	Platform     string        `json:"platform"`
	Country      string        `json:"country"`
	MetricGroups []string      `json:"metric_groups"`
	StartTime    time.Time     `json:"start_time"`
	EndTime      time.Time     `json:"end_time"`
}

type StatsRequest

type StatsRequest struct {
	Params StatsParams `json:"params"`
}

type StatusDeletionNotice

type StatusDeletionNotice struct {
	Id        int64  `json:"id"`
	IdStr     string `json:"id_str"`
	UserId    int64  `json:"user_id"`
	UserIdStr string `json:"user_id_str"`
}

type StatusWithheldNotice

type StatusWithheldNotice struct {
	Id                  int64    `json:"id"`
	UserId              int64    `json:"user_id"`
	WithheldInCountries []string `json:"withheld_in_countries"`
}

type Stream

type Stream struct {
	C chan interface{}
	// contains filtered or unexported fields
}

func (*Stream) Stop

func (s *Stream) Stop()

type Target

type Target struct {
	Id          int64  `json:"id"`
	Id_str      string `json:"id_str"`
	Screen_name string `json:"screen_name"`
	Following   bool   `json:"following"`
	Followed_by bool   `json:"followed_by"`
}

type TargetingCriteria

type TargetingCriteria struct {
	Data []TargetingCriteriaModel `json:"data"`
	Pagination
}

type TargetingCriteriaModel

type TargetingCriteriaModel struct {
	Id             string      `json:"id"`
	Name           string      `json:"name"`
	AccountId      string      `json:"account_id"`
	LineItemId     string      `json:"line_item_id"`
	TargetingType  string      `json:"targeting_type"`
	TargetingValue json.Number `json:"targeting_value"`
	LocationType   string      `json:"location_type"`
	Deleted        bool        `json:"deleted"`
	UpdatedAt      time.Time   `json:"updated_at"`
	CreatedAt      time.Time   `json:"created_at"`
}

type TimeZone

type TimeZone struct {
	Name       string `json:"name"`
	TzInfoName string `json:"tzinfo_name"`
	UtcOffset  int64  `json:"utc_offset"`
}

type TooManyFollow

type TooManyFollow struct {
	Warning *struct {
		Code    string `json:"code"`
		Message string `json:"message"`
		UserId  int64  `json:"user_id"`
	} `json:"warning"`
}

type Trend

type Trend struct {
	Name            string `json:"name"`
	Query           string `json:"query"`
	Url             string `json:"url"`
	PromotedContent string `json:"promoted_content"`
}

type TrendLocation

type TrendLocation struct {
	Country     string `json:"country"`
	CountryCode string `json:"countryCode"`
	Name        string `json:"name"`
	ParentId    int    `json:"parentid"`
	PlaceType   struct {
		Code int    `json:"code"`
		Name string `json:"name"`
	} `json:"placeType"`
	Url   string `json:"url"`
	Woeid int32  `json:"woeid"`
}

type TrendResponse

type TrendResponse struct {
	Trends    []Trend    `json:"trends"`
	AsOf      string     `json:"as_of"`
	CreatedAt string     `json:"created_at"`
	Locations []Location `json:"locations"`
}

type Tweet

type Tweet struct {
	Contributors         []int64                `json:"contributors"` // Not yet generally available to all, so hard to test
	Coordinates          *Coordinates           `json:"coordinates"`
	CreatedAt            string                 `json:"created_at"`
	Entities             Entities               `json:"entities"`
	ExtendedEntities     Entities               `json:"extended_entities"`
	FavoriteCount        int                    `json:"favorite_count"`
	Favorited            bool                   `json:"favorited"`
	FilterLevel          string                 `json:"filter_level"`
	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"`
	Lang                 string                 `json:"lang"`
	Place                Place                  `json:"place"`
	PossiblySensitive    bool                   `json:"possibly_sensitive"`
	RetweetCount         int                    `json:"retweet_count"`
	Retweeted            bool                   `json:"retweeted"`
	RetweetedStatus      *Tweet                 `json:"retweeted_status"`
	Source               string                 `json:"source"`
	Scopes               map[string]interface{} `json:"scopes"`
	Text                 string                 `json:"text"`
	Truncated            bool                   `json:"truncated"`
	User                 User                   `json:"user"`
	WithheldCopyright    bool                   `json:"withheld_copyright"`
	WithheldInCountries  []string               `json:"withheld_in_countries"`
	WithheldScope        string                 `json:"withheld_scope"`
}

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

func (Tweet) HasCoordinates

func (t Tweet) HasCoordinates() bool

HasCoordinates is a helper function to easily determine if a Tweet has coordinates associated with it

func (Tweet) Latitude

func (t Tweet) Latitude() (float64, error)

Latitude is a convenience wrapper that returns the latitude easily

func (Tweet) Longitude

func (t Tweet) Longitude() (float64, error)

Longitude is a convenience wrapper that returns the longitude easily

func (Tweet) X

func (t Tweet) X() (float64, error)

X is a concenience wrapper which returns the X (Longitude) coordinate easily

func (Tweet) Y

func (t Tweet) Y() (float64, error)

Y is a convenience wrapper which return the Y (Lattitude) corrdinate easily

type TwitterApi

type TwitterApi struct {
	Credentials *oauth.Credentials

	HttpClient *http.Client

	// Currently used only for the streaming API
	// and for checking rate-limiting headers
	// Default logger is silent
	Log Logger
	// 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) AddUserToList

func (a TwitterApi) AddUserToList(screenName string, listID int64, v url.Values) (users []User, err error)

AddUserToList implements /lists/members/create.json

func (TwitterApi) Block

func (a TwitterApi) Block(v url.Values) (user User, err error)

func (TwitterApi) BlockUser

func (a TwitterApi) BlockUser(screenName string, v url.Values) (user User, err error)

func (TwitterApi) BlockUserId

func (a TwitterApi) BlockUserId(id int64, v url.Values) (user User, err error)

func (*TwitterApi) Close

func (c *TwitterApi) Close()

Close query queue

func (TwitterApi) CreateList

func (a TwitterApi) CreateList(name, description string, v url.Values) (list List, err error)

CreateList implements /lists/create.json

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) Favorite

func (a TwitterApi) Favorite(id int64) (rt Tweet, err error)

Favorite will favorite the status (tweet) with the specified ID. https://dev.twitter.com/docs/api/1.1/post/favorites/create

func (TwitterApi) FollowUser

func (a TwitterApi) FollowUser(screenName string) (user User, err error)

FollowUserId follows the user with the specified screenname (username). This implements the /friendships/create endpoint, though the function name uses the terminology 'follow' as this is most consistent with colloquial Twitter terminology.

func (TwitterApi) FollowUserId

func (a TwitterApi) FollowUserId(userId int64, v url.Values) (user User, err error)

FollowUserId follows the user with the specified userId. This implements the /friendships/create endpoint, though the function name uses the terminology 'follow' as this is most consistent with colloquial Twitter terminology.

func (TwitterApi) GeoSearch

func (a TwitterApi) GeoSearch(v url.Values) (c GeoSearchResult, err error)

func (TwitterApi) GetAccountById

func (a TwitterApi) GetAccountById(id string, values url.Values) (account Account, err error)

func (TwitterApi) GetAccountSettings

func (a TwitterApi) GetAccountSettings(v url.Values) (s Settings, err error)

Returns settings for the authenticating user.

func (TwitterApi) GetAccountStats

func (a TwitterApi) GetAccountStats(id string, values url.Values) (stats Stats, err error)

func (TwitterApi) GetAccountVideoById

func (a TwitterApi) GetAccountVideoById(accountid, videoid string, values url.Values) (video AccountVideo, err error)

func (TwitterApi) GetAccountVideos

func (a TwitterApi) GetAccountVideos(accountid string, values url.Values) (videos AccountVideos, err error)

func (TwitterApi) GetAccounts

func (a TwitterApi) GetAccounts(values url.Values) (accounts Accounts, err error)

func (TwitterApi) GetAllCampaigns

func (a TwitterApi) GetAllCampaigns(accountid string, values url.Values) (campaigns Campaigns, err error)

func (TwitterApi) GetAllFundingInstruments

func (a TwitterApi) GetAllFundingInstruments(accountid string, values url.Values) (instruments FundingInstruments, err error)

func (TwitterApi) GetAllLineItems

func (a TwitterApi) GetAllLineItems(accountid string, values url.Values) (items LineItems, err error)

func (TwitterApi) GetAllMediaCreatives

func (a TwitterApi) GetAllMediaCreatives(accountid string, values url.Values) (creatives MediaCreatives, err error)

func (TwitterApi) GetAllPromotedTweets

func (a TwitterApi) GetAllPromotedTweets(accountid string, values url.Values) (tweets PromotedTweets, err error)

func (TwitterApi) GetBlocksIds

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

func (TwitterApi) GetBlocksList

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

func (TwitterApi) GetCampaignById

func (a TwitterApi) GetCampaignById(accountid, campaignid string, values url.Values) (campaign Campaign, err error)

func (TwitterApi) GetCampaigns

func (a TwitterApi) GetCampaigns(accountid string, values url.Values) (campaigns Campaigns, err error)

func (TwitterApi) GetConfiguration

func (a TwitterApi) GetConfiguration(v url.Values) (conf Configuration, err error)

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) GetFavorites

func (a TwitterApi) GetFavorites(v url.Values) (favorites []Tweet, err error)

func (TwitterApi) GetFollowersIds

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

func (TwitterApi) GetFollowersIdsAll

func (a TwitterApi) GetFollowersIdsAll(v url.Values) (result chan FollowersIdsPage)

Like GetFollowersIds, 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) 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) GetFollowersUser

func (a TwitterApi) GetFollowersUser(id int64, v url.Values) (c Cursor, err error)

func (TwitterApi) GetFriendsIds

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

func (TwitterApi) GetFriendsIdsAll

func (a TwitterApi) GetFriendsIdsAll(v url.Values) (result chan FriendsIdsPage)

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) GetFriendsList

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

func (TwitterApi) GetFriendsListAll

func (a TwitterApi) GetFriendsListAll(v url.Values) (result chan FriendsPage)

Like GetFriendsList, 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) GetFriendsUser

func (a TwitterApi) GetFriendsUser(id int64, v url.Values) (c Cursor, err error)

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) GetFriendshipsShow

func (a TwitterApi) GetFriendshipsShow(v url.Values) (relationshipResponse RelationshipResponse, err error)

func (TwitterApi) GetFundingInstrumentById

func (a TwitterApi) GetFundingInstrumentById(accountid, instrumentid string, values url.Values) (instrument FundingInstrument, err error)

func (TwitterApi) GetFundingInstruments

func (a TwitterApi) GetFundingInstruments(accountid string, values url.Values) (instruments FundingInstruments, err error)

func (TwitterApi) GetHomeTimeline

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

GetHomeTimeline returns the most recent tweets and retweets posted by the user and the users that they follow. https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline By default, include_entities is set to "true"

func (TwitterApi) GetLineItemById

func (a TwitterApi) GetLineItemById(accountid, itemid string, values url.Values) (item LineItem, err error)

func (TwitterApi) GetLineItems

func (a TwitterApi) GetLineItems(accountid string, values url.Values) (items LineItems, err error)

func (TwitterApi) GetListTweets

func (a TwitterApi) GetListTweets(listID int64, includeRTs bool, v url.Values) (tweets []Tweet, err error)

func (TwitterApi) GetListsOwnedBy

func (a TwitterApi) GetListsOwnedBy(userID int64, v url.Values) (lists []List, err error)

GetListsOwnedBy implements /lists/ownerships.json screen_name, count, and cursor are all optional values

func (TwitterApi) GetMediaCreativeById

func (a TwitterApi) GetMediaCreativeById(accountid, creativeid string, values url.Values) (creative MediaCreative, err error)

func (TwitterApi) GetMediaCreatives

func (a TwitterApi) GetMediaCreatives(accountid string, values url.Values) (creatives MediaCreatives, err error)

func (TwitterApi) GetMentionsTimeline

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

func (TwitterApi) GetMutedUsersIds

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

func (TwitterApi) GetMutedUsersList

func (a TwitterApi) GetMutedUsersList(v url.Values) (c UserCursor, 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) GetPromotedTweetById

func (a TwitterApi) GetPromotedTweetById(accountid, tweetid string, values url.Values) (tweet PromotedTweet, err error)

func (TwitterApi) GetPromotedTweets

func (a TwitterApi) GetPromotedTweets(accountid string, values url.Values) (tweets PromotedTweets, err error)

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) (sr SearchResponse, err error)
Example
package main

import (
	"fmt"

	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.Statuses {
		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) GetStatsJobs

func (a TwitterApi) GetStatsJobs(idaccount string, values url.Values) (jobs Jobs, err error)

func (TwitterApi) GetTargetingCriteria

func (a TwitterApi) GetTargetingCriteria(accountid string, values url.Values) (tc TargetingCriteria, err error)

func (TwitterApi) GetTrendsAvailableLocations

func (a TwitterApi) GetTrendsAvailableLocations(v url.Values) (locations []TrendLocation, err error)

https://dev.twitter.com/rest/reference/get/trends/available

func (TwitterApi) GetTrendsByPlace

func (a TwitterApi) GetTrendsByPlace(id int64, v url.Values) (trendResp TrendResponse, err error)

https://dev.twitter.com/rest/reference/get/trends/place

func (TwitterApi) GetTrendsClosestLocations

func (a TwitterApi) GetTrendsClosestLocations(lat float64, long float64, v url.Values) (locations []TrendLocation, err error)

https://dev.twitter.com/rest/reference/get/trends/closest

func (TwitterApi) GetTweet

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

func (TwitterApi) GetTweetsLookupByIds

func (a TwitterApi) GetTweetsLookupByIds(ids []int64, v url.Values) (tweet []Tweet, err error)

func (TwitterApi) GetUserSearch

func (a TwitterApi) GetUserSearch(searchTerm string, v url.Values) (u []User, 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) GetUsersShow

func (a TwitterApi) GetUsersShow(username string, v url.Values) (u User, err error)

func (TwitterApi) GetUsersShowById

func (a TwitterApi) GetUsersShowById(id int64, v url.Values) (u User, err error)

func (TwitterApi) Mute

func (a TwitterApi) Mute(v url.Values) (user User, err error)

func (TwitterApi) MuteUser

func (a TwitterApi) MuteUser(screenName string, v url.Values) (user User, err error)

func (TwitterApi) MuteUserId

func (a TwitterApi) MuteUserId(id int64, v url.Values) (user User, err error)

func (TwitterApi) ParseStatsJobs

func (a TwitterApi) ParseStatsJobs(url string) (stats Stats, err error)

func (TwitterApi) PostDMToScreenName

func (a TwitterApi) PostDMToScreenName(text, screenName string) (message DirectMessage, err error)

https://dev.twitter.com/docs/api/1.1/post/direct_messages/new

func (TwitterApi) PostDMToUserId

func (a TwitterApi) PostDMToUserId(text string, userId int64) (message DirectMessage, err error)

https://dev.twitter.com/docs/api/1.1/post/direct_messages/new

func (TwitterApi) PostStatsJobs

func (a TwitterApi) PostStatsJobs(idaccount string, values url.Values) (job Job, 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) PublicStreamFilter

func (a TwitterApi) PublicStreamFilter(v url.Values) (stream *Stream)

XXX: PublicStream(Track|Follow|Locations) func is needed?

func (TwitterApi) PublicStreamFirehose

func (a TwitterApi) PublicStreamFirehose(v url.Values) (stream *Stream)

XXX: To use this API authority is requied. but I dont have this. I cant test.

func (TwitterApi) PublicStreamSample

func (a TwitterApi) PublicStreamSample(v url.Values) (stream *Stream)

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) SetBaseUrl

func (c *TwitterApi) SetBaseUrl(baseUrl string)

SetBaseUrl is experimental and may be removed in future releases.

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) SetLogger

func (c *TwitterApi) SetLogger(l Logger)

SetLogger sets the Logger used by the API client. The default logger is silent. BasicLogger will log to STDERR using the log package from the standard library.

func (TwitterApi) SiteStream

func (a TwitterApi) SiteStream(v url.Values) (stream *Stream)

XXX: To use this API authority is requied. but I dont have this. I cant test.

func (TwitterApi) Unblock

func (a TwitterApi) Unblock(v url.Values) (user User, err error)

func (TwitterApi) UnblockUser

func (a TwitterApi) UnblockUser(screenName string, v url.Values) (user User, err error)

func (TwitterApi) UnblockUserId

func (a TwitterApi) UnblockUserId(id int64, v url.Values) (user User, err error)

func (TwitterApi) Unfavorite

func (a TwitterApi) Unfavorite(id int64) (rt Tweet, err error)

Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. https://dev.twitter.com/docs/api/1.1/post/favorites/destroy

func (TwitterApi) UnfollowUser

func (a TwitterApi) UnfollowUser(screenname string) (u User, err error)

UnfollowUser unfollows the user with the specified screenname (username) This implements the /friendships/destroy endpoint, though the function name uses the terminology 'unfollow' as this is most consistent with colloquial Twitter terminology.

func (TwitterApi) UnfollowUserId

func (a TwitterApi) UnfollowUserId(userId int64) (u User, err error)

UnfollowUserId unfollows the user with the specified userId. This implements the /friendships/destroy endpoint, though the function name uses the terminology 'unfollow' as this is most consistent with colloquial Twitter terminology.

func (TwitterApi) Unmute

func (a TwitterApi) Unmute(v url.Values) (user User, err error)

func (TwitterApi) UnmuteUser

func (a TwitterApi) UnmuteUser(screenName string, v url.Values) (user User, err error)

func (TwitterApi) UnmuteUserId

func (a TwitterApi) UnmuteUserId(id int64, v url.Values) (user User, err error)

func (TwitterApi) UploadMedia

func (a TwitterApi) UploadMedia(base64String string) (media Media, err error)

func (TwitterApi) UploadVideoAppend

func (a TwitterApi) UploadVideoAppend(mediaIdString string,
	segmentIndex int, base64String string) error

func (TwitterApi) UploadVideoFinalize

func (a TwitterApi) UploadVideoFinalize(mediaIdString string) (videoMedia VideoMedia, err error)

func (TwitterApi) UploadVideoInit

func (a TwitterApi) UploadVideoInit(totalBytes int, mimeType string) (chunkedMedia ChunkedMedia, err error)

func (TwitterApi) UserStream

func (a TwitterApi) UserStream(v url.Values) (stream *Stream)

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 UrlEntity

type UrlEntity struct {
	Urls []struct {
		Indices      []int
		Url          string
		Display_url  string
		Expanded_url string
	}
}

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"`
	Entities                       Entities `json:"entities"`
	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"` // BCP-47 code of user defined language
	ListedCount                    int64    `json:"listed_count"`
	Location                       string   `json:"location"` // User defined 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"`
	ProfileBannerURL               string   `json:"profile_banner_url"`
	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"` // From UTC in seconds
	UtcOffset                      int      `json:"utc_offset"`
	Verified                       bool     `json:"verified"`
	WithheldInCountries            []string `json:"withheld_in_countries"`
	WithheldScope                  string   `json:"withheld_scope"`
}

type UserCursor

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

type UserWithheldNotice

type UserWithheldNotice struct {
	Id                  int64    `json:"id"`
	WithheldInCountries []string `json:"withheld_in_countries"`
}

type Variant

type Variant struct {
	Bitrate     int    `json:"bitrate"`
	ContentType string `json:"content_type"`
	Url         string `json:"url"`
}

type Video

type Video struct {
	VideoType string `json:"video_type"`
}

type VideoInfo

type VideoInfo struct {
	AspectRatio    []int     `json:"aspect_ratio"`
	DurationMillis int64     `json:"duration_millis"`
	Variants       []Variant `json:"variants"`
}

type VideoMedia

type VideoMedia struct {
	MediaID          int64  `json:"media_id"`
	MediaIDString    string `json:"media_id_string"`
	Size             int    `json:"size"`
	ExpiresAfterSecs int    `json:"expires_after_secs"`
	Video            Video  `json:"video"`
}

type VideoModel

type VideoModel struct {
	Id                 string    `json:"id"`
	Title              string    `json:"title"`
	Tweeted            bool      `json:"tweeted"`
	ReadyToTweet       bool      `json:"ready_to_tweet"`
	Deleted            bool      `json:"deleted"`
	Duration           int64     `json:"duration"`
	Description        string    `json:"description"`
	PreviewUrl         string    `json:"preview_url"`
	ReasonsNotServable []string  `json:"reasons_not_servable"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
}

type WebMetrics

type WebMetrics struct {
	ConversionCustom     ConversionType `json:"conversion_custom"`
	ConversionDownloads  ConversionType `json:"conversion_downloads"`
	ConversionPurchases  ConversionType `json:"conversion_purchases"`
	ConversionSignUps    ConversionType `json:"conversion_sign_ups"`
	ConversionSiteVisits ConversionType `json:"conversion_site_visits"`
}

Jump to

Keyboard shortcuts

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