twitter

package module
v0.0.0-...-58f04a1 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2023 License: MIT Imports: 15 Imported by: 1

README

Language Build Status GoDoc Go Report Card

Twitter API v2 Client for Go

twitter is a Go package for the Twitter v2 API, inspired by ChimeraCoder/anaconda. This library uses channels for both, to retrieve data from Twitter API and return the results, with a built-in throttle to avoid rate-limit errors return from Twitter. You can bypass the throttling by usgin twitter.WithRate(time.Duration) option. The library will auto paginate results unless you use the twitter.WithAuto(false) option.

Installation
go get github.com/cvcio/twitter
Supported Endpoints
Method Implemented OAuth Rate Limit Official Documentation
VerifyCredentials Yes OAuth 1.0a User Context, OAuth 2.0 Bearer Token - -
GetUserFollowers Yes OAuth 2.0 Bearer Token 15/15m (app), 15/15m (user) Get User Followers
GetUserFollowing Yes OAuth 2.0 Bearer Token 15/15m (app), 15/15m (user) Get User Following
GetUsers Yes OAuth 2.0 Bearer Token 300/15m (app), 900/15m (user) Get Users
GetUsersBy Yes OAuth 2.0 Bearer Token 300/15m (app), 900/15m (user) Get Users By
GetUserByID Yes OAuth 2.0 Bearer Token 300/15m (app), 900/15m (user) Get User By Id
GetUsersByUserName Yes OAuth 2.0 Bearer Token 300/15m (app), 900/15m (user) Get Users By Screen Name
GetUserTweets Yes OAuth 1.0a User Context, OAuth 2.0 Bearer Token 1500/15m (app), 900/15m (user) Get User Tweets
GetUserMentions Yes OAuth 1.0a User Context, OAuth 2.0 Bearer Token 450/15m (app), 180/15m (user) Get User Mentions
GetTweets Yes OAuth 2.0 Bearer Token 300/15m (app), 900/15m (user) Get Tweets
GetTweetByID Yes OAuth 2.0 Bearer Token 300/15m (app), 900/15m (user) Get Tweets By Id
GetFilterStream Yes OAuth 2.0 Bearer Token 50/15m (app) Filter Stream
GetFilterStreamRules Yes OAuth 2.0 Bearer Token 450/15m (app) Get Filter Stream Rules
PostFilterStreamRules Yes OAuth 2.0 Bearer Token 450/15m (app) Post Filter Stream Rules
GetSampleStream Yes OAuth 2.0 Bearer Token 50/15m (app) Sample Stream
GetTweetsSearchRecent Yes OAuth 2.0 Bearer Token 450/15m (app), 180/15m (user) Search Tweets - Recent
GetTweetsSearchAll - OAuth 2.0 Bearer Token 300/15m (app), 1/1s (user) Search Tweets - All
Usage
Authentication
api, err := twitter.NewTwitterWithContext(*consumerKey, *consumerSecret, *accessToken, *accessTokenSecret)
if err != nil {
	panic(err)
}
Methods

Each method returns 2 channels, one for results and one for errors (twitter.APIError).

v := url.Values{}
v.Add("max_results", "1000")
resultsChannel, _ := api.GetUserFollowers(*id, v)
for {
	// resultsChannel
	r, ok := <-resultsChannel
	if !ok {
		break
	}
	...
}

Implement with error channel

v := url.Values{}
v.Add("max_results", "1000")
res, errs := api.GetUserFollowing(*id, v, twitter.WithRate(time.Minute/6), twitter.WithAuto(true))

for {
	select {
	case r, ok := <-res:
		if !ok {
			res = nil
			break
		}

		var d []*twitter.User
		b, err := json.Marshal(r.Data)
		if err != nil {
			t.Fatalf("json Marshar Error: %v", err)
		}

		json.Unmarshal(b, &d)

	case e, ok := <-errs:
		if !ok {
			errs = nil
			break
		}
		t.Errorf("Twitter API Error: %v", e)
	}

	if res == nil && errs == nil {
		break
	}

}
Options

cvcio/twitter supports the following options for all methods. You can pass any option during the method contrstruction.

followers, _ := api.GetUserFollowers(*id, url.Values{}, twitter.WithDelay(1*time.Minute), twitter.WithRate(1*time.Minute) ...)
WithDealy

