twitter

package
v0.0.0-...-38187bb Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2021 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package twitter provides a Client for the Twitter API.

The twitter package provides a Client for accessing the Twitter API. Here are some example requests.

// Twitter client
client := twitter.NewClient(httpClient)
// Home Timeline
tweets, resp, err := client.Timelines.HomeTimeline(&HomeTimelineParams{})
// Send a Tweet
tweet, resp, err := client.Statuses.Update("just setting up my twttr", nil)
// Status Show
tweet, resp, err := client.Statuses.Show(585613041028431872, nil)
// User Show
params := &twitter.UserShowParams{ScreenName: "dghubble"}
user, resp, err := client.Users.Show(params)
// Followers
followers, resp, err := client.Followers.List(&FollowerListParams{})

Required parameters are passed as positional arguments. Optional parameters are passed in a typed params struct (or pass nil).

Authentication

By design, the Twitter Client accepts any http.Client so user auth (OAuth1) or application auth (OAuth2) requests can be made by using the appropriate authenticated client. Use the https://github.com/dghubble/oauth1 and https://github.com/golang/oauth2 packages to obtain an http.Client which transparently authorizes requests.

For example, make requests as a consumer application on behalf of a user who has granted access, with OAuth1.

// OAuth1
import (
	"github.com/dghubble/go-twitter/twitter"
	"github.com/dghubble/oauth1"
)

config := oauth1.NewConfig("consumerKey", "consumerSecret")
token := oauth1.NewToken("accessToken", "accessSecret")
// http.Client will automatically authorize Requests
httpClient := config.Client(oauth1.NoContext, token)

// twitter client
client := twitter.NewClient(httpClient)

If no user auth context is needed, make requests as your application with application auth.

// OAuth2
import (
	"github.com/dghubble/go-twitter/twitter"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/clientcredentials"
)

// oauth2 configures a client that uses app credentials to keep a fresh token
config := &clientcredentials.Config{
	ClientID:     flags.consumerKey,
	ClientSecret: flags.consumerSecret,
	TokenURL:     "https://api.twitter.com/oauth2/token",
}
// http.Client will automatically authorize Requests
httpClient := config.Client(oauth2.NoContext)

// Twitter client
client := twitter.NewClient(httpClient)

To implement Login with Twitter, see https://github.com/dghubble/gologin.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a new pointer to the given bool value.

func Float

func Float(v float64) *float64

Float returns a new pointer to the given float64 value.

Types

type APIError

type APIError struct {
	Errors []ErrorDetail `json:"errors"`
}

APIError represents a Twitter API Error response https://dev.twitter.com/overview/api/response-codes

func (APIError) Empty

func (e APIError) Empty() bool

Empty returns true if empty. Otherwise, at least 1 error message/code is present and false is returned.

func (APIError) Error

func (e APIError) Error() string

type BoundingBox

type BoundingBox struct {
	Coordinates [][][2]float64 `json:"coordinates"`
	Type        string         `json:"type"`
}

BoundingBox represents the bounding coordinates (longitude, latitutde) defining the bounds of a box containing a Place entity.

type Client

type Client struct {

	// Twitter API Services
	Media    *MediaService
	Statuses *StatusService
	// contains filtered or unexported fields
}

Client is a Twitter client for making Twitter API requests.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient returns a new Client.

type Coordinates

type Coordinates struct {
	Coordinates [2]float64 `json:"coordinates"`
	Type        string     `json:"type"`
}

Coordinates are pairs of longitude and latitude locations.

type Demux

type Demux interface {
	Handle(message interface{})
	HandleChan(messages <-chan interface{})
}

A Demux receives interface{} messages individually or from a channel and sends those messages to one or more outputs determined by the implementation.

type Entities

type Entities struct {
	Hashtags     []HashtagEntity `json:"hashtags"`
	Media        []MediaEntity   `json:"media"`
	Urls         []URLEntity     `json:"urls"`
	UserMentions []MentionEntity `json:"user_mentions"`
}

Entities represent metadata and context info parsed from Twitter components. https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/entities-object TODO: symbols

type ErrorDetail

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

ErrorDetail represents an individual item in an APIError.

type ExtendedEntity

type ExtendedEntity struct {
	Media []MediaEntity `json:"media"`
}

ExtendedEntity contains media information. https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/extended-entities-object

type ExtendedTweet

