Convert Figma logo to code with AI

dghubble logogo-twitter

Go Twitter REST and Streaming API v1.1

1,588
315
1,588
7

Top Related Projects

Package githubv4 is a client library for accessing GitHub GraphQL API v4 (https://docs.github.com/en/graphql).

10,287

Go library for accessing the GitHub v3 API

A Go client library for the Twitter 1.1 API

A Facebook Graph API SDK For Go.

Golang bindings for the Telegram Bot API

Quick Overview

go-twitter is a Go client library for the Twitter API v1.1. It provides a simple and idiomatic way to interact with Twitter's REST and Streaming APIs, allowing developers to easily integrate Twitter functionality into their Go applications.

Pros

  • Comprehensive coverage of Twitter API v1.1 endpoints
  • Well-documented and easy to use
  • Supports both REST and Streaming APIs
  • Actively maintained with regular updates

Cons

  • Limited support for newer Twitter API v2 endpoints
  • Requires manual rate limiting management
  • Some advanced features may require additional configuration
  • Dependency on external libraries for OAuth authentication

Code Examples

  1. Posting a tweet:
client := twitter.NewClient(httpClient)
tweet, _, err := client.Statuses.Update("Hello, Twitter!", nil)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Posted tweet: %s\n", tweet.Text)
  1. Searching for tweets:
search, _, err := client.Search.Tweets(&twitter.SearchTweetParams{
    Query: "golang",
    Count: 10,
})
if err != nil {
    log.Fatal(err)
}
for _, tweet := range search.Statuses {
    fmt.Printf("Tweet: %s\n", tweet.Text)
}
  1. Streaming tweets:
demux := twitter.NewSwitchDemux()
demux.Tweet = func(tweet *twitter.Tweet) {
    fmt.Printf("Tweet: %s\n", tweet.Text)
}

filterParams := &twitter.StreamFilterParams{
    Track: []string{"golang", "programming"},
}
stream, err := client.Streams.Filter(filterParams)
if err != nil {
    log.Fatal(err)
}
defer stream.Stop()

go demux.HandleChan(stream.Messages)

Getting Started

  1. Install the library:

    go get github.com/dghubble/go-twitter/twitter
    
  2. Create a Twitter application and obtain API credentials.

  3. Set up authentication:

    config := oauth1.NewConfig("consumer-key", "consumer-secret")
    token := oauth1.NewToken("access-token", "access-token-secret")
    httpClient := config.Client(oauth1.NoContext, token)
    
  4. Create a Twitter client:

    client := twitter.NewClient(httpClient)
    
  5. Start using the client to interact with the Twitter API.

Competitor Comparisons

Package githubv4 is a client library for accessing GitHub GraphQL API v4 (https://docs.github.com/en/graphql).

Pros of githubv4

  • Utilizes GitHub's GraphQL API v4, offering more flexibility and efficiency in data fetching
  • Provides strongly typed query structures, enhancing code reliability and maintainability
  • Supports custom GraphQL queries, allowing for precise data retrieval

Cons of githubv4

  • Limited to GitHub-specific functionality, unlike go-twitter's broader Twitter API support
  • Steeper learning curve for developers unfamiliar with GraphQL
  • May require more setup and configuration compared to go-twitter's REST-based approach

Code Comparison

githubv4:

var query struct {
    Repository struct {
        Issues struct {
            Nodes []struct {
                Title string
            }
        } `graphql:"issues(first: 100)"`
    } `graphql:"repository(owner: $owner, name: $name)"`
}

go-twitter:

tweets, resp, err := client.Timelines.HomeTimeline(&twitter.HomeTimelineParams{
    Count: 20,
})

The githubv4 example demonstrates a structured GraphQL query, while go-twitter shows a simpler REST API call. githubv4 offers more control over data fetching, but requires more complex query construction.

10,287

Go library for accessing the GitHub v3 API

Pros of go-github

  • More comprehensive API coverage, including GitHub-specific features like Actions and Packages
  • Better documentation and examples
  • More active development and maintenance

Cons of go-github

  • Larger codebase, potentially more complex to use
  • Focused solely on GitHub, less versatile for other platforms

Code Comparison

go-github:

client := github.NewClient(nil)
user, _, err := client.Users.Get(context.Background(), "octocat")

go-twitter:

config := oauth1.NewConfig("consumerKey", "consumerSecret")
token := oauth1.NewToken("accessToken", "accessSecret")
client := twitter.NewClient(config.Client(oauth1.NoContext, token))

Key Differences

  • go-github is tailored for GitHub's API, while go-twitter is specific to Twitter's API
  • go-github uses context for cancellation and timeouts, go-twitter relies on OAuth1 for authentication
  • go-github has more extensive features due to GitHub's broader API surface

Use Cases

  • Choose go-github for comprehensive GitHub integrations
  • Opt for go-twitter when building Twitter-specific applications

Both libraries provide idiomatic Go interfaces for their respective APIs, making them valuable tools for developers working with these platforms.

A Go client library for the Twitter 1.1 API

Pros of Anaconda

  • More comprehensive API coverage, including streaming and media uploads
  • Better documentation and examples
  • Active community and regular updates

Cons of Anaconda

  • Larger codebase, potentially more complex to use
  • Slightly slower performance due to more abstraction layers
  • Less idiomatic Go code in some parts

Code Comparison

Anaconda:

api := anaconda.NewTwitterApiWithCredentials(accessToken, accessTokenSecret, consumerKey, consumerSecret)
tweet, err := api.PostTweet("Hello, Twitter!", nil)

go-twitter:

config := oauth1.NewConfig(consumerKey, consumerSecret)
token := oauth1.NewToken(accessToken, accessTokenSecret)
httpClient := config.Client(oauth1.NoContext, token)
client := twitter.NewClient(httpClient)
tweet, _, err := client.Statuses.Update("Hello, Twitter!", nil)

Both libraries provide similar functionality for basic Twitter API operations. Anaconda offers a more straightforward API with fewer lines of code for common tasks, while go-twitter follows a more idiomatic Go approach with explicit client creation and method chaining.

Anaconda is generally easier to get started with and offers more features out of the box, making it suitable for projects that require extensive Twitter API integration. go-twitter, on the other hand, provides a cleaner, more Go-like interface and may be preferable for developers who prioritize performance and idiomatic code.

A Facebook Graph API SDK For Go.

Pros of facebook

  • More comprehensive API coverage, including Graph API and Marketing API
  • Better documentation and examples within the repository
  • Active development with recent updates and contributions

Cons of facebook

  • Larger and more complex codebase, potentially harder to navigate
  • Fewer stars and forks on GitHub, indicating potentially less community adoption
  • Less focused on a specific API, which may lead to feature bloat

Code Comparison

go-twitter:

client := twitter.NewClient(httpClient)
search, _, err := client.Search.Tweets(&twitter.SearchTweetParams{
    Query: "golang",
})

facebook:

res, err := fb.Get("/me", fb.Params{
    "fields": "id,name,email",
})
if err != nil {
    // Handle error
}

Both libraries provide simple ways to interact with their respective APIs, but facebook offers a more flexible approach with its Params structure, allowing for easier customization of API requests.

Golang bindings for the Telegram Bot API

Pros of telegram-bot-api

  • More focused on Telegram-specific features and API
  • Simpler setup and usage for Telegram bots
  • Active development and frequent updates

Cons of telegram-bot-api

  • Limited to Telegram platform only
  • Less flexibility for custom HTTP client configurations
  • Fewer options for advanced rate limiting and request management

Code Comparison

go-twitter:

config := oauth1.NewConfig("consumerKey", "consumerSecret")
token := oauth1.NewToken("accessToken", "accessSecret")
httpClient := config.Client(oauth1.NoContext, token)
client := twitter.NewClient(httpClient)

telegram-bot-api:

bot, err := tgbotapi.NewBotAPI("BOT_TOKEN")
if err != nil {
    log.Panic(err)
}

The go-twitter library requires more setup for authentication, while telegram-bot-api has a simpler initialization process. go-twitter offers more flexibility in terms of HTTP client configuration, which can be beneficial for advanced use cases. On the other hand, telegram-bot-api provides a more straightforward approach for creating Telegram bots, making it easier for developers to get started quickly.

Both libraries have their strengths, with go-twitter being more versatile for Twitter-related applications and telegram-bot-api being more specialized for Telegram bot development. The choice between the two depends on the specific platform and requirements of your project.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

go-twitter GoDoc Workflow Sponsors Twitter

DEPRECATED As of Nov 2022, the go-twitter API library is no longer being developed. If you fork this repo, please remove the logo since it is not covered by the license.

go-twitter is a Go client library for the Twitter API. Check the usage section or try the examples to see how to access the Twitter API.

Features

  • Twitter REST API:
    • Accounts
    • Blocks
    • DirectMessageEvents
    • Favorites
    • Friends
    • Friendships
    • Followers
    • Lists
    • PremiumSearch
    • RateLimits
    • Search
    • Statuses
    • Timelines
    • Users
  • Twitter Streaming API
    • Public Streams
    • User Streams
    • Site Streams
    • Firehose Streams

Install

go get github.com/dghubble/go-twitter/twitter

Documentation

Read GoDoc

Usage

REST API

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

config := oauth1.NewConfig("consumerKey", "consumerSecret")
token := oauth1.NewToken("accessToken", "accessSecret")
httpClient := config.Client(oauth1.NoContext, token)

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

// Home Timeline
tweets, resp, err := client.Timelines.HomeTimeline(&twitter.HomeTimelineParams{
    Count: 20,
})

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

// Search Tweets
search, resp, err := client.Search.Tweets(&twitter.SearchTweetParams{
    Query: "gopher",
})

// User Show
user, resp, err := client.Users.Show(&twitter.UserShowParams{
    ScreenName: "dghubble",
})

// Followers
followers, resp, err := client.Followers.List(&twitter.FollowerListParams{})

Authentication is handled by the http.Client passed to NewClient to handle user auth (OAuth1) or application auth (OAuth2). See the Authentication section.

Required parameters are passed as positional arguments. Optional parameters are passed typed params structs (or nil).

Streaming API

The Twitter Public, User, Site, and Firehose Streaming APIs can be accessed through the Client StreamService which provides methods Filter, Sample, User, Site, and Firehose.

Create a Client with an authenticated http.Client. All stream endpoints require a user auth context so choose an OAuth1 http.Client.

client := twitter.NewClient(httpClient)

Next, request a managed Stream be started.

Filter

Filter Streams return Tweets that match one or more filtering predicates such as Track, Follow, and Locations.

params := &twitter.StreamFilterParams{
    Track: []string{"kitten"},
    StallWarnings: twitter.Bool(true),
}
stream, err := client.Streams.Filter(params)

User

User Streams provide messages specific to the authenticate User and possibly those they follow.

params := &twitter.StreamUserParams{
    With:          "followings",
    StallWarnings: twitter.Bool(true),
}
stream, err := client.Streams.User(params)

Note To see Direct Message events, your consumer application must ask Users for read/write/DM access to their account.

Sample

Sample Streams return a small sample of public Tweets.

params := &twitter.StreamSampleParams{
    StallWarnings: twitter.Bool(true),
}
stream, err := client.Streams.Sample(params)

Site, Firehose

Site and Firehose Streams require your application to have special permissions, but their API works the same way.

Receiving Messages

Each Stream maintains the connection to the Twitter Streaming API endpoint, receives messages, and sends them on the Stream.Messages channel.

Go channels support range iterations which allow you to read the messages which are of type interface{}.

for message := range stream.Messages {
    fmt.Println(message)
}

If you run this in your main goroutine, it will receive messages forever unless the stream stops. To continue execution, receive messages using a separate goroutine.

Demux

Receiving messages of type interface{} isn't very nice, it means you'll have to type switch and probably filter out message types you don't care about.

For this, try a Demux, like SwitchDemux, which receives messages and type switches them to call functions with typed messages.

For example, say you're only interested in Tweets and Direct Messages.

demux := twitter.NewSwitchDemux()
demux.Tweet = func(tweet *twitter.Tweet) {
    fmt.Println(tweet.Text)
}
demux.DM = func(dm *twitter.DirectMessage) {
    fmt.Println(dm.SenderID)
}

Pass the Demux each message or give it the entire Stream.Message channel.

for message := range stream.Messages {
    demux.Handle(message)
}
// or pass the channel
demux.HandleChan(stream.Messages)

Stopping

The Stream will stop itself if the stream disconnects and retrying produces unrecoverable errors. When this occurs, Stream will close the stream.Messages channel, so execution will break out of any message for range loops.

When you are finished receiving from a Stream, call Stop() which closes the connection, channels, and stops the goroutine before returning. This ensures resources are properly cleaned up.

Pitfalls

Bad: In this example, Stop() is unlikely to be reached. Control stays in the message loop unless the Stream becomes disconnected and cannot retry.

// program does not terminate :(
stream, _ := client.Streams.Sample(params)
for message := range stream.Messages {
    demux.Handle(message)
}
stream.Stop()

Bad: Here, messages are received on a non-main goroutine, but then Stop() is called immediately. The Stream is stopped and the program exits.

// got no messages :(
stream, _ := client.Streams.Sample(params)
go demux.HandleChan(stream.Messages)
stream.Stop()

Good: For main package scripts, one option is to receive messages in a goroutine and wait for CTRL-C to be pressed, then explicitly stop the Stream.

stream, err := client.Streams.Sample(params)
go demux.HandleChan(stream.Messages)

// Wait for SIGINT and SIGTERM (HIT CTRL-C)
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
log.Println(<-ch)

stream.Stop()

Authentication

The API client accepts an any http.Client capable of making user auth (OAuth1) or application auth (OAuth2) authorized requests. See the dghubble/oauth1 and golang/oauth2 packages which can provide such agnostic clients.

Passing an http.Client directly grants you control over the underlying transport, avoids dependencies on particular OAuth1 or OAuth2 packages, and keeps client APIs separate from authentication protocols.

See the google/go-github client which takes the same approach.

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:     "consumerKey",
    ClientSecret: "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 for web or mobile, see the gologin package and examples.

Roadmap

  • Support gzipped streams
  • Auto-stop streams in the event of long stalls

Contributing

See the Contributing Guide.

License

MIT License