tweetgo

package module
v0.0.0-...-588353f Latest Latest
Warning

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

Go to latest
Published: May 31, 2020 License: MIT Imports: 15 Imported by: 0

README

Tweetgo

GoDoc codecov CodeFactor Go Report Card Hound

Examples are posted at tweetgo-examples.

This library is not meant to be an exhaustive API for Twitter, yet. My goal is two-fold. First, I want the benefit of strong types that we all enjoy in Go. Second, I want it to be dead simple to add new endpoints to this library. I've modeled this library after aws-sdk-go where the input to every endpoint is a well-defined struct, and the output from every endpoint is also a well-defined struct.

The easiest way to run the examples is to create an example/config.json then cd into the example directory and run go run .. Put the following in the config.json file.

{
  "oauth_consumer_key": "XXXXXXXXXXXXXXXXXXXXXXXXX",
  "oauth_consumer_secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}

Below is a quick example of posting a tweet. You'll have to provide the consumer key, consumer secret, access token, and access token secret yourself. The endpoints for getting the oauth request token and converting that into an oauth access token have been implemented as OAuthRequestTokenGet and OAuthAccessTokenGet. When you want to have your application to automatically authorize the user and retrieve access tokens on their behalf checkout the provided examples.

package main

func main() {
    tc := tweetgo.NewClient(
        "OAuthConsumerKey",
        "OAuthConsumerSecret",
    )

    tc.SetAccessKeys("OAuthAccessToken", "OAuthAccessTokenSecret")

    input := tweetgo.StatusesUpdateInput{
        Status: tweetgo.String("Hello Ladies + Gentlemen, a signed OAuth request!"),
    }

    output, err := tc.StatusesUpdatePost(input)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%+v", output)
}

If you look in the model.go you'll see that every option for updating a status is in the struct StatusesUpdateInput and all the possible fields have been documented in the StatusesUpdateOutput.

If you follow these steps you can add any endpoints that you need easily and give back to the community!

Setup for local development

If you are using Go mod in your project you can add something like the following:

replace github.com/bloveless/tweetgo => ../tweetgo

to your go.mod file before any "require" lines in your go.mod (replace ../tweetgo with the path to your local copy of tweetgo).

I learned about that command from this blog post. Using "replace" in go.mod to point to your local module . Credit where credit is due!

How to add a new endpoint

The second goal for this project is to make it super easy to add new endpoints. These are the steps you'll need to follow in order to add another endpoint. I'll be adding the GET statuses/user_timeline endpoint.

Step 1: Create the input model

Refer to the link above to generate the input model. Below is the input I created for the statuses/user_timeline endpoint. Twitter uses form encoded input when receiving a request and responds in JSON. This doesn't change much about implementing a new endpoint other than you'll use the "schema" tag when you are writing the input structs, and the "json" tag when you are writing the output structs. Every input field needs to be a pointer so we can use nil values to decide if a values should be encoded and sent to the endpoint or not. There are helper function for converting between standard types and pointers to make this a little easier. Checkout value.go to see what I'm talking about. If you add a type that hasn't been used before, it will be helpful for you to add a conversion func to value.go.

type StatusesUserTimelineInput struct {
    UserID         *int64  `schema:"user_id"`
    ScreenName     *string `schema:"screen_name"`
    SinceID        *int64  `schema:"since_id"`
    Count          *int    `schema:"count"`
    MaxID          *int64  `schema:"max_id"`
    TrimUser       *bool   `schema:"trim_user"`
    ExcludeReplies *bool   `schema:"exclude_replies"`
    IncludeRts     *bool   `schema:"include_rts"`
}
Step 2: Create the output model

Refer to the Twitter docs link above to see which fields are returned from the endpoint. There are only a few different types of returns from Twitter API's so there are some utility structs that you can compose responses from. They are unexported and are intended to be composed within other structs. The statuses user timeline endpoint returns a list of Tweets so the output struct is very simple.

type StatusesUserTimelineOutput struct {
    tweet
}
Step 3: Create endpoint code

The request signing and execution has been wrapped up into utility functions which you can find in request.go. Hopefully this will make adding new endpoints extremely simple. For this endpoint I added the following code to client.go.

func (c Client) StatusesUserTimelineGet(input StatusesUserTimelineInput) ([]StatusesUserTimelineOutput, error) { // 1) change to the correct input/output types here
    uri := "https://api.twitter.com/1.1/statuses/user_timeline.json" // 2) Change to the correct URI here
    params := processParams(input)

    res, err := c.executeRequest(http.MethodGet, uri, params) // 3) Change to the correct http method here
    if err != nil {
        return []StatusesUserTimelineOutput{}, err // 4) Change to the correct output type here
    }
    defer res.Body.Close()

    resBytes, err := ioutil.ReadAll(res.Body) // NOTE: This can be changed to parse form value output
    if err != nil {
        return []StatusesUserTimelineOutput{}, err // 5) Change to the correct output type here
    }

    var output []StatusesUserTimelineOutput // 6) Change to the correct output type here
    json.Unmarshal(resBytes, &output)

    return output, nil
}

Follow the six steps above, and you'll have your own endpoint up and running.

NOTE: As far as I can tell twitter uses JSON output on nearly all of its endpoints. The oauth endpoints use form values rather than JSON output so support functions exist for processing that type of data as well. Look at OAuthRequestTokenGet which uses gorilla/scheme for parsing the data into the output format if you find another endpoint that uses form values rather than JSON.

There you go! You've added your own endpoint!


Endpoints

Basics

Authentication
  • GET oauth/authenticate
  • GET oauth/authorize
  • POST oauth/access_token
  • POST oauth/invalidate_token
  • POST oauth/request_token
  • POST oauth2/invalidate_token
  • POST oauth2/token

Accounts and users

Create and manage lists
  • GET lists/list
  • GET lists/members
  • GET lists/members/show
  • GET lists/memberships
  • GET lists/ownerships
  • GET lists/show
  • GET lists/statuses
  • GET lists/subscribers
  • GET lists/subscribers/show
  • GET lists/subscriptions
  • POST lists/create
  • POST lists/destroy
  • POST lists/members/create
  • POST lists/members/create_all
  • POST lists/members/destroy
  • POST lists/members/destroy_all
  • POST lists/subscribers/create
  • POST lists/subscribers/destroy
  • POST lists/update
Follow, search, and get users
  • GET followers/ids
  • GET followers/list
  • GET friends/ids
  • GET friends/list
  • GET friendships/incoming
  • GET friendships/lookup
  • GET friendships/no_retweets/ids
  • GET friendships/outgoing
  • GET friendships/show
  • GET users/lookup
  • GET users/search
  • GET users/show
  • POST friendships/create
  • POST friendships/destroy
  • POST friendships/update
Manage account settings and profile
  • GET account/settings
  • GET account/verify_credentials
  • GET saved_searches/list
  • GET saved_searches/show/:id
  • GET users/profile_banner
  • POST account/remove_profile_banner
  • POST account/settings
  • POST account/update_profile
  • POST account/update_profile_background_image (retired)
  • POST account/update_profile_banner
  • POST account/update_profile_image
  • POST saved_searches/create
  • POST saved_searches/destroy/:id
Mute, block, and report users
  • GET blocks/ids
  • GET blocks/list
  • GET mutes/users/ids
  • GET mutes/users/list
  • POST blocks/create
  • POST blocks/destroy
  • POST mutes/users/create
  • POST mutes/users/destroy
  • POST users/report_spam
Subscribe to account activity
  • Enterprise Account Activity API
  • Premium Account Activity API
  • Replay API

Tweets

Curate a collection of Tweets
  • GET collections/entries
  • GET collections/list
  • GET collections/show
  • POST collections/create
  • POST collections/destroy
  • POST collections/entries/add
  • POST collections/entries/curate
  • POST collections/entries/move
  • POST collections/entries/remove
  • POST collections/update
Filter realtime Tweets
  • PowerTrack API
  • PowerTrack Rules API
  • Replay API
  • POST statuses/filter
Get Tweet timelines
  • GET statuses/home_timeline
  • GET statuses/mentions_timeline
  • GET statuses/user_timeline
Get batch historical Tweets
  • Historical PowerTrack
Post, retrieve, and engage with Tweets
  • GET favorites/list
  • GET statuses/lookup
  • GET statuses/oembed
  • GET statuses/retweeters/ids
  • GET statuses/retweets/:id
  • GET statuses/retweets_of_me
  • GET statuses/show/:id
  • POST favorites/create
  • POST favorites/destroy
  • POST statuses/destroy/:id
  • POST statuses/retweet/:id
  • POST statuses/unretweet/:id
  • POST statuses/update
Sample realtime Tweets
  • Decahose stream
  • GET statuses/sample
Search Tweets
  • Enterprise search APIs
  • Premium search APIs
  • Standard search API
Tweet compliance
  • GET compliance/firehose

Direct Messages

Buttons
  • Buttons
Custom profiles
  • DELETE custom_profiles/destroy.json
  • Send a Direct Message with custom profile
  • GET custom_profiles/:id
  • GET custom_profiles/list
  • POST custom_profiles/new.json
Direct Messages
  • API Reference
Quick Replies
  • Options Quick Reply
Sending and receiving events
  • DELETE direct_messages/events/destroy
  • GET direct_messages/events/list
  • GET direct_messages/events/show
  • POST direct_messages/events/new (message_create)
Typing indicator and read receipts
  • POST direct_messages/indicate_typing
  • POST direct_messages/mark_read
Welcome Messages
  • DELETE direct_messages/welcome_messages/destroy
  • DELETE direct_messages/welcome_messages/rules/destroy
  • PUT direct_messages/welcome_messages/update
  • GET direct_messages/welcome_messages/list
  • GET direct_messages/welcome_messages/rules/list
  • GET direct_messages/welcome_messages/rules/show
  • GET direct_messages/welcome_messages/show
  • POST direct_messages/welcome_messages/new
  • POST direct_messages/welcome_messages/rules/new

Media

Upload media
  • GET media/upload (STATUS)
  • POST media/metadata/create
  • POST media/subtitles/create
  • POST media/subtitles/delete
  • POST media/upload
  • POST media/upload (APPEND)
  • POST media/upload (FINALIZE)
  • POST media/upload (INIT)
  • GET trends/available
  • GET trends/closest
  • GET trends/place

Geo

Get information about a place
  • GET geo/id/:place_id
  • Get places near a location
  • GET geo/reverse_geocode
  • GET geo/search

Ads

Analytics
  • Active Entities
  • Asynchronous Analytics
  • Reach and Average Frequency
  • Synchronous Analytics
Audiences
  • Audience Intelligence
  • Insights
  • Keyword Insights
  • Tailored Audience Permissions
  • Tailored Audiences
  • Tailored Audiences Users
Campaign management
  • Accounts
  • Advertiser Business Categories
  • Audience Summary
  • Authenticated User Access
  • Bidding Rules
  • Campaigns
  • Content Categories
  • Features
  • Funding Instruments
  • IAB Categories
  • Line Item Apps
  • Line Item Placements
  • Line Items
  • Media Creatives
  • Promotable Users
  • Promoted Accounts
  • Promoted Tweets
  • Reach Estimate
  • Recommendations
  • Scheduled Promoted Tweets
  • Targeting Criteria
  • Targeting Options
  • Targeting Suggestions
  • Tax Settings
  • User Settings
  • political-disclaimers
Creatives
  • Account Media
  • Cards Fetch
  • Draft Tweets
  • Image App Download Cards
  • Image Conversation Cards
  • Image Direct Message Cards
  • Media Library
  • Poll Cards
  • Preroll Call To Actions
  • Scheduled Tweets
  • Tweet Previews
  • Tweets
  • Video App Download Cards
  • Video Conversation Cards
  • Video Direct Message Cards
  • Video Website Cards
  • Website Cards
General
  • Analytics
  • Audiences
  • Campaign Management
  • Creatives
  • Measurement
Measurement
  • App Event Provider Configurations
  • App Event Tags
  • App Lists
  • Conversion Attribution
  • Conversion Event
  • Web Event Tags

Metrics

Get Tweet engagement
  • POST insights/engagement

Labs

COVID-19 stream
  • GET /labs/1/tweets/stream/compliance
  • GET /labs/1/tweets/stream/covid19
Filtered stream v1
  • GET /labs/1/tweets/stream/filter
  • GET /labs/1/tweets/stream/filter/rules
  • POST /labs/1/tweets/stream/filter/rules (create)
  • POST /labs/1/tweets/stream/filter/rules (delete)
Hide replies v2
  • PUT /labs/2/tweets/:id/hidden
Recent search v2
  • GET /labs/2/tweets/search
Sampled stream v1
  • GET /labs/1/tweets/stream/sample
Tweet metrics v1
  • GET /labs/1/tweets/metrics/private
Tweets and Users v2
  • GET /labs/2/tweets
  • GET /labs/2/tweets/:id
  • GET /labs/2/users
  • GET /labs/2/users/:id

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(input bool) *bool

func Float64

func Float64(input float64) *float64

func Int

func Int(input int) *int

func Int64

func Int64(input int64) *int64

func String

func String(input string) *string

Types

type Client

type Client struct {
	OAuthConsumerKey       string
	OAuthConsumerSecret    string
	OAuthAccessToken       string
	OAuthAccessTokenSecret string
	HTTPClient             requestMaker
	Noncer                 nonceMaker
	Timer                  currentTimer
}

Client is the Twitter API client which will make signed requests to twitter

func NewClient

func NewClient(oauthConsumerKey, oauthConsumerSecret string) Client

func (Client) ListsListGet

func (c Client) ListsListGet(input ListsListInput) ([]ListsListOutput, error)

ListsListGet will return all lists the authenticating user or specified user subscribes to, including thier own. https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list

func (Client) ListsMembersGet

func (c Client) ListsMembersGet(input ListsMembersInput) (ListsMembersOutput, error)

ListsMembersGet will return the members of a specified list https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members

func (Client) ListsMembersShowGet

func (c Client) ListsMembersShowGet(input ListsMembersShowInput) (ListsMembersShowOutput, error)

ListsMembersShowGet will check if the specified users is a member of the specified list https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show

func (Client) OAuthAccessTokenPost

func (c Client) OAuthAccessTokenPost(input OAuthAccessTokenInput) (OAuthAccessTokenOutput, error)

OAuthAccessTokenPost will exchange a temporary access token for a permanent one https://developer.twitter.com/en/docs/basics/authentication/api-reference/access_token

func (Client) OAuthRequestTokenPost

func (c Client) OAuthRequestTokenPost(input OAuthRequestTokenInput) (OAuthRequestTokenOutput, error)

OAuthRequestTokenPost will return an oauth_token and oauth_token_secret https://developer.twitter.com/en/docs/basics/authentication/api-reference/request_token

func (*Client) SetAccessKeys

func (c *Client) SetAccessKeys(oauthAccessToken, oauthAccessTokenSecret string)

func (Client) StatusesFilterPostRaw

func (c Client) StatusesFilterPostRaw(input StatusesFilterInput) (*http.Response, error)

StatusesFilterPostRaw will get a streaming list of tweets and return the raw http response for streaming https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter

func (Client) StatusesUpdatePost

func (c Client) StatusesUpdatePost(input StatusesUpdateInput) (StatusesUpdateOutput, error)

StatusesUpdatePost will post a status update to twitter https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update

func (Client) StatusesUserTimelineGet

func (c Client) StatusesUserTimelineGet(input StatusesUserTimelineInput) ([]StatusesUserTimelineOutput, error)

StatusesUserTimelineGet will get a users timeline and return an array of tweets https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline

type ListsListInput

type ListsListInput struct {
	UserID     *int64  `schema:"user_id"`
	ScreenName *string `schema:"screen_name"`
	Reverse    *bool   `schema:"reverse"`
}

ListsListInput contains the possible inputs when listing a list

type ListsListOutput

type ListsListOutput struct {
	ID              int64  `json:"id"`
	IDStr           string `json:"id_str"`
	Name            string `json:"name"`
	URI             string `json:"uri"`
	SubscriberCount int    `json:"subscriber_count"`
	MemberCount     int    `json:"member_count"`
	Mode            string `json:"mode"`
	Description     string `json:"description"`
	Slug            string `json:"slug"`
	FullName        string `json:"full_name"`
	CreatedAt       string `json:"created_at"`
	Following       bool   `json:"following"`
	User            user   `json:"user"`
}

ListsListOutput contains the output of listing the lists

type ListsMembersInput

type ListsMembersInput struct {
	ListID          *int64  `schema:"list_id"`
	Slug            *string `schema:"slug"`
	OwnerScreenName *string `schema:"owner_screen_name"`
	OwnerID         *int64  `schema:"owner_id"`
	Count           *int    `schema:"count"`
	Cursor          *int    `schema:"cursor"`
	IncludeEntities *bool   `schema:"include_entities"`
	SkipStatus      *bool   `schema:"skip_status"`
}

ListsMembersInput contains the possible inputs when listing the members of a list

type ListsMembersOutput

type ListsMembersOutput struct {
	Users             []user `json:"users"`
	NextCursor        int    `json:"next_cursor"`
	NextCursorStr     string `json:"next_cursor_str"`
	PreviousCursor    int    `json:"previous_cursor"`
	PreviousCursorStr string `json:"previous_cursor_str"`
	TotalCount        int    `json:"total_count"`
}

ListsMembersOutput contians the output from listing the members of a list

type ListsMembersShowInput

type ListsMembersShowInput struct {
	ListID          *int64  `schema:"list_id"`
	Slug            *string `schema:"slug"`
	UserID          *int64  `schema:"user_id"`
	ScreenName      *string `schema:"screen_name"`
	OwnerScreenName *string `schema:"owner_screen_name"`
	OwnerID         *int64  `schema:"owner_id"`
	IncludeEntities *bool   `schema:"include_entities"`
	SkipStatus      *bool   `schema:"skip_status"`
}

ListsMembersShowInput contains the possible inputs for the lists/members/show endpoint

type ListsMembersShowOutput

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

ListsMembersShowOutput contains the output for the lists/members/show endpoint

type OAuthAccessTokenInput

type OAuthAccessTokenInput struct {
	OAuthToken    *string `schema:"oauth_token"`
	OAuthVerifier *string `schema:"oauth_verifier"`
}

OAuthAccessTokenInput contains the input necessary to exchange a request token for an access token

type OAuthAccessTokenOutput

type OAuthAccessTokenOutput struct {
	OAuthToken       string `schema:"oauth_token"`
	OAuthTokenSecret string `schema:"oauth_token_secret"`
	UserID           int64  `schema:"user_id"`
	ScreenName       string `schema:"screen_name"`
}

OAuthAccessTokenOutput contains the results of calling OAuth Access Token, including a long lived token

type OAuthRequestTokenInput

type OAuthRequestTokenInput struct {
	OAuthCallback   *string `schema:"oauth_callback"`
	XAuthAccessType *string `schema:"x_auth_access_type"`
}

OAuthRequestTokenInput contains the possible inputs to the request token endpoint.

type OAuthRequestTokenOutput

type OAuthRequestTokenOutput struct {
	OAuthToken             string `schema:"oauth_token,required"`
	OAuthTokenSecret       string `schema:"oauth_token_secret,required"`
	OAuthCallbackConfirmed bool   `schema:"oauth_callback_confirmed,required"`
}

OAuthRequestTokenOutput contains the results of calling request token.

type StatusesFilterInput

type StatusesFilterInput struct {
	Follow        *string `schema:"follow"`
	Track         *string `schema:"track"`
	Locations     *string `schema:"locations"`
	Delimited     *string `schema:"delimited"`
	StallWarnings *string `schema:"stall_warnings"`
}

StatusesFilterInput contains the input options for getting filtered statuses

type StatusesFilterOutput

type StatusesFilterOutput struct {
	QuotedStatus    tweet `json:"quoted_status"`
	RetweetedStatus tweet `json:"retweeted_status"`
	ExtendedTweet   tweet `json:"extended_tweet"`
	// contains filtered or unexported fields
}

StatusesFilterOutput contains the output for a single response from the filtered statuses endpoint

type StatusesUpdateInput

type StatusesUpdateInput struct {
	Status                    *string  `schema:"status"`
	InReplyToStatusID         *int64   `schema:"in_reply_to_status_id"`
	AutoPopulateReplyMetadata *bool    `schema:"auto_populate_reply_metadata"`
	ExcludeReplyUserIDs       *string  `schema:"exclude_reply_user_ids"`
	AttachmentURL             *string  `schema:"attachment_url"`
	MediaIDs                  *string  `schema:"media_ids"`
	PossiblySensitive         *bool    `schema:"possibly_sensitive"`
	Lat                       *float64 `schema:"lat"`
	Long                      *float64 `schema:"long"`
	PlaceID                   *string  `schema:"place_id"`
	DisplayCoordinates        *bool    `schema:"display_coordinates"`
	TrimUser                  *bool    `schema:"trim_user"`
	EnableDMCommands          *bool    `schema:"enable_dmcommands"`
	FailDMCommands            *bool    `schema:"fail_dmcommands"`
	CardURI                   *string  `schema:"card_uri"`
}

StatusesUpdateInput contains the possible inputs when updating a status

type StatusesUpdateOutput

type StatusesUpdateOutput struct {
	CreatedAt            string `json:"created_at"`
	ID                   int64  `json:"id"`
	IDStr                string `json:"id_str"`
	Text                 string `json:"text"`
	Source               string `json:"source"`
	Truncated            bool   `json:"truncated"`
	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"`
	InReplyToScreenName  string `json:"in_reply_to_screen_name"`
	User                 user   `json:"user"`
}

StatusesUpdateOutput contains the output from posting a status update

type StatusesUserTimelineInput

type StatusesUserTimelineInput struct {
	UserID         *int64  `schema:"user_id"`
	ScreenName     *string `schema:"screen_name"`
	SinceID        *int64  `schema:"since_id"`
	Count          *int    `schema:"count"`
	MaxID          *int64  `schema:"max_id"`
	TrimUser       *bool   `schema:"trim_user"`
	ExcludeReplies *bool   `schema:"exclude_replies"`
	IncludeRts     *bool   `schema:"include_rts"`
}

StatusesUserTimelineInput contains the input options for getting the users timeline statuses

type StatusesUserTimelineOutput

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

StatusesUserTimelineOutput contains the output for a response from the users timeline endpoint

Jump to

Keyboard shortcuts

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