type ExtendedTweet struct {
	FullText         string          `json:"full_text"`
	DisplayTextRange Indices         `json:"display_text_range"`
	Entities         *Entities       `json:"entities"`
	ExtendedEntities *ExtendedEntity `json:"extended_entities"`
}

ExtendedTweet represents fields embedded in extended Tweets when served in compatibility mode (default). https://dev.twitter.com/overview/api/upcoming-changes-to-tweets

type HashtagEntity

type HashtagEntity struct {
	Indices Indices `json:"indices"`
	Text    string  `json:"text"`
}

HashtagEntity represents a hashtag which has been parsed from text.

type Indices

type Indices [2]int

Indices represent the start and end offsets within text.

func (Indices) End

func (i Indices) End() int

End returns the index at which an entity ends, exclusive.

func (Indices) Start

func (i Indices) Start() int

Start returns the index at which an entity starts, inclusive.

type MediaEntity

type MediaEntity struct {
	URLEntity
	ID                int64      `json:"id"`
	IDStr             string     `json:"id_str"`
	MediaURL          string     `json:"media_url"`
	MediaURLHttps     string     `json:"media_url_https"`
	SourceStatusID    int64      `json:"source_status_id"`
	SourceStatusIDStr string     `json:"source_status_id_str"`
	Type              string     `json:"type"`
	Sizes             MediaSizes `json:"sizes"`
	VideoInfo         VideoInfo  `json:"video_info"`
}

MediaEntity represents media elements associated with a Tweet.

type MediaProcessingError

type MediaProcessingError struct {
	Code    int    `json:"code"`
	Name    string `json:"name"`
	Message string `json:"message"`
}

MediaProcessingError holds information about pending media processing failures.

type MediaProcessingInfo

type MediaProcessingInfo struct {
	State           string                `json:"state"`
	CheckAfterSecs  int                   `json:"check_after_secs"`
	ProgressPercent int                   `json:"progress_percent"`
	Error           *MediaProcessingError `json:"error"`
}

MediaProcessingInfo holds information about pending media uploads.

type MediaService

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

MediaService provides methods for accessing twitter media APIs.

func (*MediaService) Status

func (m *MediaService) Status(mediaID int64) (*MediaStatusResult, *http.Response, error)

Status returns the current status of the media specified by the media ID. It's only valid to call Status on a request where the Upload call returned something in ProcessingInfo. https://developer.twitter.com/en/docs/media/upload-media/api-reference/get-media-upload-status

func (*MediaService) Upload

func (m *MediaService) Upload(media []byte, mediaType string) (*MediaUploadResult, *http.Response, error)

Upload sends a piece of media to twitter. You must provide a byte slice containing the file contents and the MIME type of the file.

This is a potentially asynchronous call, as some file types require extra processing by twitter. In those cases the returned MediaFinalizeResult will have the ProcessingInfo field set, and you can periodically poll Status with the MediaID to get the status of the upload.

type MediaSize

type MediaSize struct {
	Width  int    `json:"w"`
	Height int    `json:"h"`
	Resize string `json:"resize"`
}

MediaSize describes the height, width, and resizing method used.

type MediaSizes

type MediaSizes struct {
	Thumb  MediaSize `json:"thumb"`
	Large  MediaSize `json:"large"`
	Medium MediaSize `json:"medium"`
	Small  MediaSize `json:"small"`
}

MediaSizes contain the different size media that are available. https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/entities-object#media-size

type MediaStatusResult

type MediaStatusResult struct {
	MediaID          int                  `json:"media_id"`
	MediaIDString    string               `json:"media_id_string"`
	ExpiresAfterSecs int                  `json:"expires_after_secs"`
	ProcessingInfo   *MediaProcessingInfo `json:"processing_info"`
	Video            *MediaVideoInfo      `json:"video"`
}

MediaStatusResult holds information about the current status of a piece of media.

type MediaUploadResult

type MediaUploadResult struct {
	MediaID          int64                `json:"media_id"`
	MediaIDString    string               `json:"media_id_string"`
	Size             int                  `json:"size"`
	ExpiresAfterSecs int                  `json:"expires_after_secs"`
	Video            *MediaVideoInfo      `json:"video"`
	ProcessingInfo   *MediaProcessingInfo `json:"processing_info"`
}

MediaUploadResult holds information about a successfully completed media upload. Note that successful uploads may not be immediately usable if twitter is doing background processing on the uploaded media.