Adjust the the duration between each errored requests due to rate limit errors from Twitter API by using the WithDelay option.

twitter.WithDelay(time.Duration)
WithRate

Throttle requests (distinct for each method) to avoid rate limit errors from Twitter API.

twitter.WithRate(time.Duration)
WithAuto

Auto paginate results (if available) when pagination_token is present in the response object.

twitter.WithAuto(Bool)
Streaming
api, _ := twitter.NewTwitter(*consumerKey, *consumerSecret,)
rules := new(twitter.Rules)
rules.Add = append(rules.Add, &twitter.RulesData{
	Value: "greece",
	Tag:   "test-client",
})

res, _ := api.PostFilterStreamRules(nil, rules)

v := url.Values{}
v.Add("user.fields", "created_at,description,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified")
v.Add("expansions", "author_id,in_reply_to_user_id")
v.Add("tweet.fields", "created_at,id,lang,source,public_metrics")

s, _ := api.GetFilterStream(v)
for t := range s.C {
	f, _ := t.(twitter.StreamData)
	fmt.Println(f.Tweet)
	break
}
s.Stop()
Examples
// get all followers for a specific user id 
// and print the results
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"net/url"
	"time"

	"github.com/cvcio/twitter"
)

func main() {
	consumerKey := flag.String("consumer-key", "", "twitter API consumer key")
	consumerSecret := flag.String("consumer-secret", "", "twitter API consumer secret")

	id := flag.String("id", "", "user id")

	flag.Parse()

	start := time.Now()

	api, err := twitter.NewTwitter(*consumerKey, *consumerSecret)
	if err != nil {
		panic(err)
	}

	v := url.Values{}
	v.Add("max_results", "1000")
	followers, _ := api.GetUserFollowers(*id, v)

	for {
		r, ok := <-followers

		if !ok {
			break
		}

		b, err := json.Marshal(r.Data)
		if err != nil {
			panic(err)
		}

		var data []*twitter.User
		json.Unmarshal(b, &data)
		for _, v := range data {
			fmt.Printf("%s,%s,%s\n", v.ID, v.UserName, v.Name)
		}

		fmt.Println()
		fmt.Printf("Result Count: %d Next Token: %s\n", r.Meta.ResultCount, r.Meta.NextToken)
	}

	end := time.Now()

	fmt.Printf("Done in %s", end.Sub(start))
}

Contribution

If you're new to contributing to Open Source on Github, this guide can help you get started. Please check out the contribution guide for more details on how issues and pull requests work. Before contributing be sure to review the code of conduct.

Contributors

License

This library is distributed under the MIT license found in the LICENSE file.

Documentation

Index

Constants

View Source
const (
	BaseURL            = "https://api.twitter.com/2"
	RequestTokenURL    = "https://api.twitter.com/oauth/request_token"
	AuthorizeTokenURL  = "https://api.twitter.com/oauth/authorize"
	AccessTokenURL     = "https://api.twitter.com/oauth/access_token"
	TokenURL           = "https://api.twitter.com/oauth2/token"
	RateLimitStatusURL = "https://api.twitter.com/1.1/application/rate_limit_status.json"
)

Constants

Variables

This section is empty.

Functions

This section is empty.

Types

type Annotation