type MediaVideoInfo

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

MediaVideoInfo holds information about media identified as videos.

type MentionEntity

type MentionEntity struct {
	Indices    Indices `json:"indices"`
	ID         int64   `json:"id"`
	IDStr      string  `json:"id_str"`
	Name       string  `json:"name"`
	ScreenName string  `json:"screen_name"`
}

MentionEntity represents Twitter user mentions parsed from text.

type OEmbedTweet

type OEmbedTweet struct {
	URL          string `json:"url"`
	ProviderURL  string `json:"provider_url"`
	ProviderName string `json:"provider_name"`
	AuthorName   string `json:"author_name"`
	Version      string `json:"version"`
	AuthorURL    string `json:"author_url"`
	Type         string `json:"type"`
	HTML         string `json:"html"`
	Height       int64  `json:"height"`
	Width        int64  `json:"width"`
	CacheAge     string `json:"cache_age"`
}

OEmbedTweet represents a Tweet in oEmbed format.

type Place

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

Place represents a Twitter Place / Location https://dev.twitter.com/overview/api/places

type RateLimit

type RateLimit struct {
	RateLimitContext *RateLimitContext   `json:"rate_limit_context"`
	Resources        *RateLimitResources `json:"resources"`
}

RateLimit summarizes current rate limits of resource families.

type RateLimitContext

type RateLimitContext struct {
	AccessToken string `json:"access_token"`
}

RateLimitContext contains auth context

type RateLimitParams

type RateLimitParams struct {
	Resources []string `url:"resources,omitempty,comma"`
}

RateLimitParams are the parameters for RateLimitService.Status.

type RateLimitResource

type RateLimitResource struct {
	Limit     int `json:"limit"`
	Remaining int `json:"remaining"`
	Reset     int `json:"reset"`
}

RateLimitResource contains limit status data for a single endpoint

type RateLimitResources

type RateLimitResources struct {
	Application map[string]*RateLimitResource `json:"application"`
	Favorites   map[string]*RateLimitResource `json:"favorites"`
	Followers   map[string]*RateLimitResource `json:"followers"`
	Friends     map[string]*RateLimitResource `json:"friends"`
	Friendships map[string]*RateLimitResource `json:"friendships"`
	Geo         map[string]*RateLimitResource `json:"geo"`
	Help        map[string]*RateLimitResource `json:"help"`
	Lists       map[string]*RateLimitResource `json:"lists"`
	Search      map[string]*RateLimitResource `json:"search"`
	Statuses    map[string]*RateLimitResource `json:"statuses"`
	Trends      map[string]*RateLimitResource `json:"trends"`
	Users       map[string]*RateLimitResource `json:"users"`
}

RateLimitResources contains all limit status data for endpoints group by resources

type RateLimitService

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

RateLimitService provides methods for accessing Twitter rate limits API endpoints.

func (*RateLimitService) Status

func (s *RateLimitService) Status(params *RateLimitParams) (*RateLimit, *http.Response, error)

Status summarizes the current rate limits of specified resource families. https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status

type StatusDestroyParams

type StatusDestroyParams struct {
	ID        int64  `url:"id,omitempty"`
	TrimUser  *bool  `url:"trim_user,omitempty"`
	TweetMode string `url:"tweet_mode,omitempty"`
}

StatusDestroyParams are the parameters for StatusService.Destroy

type StatusLookupParams

type StatusLookupParams struct {
	ID              []int64 `url:"id,omitempty,comma"`
	TrimUser        *bool   `url:"trim_user,omitempty"`
	IncludeEntities *bool   `url:"include_entities,omitempty"`
	Map             *bool   `url:"map,omitempty"`
	TweetMode       string  `url:"tweet_mode,omitempty"`
}

StatusLookupParams are the parameters for StatusService.Lookup

type StatusOEmbedParams

type StatusOEmbedParams struct {
	ID         int64  `url:"id,omitempty"`
	URL        string `url:"url,omitempty"`
	Align      string `url:"align,omitempty"`
	MaxWidth   int64  `url:"maxwidth,omitempty"`
	HideMedia  *bool  `url:"hide_media,omitempty"`
	HideThread *bool  `url:"hide_media,omitempty"`
	OmitScript *bool  `url:"hide_media,omitempty"`
	WidgetType string `url:"widget_type,omitempty"`
	HideTweet  *bool  `url:"hide_tweet,omitempty"`
}

StatusOEmbedParams are the parameters for StatusService.OEmbed

type StatusRetweetParams

type StatusRetweetParams struct {
	ID        int64  `url:"id,omitempty"`
	TrimUser  *bool  `url:"trim_user,omitempty"`
	TweetMode string `url:"tweet_mode,omitempty"`
}

StatusRetweetParams are the parameters for StatusService.Retweet

type StatusRetweetsParams

type StatusRetweetsParams struct {
	ID        int64  `url:"id,omitempty"`
	Count     int    `url:"count,omitempty"`
	TrimUser  *bool  `url:"trim_user,omitempty"`
	TweetMode string `url:"tweet_mode,omitempty"`
}

StatusRetweetsParams are the parameters for StatusService.Retweets

type StatusService

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

StatusService provides methods for accessing Twitter status API endpoints.

func (*StatusService) Destroy

func (s *StatusService) Destroy(id int64, params *StatusDestroyParams) (*Tweet, *http.Response, error)

Destroy deletes the Tweet with the given id and returns it if successful. Requires a user auth context. https://dev.twitter.com/rest/reference/post/statuses/destroy/%3Aid

func (*StatusService) Lookup

func (s *StatusService) Lookup(ids []int64, params *StatusLookupParams) ([]Tweet, *http.Response, error)

Lookup returns the requested Tweets as a slice. Combines ids from the required ids argument and from params.Id. https://dev.twitter.com/rest/reference/get/statuses/lookup

func (*StatusService) OEmbed

OEmbed returns the requested Tweet in oEmbed format. https://dev.twitter.com/rest/reference/get/statuses/oembed

func (*StatusService) Retweet

func (s *StatusService) Retweet(id int64, params *StatusRetweetParams) (*Tweet, *http.Response, error)

Retweet retweets the Tweet with the given id and returns the original Tweet with embedded retweet details. Requires a user auth context. https://dev.twitter.com/rest/reference/post/statuses/retweet/%3Aid

func (*StatusService) Retweets

func (s *StatusService) Retweets(id int64, params *StatusRetweetsParams) ([]Tweet, *http.Response, error)

Retweets returns the most recent retweets of the Tweet with the given id. https://dev.twitter.com/rest/reference/get/statuses/retweets/%3Aid

func (*StatusService) Show

func (s *StatusService) Show(id int64, params *StatusShowParams) (*Tweet, *http.Response, error)

Show returns the requested Tweet. https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid

func (*StatusService) Unretweet

func (s *StatusService) Unretweet(id int64, params *StatusUnretweetParams) (*Tweet, *http.Response, error)

Unretweet unretweets the Tweet with the given id and returns the original Tweet. Requires a user auth context. https://dev.twitter.com/rest/reference/post/statuses/unretweet/%3Aid

func (*StatusService) Update

func (s *StatusService) Update(status string, params *StatusUpdateParams) (*Tweet, *http.Response, error)

Update updates the user's status, also known as Tweeting. Requires a user auth context. https://dev.twitter.com/rest/reference/post/statuses/update

type StatusShowParams

type StatusShowParams struct {
	ID               int64  `url:"id,omitempty"`
	TrimUser         *bool  `url:"trim_user,omitempty"`
	IncludeMyRetweet *bool  `url:"include_my_retweet,omitempty"`
	IncludeEntities  *bool  `url:"include_entities,omitempty"`
	TweetMode        string `url:"tweet_mode,omitempty"`
}

StatusShowParams are the parameters for StatusService.Show

type StatusUnretweetParams

type StatusUnretweetParams struct {
	ID        int64  `url:"id,omitempty"`
	TrimUser  *bool  `url:"trim_user,omitempty"`
	TweetMode string `url:"tweet_mode,omitempty"`
}

StatusUnretweetParams are the parameters for StatusService.Unretweet

type StatusUpdateParams

type StatusUpdateParams struct {
	Status                    string   `url:"status,omitempty"`
	InReplyToStatusID         int64    `url:"in_reply_to_status_id,omitempty"`
	AutoPopulateReplyMetadata *bool    `url:"auto_populate_reply_metadata,omitempty"`
	PossiblySensitive         *bool    `url:"possibly_sensitive,omitempty"`
	Lat                       *float64 `url:"lat,omitempty"`
	Long                      *float64 `url:"long,omitempty"`
	PlaceID                   string   `url:"place_id,omitempty"`
	DisplayCoordinates        *bool    `url:"display_coordinates,omitempty"`
	TrimUser                  *bool    `url:"trim_user,omitempty"`
	MediaIds                  []int64  `url:"media_ids,omitempty,comma"`
	TweetMode                 string   `url:"tweet_mode,omitempty"`
}