type Annotation struct {
	ID          string `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
}

Annotation response object.

type Attachment

type Attachment struct {
	MediaKeys []string `json:"media_keys,omitempty"`
	PollIDs   []string `json:"poll_ids,omitempty"`
}

Attachment response object.

type ContextAnnotation

type ContextAnnotation struct {
	Domain *Annotation `json:"domain,omitempty"`
	Entity *Annotation `json:"entity,omitempty"`
}

ContextAnnotation response object.

type Coordinates

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

Coordinates response object.

type Data

type Data struct {
	Data     *interface{} `json:"data,omitempty"`
	Includes *Includes    `json:"includes,omitempty"`
	Meta     *Meta        `json:"meta,omitempty"`
}

Data Struct

type EditControls

type EditControls struct {
	EditsRemaining int    `json:"edits_remaining,omitempty"`
	IsEditEligible bool   `json:"is_edit_eligible,omitempty"`
	EditableUntil  string `json:"editable_until,omitempty"`
}

type Entities

type Entities struct {
	Annotations []*EntityAnnotation `json:"annotations,omitempty"`
	URLs        []*EntityURL        `json:"urls,omitempty"`
	HashTags    []*EntityTag        `json:"hashtags,omitempty"`
	Mentions    []*EntityMention    `json:"mentions,omitempty"`
	CashTags    []*EntityTag        `json:"cashtags,omitempty"`
}

Entities response object.

type Entity

type Entity struct {
	Start int `json:"start,omitempty"`
	End   int `json:"end,omitempty"`
}

Entity response object.

type EntityAnnotation

type EntityAnnotation struct {
	*Entity
	Probability    float64 `json:"probability,omitempty"`
	Type           string  `json:"type,omitempty"`
	NormalizedText string  `json:"normalized_text,omitempty"`
}

EntityAnnotation response object.

type EntityMention

type EntityMention struct {
	*Entity
	UserName string `json:"username,omitempty"`
}

EntityMention response object.

type EntityTag

type EntityTag struct {
	*Entity
	Tag string `json:"tag,omitempty"`
}

EntityTag response object.

type EntityURL

type EntityURL struct {
	*Entity
	URL         string `json:"url,omitempty"`
	ExpandedURL string `json:"expanded_url,omitempty"`
	DisplayURL  string `json:"display_url,omitempty"`
	UnwoundURL  string `json:"unwound_url,omitempty"`
}

EntityURL response object.

type Error

type Error struct {
	Message string `json:"message,omitempty"`
	Sent    string `json:"sent.omitempty"`
}

Error response object.

type Geo

type Geo struct {
	Coordinates Coordinates `json:"coordinates,omitempty"`
	PlaceID     string      `json:"place_id,omitempty"`
}

Geo response object.

type Includes

type Includes struct {
	Tweets []*Tweet `json:"tweets,omitempty"`
	Users  []*User  `json:"users,omitempty"`
	Media  []*Media `json:"media,omitempty"`
}

Includes response object.

type Media

type Media struct {
	MediaKey         string
	Type             string
	URL              string
	DurationMS       int
	Height           int
	Width            int
	NonPublicMetrics *MediaMetrics
	OrganicMetrics   *MediaMetrics
	PromotedMetrics  *MediaMetrics
	PublicMetrics    *MediaMetrics
	PreviewImageURL  string
	AltText          string
	Variants         []*MediaVariant
}

type MediaMetrics

type MediaMetrics struct {
	Playback0Count   int `json:"playback_0_count,omitempty"`
	Playback100Count int `json:"playback_100_count,omitempty"`
	Playback25Count  int `json:"playback_25_count,omitempty"`
	Playback50Count  int `json:"playback_50_count,omitempty"`
	Playback75Count  int `json:"playback_75_count,omitempty"`
	ViewCount        int `json:"view_count,omitempty"`
}

type MediaVariant

type MediaVariant struct {
	BitRate     int
	ContentType string
	URL         string
}

type Meta

type Meta struct {
	ResultCount   int    `json:"result_count,omitempty"`
	NextToken     string `json:"next_token,omitempty"`
	PreviousToken string `json:"previous_token,omitempty"`
}

Meta Struct

type Queue

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

Queue struct holds information for each method, such as @rate time.Duration specific for each endpoint on Twitter @delay time.Duration fallback for @rate, specific for each endpoint on Twitter @requestsChannel chan *Request the incoming (requests) channel @responseChannel chan *Response the outgoing (response) channel

func NewQueue

func NewQueue(rate, delay time.Duration, auto bool, in chan *Request, out chan *Response, options ...QueueOption) *Queue

NewQueue creates a new queue

func (*Queue) Close

func (q *Queue) Close()

Close closes requests and response channels

type QueueOption

type QueueOption func(*Queue)

QueueOption queue options struct

func WithAuto

func WithAuto(auto bool) QueueOption

WithAuto (default:true) will auto continue to the next page if pagination_token exists in the response object

func WithDelay

func WithDelay(delay time.Duration) QueueOption

WithDelay (default:15 minutes) adjusts the the duration between each errored requests due to rate limit errors from Twitter API

func WithRate

func WithRate(rate time.Duration) QueueOption

WithRate (default: according to endpoint) adjusts the the duration between each request to avoid rate limits from Twitter API

type ReferencedTweet

type ReferencedTweet struct {
	Type string `json:"type,omitempty"`
	ID   string `json:"id,omitempty"`
}

ReferencedTweet response object.

type Request

type Request struct {
	Req     *http.Request
	Results Data
}

Request Struct

func NewRquest

func NewRquest(method, url string, v url.Values, body []byte) (*Request, error)

NewRquest returns a new Request struct

func (*Request) ResetResults

func (r *Request) ResetResults()

ResetResults resets request's results

func (*Request) UpdateURLValues

func (r *Request) UpdateURLValues(v url.Values)

UpdateURLValues updates request's query values

type Response

type Response struct {
	Results Data
	Error   error
}

Response Struct

type Rules

type Rules struct {
	Data   []*RulesData             `json:"data"`
	Add    []*RulesData             `json:"add"`
	Delete *RulesDelete             `json:"delete"`
	Meta   *RulesMeta               `json:"meta"`
	Errors []map[string]interface{} `json:"errors"`
}

type RulesData

type RulesData struct {
	Value string `json:"value,omitempty"`
	Tag   string `json:"tag,omitempty"`
	ID    string `json:"id,omitempty"`
}

type RulesDelete

type RulesDelete struct {
	Ids []string `json:"ids,omitempty"`
}

type RulesError

type RulesError struct {
	Value string `json:"value,omitempty"`
	Id    string `json:"id,omitempty"`
	Title string `json:"title,omitempty"`
	Type  string `json:"type,omitempty"`
}

type RulesMeta

type RulesMeta struct {
	Sent        time.Time     `json:"sent,omitempty"`
	ResultCount int           `json:"result_count,omitempty"`
	Summary     *RulesSummary `json:"summary,omitempty"`
}

type RulesSummary

type RulesSummary struct {
	Created    int `json:"created,omitempty"`
	NotCreated int `json:"not_created,omitempty"`
	Deleted    int `json:"deleted,omitempty"`
	NotDeleted int `json:"not_deleted,omitempty"`
}

type Stream

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

func (*Stream) Stop

func (stream *Stream) Stop()

type StreamData

type StreamData struct {
	Data          *Tweet       `json:"data"`
	Includes      *Includes    `json:"includes"`
	MatchingRules []*RulesData `json:"matching_rules"`
	Error         *Error       `json:"error"`
}

type Tweet

type Tweet struct {
	ID                 string               `json:"id"`
	Text               string               `json:"text,omitempty"`
	CreatedAt          string               `json:"created_at,omitempty"`
	AuthorID           string               `json:"author_id,omitempty"`
	ConversationID     string               `json:"conversation_id,omitempty"`
	InReplyToUserID    string               `json:"in_reply_to_user_id,omitempty"`
	ReferencedTweets   []*ReferencedTweet   `json:"referenced_tweets,omitempty"`
	Attachments        *Attachment          `json:"attachments,omitempty"`
	Geo                *Geo                 `json:"geo,omitempty"`
	ContextAnnotations []*ContextAnnotation `json:"context_annotations,omitempty"`
	Entities           *Entities            `json:"entities,omitempty"`
	Withheld           *Withheld            `json:"withheld,omitempty"`
	PublicMetrics      *TweetMetrics        `json:"public_metrics,omitempty"`
	NonPublicMetrics   *TweetMetrics        `json:"non_public_metrics,omitempty"`
	OrganicMetrics     *TweetMetrics        `json:"organic_metrics,omitempty"`
	PromotedMetrics    *TweetMetrics        `json:"promoted_metrics,omitempty"`
	PossibySensitive   bool                 `json:"possibly_sensitive,omitempty"`
	Lang               string               `json:"lang,omitempty"`
	ReplySettings      string               `json:"reply_settings,omitempty"`
	Source             string               `json:"source,omitempty"`
	Includes           *Includes            `json:"includes,omitempty"`
	EditHistoryIDs     []string             `json:"edit_history_ids"`
	Errors             *Error               `json:"errors,omitempty"`
}

Tweet response object as returned from /2/tweets endpoint. For detailed information refer to https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets.

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 TweetMetrics

type TweetMetrics struct {
	Retweets          int `json:"retweet_count,omitempty"`
	Replies           int `json:"reply_count,omitempty"`
	Likes             int `json:"like_count,omitempty"`
	Quotes            int `json:"quote_count,omitempty"`
	Impressions       int `json:"impression_count,omitempty"`
	URLLinkClicks     int `json:"url_link_clicks,omitempty"`
	UserProfileClicks int `json:"user_profile_clicks,omitempty"`
}

TweetMetrics response object.

type Twitter

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

Twitter API Client

func NewTwitter

func NewTwitter(consumerKey, consumerSecret string) (*Twitter, error)

NewTwitter returns a new Twitter API v2 Client using OAuth 2.0 based authentication. This method is usufull when you only need to make Application-Only requests. Official Documentation: https://developer.twitter.com/en/docs/authentication/oauth-2-0

func NewTwitterWithContext

func NewTwitterWithContext(consumerKey, consumerSecret, accessToken, accessTokenSecret string) (*Twitter, error)

NewTwitterWithContext returns a new Twitter API v2 Client using OAuth 1.0 based authentication. This method is useful when you need to make API requests, on behalf of a Twitter account. Official Documentation: https://developer.twitter.com/en/docs/authentication/oauth-1-0a

func (*Twitter) GetClient

func (api *Twitter) GetClient() *http.Client

GetClient Get HTTP Client

func (*Twitter) GetFilterStream

func (api *Twitter) GetFilterStream(v url.Values) (*Stream, error)

GetFilterStream streams tweets in real-time based on a specific set of filter rules. Endpoint URL: https://api.twitter.com/2/tweets/search/stream Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream Authentication Methods: OAuth 2.0 Bearer Token Rate Limit: 50/15m (app)

func (*Twitter) GetFilterStreamRules

func (api *Twitter) GetFilterStreamRules(v url.Values) (*Rules, error)

GetFilterStreamRules returns a list of rules currently active on the streaming endpoint, either as a list or individually. Endpoint URL: https://api.twitter.com/2/tweets/search/stream/rules Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream-rules Authentication Methods: OAuth 2.0 Bearer Token Rate Limit: 450/15m (app)

func (*Twitter) GetSampleStream

func (api *Twitter) GetSampleStream(v url.Values) (*Stream, error)

GetSampleStream streams about 1% of all Tweets in real-time. Endpoint URL: https://api.twitter.com/2/tweets/sample/stream Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/sampled-stream/api-reference/get-tweets-sample-stream Authentication Methods: OAuth 2.0 Bearer Token Rate Limit: 50/15m (app)

func (*Twitter) GetTweetByID

func (api *Twitter) GetTweetByID(id string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetTweetByID returns a variety of information about a single Tweet specified by the requested ID. Endpoint URL: https://api.twitter.com/2/tweets/:id Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference//get-tweets-id Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 900/15m (user)

func (*Twitter) GetTweets

func (api *Twitter) GetTweets(v url.Values, options ...QueueOption) (chan *Data, chan error)

GetTweets returns a variety of information about the Tweet specified by the requested ID or list of IDs. Endpoint URL: https://api.twitter.com/2/tweets Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 900/15m (user)

func (*Twitter) GetTweetsSearchAll

func (api *Twitter) GetTweetsSearchAll(v url.Values, options ...QueueOption) (chan *Data, chan error)

GetTweetsSearchAll returns the complete history of public Tweets matching a search query; since the first Tweet was created March 26, 2006. This endpoint is part of a **private beta** for academic researchers only. *Please do not share this documentation.* Endpoint URL: https://api.twitter.com/2/tweets/search/all Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/full-archive-search/api-reference/get-tweets-search-all Authentication Methods: OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 1/1s (user)

func (*Twitter) GetTweetsSearchRecent

func (api *Twitter) GetTweetsSearchRecent(v url.Values, options ...QueueOption) (chan *Data, chan error)

GetTweetsSearchRecent returns Tweets from the last 7 days that match a search query. Endpoint URL: https://api.twitter.com/2/tweets/search/recent Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 450/15m (app), 180/15m (user)

func (*Twitter) GetUserByID

func (api *Twitter) GetUserByID(id string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUserByID returns a variety of information about a single user specified by the requested ID. Endpoint URL: https://api.twitter.com/2/users/:id Official Documentation: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-id Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 900/15m (user)

func (*Twitter) GetUserFollowers

func (api *Twitter) GetUserFollowers(id string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUserFollowers returns a list of users who are followers of the specified user ID. Endpoint URL: https://api.twitter.com/2/users/:id/followers Official Documentation: https://developer.twitter.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-followers Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 15/15m (app), 15/15m (user)

func (*Twitter) GetUserFollowing

func (api *Twitter) GetUserFollowing(id string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUserFollowing returns a list of users the specified user ID is following. Endpoint URL: https://api.twitter.com/2/users/:id/following Official Documentation: https://developer.twitter.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-following Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 15/15m (app), 15/15m (user)

func (*Twitter) GetUserMentions

func (api *Twitter) GetUserMentions(id string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUserMentions returns Tweets mentioning a single user specified by the requested user ID. Endpoint URL: https://api.twitter.com/2/users/:id/mentions Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 450/15m (app), 180/15m (user)

func (*Twitter) GetUserTweets

func (api *Twitter) GetUserTweets(id string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUserTweets returns Tweets composed by a single user, specified by the requested user ID. Endpoint URL: https://api.twitter.com/2/users/:id/tweets Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 1500/15m (app), 900/15m (user)

func (*Twitter) GetUsers

func (api *Twitter) GetUsers(v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUsers returns a variety of information about one or more users specified by the requested IDs. Endpoint URL: https://api.twitter.com/2/users Official Documentation: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 900/15m (user)

func (*Twitter) GetUsersBy

func (api *Twitter) GetUsersBy(v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUsersByUserName returns a variety of information about one or more users specified by their usernames. Endpoint URL: https://api.twitter.com/2/users/by Official Documentation: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 900/15m (user)

func (*Twitter) GetUsersByUserName

func (api *Twitter) GetUsersByUserName(username string, v url.Values, options ...QueueOption) (chan *Data, chan error)

GetUserByUserName returns a variety of information about one or more users specified by their usernames. Endpoint URL: https://api.twitter.com/2/users/by/username/:username Official Documentation: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by-username-username Authentication Methods: OAuth 1.0a User Context, OAuth 2.0 Bearer Token Rate Limit: 300/15m (app), 900/15m (user)

func (*Twitter) PostFilterStreamRules

func (api *Twitter) PostFilterStreamRules(v url.Values, r *Rules) (*Rules, error)

PostFilterStreamRules adds or deletes rules to your stream. Endpoint URL: https://api.twitter.com/2/tweets/search/stream/rules Official Documentation: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/post-tweets-search-stream-rules Authentication Methods: OAuth 2.0 Bearer Token Rate Limit: 450/15m (app)

func (*Twitter) VerifyCredentials

func (api *Twitter) VerifyCredentials() (bool, error)

VerifyCredentials returns bool upon successful request. This method will make a request on the rate-limit endpoint since there is no official token validation method.

type User

type User struct {
	ID              string       `json:"id"`
	Name            string       `json:"name,omitempty"`
	UserName        string       `json:"username,omitempty"`
	CreatedAt       string       `json:"created_at,omitempty"`
	Protected       bool         `json:"protected,omitempty"`
	Withheld        *Withheld    `json:"withheld,omitempty"`
	Location        string       `json:"location,omitempty"`
	URL             string       `json:"url,omitempty"`
	Description     string       `json:"description,omitempty"`
	Verified        bool         `json:"verified,omitempty"`
	Entities        *Entities    `json:"entities,omitempty"`
	ProfileImageURL string       `json:"profile_image_url,omitempty"`
	PublicMetrics   *UserMetrics `json:"public_metrics,omitempty"`
	PinnedTweetID   string       `json:"pinned_tweet_id,omitempty"`
	Includes        *Includes    `json:"includes,omitempty"`
	Errors          *Error       `json:"errors,omitempty"`
}

User response object as returned from /2/users endpoint. For detailed information refer to https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users.

func (User) CreatedAtTime

func (u User) CreatedAtTime() (time.Time, error)

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

type UserMetrics

type UserMetrics struct {
	Followers int `json:"followers_count,omitempty"`
	Following int `json:"following_count,omitempty"`
	Tweets    int `json:"tweet_count,omitempty"`
	Listed    int `json:"listed_count,omitempty"`
}

UserMetrics response object.

type Withheld

type Withheld struct {
	Copyright    bool     `json:"copyright,omitempty"`
	CountryCodes []string `json:"country_codes,omitempty"`
	Scope        string   `json:"scope,omitempty"`
}

Withheld response object.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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