StatusUpdateParams are the parameters for StatusService.Update

type SwitchDemux

type SwitchDemux struct {
	All              func(message interface{})
	Tweet            func(tweet *Tweet)
	DM               func(dm *DirectMessage)
	StatusDeletion   func(deletion *StatusDeletion)
	LocationDeletion func(LocationDeletion *LocationDeletion)
	StreamLimit      func(limit *StreamLimit)
	StatusWithheld   func(statusWithheld *StatusWithheld)
	UserWithheld     func(userWithheld *UserWithheld)
	StreamDisconnect func(disconnect *StreamDisconnect)
	Warning          func(warning *StallWarning)
	FriendsList      func(friendsList *FriendsList)
	Event            func(event *Event)
	Other            func(message interface{})
}

SwitchDemux receives messages and uses a type switch to send each typed message to a handler function.

func NewSwitchDemux

func NewSwitchDemux() SwitchDemux

NewSwitchDemux returns a new SwitchMux which has NoOp handler functions.

func (SwitchDemux) Handle

func (d SwitchDemux) Handle(message interface{})

Handle determines the type of a message and calls the corresponding receiver function with the typed message. All messages are passed to the All func. Messages with unmatched types are passed to the Other func.

func (SwitchDemux) HandleChan

func (d SwitchDemux) HandleChan(messages <-chan interface{})

HandleChan receives messages and calls the corresponding receiver function with the typed message. All messages are passed to the All func. Messages with unmatched type are passed to the Other func.

type Tweet

type Tweet struct {
	Coordinates          *Coordinates           `json:"coordinates"`
	CreatedAt            string                 `json:"created_at"`
	CurrentUserRetweet   *TweetIdentifier       `json:"current_user_retweet"`
	Entities             *Entities              `json:"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"`
	PossiblySensitive    bool                   `json:"possibly_sensitive"`
	QuoteCount           int                    `json:"quote_count"`
	ReplyCount           int                    `json:"reply_count"`
	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"`
	FullText             string                 `json:"full_text"`
	DisplayTextRange     Indices                `json:"display_text_range"`
	Place                *Place                 `json:"place"`
	Truncated            bool                   `json:"truncated"`
	User                 *User                  `json:"user"`
	WithheldCopyright    bool                   `json:"withheld_copyright"`
	WithheldInCountries  []string               `json:"withheld_in_countries"`
	WithheldScope        string                 `json:"withheld_scope"`
	ExtendedEntities     *ExtendedEntity        `json:"extended_entities"`
	ExtendedTweet        *ExtendedTweet         `json:"extended_tweet"`
	QuotedStatusID       int64                  `json:"quoted_status_id"`
	QuotedStatusIDStr    string                 `json:"quoted_status_id_str"`
	QuotedStatus         *Tweet                 `json:"quoted_status"`
}

Tweet represents a Twitter Tweet, previously called a status. https://dev.twitter.com/overview/api/tweets

func (Tweet) CreatedAtTime

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

CreatedAtTime returns the time a tweet was created.

type TweetIdentifier

type TweetIdentifier struct {
	ID    int64  `json:"id"`
	IDStr string `json:"id_str"`
}

TweetIdentifier represents the id by which a Tweet can be identified.

type URLEntity

type URLEntity struct {
	Indices     Indices `json:"indices"`
	DisplayURL  string  `json:"display_url"`
	ExpandedURL string  `json:"expanded_url"`
	URL         string  `json:"url"`
}

URLEntity represents a URL which has been parsed from text.

type UserEntities

type UserEntities struct {
	URL         Entities `json:"url"`
	Description Entities `json:"description"`
}

UserEntities contain Entities parsed from User url and description fields. https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/entities-object#mentions

type VideoInfo

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

VideoInfo is available on video media objects.

type VideoVariant

type VideoVariant struct {
	ContentType string `json:"content_type"`
	Bitrate     int    `json:"bitrate"`
	URL         string `json:"url"`
}

VideoVariant describes one of the available video formats.

Jump to

Keyboard shortcuts

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